What is the difference between the `global` and `nonlocal` keywords?
Answer
`global` tells Python that an assignment inside a function should modify a name in the module's global scope instead of creating a new local variable. `nonlocal` does the equivalent for an enclosing function's scope in a nested-function closure, skipping the local scope but stopping before the global scope. `nonlocal` fails with a SyntaxError if no matching binding exists in an enclosing function, while `global` will happily create the name at module level if it does not already exist.
Strong answer includes
- global targets module scope
- nonlocal targets enclosing function scope
- nonlocal requires an existing enclosing binding
Practical example
A
make_counter()closure uses `nonlocal count` inside an inner
increment()function so repeated calls to the returned `increment` mutate the same `count` variable captured from `make_counter` .