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".
(Running python-2.7)
In short: you can't make it print "ok" without modifying the code.
from a import x, changeX
is equivalent to:
import a
x = a.x
changeX = a.changeX
In other words, from a import x
doesn't create an x
that indirects to ax
, it creates a new global variable x
in the b
module with the current value of ax
. From that it follows that later changes to ax
do not affect bx
.
To make your code work as intended, simply change the code in b.py
to import a
:
import a
a.changeX()
print a.x
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 reload
to work.
Also you can use mutable container, for example list:
a.py
x = ['fail']
def changeX():
x[0] = 'ok'
b.py
from a import changeX, x
changeX()
print x[0]
You can also add another import statement after changeX
. This would turn the code from b.py into
from a import x, changeX
changeX()
from a import x
print x
This illustrates that by calling changeX
, only x
in module a
is changed. Importing it again, binds the updated value again to the identifier x
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.