variable scoping problem

Steven Taschuk staschuk at telusplanet.net
Fri Apr 25 11:12:14 EDT 2003


Quoth Kristofer Wouk:
> Tung Wai Yip wrote:
  [...]
> >>>>x=1
  [...]
> >>>>def bar():
> > 
> > ...   #print x   <- referenced before assignment error
> > ...   x=2
> > ...   print x
  [...]
> 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...

Almost perfect.

The only thing you didn't mention is that assigning to x anywhere
in bar makes *all* references to x in bar refer to the local
variable, even those which precede the assignment.  This is why
referring to x before assigning to it raises an error (rather
than, say, using the value of the global variable).

(This is one of relatively few places where Python does static
analysis.  Another is generators, where the presence of yield
anywhere in the function body (except in nested functions) makes
the whole function a generator.)

-- 
Steven Taschuk                                                   w_w
staschuk at telusplanet.net                                      ,-= U
                                                               1 1





More information about the Python-list mailing list