why is this not working? (nested scope question)

Tim Chase python.list at tim.thechases.com
Wed Jul 26 16:15:34 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.

There's a subtle difference between what you have:

 >>> def f1() :
...     x=88
...     f2()
 >>> def f2() :
...     print 'x=',x
 >>> f1()
[traceback]

and

 >>> def f1():
...     x = 88
...     def f2():
...             print 'x =',x
...     f2()
...
 >>> f1()
x = 88

The E in LEGB, as far as I understand it, involves to functions 
whose *definitions* are nested within another function...not 
those functions *called* within another function.  Craziness 
ensues with the next example:

 >>> def f1():
...     x = 99
...     def f2():
...             print 'x =',x
...     x = 77
...     f2()
...
 >>> f1()
x = 77


It makes sense...you just have to understand what it's doing. :)

-tkc






More information about the Python-list mailing list