Sub topic 8
Writing your first metaclass
This chapter assumes you know how to define classes and inheritance, call super(), use decorators, and pass **kwargs. It also assumes you have seen that type(name, bases, namespace) builds a class. Here you will write a metaclass that hooks into that step.
What a metaclass is
Every class is an instance of some other class. For ordinary classes that other class is type. A metaclass is a class whose instances are classes. In practice it is a subclass of type.
When Python runs a class statement, it works out the metaclass, runs the body to collect a namespace, and then calls the metaclass with the class name, the tuple of bases and the namespace. Your metaclass can change what happens in that call.
A registering metaclass
The simplest useful metaclass overrides __new__ and records each class it creates.
class RegistryMeta(type):
registry = {}
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
mcls.registry[name] = cls
return cls
class Base(metaclass=RegistryMeta):
pass
class Child(Base):
pass
print(sorted(RegistryMeta.registry)) # ['Base', 'Child']
print(type(Child) is RegistryMeta) # TrueThree points explain this code:
__new__on a metaclass is called with the metaclass itself as the first argument. The convention is to name itmcls, to separate it fromcls, the class being built.super().__new__does the real work of creating the class. Your code runs before or after it.Childnever mentions the metaclass. A class inherits its parent's metaclass, soChildis also an instance ofRegistryMeta. This is why a metaclass affects a whole hierarchy.
`__new__` versus `__init__`
__new__ creates the class object, and __init__ receives the finished class. Use __new__ when you need to change the name, bases or namespace before the class exists. Use __init__ when you only need to inspect or validate the result.
class RequireDoc(type):
def __init__(cls, name, bases, namespace, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
if bases and not cls.__doc__:
raise TypeError(f'{name} needs a docstring')
class Base(metaclass=RequireDoc):
pass
class Good(Base):
"""Has documentation."""
try:
class Bad(Base):
pass
except TypeError as exc:
print(exc) # Bad needs a docstringThe bases check skips Base itself. Base has no parents, so the rule applies only to its subclasses. Without that check, the metaclass would reject the class that introduces it.
Changing what calling the class does
Instances of a metaclass are classes, so __call__ on the metaclass runs when you call a class, as in Config(). This is a different step from class creation. It runs every time you create an instance.
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in Singleton._instances:
Singleton._instances[cls] = super().__call__(*args, **kwargs)
return Singleton._instances[cls]
class Config(metaclass=Singleton):
pass
print(Config() is Config()) # TrueThe default type.__call__ runs the class's __new__ and then __init__. Here the metaclass calls it only the first time.
Common mistakes
- Forgetting to return the class from
__new__. The class name is then bound toNone. - Skipping
super(). The class is not built, or the hooks of other bases never run. - Dropping `kwargs
.** Class keyword arguments, such asclass A(Base, flag=True), reach both_newandinit_. If you do not forward them,typeraises aTypeError`. - Using
selfas the first argument name in__new__. It still works, but it hides whether you hold the metaclass or the class.
Exercise
A metaclass defines __init__ that raises TypeError when a class has no run method. Defining Base(metaclass=Meta) itself fails with this error. What change fixes it, and why does it work?
Show answer
Skip the check when the class has no bases, as in if bases and not hasattr(cls, 'run'). Base has an empty bases tuple, so it is exempt. Its subclasses have bases, so the rule applies to them.
Exercise
You write class Child(Base), where Base uses metaclass=RegistryMeta. You do not set a metaclass on Child. What is type(Child), and why?
Show answer
RegistryMeta. Python picks the most derived metaclass among the bases, so Child inherits the metaclass of Base.