Problem with global variables

Laurent Pointal laurent.pointal at limsi.fr
Mon Apr 2 09:18:00 EDT 2007


Ed Jensen a écrit :
> I'm having a vexing problem with global variables in Python.  Please
> consider the following Python code:
> 
> #! /usr/bin/env python
> 
> def tiny():
>     bar = []
>     for tmp in foo:
>         bar.append(tmp)
>     foo = bar
> 
> if __name__ == "__main__":
>     foo = ['hello', 'world']
>     tiny()
> 
> When I try to run this, I get:
> 
> Traceback (most recent call last):
>   File "./xtalk.py", line 11, in ?
>     tiny()
>   File "./xtalk.py", line 5, in tiny
>     for tmp in foo:
> UnboundLocalError: local variable 'foo' referenced before assignment
> 
> For some reason, Python can't see the global variable "foo" in the
> function tiny().  Why is that?
> 
> If I change the code to this:
> 
> #! /usr/bin/env python
> 
> def tiny():
>     for tmp in foo:
>         print tmp
> 
> if __name__ == "__main__":
>     foo = ['hello', 'world']
>     tiny()
> 
> I get this:
> 
> hello
> world
> 
> All of a sudden, tiny() can see the global variable "foo".  Very
> confusing!  Why is it that tiny() sometimes can, and sometimes can't,
> see the global variable "foo"?
> 
> If anyone can enlighten me about what's going on with Python and
> global variables, I would appreciate it!

To complete hg reply, Python compile your tiny function which contains a
foo assignment. As foo is not defined "global", it is considered to be
local. So the error when you tries to iterate throught foo before
assigning it. And so the solution to add "global foo" before using it.

A+

Laurent.



More information about the Python-list mailing list