BehavioralPythonverifiedVerified

Chain of Responsibility Pattern in Python

Passes a request along a chain of handlers, where each handler decides to process it or pass it to the next handler in the chain.

How to Implement the Chain of Responsibility Pattern in Python

1Step 1: Define the request type and abstract handler

from __future__ import annotations
from dataclasses import dataclass
from typing import Any


@dataclass
class Request:
    type: str
    payload: Any


class Handler:
    def __init__(self) -> None:
        self._next: Handler | None = None

    def set_next(self, handler: Handler) -> Handler:
        self._next = handler
        return handler

    def handle(self, request: Request) -> str | None:
        if self._next:
            return self._next.handle(request)
        return None

2Step 2: Implement concrete handlers

class AuthHandler(Handler):
    def handle(self, request: Request) -> str | None:
        if request.type == "auth":
            return "Handled by AuthHandler"
        return super().handle(request)


class ValidationHandler(Handler):
    def handle(self, request: Request) -> str | None:
        if request.type == "validate":
            return "Handled by ValidationHandler"
        return super().handle(request)


class LoggingHandler(Handler):
    def handle(self, request: Request) -> str | None:
        print(f"Logging: {request.type}")
        return super().handle(request)

3Step 3: Build the chain and process requests

auth = AuthHandler()
validation = ValidationHandler()
logging_handler = LoggingHandler()

logging_handler.set_next(auth).set_next(validation)

logging_handler.handle(Request("auth", {}))
logging_handler.handle(Request("validate", {}))

Chain of Responsibility Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Chain of Responsibility Pattern in the Real World

Like a customer support escalation: your call starts with a front-line agent. If they can’t resolve it, they transfer you to a specialist. If the specialist can’t help, it goes to a manager. Each level either handles it or passes it up the chain.