On Fri, May 24, 2002 at 05:10:19PM +1000, Mark Johnathan Greenaway wrote:
> On Fri, May 24, 2002 at 03:53:58PM +1000, Angus Lees wrote:
> 
> > i mostly agree. the big thing holding me back from python is
> > closures. once python gets proper anonymous, lexically scoped
> > subroutines things will start to look up.
> 
> Does
> from __future__ import nested_scopes
> do what you want? Sorry, I haven't read the definitions of lexical etc. 
> scoping in some years now.

Python's nested scopes allows you to do:

def f(x):
    def g():       # before nested scopes, using "def g(x=x):" would be
                   # more or less the same
        return x
    return g

so that f(17) will return a function that returns 17 when called.

What is missing is:

def f(x):
    def g():
        f's x = x + 1    # There's no syntax for this in Python.
        return x
    return g

where f(17) will return a function that returns 18, then 19, then 20, ...
i.e. return the value of x you passed in, and increment it ready for the
next call.

If you're desperate, you can do:

def f(x):
    mutable = [x]
    def g():
        mutable[0] += 1
        return mutable[0]
    return g

But that's not nearly as good, obviously.

I personally find closures to be a cute trick that is rarely genuinely
useful (not that I've done much programming in any language with them, but
I've never found myself wishing I had them either) -- but then, so are
generators, and Python 2.2 does have those... (I've used a generator exactly
once).

Depends on what you're doing, I guess.

-Andrew.

-- 
SLUG - Sydney Linux User's Group - http://slug.org.au/
More Info: http://lists.slug.org.au/listinfo/slug

Reply via email to