I’ve been refactoring a large Python program into separate modules for readability and ease of unit testing and part of that involves moving global variables into a separate globals module. I was interested to see if importing this globals module into other modules and then updating a variable would mean that other modules see the change, here’s what I found –
From globals import *
My first instinct was to use from globals import * in my sub modules, let’s look at an example –
globals.py
1 |
VAR = 1 |
main.py
1 2 3 4 5 6 7 8 |
from globals import * from test import * print "First: %d" % VAR VAR = 2 print "Second: %d" % VAR printVar() |
test.py
1 2 3 4 |
from globals import * def printVar(): print "printVar(): %d" % VAR |
Running the main.py we get this output –
First: 1
Second: 2
printVar(): 1
Obviously updating the global variable VAR in main.py does not reflect in test.py, this is because from globals import * will import by value giving main.py a local copy of VAR.
Import globals
In order to get a single instance of the global variable VAR we need to modify our program to use import globals and then reference the VAR variable directly inside globals.
Let’s modify the scripts –
main.py
1 2 3 4 5 6 7 8 |
import globals from test import * print "First: %d" % globals.VAR globals.VAR = 2 print "Second: %d" % globals.VAR printVar() |
test.py
1 2 3 4 |
import globals def printVar(): print "printVar(): %d" % globals.VAR |
Running this will give us the following output –
First: 1
Second: 2
printVar(): 2
Much better! The solution to this problem is to update the VAR variable directly inside globals allowing updates to be seen from both modules that import globals.
Questions? Comments?