Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Closure vs Class: Stateful Callables

Compare Python closures and classes for stateful callables: how they store state, how they differ in mutation and readability, and when to choose each.

~4 min readPython
#closures#classes#stateful callables#python functions
Diagram comparing a closure capturing a variable and a class instance holding state, both representing stateful callables in Python.

When you need a callable that remembers something between calls, Python gives you two common patterns: a closure that captures variables from an enclosing scope, or a class with a __call__ method. Both can hold state, but they behave differently under mutation, inspection, and extension. The choice between a closure and a class is not about one being universally better; it depends on how much state you need, how you plan to change it, and whether the callable is the only behavior you need.

What a Closure Captures

A closure is a function that references variables from the scope where it was defined, even after that scope has finished executing. The captured variables are stored in the function's __closure__ attribute and persist as long as the function object exists.

python
def make_counter(): count = 0 def increment(): nonlocal count count += 1 return count return increment counter = make_counter() print(counter()) # 1 print(counter()) # 2

The nonlocal declaration is required when you rebind the variable inside the inner function. Without it, Python would treat count as a local variable and raise an UnboundLocalError on the first access. The closure captures the variable itself, not just its value, so changes are visible across calls.

What a Class Provides

A class can achieve the same result by storing state as an attribute and implementing __call__ to make instances callable.

python
class Counter: def __init__(self): self.count = 0 def __call__(self): self.count += 1 return self.count counter = Counter() print(counter()) # 1 print(counter()) # 2

The instance attribute self.count is the state. The __call__ method is invoked when you use the instance as a function. This pattern is straightforward and familiar to most Python developers.

State Mutation and Reassignment

Closures and classes differ in how you can modify the captured state from outside the callable. With a closure, the captured variable is not exposed as an attribute; from outside the callable you cannot access or modify it unless the closure provides an accessor or setter. With a class, the attribute is accessible and mutable by default.

python
# Closure: no direct access to count counter = make_counter() # counter.count # Would raise AttributeError # Class: attribute is public counter = Counter() counter.count = 100 print(counter()) # 101

This difference matters when you need to reset or inspect the state. A closure forces you to add a reset function inside the factory, while a class allows you to set the attribute directly. If you want to prevent external modification, you can use a closure or make the class attribute private with a leading underscore, but that is convention, not enforcement.

Memory and Runtime Overhead

Structurally, a closure stores captured variables in a __closure__ tuple on the function object. A class instance normally stores attributes in an instance __dict__, unless __slots__ is used. In most applications, the performance difference is small and should not be the deciding factor; if you are creating thousands of callables or measuring tight loops, profile the specific pattern in your code. The closure accesses captured variables directly, while a class instance uses attribute lookup, but this is rarely the main practical concern. The bigger practical difference is the API: a closure does not expose its captured state as an attribute, while a class instance can expose attributes and additional methods.

Readability and Maintainability

A closure is concise when the callable is simple and has one responsibility. The state is local to the factory, and the code reads naturally. For example, a function that returns a multiplier:

python
def make_multiplier(factor): def multiply(x): return x * factor return multiply double = make_multiplier(2) print(double(5)) # 10

This is clean and obvious. But when the callable needs multiple methods, or when you want to expose additional behavior like reset or get_state, a class becomes clearer. You can group related methods under one class, and the state is explicit in __init__.

python
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor def set_factor(self, factor): self.factor = factor

With a closure, you would have to return a tuple of functions or attach attributes to the inner function, which is awkward and less discoverable.

When a Closure Becomes Awkward

Closures become awkward when you need to:

  • Expose the state for debugging or testing
  • Add methods beyond the callable itself
  • Subclass or reuse the behavior
  • Use the callable in a context that expects a class (e.g., some serialization or introspection)

For example, if you want to reset a counter, a closure requires you to define a reset function and return it, which complicates the API. A class can simply set counter.count = 0. If you want to add a __repr__ or a method that returns the current state, a class is the natural fit.

Practical Decision Rule

Use a closure when you have a single callable with a small amount of state, and you do not need to expose that state externally. Closures are ideal for simple factories and for capturing configuration values that should not change after creation.

Use a class when you need multiple methods, want to expose or modify state, or expect to extend the behavior later. Classes also work better when you need to maintain multiple instances with independent state and want to use inheritance or mixins.

A good heuristic: if your stateful callable is more than a few lines and you find yourself adding helper functions to the factory, switch to a class. The class will make the structure explicit and easier to maintain as the logic grows. Conversely, if the callable is a one-liner that captures a single value, a closure keeps the code compact and avoids the ceremony of a class definition.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.