nonlocal
A statement that lets an inner function rebind a variable of its enclosing function.
In more detail
Without nonlocal, any assignment to a name inside a function, including +=, makes that name local, so reading it first raises UnboundLocalError. nonlocal count tells Python to use the enclosing function's count instead. It is the usual way for a closure to keep changing state between calls.
Example
def make_counter():
count = 0
def tick():
nonlocal count
count += 1
return count
return tickRelated terms
- closure — A function bundled with the variables it remembers from the scope where it was created.
- UnboundLocalError — The error raised when a function reads a local name before anything has been assigned to it.
- scope — The region of a program where a name can be seen and used.
Taught in
- Closures: Functions That Remember — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Comprehensions, Closures And Files Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep