CKTIS / Python
Scope and lifetime
Scope determines where a name can be resolved, while references can keep an object alive beyond a function call.
Version: Python 3.14; repository image, production runtime not attested
Syntax
def outer():
count = 0
def next_value():
nonlocal count
count += 1
return count
return next_valueScope determines where a name can be resolved, while references can keep an object alive beyond a function call.
Assignment in a function usually makes a name local throughout that body. Reading it before local assignment raises UnboundLocalError. nonlocal selects the nearest existing binding in an enclosing function.
Each call to counter creates a separate count cell retained by its closure. a(), a(), b() prints 1 2 1.
name='outside'
def read_early():
value=name
name='inside'
return value
try: read_early()
except UnboundLocalError: pass
else: raise AssertionError
values=[]
alias=values
del values
assert alias==[]
Examples
def counter():
count = 0
def advance():
nonlocal count
count += 1
return count
return advance
a, b = counter(), counter()
print(a(), a(), b())
Result
1 2 1
Each call to counter creates a separate count cell retained by its closure. a(), a(), b() prints 1 2 1.