3

I'm writing a program that involves callbacks called from another module, and which need to access a global variable.
It seems that changes assigned to the global variable are not seen in the callback function, which only sees the original assignment. I'm guessing due to the import from the other module.
What is the proper way to write this pattern?

First module:

# a.py
from b import runb

myGlobal=None

def init():
    global myGlobal
    myGlobal=1

def callback():
    print myGlobal

def main():
    init()
    runb()

if __name__=='__main__':
    main()

Second module:

#b.py
def runb():
    from a import callback
    callback()

I would expect this program to print '1', but instead it prints 'None'

EDIT: init can only be called once (it is a simplification of a complex program)

Photon
  • 3,182
  • 1
  • 15
  • 16
  • You know it's best to avoid circular dependencies: http://stackoverflow.com/questions/1556387/circular-import-dependency-in-python – Scorpion_God May 19 '14 at 13:29
  • @Scorpion_God: This link discusses dependencies between packages, not modules. I know it's best to avoid circular dependencies in general, but sometimes the alternatives are not that good. – Photon May 19 '14 at 14:06

3 Answers3

5

Python imports the main module as __main__. When b.py imports a by its actual name, a new instance of the module is loaded under the name a. Each instance has its own myGlobal.

One solution is this:

#b.py
def runb():
    from __main__ import callback
    callback()

Another solution is to create a new main module. Import a there and make an explicit call to a.main().

Janne Karila
  • 24,266
  • 6
  • 53
  • 94
2

If you do this, "from a import callback", then again "myGlobal=None" will be executed, making it to print "None"

Rajesh Kumar
  • 1,270
  • 4
  • 15
  • 31
1

The main() function is not called when you import the file as a module. __name__ == "main" is true only when a.py is executed directly.

jasal
  • 1,044
  • 6
  • 14