Sub topic 9
Overriding __new__, __init__ and __call__ on a metaclass
This chapter assumes you can write a basic metaclass (a subclass of type passed with metaclass=) and that you know how super() and **kwargs work. Here you will see what each of the three methods does, when it runs, and which one fits which job.
Two moments, two call chains
A metaclass is involved at two different times. The class statement calls the metaclass to build the class. Later, calling the class to make an instance goes through the metaclass again.
| Method on the metaclass | Runs when | Receives | Typical use |
|---|---|---|---|
| `__new__` | The class is being created | `mcls, name, bases, namespace` | Edit the namespace, validate, register |
| `__init__` | Right after the class exists | `cls, name, bases, namespace` | Set attributes on the finished class |
| `__call__` | The class is called | `cls, *args, **kwargs` | Control instance creation |
__new__: shape the class before it exists
__new__ receives the namespace dict from the class body. You can change it, reject it, or only observe it, then you must call super().__new__ and return the result.
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) # TrueChild never names the metaclass, but it still runs RegistryMeta.__new__. A subclass uses the metaclass of its bases.
Validation belongs here too, because raising an error stops the class from existing:
class RequiresRun(type):
def __new__(mcls, name, bases, namespace, **kwargs):
if bases and 'run' not in namespace:
raise TypeError(f'{name} must define run()')
return super().__new__(mcls, name, bases, namespace, **kwargs)
class Task(metaclass=RequiresRun):
pass
class Good(Task):
def run(self):
pass
try:
class Bad(Task):
pass
except TypeError as exc:
print(exc) # Bad must define run()The if bases test skips Task itself, which has no bases. This check looks only at each class's own namespace, so a subclass of Good that inherits run would also be rejected.
__init__: adjust the finished class
By the time __init__ runs, the class object already exists. Changing bases or namespace now has no effect on it, so use __init__ for setup that needs the real class.
class TaggedMeta(type):
def __init__(cls, name, bases, namespace, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
cls.tag = name.lower()
class Invoice(metaclass=TaggedMeta):
pass
print(Invoice.tag) # invoicePrefer __new__ when the result depends on the namespace, and __init__ when you only decorate the finished class.
__call__: control instance creation
__call__ on a metaclass runs when you write Config(). The default type.__call__ runs the class's __new__ and then its __init__. Overriding it lets you intercept that step.
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):
def __init__(self):
print('creating Config')
print(Config() is Config()) # TrueThe output is creating Config once, then True. The second call returns the stored instance and never reaches Config.__init__.
The singleton above is not thread safe. Two threads can both pass the not in check before either stores an instance.
Exercise
Using the Singleton metaclass above, you call Config() three times and Config._init_ prints a message. How many times is the message printed, and why?
Show answer
Once. The first call goes through Singleton._call, which calls super().call and runs Config.new and Config.init_. The next two calls find the stored instance and return it without running either method.