Global variables in modules...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ttsiodras@gmail.com

    Global variables in modules...

    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...
  • Peter Otten

    #2
    Re: Global variables in modules...

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

    Comment

    • ttsiodras@gmail.com

      #3
      Re: Global variables in modules...

      That clears it up. Thanks.

      Comment

      • Terry Jones

        #4
        Re: Global variables in modules...

        >>>>"Peter" == Peter Otten <__peter__@web. dewrites:
        Peterttsiodras@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

        Comment

        Working...