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.
"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:
Python checks the local scope first: the function that is running right now.
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.
What does this print?
x = "global" def show(): x = "local" print(x) show() print(x)
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.
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 namemakes assignments go to the module-level name.nonlocal namemakes assignments go to the nearest enclosing function's name.
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.
UnboundLocalError?total = 10 def add_five(): total += 5 return total
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.
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:
Press Run (⌘ Enter) to see what happens.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))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.
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:
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:
Press Run (⌘ Enter) to see what happens.fns = [lambda x: x * n for n in range(1, 4)] print(fns[0](10))
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.
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 isNonefor 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.
make_account has returned, but its balance lives on in cell C. Both functions hold a reference to the same cell.
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.
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.
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:
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.
return limit * 2 raise NameError when limit = 10 is defined in the class body?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:
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(), aremainingcount 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
multiprocessingworkers 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).
Match each keyword or idea to what it does.
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() # 3Do not use globals.
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) # 12Careful: the obvious [lambda x: x + i for i in range(n)] makes every function add the last i.
- 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.