Confused by Python and nested scoping (2.4.3)
Terry Reedy
tjreedy at udel.edu
Wed Apr 19 20:25:57 EDT 2006
"Sean Givan" <kinsman at nbnet.nb.ca> wrote in message
news:AGy1g.62595$VV4.1170375 at ursa-nb00s0.nbnet.nb.ca...
> Hi. I'm new to Python, and downloaded a Windows copy a little while
> ago. I was doing some experiments with nested functions, and ran into
> something strange.
Experiments are good. Strange can be instructive.
...
> I'm thinking this is some bug
Blaming the interpreter is not so good, but amazingly common among
newcomers ;-)
> where the interpreter is getting ahead of itself,
...
> Or am I doing something wrong?
In a sense, you got ahead of yourself. And the issue has nothing to do
with nested scopes per se. When things seem strange, try a simpler
experiment.
>>> x=1
>>> def f():
print x
x = 2
>>> f()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in -toplevel-
f()
File "<pyshell#4>", line 2, in f
print x
UnboundLocalError: local variable 'x' referenced before assignment
The compiler compiles functions in two passes: the first to classify names
as local or global (or nested if relevant, but not really so here), the
second to generate bytecodes which depend on that classification.
Terry Jan Reedy
More information about the Python-list
mailing list