Lesson 15 - Variable Scope

The following topics are discussed in this notebook:

  • Variable scope
  • Masking

Variable Scope

When a function or variable is created in Python, it is placed into a particular scope. A scope is a organizational layer that determines which variables are visible to other variables. Some scopes will exist for the length of your python session, while others will have a limited lifetime.

Scopes are arranged in a heirarchy. At the top level of this heirarchy is the global scope. Most objects that we create in Python will exist in the global scope. The global scope will persist for the duration of our Python session, and variables define within it are accessible from anywhere within our program.

When a function is called, it creates its own local scope that will exist only during the time it takes for the function to execute. Any parameters used in the function, or variables created in the body of the function, will exist only in this local scope, and will disappear after the function finishes executing. To see a demonstration of this, consider the example below.

In [1]:
def addition(x, y):
    temp = x + y
    return temp
    
result = addition(4, 7)
print(result)
11

In the cell above, addition() and result were created in the global scope. These objects will be accessible anywhere within our program. However, x, y, and temp were created within a local scope. They are accessible from within the body of addition, but will dissappear once addition has finished executing. To verify this, uncomment each of the statements below, one at a time, and confirm that each statement produces and error.

In [2]:
#print(x)
#print(y)
#print(temp)

Masking

Assume that we create a variable within a function body or as a function parameter, and this variable has the same name as a variable within the global scope. In this situation, the local variable masks the global variable. When the variable is referenced from within the local scope, it will use the locally defined value for the variable, as opposed to the value define within the global scope.

In [3]:
def addition(x, y):
    temp = x + y
    return temp


x = 14
y = 5
temp = 73

result = addition(4, 7)

print(result)
print(x, y, temp)
11
14 5 73

When we call a function from within another function, we get a sequence of nested local scopes.

In [4]:
def multiplication(x, y):
    result = 0
    for i in range(y):
        result = addition(result, x)
    return result 
    
print(multiplication(4,6))
print(multiplication(5,7))
24
35

Accessing Global Variables from within Local Scopes

A variable defined in the global scope is accessible from anywhere within your program, even from within local scopes. Let's see an example of this.

In [5]:
def square_a():
    return a**2

#print(square_a())

a = 16

print(square_a())

a = 9

print(square_a())
256
81

Whenever a variable is referenced from within a local scope, Python will search that local scope for a variable with that name. If none is found, then it will search for the variable within the global scope. If no variable with that name is found in the global scope, then an error will be generated.

There are occasions when it is helpful to have a function access a global variable, but before doing so, you should always ask yourself if it would make more sense to simply define your function so that it can accept the global value as an argument.

In [6]:
def raise_to_a(x):
    return x**a

a = 3
print(raise_to_a(2))
print(raise_to_a(3))
print(raise_to_a(4))
8
27
64
In [7]:
def raise_to_power(x, power):
    return x**power

a = 3
print(raise_to_power(2, a))
print(raise_to_power(3, a))
print(raise_to_power(4, a))
8
27
64

Altering Global Variables from Within a Local Scope

Assume that we have a variable named my_var in the global scope, but do not currently have a variable with that name in body of a certain function.

  • If we reference my_var from within the function, in an expression like temp = my_var * 2, for example, then the value of my_var will be pulled from the global scope.
  • If we include in our function a line such as my_var = 2, then this will create a new local variable named my_var, masking the global variable with the same name. The value of my_var in the global scope will be unchanged.
In [8]:
def setAto50():
    a = 50
    return a

a = 37
print(a)
print(setAto50())
print(a)
37
50
37

But what if we do wish to change the value of a global variable from within a local scope? We can provide a function with permission to alter global variables using the global keyword. If we would like for a function to have write permission for a global variable, then at the beginning of the function, we can include a line containing the keyword global followed by the name of the variable.

In [9]:
def setAto50():
    global a 
    a = 50
    return a

a = 37
print(a)
print(setAto50())
print(a)
37
50
50