What does the nonlocal keyword do?medium

Type
conceptual
Topic
scope
Frequency
common
Tags
nonlocal, scope, closures
Answer

nonlocal lets an inner function reassign a variable in its enclosing function's scope rather than creating a new local variable.

Explanation

Without nonlocal, any assignment inside a function makes that name local. With nonlocal count, count += 1 modifies the enclosing function's count — the standard pattern for a counter in a closure. global does the same for module-level variables but is rarely the right choice in modern code.

Follow-upWhat's the difference between nonlocal and global?