Click here to Skip to main content
15,880,725 members
Articles / Programming Languages / Python

Python and Global Variables

Rate me:
Please Sign up or sign in to vote.
4.41/5 (9 votes)
10 Nov 2014CPOL1 min read 9.4K   5  
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)


Written By
Student
Europe Europe
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --