Search GimmeJob

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

Explain the LEGB rule Python uses to resolve a name reference.

Answer

Python looks up a bare name in four scopes in order: Local (the current function), Enclosing (any enclosing function, for closures), Global (the module's top level) and Built-in (Python's built-in namespace). Resolution stops at the first scope where the name is found, so a local variable shadows a global with the same name, and a name that is assigned anywhere inside a function is treated as local for the whole function unless declared `global` or `nonlocal`.

Strong answer includes

  • Local, Enclosing, Global, Built-in order
  • first match wins
  • assignment anywhere makes a name local

Practical example

If a function assigns

Python example
count = count + 1

without declaring `global count` , Python raises UnboundLocalError, because the assignment marks `count` local for the entire function body, including the read before the assignment.

#scoping#closures

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semanticsThe Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basics