Hooks in Python

Let other code run at a named point in yours, without your code knowing who is listening.

Python hooks are named points in a program where other code can plug in. Your code announces "an order was created"; any function registered for that name runs. Python has no hook keyword, and it does not need one: a dict of lists does the job.

The short answer

from collections import defaultdict

hooks = defaultdict(list)


def hook(event):
    def decorator(func):
        hooks[event].append(func)
        return func
    return decorator


def trigger(event, *args):
    for func in hooks[event]:
        func(*args)


@hook("order.created")
def send_receipt(order):
    print(f"receipt for order {order['id']}")


@hook("order.created")
def update_stock(order):
    print(f"stock updated for {order['item']}")


trigger("order.created", {"id": 1, "item": "lamp"})
# stock updated for lamp

That is the whole idea. hooks maps an event name to the functions that want to hear about it. The hook decorator adds a function to the list and hands it back unchanged, so it still works as a normal function. trigger calls each one in turn.

The code that calls trigger never imports send_receipt or update_stock. That is the point: you can add a third behaviour without touching the checkout code.

Controlling the order with priorities

Hooks run in the order they were registered, which usually means the order your modules were imported. Once that matters, store a priority next to each function and sort:

hooks = defaultdict(list)


def hook(event, priority=50):
    def decorator(func):
        hooks[event].append((priority, func))
        hooks[event].sort(key=lambda pair: pair[0], reverse=True)
        return func
    return decorator


@hook("page.render", priority=10)
def add_footer(page):
    print("footer")


@hook("page.render", priority=100)
def add_header(page):
    print("header")


for priority, func in hooks["page.render"]:
    func({})
# header
# footer

Python's sort is stable, so two hooks with the same priority keep their registration order.

Letting hooks modify data

So far hooks only react. The other common kind is a filter: each hook receives a value, returns a new one, and the next hook gets the result. WordPress calls these filters; the pattern is the same everywhere.

def apply(event, data):
    for priority, func in hooks[event]:
        data = func(data)
    return data


@hook("post.save", priority=100)
def add_slug(post):
    post["slug"] = post["title"].lower().replace(" ", "-")
    return post


@hook("post.save", priority=10)
def add_url(post):
    post["url"] = f"/blog/{post['slug']}"
    return post


apply("post.save", {"title": "Hello World"})
# {'title': 'Hello World', 'slug': 'hello-world', 'url': '/blog/hello-world'}

The catch is that a hook which forgets to return passes None to the next one. That is the most common bug in a hand-rolled filter chain.

From hooks to a Python plugin system

A plugin system is hooks plus the housekeeping around them. The registry above is about twenty lines. What takes the time is everything else:

  • Discovery: finding plugin files or installed packages and importing them.
  • Error isolation: one broken plugin should not take the app down.
  • Dependencies: loading plugin B after the plugin A it relies on.
  • Turning plugins off without deleting them.
  • Async hooks and timeouts for slow ones.

If you are choosing a Python plugin framework for a tool other people will extend, look at pluggy first. It is what pytest uses for its own plugins. In a pluggy-style plugin architecture you declare hook specifications up front, and plugins are checked against them, which suits a large project with third-party plugin authors. It is more ceremony than a small app needs.

The shorter way with Nitro Dispatch

Nitro Dispatch is the registry above with the housekeeping done. A plugin is a class, and @hook marks its methods:

from nitro_dispatch import PluginManager, PluginBase, hook as on


class SlugPlugin(PluginBase):
    name = "slug"

    @on("post.save", priority=100)
    def add_slug(self, data):
        data["slug"] = data["title"].lower().replace(" ", "-")
        return data


class AuditPlugin(PluginBase):
    name = "audit"

    @on("post.*", priority=10)
    def log(self, data):
        print(f"saved {data['slug']}")
        return data


manager = PluginManager()
manager.register(SlugPlugin)
manager.register(AuditPlugin)
manager.load_all()

manager.trigger("post.save", {"title": "Hello World"})
# saved hello-world
# {'title': 'Hello World', 'slug': 'hello-world'}

The import is renamed to on here only because this page already defined its own hook. In your code, import hook as it is.

Higher priorities run first, post.* matches every event in that namespace, and a hook that raises is logged and skipped instead of stopping the chain. You can also register a plain function with manager.register_hook("post.save", func) and skip the class.

It has no dependencies. For a single script with two callbacks, the dict of lists is still the right size. Reach for the library when plugins come from other files or other people.

Common questions

Is a hook the same as a callback? A callback is one function you pass to one call. A hook is a named place where any number of callbacks can be registered, usually by code the caller has never seen.

What about Git hooks or pre-commit hooks? Different thing with the same name. Those are scripts Git runs at points like commit or push. This page is about hooks inside a Python program.

How do I unregister a hook? Remove it from the list: hooks[event].remove(func) in the first version. Keep a reference to the function when you register it, since you need the same object to find it again.

This page uses Nitro Dispatch.

Add plugins to any Python app. Async-ready hooks with priorities and error isolation built in.

$ pip install nitro-dispatch