Local and Global Variables in Python

One of the basic elements of programming languages are variables. Simply speaking a variable is an abstraction layer for the memory cells that contain the actual value. For us, as a developer, it is easier to remember the name of the memory cell than it is to remember its physical memory address. A valid name can consist of characters from 'a' to 'z' (in both lower and upper cases) as well as digits. No spaces or special characters, like umlauts and hyphens, are allowed in the name.

Furthermore, variables have a specific data type like strings (characters), digits, lists or references to other variables. In Python, we may reuse the same variable to store values of any type. The type is automatically determined by the value that is assigned to the name. In order to define a variable with a specific value, simply assign this value to a name as follows:

age = 42  
name = "Dominic"  
places = ["Berlin", "Cape Town", "New York"]  

The Python interpreter creates the three variables age, name, and places, and assigns the value 42 to the first and "Dominic" to the second variable, and places becomes a list of three elements that contains the strings "Berlin", "Cape Town", and "New York".

Namespaces

All the variables from above are part of the same namespace and therefore have the same scope. Unless redefined as a local variable later on, a variable defined in the main program belongs to the global namespace, that can be accessed by any function in your Python program. The following example code demonstrates that and uses the two variables name and age in the function info().

age = 42  
name = "Dominic"  
places = ["Berlin", "Cape Town", "New York"]

def info():  
    print("%s is %i years old." % (name, age))
    return

info()  

The output consists of the single line that comes from the print statement in function info():

$ python3 global.py
Dominic is 42 years old.  

To be more precise, every module, class and function has its own namespace and variables are locally bound to that. In the next example we make use of two namespaces - the outer, global one from the main program and the inner, local one from the function simply named output(). The variable place exists in the main program (line 6) and is redefined as a local variable with a new value in line 2 of the function output().

def output():  
   place = "Cape Town"
   print("%s lives in %s." % (name, place))
   return

place = "Berlin"  
name = "Dominic"  
print("%s lives in %s." % (name, place))  
output()  

The output consists of these two lines, whereas the first line originates from the main program (line 8) and the second line from the print statement in line 3 in the function output(). At first the two variables name and place are defined in the main program (lines 6 and 7) and printed to stdout. Calling the output() function, the variable place is locally redefined in line 2 and name comes from the global namespace, instead. This leads to the output as shown below.

$ python3 localscope.py
Dominic lives in Berlin.  
Dominic lives in Cape Town.  

Modifying Global Variables in a Different Namespace

The value of a global variable can be accessed throughout the entire program. In order to achieve that from within functions, Python offers the usage of the keyword global. The function below demonstrates how to use it and imports the variable name into the namespace of the function:

def location():  
    global place
    place = "Cape Town"
    return

place = "Berlin"  
print(place)  
location()  
print(place)  

The variable place is already defined in the main program (line 6). Using the keyword global in line 2, the variable becomes available in the function location() and can be set to a different value, immediately (line 3). The output of the the code is shown here:

$ python3 globalscope.py
Berlin  
Cape Town  

Without using the keyword global as seen in line 2, the variable place would be treated as a local variable in the function location() instead and the variable place from the main program is unchanged then.

Detect the Scope of a Variable

Python has two built-in methods named globals() and locals(). They allow you to determine whether a variable is either part of the global namespace or the local namespace. The following example shows how to use these methods:

def calculation():  
    "do a complex calculation"

    global place
    place = "Cape Town"
    name = "John"

    print("place in global:", 'place' in globals())
    print("place in local :", 'place' in locals())
    print("name in global :", 'name' in globals())
    print("name in local  :", 'name' in locals())
    return

place = "Berlin"  
print(place)  
calculation()  

The output is as follows and shows the scope of the two variables place and name inside the function calculation():

$ python3 variablelist.py
Berlin  
place in global: True  
place in local : False  
name in global : False  
name in local  : True  

Using Global Variables in Practice

Using and modifying global variables from inside functions is seen as a very bad programming style, as it causes side effects, which are rather difficult to detect. It is strongly recommended to use proper function parameters, instead.

Acknowledgements

The author would like to thank Mandy Neumeyer for her support while preparing the article.

Links and References

Author image
Berlin -- Genève -- Cape Town Twitter Github
IT developer, trainer, and author. Coauthor of the Debian Package Management Book (http://www.dpmb.org/).