Python global variables do not seem to work with modules

the code

I would like to use a global variable in other modules with changes in its value, "distributed" to other modules.

a.py:

x="fail" def changeX(): global x x="ok" 

b.py:

 from a import x, changeX changeX() print x 

If I ran b.py, I would like it to print “ok,” but it does print “fail”.

Questions

  • Why is this?
  • How can I make it print "ok" instead?

(Running python-2.7)

+6
source share
3 answers

In short: you cannot force it to print "ok" without changing the code.

from a import x, changeX equivalent to:

 import a x = ax changeX = a.changeX 

In other words, from a import x does not create x , which is indirectly related to ax , it creates a new global variable x in module b with the current value of ax . It follows that later changes to ax do not affect bx .

To make your code work as intended, just change the code in b.py to import a :

 import a a.changeX() print ax 

You will have less cluttered imports, it is easier to read the code (because it clears which identifier comes from without looking at the import list), fewer problems with cyclic import (because not all identifiers are needed right away), and more chances for such tools to work like reload .

+10
source

You can also use a 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] 
+2
source

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 invoking changeX , only x in module a changes. By importing it again, it binds the updated value to the identifier x again.

+1
source

All Articles