[Tutor] re: Scoping question

Charlie Clark charlie@begeistert.org
Mon, 09 Sep 2002 18:16:37 +0000


On 2002-09-09 at 16:00:06 [+0000], you wrote:
> (Hope this is the right mailing list for this question!)
yes, it is
> 
> I've been using Python for several months now, and I've run across a
> scoping issue involving global variables.  Consider this program scrap:
> 
> blah =3D 0
> list =3D [0]
^^^^^^
list is a key word in Python for turning other objects into lists so it's a=
 
good idea to use another name, although Python will let you reassign it 
without complaining.

> def foo():
>   blah +=3D 1
> 
> def bar():
>   list[0] +=3D 1
> 
> Now, bar would compile and execute fine, but foo is illegal because:
> 
> 'UnboundLocalError: local variable 'blah' referenced before assignment'
You can read 'blah' from the global scope but can't rewrite it. This is for=
 
safety reasons, I think because you have to consider the convenience of 
rewriting global variables from within functions against the possible 
damage this can cause when several functions use this variable. Maybe some 
of the gurus can give more authoritative explanations but I think that is 
the gist.

The way around this is to pass in the variable you want and return it.
def foo(blah=3Dblah):
   return blah+1
 
> Now, I'll guess that my problem is that Python is treating blah as though
> it were local and the assignment fails because the variable hasn't been
> created yet.  But why doesn't Python search up the scoping chain when the
> local assignment fails?  Also, if foo had been defined as just being:
> 
> def foo():
>   print blah
> 
> It executes just fine and can find blah.  Why can it find the global in
> this context but not the other?
> 
> And finally, why does the assignment to a list element execute
> successfully?
It doesn't for me. Maybe it's your choice of keyword.

Charlie Clark
-- 
Charlie Clark
Helmholtzstr. 20
D=1Asseldorf
D- 40215
Tel: +49-211-938-5360
GSM: +49-178-782-6226