Who Creates Python Classes? The Magic of Metaclasses
This article explains how Python creates classes through metaclasses, describes the steps of a class statement, and compares custom metaclasses with __init_subclass__, class decorators and abstract base classes.
The present article addresses metaclasses, the mechanism that Python uses to create classes and, therefore, the point at which the behaviour of a whole family of classes can be defined in a single place. The starting question is simple: if a class creates its instances, some other object must create the class. Strategy games offer a precise image of this hierarchy, since soldiers are trained in a barracks, while the barracks itself is raised by a worker who follows a construction manual. This means that a metaclass occupies the position of that worker: it builds the class, and any rule it applies during construction reaches every class it builds and, through them, every instance. The analogy, however, stops at this point, because a worker leaves once the building is finished, whereas a metaclass remains the type of the class for its entire life and keeps intervening in operations such as instantiation.
Classes Are Objects Too
Every value in Python is an object, and classes are no exception: a class can be stored in a variable, passed to a function and inspected at runtime. Its type reveals which object created it, as the following example shows.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof"
print(type(Dog("Rex"))) # Output: <class '__main__.Dog'>
print(type(Dog)) # Output: <class 'type'>
print(isinstance(Dog, type)) # Output: True
print(type(type)) # Output: <class 'type'>
The instance Dog("Rex") has Dog as its type, and Dog has type as its type. Consequently, type is the default metaclass of Python, that is, the class whose instances are classes. The last line closes the chain: type is its own type, which prevents an infinite regress of metaclasses.
Creating a Class Without the class Statement
The present section shows that type can build a class directly when it is called with three arguments: the name of the class, a tuple of base classes and a dictionary that becomes its namespace. The following code produces a class equivalent to Dog without the class statement.
def bark(self):
return f"{self.name} says woof"
def init(self, name):
self.name = name
Dog = type("Dog", (), {"__init__": init, "bark": bark})
buddy = Dog("Buddy")
print(buddy.bark()) # Output: Buddy says woof
print(type(buddy).__name__) # Output: Dog
The result behaves exactly like the class defined with the statement. It would be inaccurate, nevertheless, to describe the class statement as a mere abbreviation of this call, because the statement performs several additional steps before type is invoked, which are described in the following section.
Build Order: What Happens When a class Statement Runs
Python executes a class statement in a fixed sequence of five steps, which are the following:
- Metaclass resolution. The metaclass is taken from the
metaclass=keyword or, in its absence, from the bases;typeis used when neither provides one. - Namespace preparation. The method
__prepare__of the metaclass returns the mapping in which the body of the class will be executed; by default, an ordinary dictionary. - Body execution. The body of the class runs as ordinary code, and every assignment is stored in that namespace.
- Class creation. The metaclass is called with the name, the bases and the namespace, which runs its
__new__method; insidetype.__new__, the attributes that define__set_name__are notified, and the__init_subclass__hook of the parent class is called. - Initialization. The
__init__method of the metaclass completes the new class.
A metaclass that prints a message at each step makes the sequence visible.
class Tracer(type):
@classmethod
def __prepare__(mcs, name, bases):
print(f"1. __prepare__ for {name}")
return {}
def __new__(mcs, name, bases, namespace):
public = [key for key in namespace if not key.startswith("__")]
print(f"3. __new__ receives {public}")
return super().__new__(mcs, name, bases, namespace)
def __init__(cls, name, bases, namespace):
print("5. __init__ completes the class")
super().__init__(name, bases, namespace)
class Field:
def __set_name__(self, owner, name):
print(f"4. __set_name__ binds {name!r}")
class Model(metaclass=Tracer):
print("2. the body executes")
title = Field()
# Output: 1. __prepare__ for Model
# Output: 2. the body executes
# Output: 3. __new__ receives ['title']
# Output: 4. __set_name__ binds 'title'
# Output: 5. __init__ completes the class
The output corroborates that the body of the class runs before the metaclass sees it, which is why __new__ receives a complete namespace that it can inspect, modify or reject. Furthermore, the hook __set_name__ runs inside the creation of the class, so a descriptor learns the name of the attribute to which it was assigned without any additional code.
Writing a Custom Metaclass
A custom metaclass is a subclass of type that overrides one or more of the steps described above. The most frequent use in practice is the automatic registration of classes, combined with a validation of their contents; the following metaclass registers every plugin and refuses any plugin that does not define a run method.
class PluginMeta(type):
registry = {}
def __new__(mcs, name, bases, namespace):
cls = super().__new__(mcs, name, bases, namespace)
if bases: # The base class itself is not registered.
if not callable(namespace.get("run")):
raise TypeError(f"{name} must define run()")
mcs.registry[name.lower()] = cls
return cls
class Plugin(metaclass=PluginMeta):
pass
class Export(Plugin):
def run(self):
return "exporting"
print(PluginMeta.registry) # Output: {'export': <class '__main__.Export'>}
try:
class Broken(Plugin):
pass
except TypeError as error:
print(error) # Output: Broken must define run()
The class Export is registered at the moment in which its definition is executed, without any explicit call, and the class Broken never comes into existence, because the error is raised while it is being built. This is the principle that frameworks such as the Django ORM apply on a larger scale, where the metaclass of the models converts the fields declared in the class into the description of a database table.
A metaclass can also control what happens when a class is called to create an instance, since that call is resolved by the method __call__ of the metaclass. The following example uses it to guarantee a single instance per class.
class SingleInstance(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Settings(metaclass=SingleInstance):
def __init__(self):
print("Settings initialized")
first = Settings() # Output: Settings initialized
second = Settings() # No output: the stored instance is returned.
print(first is second) # Output: True
The method __init__ of Settings runs only once, because the second call never reaches type.__call__. This example also shows the reach of a metaclass: the behaviour of the expression Settings() changes without any modification of the class itself.
Simpler Alternatives to a Metaclass
This section presents the tools that solve most of the problems for which a metaclass would otherwise be written, and that are preferable because they are easier to read and to combine. Since Python 3.6, as established in PEP 487, the hook __init_subclass__ is called on the parent class every time a subclass is created, which covers registration and validation without any metaclass.
class Plugin:
registry = {}
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not callable(getattr(cls, "run", None)):
raise TypeError(f"{cls.__name__} must define run()")
Plugin.registry[cls.__name__.lower()] = cls
class Export(Plugin):
def run(self):
return "exporting"
print(Plugin.registry) # Output: {'export': <class '__main__.Export'>}
The result is identical to that of PluginMeta, with a shorter definition and with no metaclass that could conflict with others. Two further alternatives complete the picture. On the one hand, a class decorator receives the finished class and can register or modify it, following the same principle that was examined in the article devoted to decorators, with the difference that it applies only to the decorated class and not to its subclasses. On the other hand, the requirement that a subclass implement certain methods is already solved by abc.ABC and @abstractmethod, which refuse to instantiate any class that leaves an abstract method undefined; the module abc is itself built on a metaclass, ABCMeta.
Pitfalls of Metaclasses
Metaclasses impose costs that do not appear in short examples, and four of them deserve particular attention, which are the following:
- Metaclass conflicts. A class whose bases have unrelated metaclasses cannot be created, because Python cannot decide which metaclass should build it. This situation arises, for example, when a class combines
abc.ABCwith a base that uses a custom metaclass. - Inheritance of the metaclass. Every subclass is built by the metaclass of its parent, so its logic runs for classes that may be defined in other modules or by other developers.
- Debugging. Errors raised during the creation of a class appear when a module is imported, often far from the code that caused them.
- Annotations in Python 3.14. With the deferred evaluation of annotations introduced by PEP 649 and PEP 749, a metaclass that inspects annotations while the class is being built should not read
__annotations__from the namespace; the documented route isannotationlib.get_annotate_from_class_namespace.
The first pitfall is reproduced in the following example.
class MetaA(type):
pass
class MetaB(type):
pass
class A(metaclass=MetaA):
pass
class B(metaclass=MetaB):
pass
try:
class C(A, B):
pass
except TypeError as error:
print(error)
# Output: metaclass conflict: the metaclass of a derived class must be
# a (non-strict) subclass of the metaclasses of all its bases
The conflict is resolved only by defining a metaclass that inherits from both MetaA and MetaB, a solution that requires both metaclasses to cooperate through super(). This cost grows with each library that introduces its own metaclass, which is one of the reasons why __init_subclass__ is preferred whenever it suffices.
When to Use a Metaclass
Consequently, the decision should begin with the simplest tool that solves the problem and reach a metaclass only when the others are insufficient. The criteria are summarized in the following table.
| Need | Recommended tool |
|---|---|
| Modify or register one specific class | Class decorator |
| Register or validate every subclass of a base | __init_subclass__ |
| Require subclasses to implement certain methods | abc.ABC with @abstractmethod |
| Let an attribute know its own name | __set_name__ on a descriptor |
| Customize the namespace in which the class body runs | Metaclass with __prepare__ |
| Control the call that creates instances | Metaclass with __call__ |
| Build a declarative framework, such as an ORM | Metaclass |
It follows from the table that most of the classic uses of metaclasses have a simpler replacement since Python 3.6, and that the metaclass remains the appropriate tool for the namespace, for instantiation and for frameworks that redefine what a class means.
Conclusion
It is concluded that a metaclass is the object that builds a class, that type fulfils this role by default, and that a custom metaclass can intervene in every step of the creation of a class and in the instantiation of its objects. This secret weapon explains how frameworks transform simple class declarations into database models or plugin registries. Its magic, however, is best used sparingly: Tim Peters described metaclasses as "deeper magic than 99% of users should ever worry about", and the existence of __init_subclass__, class decorators and abstract base classes confirms that judgement for everyday code. The descriptor protocol, which __set_name__ has briefly introduced here, is the natural next step to understand how attributes themselves acquire their behaviour, and it is developed in a future article of this series.