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:
list_with_data = []
def load_data_into_list():
list_with_data = [1, 2, 3]
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:
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:
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.