Function Scope and Closures

Carson West

Chaining Decorators

Function Scope and Closures

Python’s scope rules determine where a variable is accessible within your code. Understanding this is crucial for writing clean and predictable functions.

x = 10  # Global scope

def outer_function():
    y = 20  # Enclosing function scope
    def inner_function():
        z = 30  # Local scope
        print(x, y, z)  # Accesses x, y, and z
    inner_function()

outer_function() # Output: 10 20 30

print(x) # Output: 10
#print(y) # NameError: name 'y' is not defined (y is not in global scope)
global_var = 5

def modify_global():
    global global_var  # Declare that we are modifying the global variable
    global_var = 10

modify_global()
print(global_var)  # Output: 10
def outer():
    enclosing_var = 5
    def inner():
        nonlocal enclosing_var #Declare that we are modifying a variable in the enclosing scope
        enclosing_var = 10
    inner()
    print(enclosing_var) # Output: 10

outer()
def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

closure = outer_function(5)  # 'closure' now holds a reference to 'inner_function' with x=5
result = closure(3)  # result will be 5 + 3 = 8
print(result)  # Output: 8

Nested Functions Variable Scope