Sub topic 3
Overriding `__new__`, `__init__` and `__call__` on a Metaclass
Assume you know classes, inheritance, super(), decorators, and keyword arguments. A metaclass is the class of a class. Most metaclasses inherit from type.
Metaclass hooks
A metaclass can customize three different stages:
__new__creates the class object.__init__initializes the class object after creation.__call__runs when someone calls the class, such asUser().
class RegistryMeta(type):
registry = {}
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, namespace)
mcls.registry[name] = cls
return cls
def __init__(cls, name, bases, namespace, **kwargs):
super().__init__(name, bases, namespace)
cls.created_by = "RegistryMeta"
def __call__(cls, *args, **kwargs):
print(f"Creating an instance of {cls.__name__}")
return super().__call__(*args, **kwargs)
class User(metaclass=RegistryMeta):
pass
user = User()
print(User.created_by)
print(sorted(RegistryMeta.registry))Call super() in these hooks unless you deliberately replace the normal behavior. In particular, omitting super().__new__() usually prevents Python from creating the class correctly.
__call__ on the metaclass is different from __call__ on an ordinary class. It controls instance creation and can implement caching, validation, or a singleton pattern.
Controlling the class body with `__prepare__`
Python calls __prepare__ before it executes the class body. The method returns the mapping used for names such as methods and class attributes.
class StrictMeta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
return {}
def __new__(mcls, name, bases, namespace, **kwargs):
return super().__new__(mcls, name, bases, namespace)
class Report(metaclass=StrictMeta):
format = "text"Custom mappings can detect duplicate definitions or preserve special metadata. Use this hook only when a class decorator or __init_subclass__ cannot solve the problem.
Metaclass conflicts
For multiple inheritance, Python must choose one metaclass that is a subclass of every base class's metaclass. Unrelated metaclasses cause a conflict.
class MetaA(type):
pass
class MetaB(type):
pass
class A(metaclass=MetaA):
pass
class B(metaclass=MetaB):
pass
# class C(A, B): # TypeError: metaclass conflict
# passYou can sometimes solve this by defining a combined metaclass inheriting from both MetaA and MetaB, but that increases coupling.
Choosing the lightest tool
| Need | Prefer |
|---|---|
| Register or validate subclasses | `__init_subclass__` |
| Modify one completed class | Class decorator |
| Control class creation or instance calls globally | Metaclass |
Use a metaclass only when the other tools cannot express the rule clearly.
Exercise
Which hook controls Config() calls: Config.__call__ or the metaclass's __call__?
Show answer
The metaclass's __call__ controls Config() because the class object is being called.