Skip to main content

Functions Scope

In Python, the interpreter searches four levels to find a variable name, following the LEGB rule: LocalEnclosingGlobalBuilt-in. By default, we can read outside variables, but we cannot modify them without explicit keywords.

The LEGB Scope Rule

Python's scope rules might feel broader if we are coming from C.

x = "Global"

def outer():
x = "Enclosing"

def inner():
x = "Local"
print(f"Inner: {x}") # Prints "Local"

inner()
print(f"Outer: {x}") # Prints "Enclosing"

outer()
print(f"Global: {x}") # Prints "Global"

Output:

Inner: Local
Outer: Enclosing
Global: Global

Modifying Outside Variables

To change a variable defined outside the current function's local scope, we must explicitly declare our intent using global or nonlocal.

Global Keyword

Use global to modify a variable defined at the top level of the file.

count = 0

def increment():
global count # Tells Python to use the top-level 'count'
count += 1

increment()
print(f"Global count: {count}")
Global count: 1

Nonlocal Keyword

Use nonlocal to modify a variable in the parent (enclosing) function's scope.

def parent():
name = "Alice"
def child():
nonlocal name # Targets the variable in 'parent' scope
name = "Bob"
child()
print(f"Parent name: {name}")

parent()
Parent name: Bob