Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Python

Python and Global Variables

4.41/5 (9 votes)
10 Nov 2014CPOL1 min read 9.7K  
The issue I came across when setting a Python global variable from a method, and how I solved it.

Recently I was writing some Python code, and I used a global variable whose value was set in a method. Here is a simple piece of code to demonstrate this:

Python
list_with_data = []

def load_data_into_list():
    list_with_data = [1, 2, 3] # the actual code loaded data from a file, this is just to demonstrate what the code does

load_data_into_list()

When running the code, it didn’t work because the list was still empty after calling the load_data_into_list() function, but I didn’t notice that until I stored the list (with some new data) into the same file. Then I saw that the previous data was wiped and only the new data remained. So I did some debugging and I found out that the list was still empty though I called the method. The reason was that I intended to load the data into the global list_with_data variable, but Python created another variable list_with_data, but only in the scope of the function. Fortunately, that could be easily solved:

Python
list_with_data = []

def load_data_into_list():
    global list_with_data
    list_with_data = [1, 2, 3]

load_data_into_list()

The global keyword tells the interpreter that I want to use the global variable.

Now, if you have many global variables, it’s quite difficult to write a global ... statement for them all. And there were some more global variables in the code, so instead, I put them in a class, like this:

Python
class GlobalVariables:
    list_with_data = []

def load_data_into_list():
    GlobalVariables.list_with_data = [1, 2, 3]

load_data_into_list()

With a class, you don’t have to use the global keyword anymore, which saves you from writing 10 (or more) lines only to tell the interpreter that you want to use a global variable.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)