Python Global Variables in multiple files

How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere.:

import time
import glb

while(True):
    glb.t +=  1
    time.sleep(3)
    print glb.t 

b.py:

import glb
import a
while(True):
    print(glb.t)

glb.py:

t = 0

Output after starting a.py:

python b.py
1
2
3
4
5
6

Leave a Comment