Name lookup and closures
Learn in depth →Functions resolve names through local, enclosing, global and built-in scopes. Closures retain bindings.
nonlocal name; global nameExample
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = make_counter()
print(c(), c())Result
1 2
Watch for: Assignment makes a name local unless declared otherwise. Late-bound closures observe a binding at call time.
Practise this topic →