Adding Behaviour Without Editing a Dispatcher: The Registry Pattern in Python

This article explains how the Registry pattern maps names to functions in Python, how a registration decorator and a registry object prevent silent errors, why registration depends on imports, and what a lookup really saves.

A green tree python folded in neat stacked coils over a branch, its head centred among them against a black background.
Photo by Mykhailo Amirdzhanian on Unsplash

A dispatcher written as a chain of if and elif statements must be edited every time a new format, command or message type appears, and it grows until nobody wants to touch it. The present article addresses the Registry pattern, in which a central mapping associates names with functions or classes, and the code that adds a behaviour registers it there instead of editing the dispatcher. Self-registering classes and plug-ins loaded through entry points were already examined for object creation; this article concentrates on registries of functions, the decorator that fills them, the errors that a registry must report clearly, and the side effects that make registries fragile in tests. Adding behaviour to a program by declaring it, without modifying the code that selects it, is the secret weapon of the Registry pattern.

A Registry Object Instead of a Bare Dictionary

A plain dictionary already maps names to handlers, but it overwrites a duplicate name silently and answers an unknown name with a bare KeyError. A small class can enforce both rules and still expose the mapping's speed: registration rejects duplicates, and lookup reports the known names and the closest match. The following example registers exporters with a decorator and selects one by name.

import difflib
import json


class Registry:
    def __init__(self, kind):
        self.kind = kind
        self._entries = {}

    def register(self, name):
        def decorator(func):
            if name in self._entries:
                raise ValueError(f"{self.kind} {name!r} is already registered")
            self._entries[name] = func
            return func
        return decorator

    def get(self, name):
        try:
            return self._entries[name]
        except KeyError:
            close = difflib.get_close_matches(name, self._entries, n=1)
            hint = f"; did you mean {close[0]!r}?" if close else ""
            raise LookupError(f"unknown {self.kind} {name!r}{hint}") from None

    def names(self):
        return sorted(self._entries)


exporters = Registry("exporter")


@exporters.register("json")
def to_json(rows):
    return json.dumps(rows)


@exporters.register("csv")
def to_csv(rows):
    return "\n".join(",".join(map(str, row)) for row in rows)


rows = [[1, 2], [3, 4]]
print(exporters.get("csv")(rows).replace("\n", " | "))  # Output: 1,2 | 3,4
print(exporters.names())                                # Output: ['csv', 'json']
try:
    exporters.get("jsno")
except LookupError as error:
    print(error)  # Output: unknown exporter 'jsno'; did you mean 'json'?
try:
    exporters.register("csv")(print)
except ValueError as error:
    print(error)  # Output: exporter 'csv' is already registered

The decorator returns the function unchanged, so to_json remains an ordinary function that can be called and tested directly. The same idea of registering one implementation per key appears in the standard library in functools.singledispatch, which keys its registry by type instead of by name, as described in the article devoted to singledispatch, and in atexit.register and codecs.register.

Registration Happens at Import Time

Many games keep a table of key bindings, in which each key is associated with an action, so that players can rebind keys and modifications can add new actions without any change to the code that reads the keyboard. This means that the dispatcher consults a table at run time, and each module that defines a behaviour adds its entry to that table when it is loaded. The analogy, however, stops at this point, because a game builds its binding table before play begins, whereas a registry is filled only as modules are imported, so an entry whose module was never imported simply does not exist. The following example builds a module in memory to show the dependency on imports, and then registers a handler temporarily, as a test would.

import sys
import types
from contextlib import contextmanager

handlers = {}


def register(name):
    def decorator(func):
        handlers[name] = func
        return func
    return decorator


sys.modules["registry"] = types.SimpleNamespace(register=register)
plugin_source = '''
from registry import register

@register("yaml")
def to_yaml(rows):
    return "- " + "\\n- ".join(map(str, rows))
'''
print("yaml" in handlers)  # Output: False
exec(compile(plugin_source, "plugin_yaml", "exec"), {})
print("yaml" in handlers)  # Output: True


@contextmanager
def temporary(name, func):
    previous = handlers.copy()
    handlers[name] = func
    try:
        yield
    finally:
        handlers.clear()
        handlers.update(previous)


with temporary("fake", lambda rows: "stub"):
    print(sorted(handlers))  # Output: ['fake', 'yaml']
print(sorted(handlers))      # Output: ['yaml']

The handler yaml appears only after the code of its module runs, which is why applications import their plug-in modules explicitly or load them through entry points, as examined in the article devoted to the Factory pattern. The context manager restores the global registry after the block, so a test that registers a fake handler cannot leak it into the tests that follow.

Pitfalls of the Registry Pattern

A registry replaces explicit code with a table that is filled elsewhere, so its pitfalls come from entries that are missing, replaced or shared without anyone noticing. Six pitfalls are distinguished, which are the following:

  1. Import-dependent entries. A handler whose module is never imported is absent, and the error appears only when its name is requested.
  2. Silent overwrites. A plain dictionary replaces an earlier handler with the same name without warning.
  3. Decorators that return nothing. A registration decorator without return func replaces the decorated name in its module with None.
  4. Global state in tests. Entries registered by one test remain for the others unless the registry is restored.
  5. Opaque errors. A bare KeyError does not tell the caller which names exist.
  6. Hidden control flow. Reading the dispatcher no longer shows which functions can run, so the registry needs a way to list its entries.

The third pitfall, and the speed argument often made for registries, are reproduced in the following example, which compares a chain of 50 conditions with a dictionary lookup.

import timeit

table = {}


def broken_register(name):
    def decorator(func):
        table[name] = func
    return decorator


@broken_register("pdf")
def to_pdf(rows):
    return b"%PDF"


print(to_pdf, table["pdf"].__name__)  # Output: None to_pdf

source = "def chain(x):\n" + "".join(
    f"    {'if' if i == 0 else 'elif'} x == 'k{i}': return {i}\n" for i in range(50)
)
namespace = {}
exec(source, namespace)
chain = namespace["chain"]
lookup = {f"k{i}": i for i in range(50)}

t_chain = min(timeit.repeat(lambda: chain("k49"), number=1_000_000, repeat=5))
t_dict = min(timeit.repeat(lambda: lookup["k49"], number=1_000_000, repeat=5))
print(t_chain > 10 * t_dict)  # Output: True

The function remains reachable through the registry, but the module-level name to_pdf became None, which breaks any direct call or test of it. On CPython 3.12, reaching the last of 50 branches took about 365 nanoseconds against 23 for the dictionary, whereas with only 5 branches the chain took between 35 and 62 nanoseconds, so the speed of the lookup matters only for long chains, and the main benefit of a registry is that the dispatcher no longer changes.

Choosing How to Select Behaviour

Consequently, a registry suits sets of interchangeable handlers that grow independently of the code that selects them, as the following table summarizes.

Situation Recommended approach
A few fixed alternatives An if chain or a match statement
Handlers selected by name and added over time A registry with a registration decorator
Classes that register themselves when defined __init_subclass__ writing to the base's registry
Implementations selected by argument type functools.singledispatch
Handlers provided by other installed packages Entry points loaded with importlib.metadata.entry_points
Tests that add or replace handlers A context manager that restores the registry

Conclusion

It is concluded that a registry maps names to functions or classes, that a registration decorator must return the decorated object and reject duplicates, and that a registry object can explain unknown names instead of raising a bare KeyError. This magic depends on imports and on global state: entries exist only after their modules run, and tests must restore what they register. Using the functions of the module operator as fast, picklable replacements for small lambdas in sorting and mapping is the subject of a future article of this series.