variable scope question?

Gary Herron gherron at islandtraining.com
Tue May 13 17:12:57 EDT 2008


globalrev wrote:
> http://mail.python.org/pipermail/python-list/2003-October/233435.html
>
> why isnt it printing a in the second(second here, last one in OP)
> example before complaining?
>
> def run():
>   a = 1
>   def run2(b):
>     a = b
>     print a
>   run2(2)
>   print a
> run()
>
> def run():
>   a = 1
>   def run2(b):
>     print a
>     a = b
>   run2(2)
>   print a
> run()
> --
> http://mail.python.org/mailman/listinfo/python-list
>   
If you had told us what error you got, I would have answered you hours 
ago.   But without that information I ignored you until is was 
convenient to run it myself.  Now that I see no one has answered, and I 
have time to run your examples, I see the error produced is

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in run
  File "<stdin>", line 4, in run2
UnboundLocalError: local variable 'a' referenced before assignment

and its obvious what the problem is. 

In run2 (of the second example),  The assignment to a in the line "a=b" 
implies that a *must* be a local variable.    Python's scoping rules say 
that if "a" is a local variable anywhere in a function, it is a local 
variable for *all* uses in that function.  Then it's clear that "print 
a" is trying to access the local variable before the assignment gives it 
a value.

You were expecting that the "print a" pickups it the outer scope "a" and 
the assignment later creates a local scope "a",  but Python explicitly 
refuses to do that.

Gary Herron




More information about the Python-list mailing list