a = b = 1 just syntactic sugar?
Terry Reedy
tjreedy at udel.edu
Sat Jun 7 20:51:26 EDT 2003
"Ed Avis" <ed at membled.com> wrote in message
news:l1wufxh9g8.fsf at budvar.future-i.net...
> Steven Taschuk <staschuk at telusplanet.net> writes:
>
> >We already have closures, don't we?
> >
> > >>> def f(x):
> > ... def g(y):
> > ... return x + y
> > ... return g
> > ...
> > >>> q = f(3)
> > >>> q(4)
> > 7
>
> Which Python version does this require?
2.1 with future statement, 2.2 without
> (The machine to hand has only 1.5.2, although normally I use 2.2 or
so.)
Upgrade if you can.
> I mean things like
>
> def make_adder():
> x = 0
> def incr():
> x += 1
> return x
> return incr
>
> f = make_adder()
> g = make_adder()
> print f(), f(), g(), g() # 1 2 1 2
You can read but not rebind variable in outer scope. But this works:
def make_counter():
counter = [0]
def incr():
counter[0] += 1
return counter[0]
return incr
>>> c1=make_counter()
>>> c2=make_counter()
>>> print c1(), c1(), c2(), c2()
1 2 1 2
Terry J. Reedy
More information about the Python-list
mailing list