Three module exists. Cfg, Main and Component
Cfg.py
value = 0
Component.py
import Cfg
class index:
def GET(self):
return Cfg.value
Main.py
from Test import Cfg
import Component
urls = ('/', 'Component.index')
if __name__ == '__main__':
Cfg.value = 1
app = web.application(urls, globals())
app.run()
Get method of Component.Index returns 0, but i’m expecting 1. What did i miss?
Edit #1
first modification main.py to test :
from test import Cfg
import Component
import test
if __name__ == '__main__':
importedCfg = id(Cfg)
cfgInComponent = id(Component.Cfg)
cfgInTest = id(test.Cfg)
print importedCfg, cfgInComponent, cfgInTest
print importedCfg == cfgInComponent == cfgInTest
Result :
36202928 36203088 36202928
False
Second modification in main.py :
import Cfg
import Component
if __name__ == '__main__':
importedCfg = id(Cfg)
cfgInComponent = id(Component.Cfg)
# cfgInTest = id(test.Cfg)
print importedCfg, cfgInComponent
print importedCfg == cfgInComponent
36858160 36858160 True
if you do not want to create multiple instance you should follow the second way.
Compare the result of:
and
this means that doing a “from module” import creates different instances of
Cfg. (I wasn’t aware of this either).This behavior is present in Python 2.7 and Python 3.2 (Python 2.6 wasn’t tested).