Python: Why are my module variables missing their contents? … here is a solution to the problem.
Python: Why are my module variables missing their contents?
Please take a look at that “module”:
"""Module a"""
a = None
b = None
def gna():
global a
if a is None:
global b
a = 7
b = "b"
print("in a.py: a={}".format(a))
print("in a.py: b={}".format(b))
I thought calling gna() from another module would initialize the variable:
"""Module b"""
from a import a, b, gna
print("in b.py: a={}".format(a))
print("in b.py: b={}".format(b))
gna()
print("in b.py: a={}".format(a))
print("in b.py: b={}".format(b))
But:
% python3 b.py
in b.py: a=None
in b.py: b=None
in a.py: a=7
in a.py: b=b
in b.py: a=None
in b.py: b=None
I don’t really understand why a and b are None…. after calling gna….
Solution
When the name
is imported into the module, the name becomes local. You should import module A instead of importing variables A and B from module A so that module B will be able to access the same references to variables
A
and
B
, whose values were modified by function GNA
:
"""Module b"""
import a
print("in b.py: a={}".format(a.a))
print("in b.py: b={}".format(a.b))
a.gna()
print("in b.py: a={}".format(a.a))
print("in b.py: b={}".format(a.b))