Skip to the page

Functions and flow · core

Closures, LEGB and late binding

Python looks up a name in Local, Enclosing, Global, Built-in order. A closure keeps the variable, not its value, so a lambda made in a loop sees the last value, and assigning to a name inside a function makes it local for the whole function.

The notes

What you must know

  • LEGB: Local, Enclosing, Global, Built-in.
  • A closure captures the variable and reads it when called. Lambdas created in a loop over level all see the last value: they print [error] three times.
  • Fixes: a default argument (lambda msg, level=level: ...), functools.partial, or a small factory function.
  • Assigning to a name anywhere in a function makes it local for the whole function. counter += 1 on a global then raises UnboundLocalError.
  • Fix with global counter (avoid shared globals), nonlocal inside a nested function, or return the new value or use a class.
  • Real bugs: callbacks, threads or tasks created in a loop that use the loop variable.
  • Shared module-level state is a risk in a web server: the same global is visible to every request in that process.

The red pen

Common traps: mistake → fix

  • Mistake: The lambda keeps the value the variable had when the lambda was made

    Fix: it keeps the variable, and reads it later.

  • Mistake: The fix is global everywhere

    Fix: prefer returning values, a class, or nonlocal in a nested function.

  • Mistake: A name is local only after the assignment line

    Fix: it is local for the whole function body.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does the list of lambdas created in a for loop print, and why?
  2. What does LEGB mean?
  3. Why does counter += 1 inside a function raise UnboundLocalError?
  4. What is the difference between global and nonlocal?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview