Sub topic 9
Overriding __new__, __init__ and __call__ on a metaclass
This chapter assumes you can already write a basic metaclass (a subclass of type passed with metaclass=). It also assumes you know what a class statement does: it runs the body in a namespace, then calls the metaclass. You should be comfortable with super() and **kwargs.
A metaclass can hook three moments. Two of them happen once per class: __new__ and __init__ on the metaclass. The third happens once per instance: __call__. This chapter covers what each hook receives, what it must return, and when to choose it.
Two levels, three hooks
A metaclass method receives the class as its first argument where an ordinary method receives the instance. That is why the __init__ and __call__ hooks below name their first parameter cls, and __new__ names it mcls (the metaclass itself).
| Hook | Runs when | First argument | Typical job |
|---|---|---|---|
| `Meta.__new__(mcls, name, bases, namespace, **kwargs)` | A class statement executes | The metaclass | Edit the namespace or bases, then build the class |
| `Meta.__init__(cls, name, bases, namespace, **kwargs)` | Right after `__new__` returns the class | The new class | Register, validate, or set attributes on the finished class |
| `Meta.__call__(cls, *args, **kwargs)` | Code calls the class, as in `Cls()` | The class | Control how instances are created |
You can see the class-creation order by printing from each stage. This also shows where __set_name__ and __init_subclass__ fall relative to the metaclass hooks.
class Marker:
def __set_name__(self, owner, name):
print(f'3. __set_name__ called for {name!r} on {owner.__name__}')
class Base:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print(f'4. __init_subclass__ called for {cls.__name__}')
class TraceMeta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
print(f'1. __prepare__ for {name}')
return {}
def __new__(mcls, name, bases, namespace, **kwargs):
print(f'2. Meta.__new__ starts for {name}')
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
print(f'5. Meta.__new__ ends for {name}')
return cls
def __init__(cls, name, bases, namespace, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
print(f'6. Meta.__init__ for {name}')
class Widget(Base, metaclass=TraceMeta):
mark = Marker()Running this prints the six lines in numbered order. Steps 3 and 4 happen inside super().__new__, so by the time your __init__ runs, both hooks have finished.
__new__: shape the class before it exists
In Meta.__new__ the class does not exist yet. You get the namespace (the dict filled by the class body), and anything you change in it, or in bases, becomes part of the class. You must call super().__new__ to get the class, and you must return it.
class CommandMeta(type):
def __new__(mcls, name, bases, namespace, **kwargs):
commands = tuple(
key for key, value in namespace.items()
if callable(value) and not key.startswith('_')
)
namespace['commands'] = commands
return super().__new__(mcls, name, bases, namespace, **kwargs)
class Tool(metaclass=CommandMeta):
limit = 3
def start(self):
pass
def stop(self):
pass
print(Tool.commands) # ('start', 'stop')The metaclass added commands to the namespace, so Tool is created with it already in place. Things only __new__ can do cleanly:
- Add or remove entries in the namespace, including
__slots__, which must exist at creation time. - Change
bases, for example to insert a mixin. - Return an object other than a normal new class.
Class keyword arguments
Keyword arguments in the class line go to __prepare__, __new__ and __init__. If your metaclass consumes one, name it in the signature so it is not forwarded. type.__new__ passes leftover keywords to __init_subclass__, and object.__init_subclass__ raises TypeError for any it does not expect.
class TableMeta(type):
def __new__(mcls, name, bases, namespace, table=None, **kwargs):
namespace['table_name'] = table or name.lower()
return super().__new__(mcls, name, bases, namespace, **kwargs)
def __init__(cls, name, bases, namespace, table=None, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
class User(metaclass=TableMeta, table='users'):
pass
class Order(metaclass=TableMeta):
pass
print(User.table_name, Order.table_name) # users orderNote that __init__ also declares table. type.__init__ accepts and ignores extra keywords, but your own override must at least tolerate the keyword, or the class statement fails.
Common mistakes in __new__
- Forgetting
return. The class name is then bound toNone, and the error appears much later. - Calling
type.__new__(mcls, ...)directly instead ofsuper().__new__(...). This works for one metaclass but breaks cooperation when several metaclasses are combined. - Returning something that is not an instance of
mcls. Python then skipsMeta.__init__, becausetype.__call__only runs__init__when the result is an instance of the type being called.
__init__: work with the finished class
In Meta.__init__ the class exists, and cls is a normal class object. Changing namespace here does nothing, because the class has already copied it. Instead you read the class and set attributes on it, using setattr or plain assignment.
This is the right hook for validation and registration, where you only need to look at the result. This metaclass rejects subclasses that forget a required method:
class RequiresMeta(type):
def __init__(cls, name, bases, namespace, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
if bases and not callable(getattr(cls, 'handle', None)):
raise TypeError(f'{name} must define handle()')
class Handler(metaclass=RequiresMeta):
pass
class Good(Handler):
def handle(self):
return 'ok'
try:
class Broken(Handler):
pass
except TypeError as exc:
print(exc) # Broken must define handle()The if bases guard skips the root class Handler, which would otherwise fail its own check. Every metaclass hook also runs for the base class that declares the metaclass, so a registry or validator usually needs a guard like this one.
The registry from the spine's earlier example can use either hook:
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) # TrueHere __new__ registers the class only because it already has the class in hand after super().__new__. Moving the registration into __init__ gives the same result with less to remember, because cls is passed in.
Choosing between the two
| You want to | Use |
|---|---|
| Add or change namespace entries before creation | `__new__` |
| Set `__slots__` or change `bases` | `__new__` |
| Register, validate or annotate the finished class | `__init__` |
| Run code after `__set_name__` and `__init_subclass__` have finished | `__init__` (or after `super().__new__` in `__new__`) |
If you can do the job in __init__, prefer it. It cannot lose the class by forgetting a return.
__call__: control instance creation
When you write Config(), Python looks up __call__ on type(Config), which is the metaclass. The default, type.__call__, does roughly this:
def default_call(cls, *args, **kwargs):
obj = cls.__new__(cls, *args, **kwargs)
if isinstance(obj, cls):
obj.__init__(*args, **kwargs)
return objOverriding __call__ on the metaclass lets you intercept this step. The singleton from the earlier example returns the same instance on every call:
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 dictionary is keyed by cls, so each class using this metaclass, including subclasses, gets its own single instance.
A more useful variant caches instances per argument tuple. It also shows __init__ and __call__ working together: __init__ gives every class its own cache, and __call__ uses it.
class CachedMeta(type):
def __init__(cls, name, bases, namespace, **kwargs):
super().__init__(name, bases, namespace, **kwargs)
cls._cache = {}
def __call__(cls, *args):
if args not in cls._cache:
cls._cache[args] = super().__call__(*args)
return cls._cache[args]
class Color(metaclass=CachedMeta):
created = 0
def __init__(self, name):
Color.created += 1
self.name = name
print(Color('red') is Color('red')) # True
print(Color('blue') is Color('red')) # False
print(Color.created) # 2Color.created is 2, not 3, because the second Color('red') never reaches Color.__init__.
Gotchas with __call__
- Skipping
super().__call__skips everything. If you return an object without calling it, neither the class's__new__nor its__init__runs. - Arguments are silently ignored on cache hits. A singleton called as
Config(debug=True)after the first call returns the old instance and dropsdebug. Document this, or raise an error when the arguments differ. - Other creation paths bypass the metaclass.
pickleandcopyrebuild objects by callingcls.__new__directly, so unpickling can produce a second "singleton". - Cached arguments must be hashable.
CachedMetafails on a list argument withTypeError: unhashable type. - Thread safety is your job. The check-then-create pattern above can create two instances if two threads race. Use a lock if that matters.
Metaclass methods are not instance methods
A method defined on the metaclass is available on the class but not on its instances. Attribute lookup on an instance searches the class and its bases, and does not consult the metaclass.
class Meta(type):
def describe(cls):
return f'class {cls.__name__}'
class Thing(metaclass=Meta):
pass
print(Thing.describe()) # class Thing
print(hasattr(Thing(), 'describe')) # FalseThis is why Tool.commands in the earlier example was written into the namespace. That put it on the class itself, where instances can see it too.
Summary of rules
- Use
__new__when the namespace, bases or slots must change before the class exists. Alwaysreturn super().__new__(...). - Use
__init__to inspect or decorate the finished class. Always callsuper().__init__(...). - Use
__call__to change instance creation. Callsuper().__call__(...)unless you deliberately return an existing object. - Accept
**kwargsin all three, and forward whatever you do not consume. - Guard with
if baseswhen a hook should skip the root class that declares the metaclass.
Exercise
A metaclass defines __init__(cls, name, bases, namespace, **kwargs) and runs namespace['version'] = 2 inside it. After the class statement finishes, Cls.version raises AttributeError. Why, and how do you fix it in __init__? When would you need __new__ instead?
Show answer
By the time __init__ runs, type.__new__ has already built the class and copied the namespace into it, so editing the namespace dict no longer affects the class. In __init__, assign on the class instead: cls.version = 2. You need __new__ when the change must exist at creation time, such as __slots__ or changed bases, because those cannot be added to an existing class.
Exercise
Using CachedMeta and Color from this chapter, what do Color('red') is Color('red') and Color.created show after the calls Color('red'), Color('red'), Color('blue')? What happens if you remove super().__init__(...) from CachedMeta.__init__, and what does Color(['red']) raise?
Show answer
The two Color('red') calls return the same object, and Color.created is 2, because only two distinct argument tuples were created. Removing super().__init__(...) still works for this metaclass, since type.__init__ does nothing important, but it breaks cooperation when metaclasses are combined, so keep the call. Color(['red']) raises TypeError: unhashable type: 'list', because the argument tuple is used as a dictionary key.