ZetCode

Python metaclasses

last modified November 30, 2026 Python 3.15

In this article we show how metaclasses work in Python and how to write our own.

In Python, classes are objects. Just as an object is an instance of a class, a class is an instance of a metaclass. The default metaclass is type; the type builtin function article shows how type creates classes directly. A custom metaclass is a subclass of type that changes how classes are created and how they behave.

Metaclasses are a powerful but rarely needed tool. Most tasks that once required them, such as registering or validating subclasses, are now simpler with the __init_subclass__ hook or with class decorators. Metaclasses remain useful when we need to control the class namespace, instance creation, or operations on the class itself. The standard library uses them in the abc and enum modules.

Classes are objects

A class can be assigned to a variable, passed to a function, and changed at run time, like any other object.

classes_are_objects.py
class Greeter:
    greeting = 'Hello there'

    def greet(self, name):
        return f'{self.greeting}, {name}!'


def build(cls):
    return cls()


Alias = Greeter
obj = build(Alias)
print(obj.greet('Ada'))

Greeter.greeting = 'Good morning'
print(obj.greet('Ada'))

print(type(obj), type(Greeter))
print(isinstance(Greeter, type))

The program treats the Greeter class as a value.

Alias = Greeter
obj = build(Alias)

The build function receives a class and calls it to create an instance.

Greeter.greeting = 'Good morning'

Changing a class attribute changes the class object; existing instances see the new value.

print(type(obj), type(Greeter))

The type of the instance is Greeter, and the type of Greeter is type, its metaclass.

$ python classes_are_objects.py
Hello there, Ada!
Good morning, Ada!
<class '__main__.Greeter'> <class 'type'>
True

What the class statement does

A class statement runs the class body, collects the names it defines in a namespace dictionary, and then calls the metaclass with the name, the bases, and the namespace. A metaclass that prints its arguments shows this.

tracing.py
class Tracing(type):
    def __new__(mcls, name, bases, namespace):
        print('metaclass:', mcls.__name__)
        print('name:', name)
        print('bases:', bases)
        print('namespace:', list(namespace))
        return super().__new__(mcls, name, bases, namespace)


print('before the class statement')


class Account(metaclass=Tracing):
    rate = 0.02

    def deposit(self, amount):
        pass


print('after the class statement')
print(type(Account))

The Tracing metaclass overrides __new__, which creates the class object.

class Tracing(type):
    def __new__(mcls, name, bases, namespace):
        ...
        return super().__new__(mcls, name, bases, namespace)

The first parameter is the metaclass itself, by convention called mcls. After printing, the method lets type create the class.

class Account(metaclass=Tracing):

The metaclass keyword selects the metaclass. The output appears when the class statement runs, before any instance exists. The namespace contains the attribute and the method from the body, plus entries that Python adds, such as __module__ and __qualname__.

$ python tracing.py
before the class statement
metaclass: Tracing
name: Account
bases: ()
namespace: ['__module__', '__qualname__', '__firstlineno__', 'rate', 'deposit', '__static_attributes__', '__classdictcell__']
after the class statement
<class '__main__.Tracing'>

Checking classes at definition time

Since the metaclass sees every class body, it can reject classes that break a rule. The error then appears when the class is defined, not when it is first used.

require_docs.py
class Documented(type):
    def __new__(mcls, name, bases, namespace):
        for attr, value in namespace.items():
            if callable(value) and not attr.startswith('_'):
                if not value.__doc__:
                    raise TypeError(f'{name}.{attr} has no docstring')
        return super().__new__(mcls, name, bases, namespace)


class Service(metaclass=Documented):
    def start(self):
        """Start the service."""

    def _helper(self):
        pass


print('Service created')

try:
    class Broken(Service):
        def stop(self):
            pass
except TypeError as e:
    print('error:', e)

The Documented metaclass requires a docstring for every public method.

for attr, value in namespace.items():
    if callable(value) and not attr.startswith('_'):
        if not value.__doc__:
            raise TypeError(f'{name}.{attr} has no docstring')

We check the callable entries of the namespace whose names do not start with an underscore. A function without a docstring has None as __doc__.

class Broken(Service):
    def stop(self):
        pass

The metaclass is inherited: Broken derives from Service, so it is created by Documented too, and its definition fails.

$ python require_docs.py
Service created
error: Broken.stop has no docstring

The metaclass __init__ method

The __init__ method of a metaclass runs after the class has been created. It receives the finished class as its first argument and suits tasks that do not change the namespace, such as registering classes.

registry.py
class PluginMeta(type):
    def __init__(cls, name, bases, namespace):
        super().__init__(name, bases, namespace)
        if not hasattr(cls, 'plugins'):
            cls.plugins = {}
        else:
            cls.plugins[name.lower()] = cls


class Exporter(metaclass=PluginMeta):
    def export(self, data):
        raise NotImplementedError


class CSV(Exporter):
    def export(self, data):
        return ','.join(data)


class TSV(Exporter):
    def export(self, data):
        return '\t'.join(data)


print(Exporter.plugins)

for key, plugin in Exporter.plugins.items():
    print(key, repr(plugin().export(['a', 'b', 'c'])))

The PluginMeta metaclass collects all subclasses of Exporter in a dictionary.

def __init__(cls, name, bases, namespace):
    super().__init__(name, bases, namespace)
    if not hasattr(cls, 'plugins'):
        cls.plugins = {}
    else:
        cls.plugins[name.lower()] = cls

The first parameter is the new class, by convention called cls. When the base class Exporter is created, it has no plugins attribute yet, so we create the dictionary. The subclasses inherit the attribute, and each of them adds itself to the shared dictionary.

for key, plugin in Exporter.plugins.items():
    print(key, repr(plugin().export(['a', 'b', 'c'])))

The program can find all exporters without listing them by hand. The same registry is shorter with __init_subclass__, which is the recommended way for this task.

$ python registry.py
{'csv': <class '__main__.CSV'>, 'tsv': <class '__main__.TSV'>}
csv 'a,b,c'
tsv 'a\tb\tc'

Inheritance and metaclass conflicts

A class gets the metaclass of its bases. When the bases have different metaclasses, Python needs a metaclass that is a subclass of all of them.

conflict.py
class MetaA(type):
    pass


class MetaB(type):
    pass


class A(metaclass=MetaA):
    pass


class B(metaclass=MetaB):
    pass


class Child(A):
    pass


print(type(Child))

try:
    class Both(A, B):
        pass
except TypeError as e:
    print('error:', e)


class MetaAB(MetaA, MetaB):
    pass


class Both(A, B, metaclass=MetaAB):
    pass


print(type(Both))

Classes A and B have unrelated metaclasses.

class Child(A):
    pass

The Child class has no metaclass keyword, but it is created by MetaA, the metaclass of its base.

class Both(A, B):
    pass

For Both, neither MetaA nor MetaB is a subclass of the other, so Python cannot choose and raises a TypeError.

class MetaAB(MetaA, MetaB):
    pass


class Both(A, B, metaclass=MetaAB):

A metaclass derived from both resolves the conflict. This problem is a common reason to avoid metaclasses in libraries: a class that combines two libraries can run into it. It shows up, for instance, when mixing ABC with a class that has another metaclass.

$ python conflict.py
<class '__main__.MetaA'>
error: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
<class '__main__.MetaAB'>

The __prepare__ method

Before the class body runs, Python calls the __prepare__ method of the metaclass to get the namespace object. A custom mapping lets the metaclass watch every assignment in the body.

prepare.py
class NoDuplicates(dict):
    def __setitem__(self, key, value):
        if key in self:
            raise TypeError(f'{key!r} is defined twice')
        super().__setitem__(key, value)


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

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


try:
    class Report(metaclass=StrictMeta):
        def total(self):
            return 10

        def average(self):
            return 2

        def total(self):
            return 20
except TypeError as e:
    print('error:', e)

A method defined twice in a class body silently replaces the first definition. The StrictMeta metaclass turns this into an error.

class NoDuplicates(dict):
    def __setitem__(self, key, value):
        if key in self:
            raise TypeError(f'{key!r} is defined twice')
        super().__setitem__(key, value)

Each definition in the class body is stored with __setitem__, including the special names that Python adds, such as __module__. A name that is already present was defined before.

@classmethod
def __prepare__(mcls, name, bases):
    return NoDuplicates()

The __prepare__ method is a class method of the metaclass. It returns the object in which the body stores its names.

return super().__new__(mcls, name, bases, dict(namespace))

We convert the namespace to a plain dictionary before creating the class, so that the class does not keep the special mapping.

$ python prepare.py
error: 'total' is defined twice

The metaclass __call__ method

Creating an instance with Range(1, 5) calls the class. Since the class is an instance of its metaclass, this call runs the __call__ method of the metaclass, which in turn runs __new__ and __init__ of the class.

call.py
class Validated(type):
    def __call__(cls, *args, **kwargs):
        obj = super().__call__(*args, **kwargs)
        obj.validate()
        return obj


class Range(metaclass=Validated):
    def __init__(self, low, high):
        self.low = low
        self.high = high

    def validate(self):
        if self.low > self.high:
            raise ValueError(f'invalid range {self.low}..{self.high}')


class Percent(Range):
    def __init__(self, value):
        super().__init__(value, 100)


def create(cls, *args):
    try:
        print(vars(cls(*args)))
    except ValueError as e:
        print('error:', e)


create(Range, 1, 5)
create(Percent, 40)
create(Range, 5, 1)
create(Percent, 120)

The Validated metaclass checks every object after its __init__ has finished.

def __call__(cls, *args, **kwargs):
    obj = super().__call__(*args, **kwargs)
    obj.validate()
    return obj

The call to super().__call__ creates and initializes the object as usual. Then we call its validate method.

class Percent(Range):
    def __init__(self, value):
        super().__init__(value, 100)

Calling validate at the end of Range.__init__ would run it before a subclass has finished its own initialization. The metaclass runs it once, after the whole chain of __init__ methods. Controlling object creation from inside the class, for example for singletons, is shown in Python __new__.

$ python call.py
{'low': 1, 'high': 5}
{'low': 40, 'high': 100}
error: invalid range 5..1
error: invalid range 120..100

Methods on the metaclass

Methods defined in a metaclass are methods of the class object. Special methods there define operations on the class itself, such as iteration or len. This is how the members of an Enum class can be iterated.

class_methods.py
class Constants(type):
    def __iter__(cls):
        for name, value in vars(cls).items():
            if name.isupper():
                yield name, value

    def __len__(cls):
        return len(list(iter(cls)))

    def __contains__(cls, value):
        for name, val in cls:
            if val == value:
                return True
        return False


class Color(metaclass=Constants):
    RED = '#ff0000'
    GREEN = '#00ff00'
    BLUE = '#0000ff'


print(len(Color))

for name, value in Color:
    print(name, value)

print('#00ff00' in Color, '#123456' in Color)

try:
    len(Color())
except TypeError as e:
    print('error:', e)

The Constants metaclass makes classes with upper-case attributes behave like collections of constants.

def __iter__(cls):
    for name, value in vars(cls).items():
        if name.isupper():
            yield name, value

The vars function returns the namespace of the class. The method yields the names and values of the constants, so that for name, value in Color works on the class.

print(len(Color))
...
print('#00ff00' in Color, '#123456' in Color)

The len function and the in operator call __len__ and __contains__ of the metaclass.

len(Color())

The methods belong to the class, not to its instances. An instance of Color has no length.

$ python class_methods.py
3
RED #ff0000
GREEN #00ff00
BLUE #0000ff
True False
error: object of type 'Color' has no len()

Source

Metaclasses, Customizing class creation, PEP 3115 – Metaclasses in Python 3000

In this article we have treated classes as objects, traced what a class statement does, and written metaclasses that check classes at definition time, register subclasses, watch the class body with __prepare__, run code after instance creation with __call__, and add operations to the class itself. We have also resolved a metaclass conflict. See also Python type builtin function, Python __init_subclass__, Python __new__, and Python abstract classes.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.