why is this not working? (nested scope question)
Peter Otten
__peter__ at web.de
Wed Jul 26 16:11:18 EDT 2006
biner.sebastien at ouranos.ca wrote:
> I have a problem understanding the scope of variable in nested
> function. I think I got it nailed to the following example copied from
> Learning Python 2nd edition page 205. Here is the code.
>
> def f1() :
> x=88
> f2()
> def f2() :
> print 'x=',x
> f1()
>
> that returns an error saying that "NameError: global name 'x' is not
> defined". I expected f2 to "see" the value of x defined in f1 since it
> is nested at runtime. My reading of the book comforted me in this.
>
> What am I missing? Shouldn't the E of the LEGB rule take care of that.
> BTW, I am running this on python 2.3.
For f1 to be seen as the enclosing scope of f2 f2 has to be /defined/ in f1:
>>> def f1():
... x = 88
... def f2():
... print "x =", x
... f2()
...
>>> f1()
x = 88
Just /calling/ a function inside another does not give the inner one access
to variables that are visible in the outer.
Peter
More information about the Python-list
mailing list