Scope determines where a name can be used. Python resolves names using the local, enclosing, global, and built-in scopes, often remembered as LEGB.
Local scope#
Names assigned inside a function are local by default:
def calculate():
result = 42
return result
print(calculate())
# print(result) # NameError: result is not definedThe local name exists only while the function runs. Each call gets a fresh local namespace.
Reading globals#
A function can read a global name without declaring it:
site_name = "ILoveCompiler"
def banner():
print(f"Welcome to {site_name}")
banner()Reading works because Python falls back to the module scope when a name is not local.
Modifying globals#
Assigning to a global name inside a function creates a local name unless you declare global:
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # 1This works, but global mutable state makes programs harder to reason about and test. Prefer passing values in and returning results:
def increment(value):
return value + 1
counter = increment(counter)The second version makes the data flow explicit.
Enclosing scope and nonlocal#
A nested function can read names from its enclosing function. To rebind them, use nonlocal:
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2make_counter returns the inner function, which keeps a reference to count. This is a closure. The count variable survives between calls because the inner function still refers to it.
Without nonlocal, count += 1 would create a new local variable and raise UnboundLocalError.
Name resolution example#
value = "global"
def outer():
value = "enclosing"
def inner():
print(value)
inner()
outer()enclosing
inner reads the closest enclosing binding. If it assigned to value, that name would become local unless declared nonlocal.
Object lifetime#
CPython uses reference counting plus a garbage collector. An object stays alive while something references it. When the last reference disappears, it becomes eligible for collection.
def make_greeting():
text = "Hello"
return text
message = make_greeting()
print(message)The string survives the function call because the returned reference is stored in message.
You rarely manage memory manually in Python. Cycles are handled by the garbage collector, and files or network connections should still be closed with with statements or finally blocks.
Practice#
Write make_accumulator() that returns a function. Each call to the returned function adds its argument to a running total and returns the new total. Use nonlocal. Then rewrite a small global counter example as a function that takes and returns the count.
