Reputation: 41
I have two modules and I'm trying to modify a global variable in the first module from the 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 is set"
else:
print"glob is unset"
time.sleep(1)
bau()
start.py
:
from app import setval
app.setval(1)
I not able to understand why in start.py
the full content of app.py
is included and not only the function that I want.
Second I don't understand why by running the first app.py
and then start.py
, that start.py
does not modify the value of the global variable in app.
Upvotes: 1
Views: 700
Reputation: 3244
As suggested by freakish, you can use that approach.
Or if you want to keep it in this format that it's called by different scripts , I suggest you use enviroment variables.
start.py
import os
os.environ['glob_var'] = 'any_variable'
app.py
import os
print os.environ.get('glob_var', 'Not Set')
Upvotes: 0
Reputation: 56467
I not able to understand why in start.py the full content of app.py is included and not only the function that I want.
You misunderstand how import works. What it does it actually runs the script you are importing and then binds to things defined inside. If you wish to only import a function then your script is not supposed to do anything other then declarations, i.e. remove bau()
line.
So normally you would only declare functions, classes and constants inside your scripts and in one root script you would call them.
Second I don't understand why by running the first app.py and then start.py, that start.py does not modify the value of the global variable in app.
That's because setval()
is never reached due to bau()
call, i.e. start.py
is blocked on import
statement.
Side note: I suggest you stop using globals. Wrap everything with functions/classes and pass parameters around. Globals are very hard to control.
Upvotes: 4