Problem with global variables

Anthony Kuhlman kuhlmana at BATTELLE.ORG
Fri Aug 8 13:10:48 EDT 2008


Pythoners,
I'm having trouble understanding the behavior of global variables in a
code I'm writing.  I have a file, test.py, with the following contents

foo = []

def goo():
    global foo
    foo = []
    foo.append(2)

def moo():
    print foo

In an ipython session, I see the following:

In [1]: from test import *

In [2]: foo
Out[2]: []

In [3]: goo()

In [4]: foo
Out[4]: []

In [5]: moo()
[2]

I don't understand this behavior.  I assumed that foo as defined in
test.py is a global object, but that doesn't seem to be the case.
Obviously, there's some sort of namespace thing going on here that I
don't get.  The ipython session seems to be dealing with one copy of foo
while goo() and moo() are using an entirely different copy.  

If I take out the line 'foo = []' in goo(), everything behaves exactly
as I expect, that is, in ipython, when I type goo() followed by foo I
get [2].

Can anyone shed some light on this behavior?

Cheers,
A.J.



More information about the Python-list mailing list