import and shared global variables

Michael Brenner brenner at
Fri Mar 10 15:06:03 CET 2006


I'm implementing a plugin-based program, structured like the example
below (where m1 in the main module, loading m2 as a plugin).  I wanted
to use a single global variable (m1.glob in the example) to store some
config data that the plugins can access.  However, the output shown
belown seems to imply that glob is *copied* or recreated during the
import in m2.  Am I missing something? I thought m1 should be in
sys.modules and not be recreated during the import in m2.

After browsing c.l.p, it seems that this is probably somehow due to the
circular import.  However, I do not really see why this should be a
problem here.  Interestingly, the problem disappears when I put the code
in m1 in a real main() function instead of "if __name__" etc.  Though
this seems to solve my problem, I still want to understand what's


glob = [1]
if __name__ == "__main__":
     print "m1.main().1:", glob
     m2 = __import__("m2")
     print "m1.main().2:", glob
def test():
     import m1
     print "m2.test():", m1.glob

m1.main().1: [1, 2]
m2.test(): [1]
m1.main().2: [1, 2]

More information about the Python-list mailing list