Problem with global variables

Ed Jensen ejensen at visi.com
Mon Apr 2 08:35:20 EDT 2007


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!



More information about the Python-list mailing list