Skip to content

Lesson 13 of 52Functions

Scope and Closures

Know where Python looks up a name (LEGB), when to use global and nonlocal, and how closures remember values.

21 min read0/7 questions

"Why is this variable undefined?" and "why did all my callbacks use the last value?" are two of the most common Python head-scratchers, and both are about scope: which names are visible where. Closures, built on the same rules, are what make decorators, callbacks and function factories work. Interviewers use the late-binding loop bug as a favourite trick question.

Where names live: LEGB

The scope of a name is the region of code where it can be seen. When Python meets a name, it searches four scopes in a fixed order, remembered as LEGB:

Looking up a name: LEGB
  1. LocalNames assigned inside the current function
  2. EnclosingNames in any outer function this one is nested in
  3. GlobalNames assigned at the top level of the module (file)
  4. Built-inNames Python provides: len, print, range, ...

Python checks the local scope first: the function that is running right now.

1/4
Python
rate = 0.2 # global def outer(): bonus = 100 # enclosing (for inner) def inner(salary): # salary is local to inner return salary * (1 + rate) + bonus return inner(1000) print(outer())print(len("found in built-ins"))
Output
Press Run (⌘ Enter) to see what happens.

The first match wins. That is why naming a variable list or sum is a bad idea: your global name shadows the built-in, and list("abc") suddenly breaks.

Predict the outputPython

What does this print?

x = "global"
def show():
  x = "local"
  print(x)
show()
print(x)
Need a nudge? Hints walk you through it.

Assignment makes a name local

Here is the rule behind many confusing errors: if a function assigns to a name anywhere in its body, that name is local for the whole function. Python decides this when it compiles the function, before running it.

Python
count = 0 def increment(): count = count + 1 # count is local here, but has no value yet return count try: increment()except UnboundLocalError as err: print("UnboundLocalError:", err)
Output
Press Run (⌘ Enter) to see what happens.

Reading a global works fine. Assigning to it inside a function, without saying so, does not.

global and nonlocal

To rebind a name from an outer scope, declare it:

  • global name makes assignments go to the module-level name.
  • nonlocal name makes assignments go to the nearest enclosing function's name.
Python
count = 0 def increment(): global count count += 1 increment()increment()print(count)
Output
Press Run (⌘ Enter) to see what happens.

global works, but functions that quietly change globals are hard to test and reason about. Prefer returning a value, or keeping state in an object. nonlocal is the useful one, as you will see with closures.

Quick check
Why does calling this raise UnboundLocalError?
total = 10
def add_five():
  total += 5
  return total
Need a nudge? A hint rules out a wrong answer.

Closures: functions that remember

A function defined inside another function can use the outer function's variables. Here is the surprising part: it keeps access to them even after the outer function has returned. A function bundled with the variables it captured is called a closure.

Python
def make_multiplier(factor): def multiply(n): return n * factor # factor comes from the enclosing scope return multiply double = make_multiplier(2)triple = make_multiplier(3)print(double(10), triple(10))print(double.__closure__[0].cell_contents)
Output
Press Run (⌘ Enter) to see what happens.

make_multiplier(2) has finished, but double still remembers factor = 2. Each call to make_multiplier creates a separate closure with its own factor. Functions that build and return other functions like this are sometimes called factories.

Closures with state: nonlocal

To change a captured variable, the inner function needs nonlocal. This gives you private, persistent state without a class or a global:

Python
def make_counter(): count = 0 def counter(): nonlocal count count += 1 return count return counter a = make_counter()b = make_counter()print(a(), a(), a())print(b())
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

def make_acc(start):
  total = start
  def add(n):
      nonlocal total
      total += n
      return total
  return add

acc = make_acc(10)
acc(5)
print(acc(1))
Need a nudge? Hints walk you through it.

Mutating is not rebinding

nonlocal and global are only needed when you rebind a name: =, +=, del, or using it as a loop target. Calling a method that changes the object the name points to is not an assignment, so it needs no declaration.

Python
def make_log(): lines = [] def log(msg): lines.append(msg) # mutates: no nonlocal needed return len(lines) return log log = make_log()log("start")print(log("stop")) def make_total(): total = 0 def add(n): total += n # rebinds: needs nonlocal return total return add try: make_total()(5)except UnboundLocalError as err: print("UnboundLocalError:", err)
Output
Press Run (⌘ Enter) to see what happens.

This is the same names-versus-objects idea from The Python Memory Model. lines.append follows the name to the list and changes the list. total += n tries to point the name total at a new int, and that is what makes it local. Before nonlocal existed (Python 2), people wrapped counters in a one-item list, count = [0] and count[0] += 1, to dodge exactly this rule. You will still see that trick in old code.

The late binding gotcha

Closures capture variables, not values. The value is looked up when the inner function runs, not when it is created. That is called late binding, and it bites hardest in loops:

Python
callbacks = []for i in range(3): callbacks.append(lambda: i) print([f() for f in callbacks]) # not [0, 1, 2]!
Output
Press Run (⌘ Enter) to see what happens.

(lambda: i is a tiny one-line function that returns i. You will learn lambda properly in the next lesson.)

All three functions refer to the same variable i. By the time you call them, the loop has finished and i is 2. The standard fix is a default argument, because defaults are evaluated when the function is created:

Python
callbacks = []for i in range(3): callbacks.append(lambda i=i: i) # capture the current value print([f() for f in callbacks])
Output
Press Run (⌘ Enter) to see what happens.
Quick check
What does this print?
fns = [lambda x: x * n for n in range(1, 4)]
print(fns[0](10))
Need a nudge? A hint rules out a wrong answer.

Inspecting closures: cells

A closure does not copy values. When the compiler sees that an inner function uses a variable from an outer function, it stores that variable in a small box called a cell. The outer function reads and writes the variable through the cell, and every inner function that uses it gets a reference to the same cell. That shared box is why late binding happens, and also why two closures can share state.

Python
def make_account(balance): def deposit(amount): nonlocal balance balance += amount return balance def read(): return balance return deposit, read deposit, read = make_account(100)print(deposit.__code__.co_freevars, read.__code__.co_freevars)print(deposit.__closure__[0] is read.__closure__[0]) # one shared celldeposit(50)print(read(), read.__closure__[0].cell_contents)print(make_account.__code__.co_cellvars)
Output
Press Run (⌘ Enter) to see what happens.

The names to know:

  • fn.__code__.co_freevars: the names this function uses from an enclosing scope (its free variables).
  • fn.__closure__: a tuple of cells, one per free variable, in the same order. It is None for a function with no free variables.
  • cell.cell_contents: the value currently in the cell.
  • outer.__code__.co_cellvars: the names of the outer function that live in cells because some inner function uses them.
Two closures, one cell
deposit, read = make_account(100)
NamesObjects in memorydepositreadfunctiondeposit, closure=(C,)functionread, closure=(C,)cell-> 100

make_account has returned, but its balance lives on in cell C. Both functions hold a reference to the same cell.

1/3

Two practical consequences. Debuggers and test helpers can read cell_contents to see what a callback captured, which is handy when a handler behaves as if it has stale data. And a cell keeps its object alive as long as any closure holding it is alive. A callback registered on a long-lived object that captured a large DataFrame or a database connection keeps that object in memory too. If memory grows and a profiler points at functions, look at what they close over.

How CPython decides scope: compile time, not run time

Python decides the scope of every name when it compiles the function, before any line runs. The compiler builds a symbol table: names assigned in the function are local, names declared global or nonlocal are redirected, names used but owned by an enclosing function become free variables, and everything else is looked up as global then built-in. Each choice becomes a different bytecode instruction.

Python
import dis x = 1def outer(): y = 2 def inner(): z = 3 return x + y + z return inner dis.dis(outer())
Output
Press Run (⌘ Enter) to see what happens.

You will see LOAD_GLOBAL for x (look in the module dict, then built-ins), LOAD_DEREF for y (read through a cell) and a LOAD_FAST variant for z (a slot in the frame, the fastest lookup). Exact opcode names change between Python versions, but the three kinds stay. This is also why UnboundLocalError exists at all: the compiler already chose LOAD_FAST for a name assigned later, so at run time there is no fallback to the global.

Class bodies are not enclosing scopes

LEGB has an exception that catches experienced developers. The body of a class statement runs in its own namespace, but that namespace is not an enclosing scope for the functions defined inside it. Methods cannot see class variables by their bare names.

Python
class Config: retries = 3 def attempts(self): try: return list(range(retries)) except NameError as err: print("NameError:", err) return list(range(self.retries)) print(Config().attempts())
Output
Press Run (⌘ Enter) to see what happens.

Inside a method, reach class attributes through self.retries (respects overrides in subclasses and instances) or type(self).retries / Config.retries (always the class value). This is deliberate: if methods could see class variables as plain names, a local variable in a method could silently mean different things depending on what the class happened to define.

The same rule applies to comprehensions and lambdas inside a class body, because they are function scopes too. The one exception is the first iterable of a comprehension, which is evaluated in the class body itself:

Python
class Grid: size = 3 row = [r * 10 for r in range(size)] # first iterable: fineprint(Grid.row) try: class Grid2: size = 3 cells = [(r, c) for r in range(size) for c in range(size)]except NameError as err: print("NameError:", err) # the second range(size) fails
Output
Press Run (⌘ Enter) to see what happens.

Python 3.12 inlined comprehensions for speed (PEP 709) but kept this behaviour on purpose, so the code above fails the same way on every current version. The fix is to compute the value outside the class, or in a classmethod or __init_subclass__ where you have a real function scope.

Quick check
Inside a method, why does return limit * 2 raise NameError when limit = 10 is defined in the class body?
Need a nudge? A hint rules out a wrong answer.

Closures vs small classes

A closure with nonlocal state and a class with attributes can do the same job. Here is a rate limiter both ways:

Python
import pickle def make_limiter(limit): calls = 0 def allow(): nonlocal calls calls += 1 return calls <= limit return allow class Limiter: def __init__(self, limit): self.limit = limit self.calls = 0 def __call__(self): self.calls += 1 return self.calls <= self.limit def reset(self): self.calls = 0 def __repr__(self): return f"Limiter(limit={self.limit}, calls={self.calls})" f = make_limiter(2)g = Limiter(2)print([f() for _ in range(3)], [g() for _ in range(3)])print(f)print(g)g.reset()print(g(), g.calls) for obj in (f, g): try: pickle.dumps(obj) print("pickled", type(obj).__name__) except Exception as err: print(type(err).__name__, "for", type(obj).__name__)
Output
Press Run (⌘ Enter) to see what happens.

Both are called the same way, f() and g(), because __call__ makes an instance callable (more in Dunder Methods). The differences show up later in the code's life:

  • One behaviour, little state: a closure is shorter and the state is truly private. Key functions, small factories, callbacks and decorators are the sweet spot.
  • More than one operation on the state: the moment you want reset(), a remaining count or a way to inspect it, you are fighting the closure. A class gives each operation a name.
  • Debugging and logs: the closure prints as <function make_limiter.<locals>.allow at 0x...>. The class can have a useful __repr__.
  • Pickling: nested functions cannot be pickled, so they cannot be sent to multiprocessing workers or stored in task queues. Instances of a module-level class can.
  • Testing: tests can read and set attributes on an instance. Poking at __closure__ in a test is a sign the code wanted to be a class.

A good rule from code review: start with a closure when it is one function and one or two captured values, and convert to a class the first time someone asks for a second method. functools.partial sits in between: it captures values like a closure but has a readable repr and pickles when its function does (see Higher-Order Functions).

Predict the outputPython

What does this print?

def make_pair():
  n = 0
  def inc():
      nonlocal n
      n += 1
  def get():
      return n
  return inc, get

inc, get = make_pair()
inc(); inc()
inc2, get2 = make_pair()
inc2()
print(get(), get2())
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match each keyword or idea to what it does.

Choose an item, then its match on the other side.
ChallengeMedium

Make a counter

Write make_counter() that returns a function. Each time you call that function it returns the next number, starting at 1. Separate counters keep separate counts.

a = make_counter()
a()  # 1
a()  # 2
b = make_counter()
b()  # 1
a()  # 3

Do not use globals.

Python
def make_counter(): # Keep the count in make_counter's scope and return an inner function. pass
ChallengeMedium

Adders without the loop bug

Write make_adders(n) that returns a list of n functions. The function at index i adds i to its argument.

adders = make_adders(3)
adders[0](10)  # 10
adders[2](10)  # 12

Careful: the obvious [lambda x: x + i for i in range(n)] makes every function add the last i.

Python
def make_adders(n: int) -> list: # Each function needs its own i, captured at creation time. pass
Key terms
scope
The region of code where a name is visible.
LEGB
Python's lookup order: Local, Enclosing, Global, Built-in. First match wins.
UnboundLocalError
Reading a local name before it is assigned, often because an assignment later in the function made it local.
nonlocal
Lets an inner function rebind a variable from its enclosing function.
closure
A function that remembers variables from the scope where it was created, even after that scope has finished.
late binding
Closures look up captured variables at call time, so loop variables show their final value.
cell
The box CPython uses to hold a variable shared between a function and the closures that use it. Read it with cell_contents.
free variable
A name a function uses but that belongs to an enclosing function. Listed in __code__.co_freevars.
class body scope
The namespace a class statement runs in. It is not an enclosing scope for methods, so they use self.name.