The global Statement in Python

The global statement and its nonlocal cousin are not type or size declarations, they are namespace declarations. The global statement tells Python that a function plans to change one or more global names.

A global statement allows us to change names that live outside a def at the top level of a module file. The nonlocal statement is almost identical but applies to names in the enclosing def local scope, rather than names in the enclosing module.

The global statement consists of the keyword global , followed by one or more names separated by commas.

Example 1:

>>> a = 4
>>> 
>>> def my_function():
...     global a
...     a = 5
... 
>>> my_function()
>>> print(a)
5

In this example changing a inside the function changes the a outside it.

Example 2:

>>> a, b = 4, 3
>>> 
>>> def my_function():
...     global c
...     c = a + b
... 
>>> print(a, b, c)
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'c' is not defined
>>> 
>>> my_function()
>>> print(a, b, c)
4 3 7

In this example the a, b, and c are all globals inside the function my_function() . The a and b are global because they aren’t assigned in the function; c is global because it was listed in a global statement to map it to the module’s scope explicitly.

Note:
Notice that c does not even exist before the function runs (see the error in the sample code).

Consider the following piece of code:

>>> a = 10
>>> def func1():
...     global a
...     a = 11
... 
>>> def func2():
...     global a
...     a = 12
... 
>>> func1()
>>> func2()
>>> print(a)
12
>>> func1()
>>> print(a)
11
>>> func2()
>>> print(a)
12

At the first glance you might be confuse about the value of a. The value of a is timing-dependent, as it depends on which function was called last.

Let’s consider to files, test1.py and test2.py that contain the following code:

The test1.py file

# test1.py
a = 4

The test2.py file

# test2.py
import test1
print(test1.a)
test1.a = 5
print(test1.a)

Now, when you run the test2.py file in the terminal you will see how the variable a was changed.

ddn_ro@Linux:~$ python3 test2.py
4
5

The first file defines a variable a, which the second file prints and then changes it by assignment and prints again the variable a with the modified value.
Notice that we must import the first module into the second file to get to its variable because each module is a self-contained namespace.

However, such implicit cross-file dependencies can lead to inflexible code at best, and outright bugs at worst. The best way to communicate across file boundaries is to call functions, passing in arguments and getting back return values. You could you as shown below:

The test1.py file

# test1.py
a = 4

def seta(new):
	global a
	a = new

The test2.py file

# second.py
import test1
print(test1.a)
test1.seta(5)
print(test1.a)

This code makes a huge difference in terms of readability and maintainability.

Leave a Reply