I came across a strange issue in Python when using global variables.
I have two modules(files):mod1.py and mod2.py
mod1 tries to modify the global variable var defined in mod2. But the var in mod2 and var in mod seems to be two different things. Thus, the result shows that such modification does not work.
Here is the code:
#code for mod2.py
global var
var = 1
def fun_of_mod2():
print var
#code for mod1.py
from mod2 import var,fun_of_mod2
global var #commenting out this line yields the same result
var = 2 #I want to modify the value of var defined in mod2
fun_of_mod2() #but it prints: 1 instead of 2. Modification failed :-(
Any hint on why this happens? And how can I modify the value of val defined in mod2 in mod1?
Thanks
When you import
varintomod1:You are giving it the name
varin mod1’s namespace. It is as if you did this:In other words, there are now two names for the value,
mod1.varandmod2.var. They are the same at first, but when you reassignmod1.var,mod2.varstill points to the same thing.What you want to do is just:
Then access and assign the variable as
mod2.var.It’s important to note that global variables in Python are not truly global. They are global only to the module they’re declared in. To access global variables inside another module, you use the
module.variablesyntax. Theglobalstatement can be used inside a function to allow a module-global name to be assigned to (without it, assigning to a variable makes it a local variable in that function). It has no other effect.