variable scoping problem

Kristofer Wouk kristofer at hotpop.com
Fri Apr 25 01:02:50 EDT 2003


Tung Wai Yip wrote:
> Consider this
> 
> 
>>>>x=1
>>>>def foo():
> 
> ...   print x
> ...
> 
>>>>def bar():
> 
> ...   #print x   <- referenced before assignment error
> ...   x=2
> ...   print x
> ...
> 
>>>>foo()
> 
> 1
> 
>>>>bar()
> 
> 2
> 
>>>>print x
> 
> 1
> 
> 
> What rules in Python explain the scoping of x? Is there a name for the
> scope of the first x? 'module' scope? Why is bar() not able to access
> x but foo() can?
> 
> Wai Yip Tung
> 
OK, I'm a newbie but let me give this a try. I think since foo() has no 
internal variable x it is forced to use the global(?, or whatever) x. 
However, since bar() actually assigns something to x, it just creates a 
new variable in bar()'s scope. Am I correct? I'd like to know myself...

Kris





More information about the Python-list mailing list