python global variable between modules -
i have 2 modules , i'm trying modify global variable in first module second module.
app.py
:
import time glob=0; def setval(val): global glob glob = val print "glob = "+glob def bau(): while(1): if(glob): print"glob set" else: print"glob unset" time.sleep(1) bau()
start.py
:
from app import setval app.setval(1)
i not able understand why in start.py
full content of app.py
included , not function want.
second don't understand why running first app.py
, start.py
, start.py
not modify value of global variable in app.
i not able understand why in start.py full content of app.py included , not function want.
you misunderstand how import works. runs script importing , then binds things defined inside. if wish import function script not supposed other declarations, i.e. remove bau()
line.
so declare functions, classes , constants inside scripts , in 1 root script call them.
second don't understand why running first app.py , start.py, start.py not modify value of global variable in app.
that's because setval()
never reached due bau()
call, i.e. start.py
blocked on import
statement.
side note: suggest stop using globals. wrap functions/classes , pass parameters around. globals hard control.
Comments
Post a Comment