Nested scopes question
Fernando Pérez
fperez528 at yahoo.com
Thu Jul 18 23:03:14 EDT 2002
In the following code:
def foo():
def bar():
print 'x from foo',x
x+=1
x=0
for i in range(5):
bar()
foo()
the call to foo() raises a NameError b/c x is incremented, and python (2.2)
then assumes it is a local variable. Is there a way to make python honor the
nesting of the scopes (global doesn't work). The only solution I found was
the rather unsightly one of putting my value for x inside a list:
def foo():
def bar():
print 'x from foo',x[0]
x[0]+=1
x=[0] # put value in a list so nested scopes work like I want
for i in range(5):
bar()
foo()
Is there a better option?
Thanks,
f.
More information about the Python-list
mailing list