Categories
Python Answers

How to use global variables between files with Python?

Spread the love

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

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

How to use global variables between files with Python?

To use global variables between files with Python, we can import the variable in another module.

For instance, we write

settings.py

def init():
    global my_list
    my_list = []

to add the my_list global variable.

Then we import the variable in foo.py and use it by writing

import settings

def stuff():
    settings.my_list.append('abc')

to import the global variables from settings.py with

import settings

And then we use it by calling settings.my_list.append.

Conclusion

To use global variables between files with Python, we can import the variable in another module.

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 *