Code
I’d like to use a global variable in other modules with having changes to its value “propagated” to the other modules.
a.py:
x="fail"
def changeX():
global x
x="ok"
b.py:
from a import x, changeX
changeX()
print x
If I run b.py, I’d want it to print “ok”, but it really prints “fail”.
Questions
- Why is that?
- How can I make it print “ok” instead?
(Running python-2.7)
In short: you can’t make it print “ok” without modifying the code.
from a import x, changeXis equivalent to:In other words,
from a import xdoesn’t create anxthat indirects toa.x, it creates a new global variablexin thebmodule with the current value ofa.x. From that it follows that later changes toa.xdo not affectb.x.To make your code work as intended, simply change the code in
b.pytoimport a:You will have less cluttered imports, easier to read code (because it’s clear what identifier comes from where without looking at the list of imports), less problems with circular imports (because not all identifiers are needed at once), and a better chance for tools like
reloadto work.