What do the global and nonlocal keywords do, and when should you use them?
global declares that a name inside a function refers to the module-level variable, allowing reassignment. nonlocal does the same for the nearest enclosing function scope. Both should be used sparingly — they make control flow harder to reason about, and a class or closure that returns a value is usually a cleaner design.
How to think about it
What this question is testing
Python has a specific name-resolution order called LEGB: Local, Enclosing, Global, Built-in. Without a declaration, any name that appears on the left side of = inside a function is treated as a new local variable for the function’s entire body. global and nonlocal override that default.
The follow-up interviewers care about: when shouldn’t you use them? The honest answer is: almost never — a class or a closure that returns a new value is almost always cleaner.
global — target the module namespace
_cache = {}
def fetch(key):
global _cache
if key not in _cache:
_cache[key] = key.upper() # simulated expensive lookup
return _cache[key]
Without global _cache, the assignment _cache[key] = ... would still work for mutation (dict mutation, not rebinding). But if you wrote _cache = {} inside the function to reset it, you’d create a local shadow and the module-level cache would be untouched.
nonlocal — target the enclosing function scope
The cleaner alternatives
nonlocal and global are worth knowing but should make you pause. The same state can be managed more transparently with:
- A class —
__init__+ methods; state is explicit and testable. - Return the new value — the caller holds state; functions stay pure.
- A mutable container in the enclosing scope — mutating a
listordictdoesn’t requirenonlocal(but watch the mutable-default trap).
Key insight
nonlocal requires the name to already exist in an enclosing scope — it cannot create a new module-level name. global can create the module-level name if it doesn’t yet exist. Both keywords change where a binding lives, not what happens at read time (reads already walk LEGB automatically).