Misunderstanding about closures

Hung Jung Lu hungjunglu at yahoo.com
Mon Jun 7 12:55:15 EDT 2004


"Michael Geary" <Mike at DeleteThis.Geary.com> wrote:
> 
> Your message title is correct: you're misunderstanding how closures work.
> :-)

So seems to be your case. :)

> In your first example, there is a single local name x that each instance of
> the f closure refers to, so they all see the same value.

There is a name, period. This name is neither local or global. This
name is looked up first in the locals() dictionary, then in the
globals() dictionary. In this particular example, because the locals()
dictionary is empty, this name is actually pulled from globals().

> In the second example, each time you call the makef function, you create a
> new local name x that belongs to that instance of makef. So when you create
> the closures inside makef, each one sees its own value that is unrelated to
> the others.

And your explanation is supposed to enlighten a beginner?

A more complete explanation. The key is in the argument list. Because
'x' appears in the argument list of makef(x), this name is inserted
into the locals() dictionary of makef()'s scope. That is, the name 'x'
inside makef()'s scope is pulled from the locals() dictionary of that
scope. Now, due to the magic of nested scope (which was not always the
case in older versions of Python), this 'x' is also inserted into the
locals() dictionary of the nested f() function, and this 'x' is bound
to the value at that moment, because during the constructions of f(),
it is found that 'x' is used in expressions AND it exists in the
containing scope's locals() dictionary at the moment of construction.
In particular, it will not work correctly if you replace the statement
"return x" with "return eval('x')". Everything becomes more clear when
you insert statements to print out the locals() and globals()
dictionaries.

regards,

Hung Jung



More information about the Python-list mailing list