Lambda forms and scoping
gagsl-py2 at yahoo.com.ar
Fri Mar 20 14:03:24 CET 2009
En Fri, 20 Mar 2009 09:28:08 -0300, R. David Murray
<rdmurray at bitdance.com> escribió:
> Benjamin Peterson <benjamin at python.org> wrote:
>> Márcio Faustino <m.faustino <at> gmail.com> writes:
>> > Executing the example below doesn't produce the expected behavior, but
>> > using the commented code does. Is this normal, or is it a problem with
>> > Python? I've tested it with version 2.6.1 on Windows XP.
> Here's the way I find it useful to think about this:
> When your lambda is created in your for loop inside your __init__ method,
> it acquires a pointer to __init__'s local namespace. (That's how I
> understand what "closure" means in this case, though I imagine "closure"
> probably means something slightly different in computer-science-ese :)
Well, some people would say that the function "closes over" part of its
environment, but that's the idea.
> So, when any of those lambdas is executed, they all have a pointer to
> the exact same namespace, that of __init__. And when they are called,
> __init__'s namespace is in whatever state it was left in when __init__
> ended. In this case, that means that 'option' is pointing to the value
> it had at the _end_ of the for loop.
That's a pretty good explanation -- I would just substitute "pointer" by
> Hope this helps. I find that thinking in terms of namespaces helps
> me understand how Python works better than any other mental model
> I've come across.
Good to know! The Python execution model *is* based on namespaces - any
other mental model won't be accurate past certain point (although some
More information about the Python-list