nested scopes clarification
Terry Reedy
tjreedy at udel.edu
Mon Feb 24 19:31:35 EST 2003
"Erik Price" <eprice at ptc.com> wrote in message
news:mailman.1046127742.25392.python-list at python.org...
> Hi,
>
> I'm reading "Python Essential Reference 2nd ed" by David Beazley,
and
> have encountered the topic of Python's nested scopes in functions,
and
> the lack thereof in Python 2.0 or earlier. I was hoping someone
could
> clarify this for me.
>
> The book gives this example:
>
> def bar():
> x = 10
> def spam():
> print 'x is ', x
> while x > 0:
> spam()
> x -= 1
This now runs just fine:
>>> bar()
x is 10
x is 9
x is 8
x is 7
x is 6
x is 5
x is 4
x is 3
x is 2
x is 1
> Beazley writes: "In this case, when the nested function spam()
> executes, its global namespace is the same as the global namespace
for
> bar(), the module in which functions is defined.
This much is still true.
> As a result, spam() is unable to resolve any symbols in the
namespace
> of bar() and fails with NameError."
This statement is now obsolete.
> Is that another way of saying that Python puts all of its function
> declarations into the same scope in pre-2.1 Pythons?
No. spam is in the local scope of bar, and has its own local scope.
Reread the still-true statement, or go to current ref manual.
Terry J. Reedy
More information about the Python-list
mailing list