Global variables shared across modules

The culprit is not in the global command but in the way you imported the variable. To get the result you originally expected change the import this way:

File test2.py

import test1

def f():
  test1.a = 2 * test1.a

File test3.py

import test1
from test2 import f

f()
print(test1.a)

Explanation

In test2 when you do from test1 import a you are creating a global variable a in the current module (test2.a) bound to the same object as the variable a in the module test1 (test1.a) but these two variables are different variables. Assignment to a in test2 changes just to what test2.a is bound to, test1.a is still bound to the original object 100.

When you do import test1. Then you can refer to the original variable as test1.a and you can re-bind it.

The concept of binding between variable names and objects is very important for good understanding of Python. It is explained for example here: 4. Execution model — Python 3.10.5 documentation or here: Assignment in Python – Real Python (the course video requires payment).

4 Likes