Skip to content

python 2 min read

TIL - what metaclasses can do that nothing else can

Classes are objects made by metaclasses. Here are the few jobs only a metaclass can do, including controlling the class body itself with __prepare__.

A class is an object, and the thing that builds it is its metaclass (usually type). Most metaclass tricks are better done with __init_subclass__ or class decorators. A few jobs still need one.

Here’s the lifecycle. When Python runs a class statement, it:

  1. calls Meta.__prepare__(name, bases) to get the namespace the class body executes in
  2. runs the class body inside that namespace
  3. calls Meta.__new__(meta, name, bases, namespace) to build the class

Job 1: control the class body. Only a metaclass can hook step 1. For example, it can catch an accidental method redefinition:

class NoDupes(dict):
    def __setitem__(self, key, value):
        if key in self and not key.startswith("__"):
            raise TypeError(f"{key!r} defined twice")
        super().__setitem__(key, value)

class StrictMeta(type):
    @classmethod
    def __prepare__(mcls, name, bases):
        return NoDupes()

    def __new__(mcls, name, bases, ns):
        return super().__new__(mcls, name, bases, dict(ns))

try:
    class Service(metaclass=StrictMeta):
        def handle(self): ...
        def handle(self): ...      # copy-paste bug
except TypeError as e:
    print(e)                       # 'handle' defined twice
python

Job 2: give the class itself operators. Methods on the metaclass become methods on the class. That’s how Enum lets you write len(Color) and for c in Color:

class Registry(type):
    def __iter__(cls):
        return iter(cls._items)
    def __len__(cls):
        return len(cls._items)

class Colors(metaclass=Registry):
    _items = ["red", "green"]

print(len(Colors), list(Colors))   # 2 ['red', 'green']
python

Gotcha: a class can only have one metaclass lineage, so mixing two libraries’ metaclasses raises a “metaclass conflict” error. That’s the main reason to avoid them when you can.

Takeaway: reach for a metaclass only when you need __prepare__ or class-level dunder methods. For everything else, use __init_subclass__ or a decorator.