[Tutor] python closures
Hugo Arts
hugo.yoshi at gmail.com
Mon Nov 30 17:38:57 CET 2009
On Mon, Nov 30, 2009 at 4:16 PM, Kent Johnson <kent37 at tds.net> wrote:
> That has not been needed since 2.1 though it is still useful when
> closures are created in a loop (because closures are kind of late
> bound - I'm not sure the exact technical explanation):
> In [13]: def f():
> ....: l = []
> ....: for i in range(3):
> ....: def g():
> ....: print i
> ....: l.append(g)
> ....: return l
>
> In [14]: for g in f(): g()
> ....:
> 2
> 2
> 2
>
This doesn't really have anything to do with closures specifically.
Variable lookup is done at runtime, not definition time. So when these
lookups for i are performed the value of i is indeed 2.
This wouldn't happen if closures used pointer references (as spir
called them). Then again, even with pointer references modifications
to mutable variables are still visible inside a closure.
Hugo
More information about the Tutor
mailing list