Reputation: 120
I'm trying to have a changed variable affect another module. That other module doesn't seem to notice the change.
a.py:
import b
b.changeMyVar()
print(b.myVar["key"])
b.py:
myVar = {"key": "foo"}
def changeMyVar():
myVar["key"] = "value"
What I expect (on running a.py):
value
What I get:
foo
How do I make this work? Why doesn't it work? Would things be different if myVar
was a dictionary that is mutated by changeMyVar
(both situations occur in my program)?
Note how I didn't write from b import *
, which is evil as I understand.
Edit 1: As commenters pointed out, if myVar
was an immutable object, this wouldn't work without global myVar
. I changed the example to better reflect what I mean.
Edit 2: I forgot to add b.
However, my question remains unchanged. The variables is defined but runtime changes are not visible from the other module. I have again edited the code to clarify my problem.
Upvotes: 1
Views: 1288
Reputation: 612
import b
does't import myVar
or changeMyVar
to the scope of a.py, it only defines the name b
referring to the module.
So you have to use the name b
to access myVar
and changeMyVar()
in a.py:
import b
b.changeMyVar()
print(b.myVar["key"])
Upvotes: 2