Reputation: 205
I have these 4 modules
globals.py
globvara = "a"
mod1.py
from globals import *
print globvara
output:
a
mod2.py
from mod1 import *
def changegv(newval1):
#global globvara
globvara = newval1
def usechangegv(newval2):
changegv(newval2)
and mod3.py
from mod2 import *
usechangegv("b")
print globvara
output:
a
a
I am wondering why the global var does not change in module 2. I am missing something in global variables. Even if I uncomment the global globvara
line I get the same result. Where is the error?
Upvotes: 0
Views: 88
Reputation: 521
Don't use the
from <module> import <variable>
As it creates a copy of the variable.
Do a simple:
import <module>
And all accesses to the global variable should use the "variable" within "module":
<module>.<variable> = ...
or
print <module>.<variable>
Upvotes: 1
Reputation: 184091
Python global variables are global only to modules. When you import a variable from another module (e.g. from mod1 import *
), Python creates duplicate references to the value in the importing module. So you now have two names, mod1.globvara
and mod2.globvara
, which initially point to the same value, but which are not in any way connected. If you change globvara
in mod2.py
, you are changing mod2.globvara
and mod1.globvara
is not affected.
To avoid this problem, import the module, not the individual names defined in it. For example, import globals
. Then always refer to globals.globvara
(or better yet, globals.a
). Since you are always accessing and assigning the same name, it will work the way you expect.
Upvotes: 5