Skip to the solution
MediumDSA12 min read

What is the LEGB rule for scope resolution?

888 views

The problem

Question presented to candidate: "When Python meets a name like total inside a function, how does it decide which variable you mean? Walk me through the LEGB rule and the cases where it surprises people."

What a strong answer should cover:

  • The search order Local, Enclosing function, Global (module), Built-in; the first match wins and a miss raises NameError.
  • Scope is decided at compile time: an assignment anywhere in a function makes the name local for the whole body, which is why reading it first raises UnboundLocalError.
  • Only modules, functions, lambdas, comprehensions and class bodies create scopes; if, for, with and try blocks do not.
  • Class bodies are skipped: a method cannot see class attributes as bare names, it must use self.x or ClassName.x.
  • Reading follows LEGB, but rebinding an outer name needs global or nonlocal; shadowing a built-in such as list or len hides it.
  • A CPython detail: the compiler emits LOAD_FAST, LOAD_DEREF or LOAD_GLOBAL, and LOAD_GLOBAL checks the module dict first and the builtins second.

Code / implementation expected: Optional β€” predict the output of a nested-function snippet, or explain the UnboundLocalError case.

  • scope
  • legb

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonLEGB in action: the four scopes, shadowing, and what is not a scope
PythonCompile time decides: UnboundLocalError, dis, symtable and class bodies

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 60 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What are common Python security pitfalls?

Continue