Mathematics, Sciences, and Technologies

Python for Scientists 2-7: Global versus Local Scope

,

Variables in Global/Local Scope

In this section, we shall take a detour to discuss a very important concept in Python (and programming in general), which is the distinction between global and local scope. We will skip all the technical details, and only examine the key mechanism. Interested readers can search for the keyword “namespace”.

The global scope can be viewed as the full space that the Python script resides in. Variables in the global scope are defined and used/referenced throughout the entire script. A trivial example is

a = 3
b = 4
print("a =", a)
print("b =", b)

that prints a = 3, b = 4 without any problem, because a and b are global variables that may be referenced everywhere in the script, when applicable. In contrast, we also have the local scope, which as its name suggests, only applies locally to a smaller “subspace” embedded within the full global scope. The most common appearance of a local scope occurs when we define a function, in which local variables defined there can only be referenced inside it, but are unknown to the global scope. For instance,

def some_function(x):
y = 9
z = x + 3
return z
a = some_function(7)
print(y) # or print(z)

In this case, y and z are local variables for some_function. Even after some_function has been called, if we want to reference and retrieve the values for y and z, an error will arise, saying

    print(y)
          ^
NameError: name 'y' is not defined

This is because y and z only exist in the local scope, and in the global scope they cannot be found. In the same vein, local variables between two different local scopes are also unknown to each other.

However, conversely, the local scope will instead try to look into the global scope (or more accurately, one level above) if the variable cannot be found in the local scope itself. For example, if we write

p = 5
def another_function(q):
r = p + q
return(r)
print(another_function(q=8))

we will obtain 13 as expected. Within the scope of another_function, we take the global value of q as a substitute as there is no q locally.

Now let’s investigate more complex cases. First, what will happen if the same variable (i.e., that bears the same name) is defined in both the global and local scopes? The answer is that the global/local scope will reference the corresponding global/local variable respectively. For example, something like

x = 5
def local_x():
x = 7
print("Locally, x =", x)
local_x()
print("Globally, x =", x)

will produce

Locally, x = 7
Globally, x = 5

A Common Pitfall

Beginners meddling with functions may sometimes encounter this confusing error. Let’s take a look at the code that produces it:

x = 1
def add_one():
x = x + 1
add_one()
print(x)
    x = x + 1
        ^
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value

To put it shortly, when we write x = x + 1, we haven’t really defined x in the local scope beforehand (the global scope x = 1 has no effect on this), and this line is trying to create a local x (L.H.S.) while x on the R.H.S. is global, resulting in a conflict. (If we haven’t defined x = 1 globally, then the error still occurs as there is no x to start with for evaluating the R.H.S.) In general, we need to be careful about distinguishing local and global variables when writing our own functions.

Exercise

Determine the outputs of the following code without running it first. What happens if we replace y = x by y = z?

x = 3
y = 8
z = -1
def my_function(x):
y = x
z = x + y
print("Local x:", x)
print("Local y:", y)
print("Local z:", z)
my_function(2)
print("Global x:", x)
print("Global y:", y)
print("Global z:", z)
Suggested Solution

It should give

Local x: 2
Local y: 2
Local z: 4
Global x: 3
Global y: 8
Global z: -1

If we do y = z inside the function instead, then there will be an UnboundLocalError as explained above.

Leave a Reply

I’m Benjamin

Welcome to my Mathematical World! Here you can find posts and tutorials related to applied topics like Linear Algebra, Calculus, Differential Equations, and Programming. Feel free to leave comments and suggestions!