Local variable in a closure

Chris Angelico rosuav at gmail.com
Sun Aug 18 06:28:40 EDT 2013


On Sun, Aug 18, 2013 at 10:41 AM,  <w.w.milner at googlemail.com> wrote:
> Is f local or not?
> http://pastebin.com/AKDJrbDs

With something that short, it'd be easier to simply paste it straight
into your post, rather than having it off elsewhere. But to answer
your question: It is its own kind of beast. You can play around with
the dis.dis() function (start with "import dis", which is not just
"import this" with an accent) in the interactive interpreter, as an
effective way of finding out what actually happens. In my testing, the
opcodes for retrieving and updating 'f' are LOAD_DEREF and
STORE_DEREF, different from LOAD_FAST/STORE_FAST as used for locals,
and LOAD_GLOBAL/STORE_GLOBAL for globals. In normal usage, nonlocal
variables are most like local variables, but they happen to span one
level of function nesting. So they're still basically locals, hence
they appear in locals(). At least, that's my understanding of it.

ChrisA



More information about the Python-list mailing list