Categories
Python Answers

How to use global variables between files in Python?

Spread the love

Sometimes, we want to use global variables between files in Python.

In this article, we’ll look at how to use global variables between files in Python.

How to use global variables between files in Python?

To use global variables between files in Python, we can use the global keyword to define a global variable in a module file.

Then we can import the module in another module and reference the global variable directly.

For instance, we write:

settings.py

def init():
    global myList
    myList = []

subfile.py

import settings


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

main.py

import settings
import subfile

settings.init()
subfile.stuff()
print(settings.myList[0])

We import the settings and subfile modules in main.py.

Then we call settings.init to create the myList global variable and assign it to an empty array.

Then we call subfile.stuff to call settings.myList.append to add an entry to the settings.myList global variable.

Then we print the value of settings.myList[0], which is 'hi'.

Conclusion

To use global variables between files in Python, we can use the global keyword to define a global variable in a module file.

Then we can import the module in another module and reference the global variable directly.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *