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.

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.

#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.

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.

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