Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Core language & syntaxMiddleCommonTheory

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

Python example
make_counter()

closure uses `nonlocal count` inside an inner

Python example
increment()

function so repeated calls to the returned `increment` mutate the same `count` variable captured from `make_counter` .

#scoping#closures

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics