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

main.py

test.py

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

test.py

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.