Sub topic 8
Writing Your First Metaclass
What this chapter assumes
This chapter assumes you know the following:
- How to define classes, methods and inheritance.
- How to call
super(). - How
**kwargsworks. - That a class is itself an object, and that
type(name, bases, namespace)builds one at runtime. - That
__init_subclass__and__set_name__run during class creation.
This chapter covers the basic mechanics of a metaclass: how to define one, attach it to a class, and see what it does. Later chapters go deeper into __init__, __call__, __prepare__ and conflicts.
A metaclass is a subclass of type
Every class is an instance of some other class, and that other class is its metaclass. For ordinary classes the metaclass is type. A custom metaclass is a subclass of type:
class Meta(type):
pass
class Widget(metaclass=Meta):
pass
print(type(Widget)) # <class '__main__.Meta'>
print(type(Widget) is Meta) # True
print(isinstance(Widget, Meta)) # True
print(isinstance(Widget(), Meta)) # FalseWidget is an instance of Meta, the same way Widget() is an instance of Widget. The last line shows that instances of Widget are not instances of Meta. A metaclass describes how a class behaves, not how its instances behave.
You choose the metaclass with the metaclass= keyword in the class line. Without it, Python uses the metaclass of the base classes, which is type unless a base says otherwise.
What the class statement calls
When Python executes a class statement, it runs the body to fill a namespace, then calls the metaclass with three arguments: the class name, a tuple of bases, and the namespace. The result of that call is bound to the class name. These two definitions are equivalent:
class Meta(type):
pass
class A(metaclass=Meta):
x = 1
B = Meta('B', (), {'x': 1})
print(type(A) is type(B)) # True
print(A.x, B.x) # 1 1Calling Meta(...) is an ordinary instance-creation call, so it follows the usual two steps. type.__call__ runs Meta.__new__ to create the class object, then Meta.__init__ to initialize it.
This order explains what each hook can do:
__new__sees the namespace before the class exists, so it can add, remove or rewrite attributes. It can also pick the bases.__init__receives a finished class and can only modify it.__set_name__and__init_subclass__run insidetype.__new__. Your metaclass__new__can therefore change the namespace before they run, but it cannot run code between class creation and those hooks.
A minimal metaclass
A metaclass that only traces creation overrides __new__ and delegates to type:
class TraceMeta(type):
def __new__(mcls, name, bases, namespace, **kwargs):
print(f'creating {name} with bases {[b.__name__ for b in bases]}')
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
print(f'created {cls!r}')
return cls
class Base(metaclass=TraceMeta):
pass
class Child(Base):
passRunning this prints:
creating Base with bases []
created <class '__main__.Base'>
creating Child with bases ['Base']
created <class '__main__.Child'>Notice that Child never names TraceMeta. It inherits the metaclass from Base, so the hook runs for the whole hierarchy.
Three conventions apply to __new__:
- The first parameter is the metaclass itself, usually named
mclsormetacls, because__new__is a static method that receives the class to instantiate. Plainclsis reserved for the class being built. - Accept
**kwargsand pass it on. Class keyword arguments reachtype.__new__, which forwards them to__init_subclass__. - Return the class. If you forget the
return, the class name is bound toNone.
A useful example: collecting fields
The next metaclass does something a plain class cannot do on its own. It scans the namespace for Field declarations, merges them with the fields of base classes, and stores the result on the new class:
class Field:
def __init__(self, kind):
self.kind = kind
class ModelMeta(type):
def __new__(mcls, name, bases, namespace, **kwargs):
fields = {}
for base in reversed(bases):
fields.update(getattr(base, '_fields', {}))
for key, value in namespace.items():
if isinstance(value, Field):
fields[key] = value
namespace['_fields'] = fields
return super().__new__(mcls, name, bases, namespace, **kwargs)
class Model(metaclass=ModelMeta):
def __init__(self, **values):
for key, value in values.items():
if key not in self._fields:
raise TypeError(f'unknown field: {key}')
expected = self._fields[key].kind
if not isinstance(value, expected):
raise TypeError(f'{key} must be {expected.__name__}')
setattr(self, key, value)
class User(Model):
name = Field(str)
age = Field(int)
class Admin(User):
level = Field(int)
print(list(Admin._fields)) # ['name', 'age', 'level']
admin = Admin(name='Ada', age=36, level=3)
print(admin.name, admin.level) # Ada 3
try:
Admin(name='Ada', age='36')
except TypeError as exc:
print(exc) # age must be intModelMeta.__new__ runs once for Model, once for User and once for Admin. Each class gets its own _fields dictionary, and a subclass starts from a copy of its parents' fields. If User and Admin shared one dictionary, adding a field to Admin would leak into User.
The namespace in __new__ is a mutable mapping, so namespace['_fields'] = fields adds an attribute to the class before it exists. A class decorator or __init_subclass__ could do the same job after creation. A metaclass is justified only when you need to act before the class exists, or to change how the class object itself behaves.
Metaclass methods belong to the class, not the instance
A method defined on a metaclass is a method of the class object. Instances of the class cannot see it:
class Meta(type):
def describe(cls):
return f'class {cls.__name__} with {len(vars(cls))} entries'
class A(metaclass=Meta):
pass
print(A.describe()) # class A with 4 entries
try:
A().describe()
except AttributeError:
print('instances cannot call it') # instances cannot call itAttribute lookup on an instance searches the instance and the classes in type(instance).__mro__. Lookup on a class searches the class and its bases first, then the metaclass. So A.describe is found on Meta, while A().describe never reaches Meta. The entry count of 4 is __module__, __dict__, __weakref__ and __doc__. The exact number can vary between Python versions, so do not rely on it.
This gives you a way to add class-level behavior, such as len(MyEnum) or for item in MyEnum, by defining __len__ or __iter__ on the metaclass. The standard library's enum module works this way.
Class keyword arguments with a metaclass
Keyword arguments in the class line go to the metaclass in three places: __prepare__, __new__ and __init__. Your __new__ can consume the ones it understands and forward the rest. __init__ must accept the same arguments, even if it ignores them:
class TagMeta(type):
def __new__(mcls, name, bases, namespace, *, tag=None, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
cls.tag = tag
return cls
def __init__(cls, name, bases, namespace, *, tag=None, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
class Job(metaclass=TagMeta, tag='batch'):
pass
print(Job.tag) # batchIf __init__ took only (cls, name, bases, namespace), the class line above would fail with a TypeError about an unexpected keyword argument. Also note that tag is not forwarded to type.__new__. Unconsumed keywords reach __init_subclass__ on the parent, and object.__init_subclass__ rejects any keyword it receives.
Metaclass inheritance
A subclass keeps its parent's metaclass unless you choose a more specific one:
class Meta(type):
pass
class Base(metaclass=Meta):
pass
class Child(Base):
pass
print(type(Child) is Meta) # True
print(Child.__mro__[1] is Base) # True
print(type(Child).__mro__) # (<class '__main__.Meta'>, <class 'type'>, <class 'object'>)Two separate inheritance chains exist here. Child inherits from Base, and type(Child), which is Meta, inherits from type. Do not mix them up. Mixing metaclasses from different bases is the source of metaclass conflicts, which a later chapter covers.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Class name is `None` after the class statement | `__new__` did not return the class | End `__new__` with `return cls` |
| `TypeError: ... got an unexpected keyword argument` | `__init__` or `__new__` does not accept class keyword arguments | Add `**kwargs` to both and forward the rest |
| `TypeError` from `object.__init_subclass__` | A keyword argument reached `type.__new__` but no parent consumes it | Consume it in your metaclass or remove it |
| `AttributeError` on an instance for a metaclass method | Metaclass methods are visible only on the class | Call it on the class, or put the method on the class itself |
| Subclasses share mutable state | One dictionary stored on a base class and mutated by every subclass | Create a new container per class in `__new__` |
| Infinite recursion in `__new__` | Calling `cls(...)` or `type(...)` instead of `super().__new__` | Use `super().__new__(mcls, ...)` |
When a metaclass is the right tool
A metaclass is worth writing when you need one of these:
- To change the namespace or the bases before the class is created.
- To give the class object its own operators or iteration, such as
len(Cls). - To control instance creation for the whole hierarchy through
__call__.
If you only need to register or validate subclasses, __init_subclass__ is shorter and avoids metaclass conflicts. If you need to modify a single class after it exists, a class decorator is enough. The final chapter compares the three tools in detail.
Exercise
Write a metaclass RequireRun whose __new__ raises TypeError if the class namespace does not define a callable named run, except for the class named Base. Then explain why a subclass of a class created with RequireRun is also checked.
Show answer
Define class RequireRun(type) with __new__(mcls, name, bases, namespace, **kwargs). Inside, check if name != 'Base' and not callable(namespace.get('run')) and raise TypeError(f'{name} must define run'). Otherwise return super().__new__(mcls, name, bases, namespace, **kwargs). Create class Base(metaclass=RequireRun) with no run; it passes because of the name exception. A subclass such as class Task(Base) is also checked because it inherits RequireRun as its metaclass, so RequireRun.__new__ runs for every class created beneath Base. Note that namespace.get('run') checks only the class's own body, so a subclass that inherits run from a parent but does not redefine it would still be rejected.
Exercise
In the ModelMeta example, what would go wrong if fields = {} were replaced by fields = getattr(bases[0], '_fields', {}) without copying, for a class with a base that has _fields?
Show answer
The new class would use the same dictionary object as its base. Adding level to Admin would also add it to User._fields and Model._fields, so unrelated subclasses would see each other's fields. Copying the base fields into a new dictionary, as the example does, gives every class its own _fields.