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

Global variables in modules...

P: n/a
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...
Mar 28 '08 #1
Share this Question
Share on Google+
3 Replies


P: n/a
tt*******@gmail.com wrote:
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
0
>>import __main__, a
a.g
0
>>__main__.g
1

Peter
Mar 28 '08 #2

P: n/a
That clears it up. Thanks.
Mar 28 '08 #3

P: n/a
>>>>"Peter" == Peter Otten <__*******@web.dewrites:
Petertt*******@gmail.com wrote:
[snip]
>...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...
PeterWhen you run a.py as a script it is put into the sys.modules module
Petercache under the key "__main__" instead of "a". Thus, when you import
Petera the cache lookup fails and a.py is executed again. You end up with
Petertwo 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
Mar 28 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.