Global variables in modules...

T

ttsiodras

With a.py containing this:

========== a.py ===========
#!/usr/bin/env python
import b

g = 0

def main():
global g
g = 1
b.callb()

if __name__ == "__main__":
main()
==========================

....and b.py containing...

========= b.py =============
import a, sys

def callb():
print a.g
==========================

....can someone explain why invoking a.py prints 0?
I would have thought that the global variable 'g' of module 'a' would
be set to 1...
 
P

Peter Otten

With a.py containing this:

========== a.py ===========
#!/usr/bin/env python
import b

g = 0

def main():
global g
g = 1
b.callb()

if __name__ == "__main__":
main()
==========================

...and b.py containing...

========= b.py =============
import a, sys

def callb():
print a.g
==========================

...can someone explain why invoking a.py prints 0?
I would have thought that the global variable 'g' of module 'a' would
be set to 1...

When you run a.py as a script it is put into the sys.modules module cache
under the key "__main__" instead of "a". Thus, when you import a the cache
lookup fails and a.py is executed again. You end up with two distinct
copies of the script and its globals:

$ python -i a.py
01

Peter
 
T

Terry Jones

Peter> (e-mail address removed) wrote:
[snip]
Peter> When you run a.py as a script it is put into the sys.modules module
Peter> cache under the key "__main__" instead of "a". Thus, when you import
Peter> a the cache lookup fails and a.py is executed again. You end up with
Peter> two distinct copies of the script and its globals
[snip]


Suggesting the following horribleness in a.py

g = 0

def main():
global g
import b
g = 1
b.callb()

if __name__ == "__main__":
import sys, __main__
sys.modules['a'] = __main__
main()


Terry
 
D

Dennis Lee Bieber

That clears it up. Thanks.

The safest route is usually to put real shared globals into a
separate module, that others then import...

-=-=-=- myglobals.py
g = 0

-=-=-=- a.py
import myglobals
import b

def main():
myglobals.g = 1
b.callb()

if __name__ == "__main__":
main()

-=-=-=- b.py
import myglobals
import sys

def callb():
print myglobals.g
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top