By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,536 Members | 1,397 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,536 IT Pros & Developers. It's quick & easy.

what is happening here?

P: n/a
trying to figure out scoping of 'globals' in modules. So I have test.py:

glob = 1

def setglob(v):
global glob
glob = v

def getglob():
return glob
and I do this:
from test import *
glob 1 getglob() 1 glob=2
glob 2 getglob() 1 setglob(3)
getglob() 3 glob

2
Seems to me like the first time I invoke glob, it creates a new global
in my namespace, and initializes it to the value of the glob in test.py.
Seems counterintuitive!

Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"dan miller (moderator, s.p.d)" <da*****@cmu.edu> wrote in message
news:c4**********@nntp.ece.cmu.edu...
trying to figure out scoping of 'globals' in modules. So I have test.py:

glob = 1

def setglob(v):
global glob
glob = v

def getglob():
return glob
and I do this:
>>> from test import *
>>> glob 1 >>> getglob() 1 >>> glob=2
>>> glob 2 >>> getglob() 1 >>> setglob(3)
>>> getglob() 3 >>> glob
2
Seems to me like the first time I invoke glob, it creates a new global
in my namespace, and initializes it to the value of the glob in test.py.
Seems counterintuitive!


Sure seems wierd. What it looks like to me is that
your import is binding three objects, but the actual
functions are still refering to whatever object is bound
in the "test" module, not in the interpreter's namespace.
In other words, they are using the global dictionary
they were compiled with, not their caller's global
dictionary.

Make sense?

John Roth

Jul 18 '05 #2

P: n/a
dan miller (moderator, s.p.d) wrote:
>>> from test import *
Here you create a variable glob that is a reference to the one in your test
module.
>>> glob 1


This returns the value of glob in the test module
>>> getglob() 1


Here you're calling getglob, which is in the test module.
>>> glob=2
Here's where your problem lies... You're creating a new variable glob that
*replaces* the old variable. The variable that is also called glob in the
test module is unaffected.
>>> glob 2


Now you're refering to the newly create variable, hence the value 2.
>>> getglob() 1


Here you're calling getglob, which is in the test module and hence it uses
the glob variable in test - which has the value 1.
>>> setglob(3)
>>> getglob() 3


Same with these two, they're both in test - and so use the variable glob in
test.
>>> glob

2


This still refers to glob in your local namespace, which still has the value
2.

Hope this is of some help,
Andrew
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.