what is happening here?

  • Thread starter dan miller (moderator, s.p.d)
  • Start date
D

dan miller (moderator, s.p.d)

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:
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!
 
J

John Roth

dan miller (moderator said:
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:

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
 
A

Andrew Wilkinson

Here you create a variable glob that is a reference to the one in your test
module.

This returns the value of glob in the test module

Here you're calling getglob, which is in the test module.

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.

Now you're refering to the newly create variable, hence the value 2.

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.

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

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

Hope this is of some help,
Andrew
 
D

DomF

dan miller (moderator said:
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:

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!

This is an instance of "from x import *" being harmful. Try this with just
"import test" in the shell and it doesn't look confusing at all:
Traceback (most recent call last):
2

Dom
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top