Letting a Request Find Its Handler: Chain of Responsibility in Python
This article explains how the Chain of Responsibility pattern passes a request along ordered handlers in Python, from linked objects to lists of functions and middleware, and why order and signalling matter.
When several parts of a program may be able to deal with a request, the code that sends it often decides in advance which one to call, with a chain of conditions that grows every time a new case appears. The present article examines the Chain of Responsibility pattern, in which the request travels along an ordered sequence of handlers until one of them accepts it, so that the sender knows only the start of the chain. It presents the classic form with linked handler objects, a more idiomatic Python form with a list of functions, the variant in which every handler acts on the request as in web middleware, and the places in the standard library where the pattern already operates, before describing the errors that the order of the chain and the meaning of "not handled" can introduce. Letting the request find its handler, instead of making the sender choose it, is the secret weapon of this pattern.
Tag Team: Handlers That Pass the Request Along
In the classic form, each handler holds a reference to its successor; it either processes the request and returns a result, or passes the request to the next handler. The last handler of the chain must decide what happens to a request that nobody accepted.
NOT_HANDLED = object()
class Handler:
def __init__(self, successor=None):
self.successor = successor
def handle(self, request):
if self.successor is None:
return NOT_HANDLED
return self.successor.handle(request)
class Billing(Handler):
def handle(self, request):
if request["topic"] == "billing":
return "billing: invoice corrected"
return super().handle(request)
class Technical(Handler):
def handle(self, request):
if request["topic"] == "technical":
return "technical: bug reproduced"
return super().handle(request)
chain = Billing(Technical())
print(chain.handle({"topic": "technical"})) # Output: technical: bug reproduced
print(chain.handle({"topic": "billing"})) # Output: billing: invoice corrected
print(chain.handle({"topic": "general"}) is NOT_HANDLED) # Output: True
The sender calls only chain.handle, and adding a new kind of support means writing one class and inserting it into the chain where it is assembled. An unhandled request returns the sentinel NOT_HANDLED rather than a message string, so the caller can distinguish a request that nobody accepted from a valid answer and decide whether to log it, raise an error or apply a default.
A List of Functions
In Python, a chain does not require a class hierarchy: an ordered list of functions, each of which returns a result or None, expresses the same idea, and a loop replaces the recursive calls between handlers.
def billing(request):
if request["topic"] == "billing":
return "billing: invoice corrected"
def technical(request):
if request["topic"] == "technical":
return "technical: bug reproduced"
def fallback(request):
return f"general: ticket opened for {request['topic']!r}"
HANDLERS = [billing, technical, fallback]
def dispatch(request, handlers=HANDLERS):
for handler in handlers:
result = handler(request)
if result is not None:
return handler.__name__, result
raise LookupError(f"no handler for {request!r}")
print(dispatch({"topic": "technical"})) # Output: ('technical', 'technical: bug reproduced')
print(dispatch({"topic": "shipping"})) # Output: ('fallback', "general: ticket opened for 'shipping'")
The chain is now data: it can be reordered, extended or replaced in a test without defining any class, a form of the injection of collaborators described in the article devoted to dependency injection. Returning the name of the handler together with the result records which link answered, and the final LookupError makes an unhandled request impossible to overlook. A loop also avoids the recursion of the linked form, whose depth grows with the length of the chain.
Chains in Which Every Handler Acts
A variant of the pattern lets every handler do some work and then call the next one, so that the request passes through the whole chain and each link may modify it, stop it or wrap the result. Web frameworks call such handlers middleware, and the structure is the same as that of nested decorators, examined in the article devoted to decorators.
def authenticate(request, next_handler):
if not request.get("user"):
return "401 unauthorized"
return next_handler(request)
def log(request, next_handler):
response = next_handler(request)
return f"{response} [logged {request['path']}]"
def endpoint(request):
return f"200 hello {request['user']}"
def build(middlewares, endpoint):
handler = endpoint
for middleware in reversed(middlewares):
handler = (lambda m, nxt: lambda req: m(req, nxt))(middleware, handler)
return handler
app = build([log, authenticate], endpoint)
print(app({"path": "/", "user": "ada"})) # Output: 200 hello ada [logged /]
print(app({"path": "/"})) # Output: 401 unauthorized [logged /]
The middleware authenticate stops the request without calling the endpoint, while log runs for every request, since it is placed before the check. The standard library applies both variants: the finders of sys.meta_path are tried in order until one returns a module specification, as described in the article devoted to import hooks; a logging record propagates from a logger to the handlers of its parents; and an exception travels up the call stack until an except clause accepts it.
Pitfalls of the Chain of Responsibility
The pattern removes the decision from the sender and places it in the order of the chain, so most of its errors are errors of order or of signalling. Six pitfalls are distinguished, which are the following:
- A broad handler too early. A handler that accepts almost everything, placed before specific ones, prevents them from ever running.
- Silent unhandled requests. A chain that ends without any result loses the request unless the end of the chain raises an error or returns an explicit sentinel.
Noneas a valid result. WhenNonecan be a legitimate answer, it cannot also mean "not handled"; a dedicated sentinel object is needed.- Deep recursion. A long chain of linked handlers that call one another recursively consumes one stack frame per link; a loop over a list does not.
- Cycles. A handler that, through a configuration error, appears twice in a linked chain can send a request around forever.
- Invisible routing. Without a record of which handler answered, debugging a chain requires stepping through every link.
The first pitfall is reproduced in the following example.
def fallback(request):
return "general: ticket opened"
def billing(request):
if request["topic"] == "billing":
return "billing: invoice corrected"
def dispatch(request, handlers):
for handler in handlers:
result = handler(request)
if result is not None:
return result
print(dispatch({"topic": "billing"}, [fallback, billing])) # Output: general: ticket opened
print(dispatch({"topic": "billing"}, [billing, fallback])) # Output: billing: invoice corrected
Both chains contain the same handlers, and only their order differs; in the first one, the fallback answers every request before the billing handler is consulted. The order of a chain is therefore part of its logic, and it should be defined in one place and covered by tests.
Choosing How to Route a Request
Consequently, a chain fits requests whose handler depends on conditions that each handler knows best, while fixed mappings call for simpler tools, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| The handler is known from a single key | A dictionary from keys to functions |
| Each handler decides whether a request concerns it | A chain, as a list of functions tried in order |
| Every handler must act on the request | A middleware chain, each calling the next |
| Handlers are added by plug-ins or configuration | A chain assembled at the entry point of the program |
| Errors that callers higher in the stack may handle | Exceptions, the chain that Python already provides |
Conclusion
It is concluded that the Chain of Responsibility pattern delivers a request to an ordered sequence of handlers, each of which either accepts it or passes it on, and that in Python the chain is most naturally a list of functions traversed by a loop, with a sentinel or an exception for requests that nobody accepts. This magic places a decisive part of the logic in the order of the chain, which must therefore be explicit, tested and observable. Turning the request itself into an object, which can be stored, queued, logged and undone, is the purpose of the Command pattern, which is developed in a future article of this series.