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: and In, we define a global variable my_var:

my_var = 100

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

In, we import and access the global variable my_var:

import mymodule


mymodule.my_var = 100 # Modify the value of my_var


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


def init():
    global myList
    myList = []

Next, your subfile can import globals:


import settings

def stuff():

Note that subfile does not call init()— that task belongs to


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