Misunderstanding about closures

Michael Geary Mike at DeleteThis.Geary.com
Mon Jun 7 19:37:03 CEST 2004


Hung Jung Lu wrote:
> 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.

Thank you for the more complete and accurate explanation, Hung Jung. I was
thinking in two languages at once, JavaScript and Python, and I started to
write in terms of how closures work in JavaScript. Then I thought I'd better
make it more relevant to Python but didn't do a very good job switching
over. :-)

-Mike





More information about the Python-list mailing list