Global variables in modules...

Terry Jones terry at jon.es
Fri Mar 28 10:54:36 EDT 2008


>>>>> "Peter" == Peter Otten <__peter__ at web.de> writes:
Peter> ttsiodras at 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...

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



More information about the Python-list mailing list