Global variables in modules...

Peter Otten __peter__ at web.de
Fri Mar 28 10:13:15 EDT 2008


ttsiodras at 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



More information about the Python-list mailing list