Skip to content

Python global variable across modules

  • by

Python global variable can access across modules if they are defined in a module that is imported by other modules. Generally not recommended to use global variables across modules as it can make code harder to understand and maintain.

It is better to use local variables or pass variables between functions as parameters and return values.

Python global variable across modules example

Simple example code have two Python files: mymodule.py and main.py. In mymodule.py, we define a global variable my_var:

mymoudle.py

my_var = 100


def print_var():
print("my_var:", my_var)

main.py

In main.py, we import mymodule.py and access the global variable my_var:

import mymodule

print(mymodule.my_var)
mymodule.print_var()

mymodule.my_var = 100 # Modify the value of my_var
mymodule.print_var()

Output:

Python global variable across modules

The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name.

Using global variables between files

# settings.py

def init():
    global myList
    myList = []

Next, your subfile can import globals:

# subfile.py

import settings

def stuff():
    settings.myList.append('hey')

Note that subfile does not call init()— that task belongs to main.py:

# main.py

import settings
import subfile

settings.init()          # Call only once
subfile.stuff()         # Do stuff with global var
print settings.myList[0] # Check the result

Do comment if you have any doubts or suggestions on this Python global topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading