🐍 python global vs nonlocal keyword — when to use each?
The article explains Python's scope resolution rules for modifying variables in outer scopes using global and nonlocal keywords. Global allows assignment to module-level names, while nonlocal targets variables in enclosing function scopes (excluding global). Both are resolved at compile time: global marks names as module-level, nonlocal creates cell variables for closures. Practical examples include a simple call counter using global and retry logic with backoff using nonlocal to maintain state in a closure. Key differences: global affects module scope, nonlocal affects enclosing function scope; global binds to module dict, nonlocal uses cell variables; name resolution for global skips enclosing functions, nonlocal searches up the lexical scope. Best practices: use global for module-wide configuration, nonlocal for closure state, avoid both when passing arguments or returning values suffices. Common pitfalls: UnboundLocalError when assigning without declaration, and inability to use nonlocal for global or class scopes.
Misusing global or nonlocal causes subtle bugs in closures and nested functions.