Problem with global variables

  • Thread starter Anthony Kuhlman
  • Start date
A

Anthony Kuhlman

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.
 
M

Marc 'BlackJack' Rintsch

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.

``global`` means module global. There's no really global namespace in
Python.
The ipython session seems to be dealing with one copy of foo while
goo() and moo() are using an entirely different copy.

The import binds the list from the module to the name `foo` in the
IPython namespace. When you call `goo()` it binds the name `foo` *within
the module* to a new list. This has of course no influence on the name
in the IPython namespace which is still bound to the list object that was
bound to `test.foo` before.

Ciao,
Marc 'BlackJack' Rintsch
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top