Sub topic 10
Controlling the class body with __prepare__
This chapter assumes you know how a class statement calls its metaclass, and that you can write a metaclass with __new__. It also assumes you know that a class body is ordinary code that runs once.
Where __prepare__ fits
A class body is executed like a function body. Its assignments and def statements need a mapping to write into. By default that mapping is an empty dict.
__prepare__ is a metaclass hook that returns that mapping. Python calls it before the body runs, so it is the only hook that can affect the body while the body executes. __new__ and __init__ run afterwards, when the namespace is already filled.
The signature
__prepare__ must be a class method on the metaclass. It receives the class name, the tuple of bases, and any class keyword arguments:
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
...It must return a mapping object. The default implementation, type.__prepare__, returns an empty dict. Call it with super().__prepare__(name, bases, **kwargs) when you want the default and then add to it.
Rejecting duplicate names
Normally, defining the same method twice in a class body silently keeps the second one. A custom mapping can make that an error, because it sees every assignment as it happens:
class NoDuplicateDict(dict):
def __setitem__(self, key, value):
if key in self:
raise TypeError(f'duplicate attribute: {key}')
super().__setitem__(key, value)
class StrictMeta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
return NoDuplicateDict()
try:
class Example(metaclass=StrictMeta):
def run(self):
pass
def run(self):
pass
except TypeError as exc:
print(exc) # duplicate attribute: runEach def stores its name through __setitem__. The second run finds the key already present and raises. No later hook could catch this, because by the time __new__ receives the namespace, the first run has been overwritten.
Pre-filling the namespace
The returned mapping can already contain names. Code in the class body can then use them as if they were globals:
class HelperMeta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
namespace = super().__prepare__(name, bases, **kwargs)
namespace['shout'] = lambda text: text.upper() + '!'
return namespace
class Greeter(metaclass=HelperMeta):
greeting = shout('hello')
print(Greeter.greeting) # HELLO!Name lookup in the body checks the namespace first, so shout resolves. Anything you pre-fill also ends up as an attribute of the finished class, so Greeter.shout exists too. Delete it in __new__ if that is unwanted.
What the namespace becomes
After the body finishes, Python passes the namespace to the metaclass as the third argument. type.__new__ copies its contents into a plain dict for the new class. Your custom mapping therefore exists only during the body. The class does not keep it, and later assignments such as Example.run = ... do not go through __setitem__ on your mapping.
Python also writes __module__ and __qualname__ into the namespace before your code runs. A custom mapping must tolerate these writes. A duplicate-checking mapping works here because each is set once, but a mapping that rejects unknown keys would fail.
Common errors
- Forgetting
@classmethod. Without it, Python calls__prepare__with the wrong arguments and raises aTypeError. - Expecting it to run on subclasses of a normal class.
__prepare__is found on the metaclass of the class being defined. A subclass of a class whose metaclass defines__prepare__uses it too, because the subclass inherits that metaclass. - Reaching for it too early. Most tasks, such as registering subclasses or validating attributes, only need the finished namespace. Use
__prepare__only when you must see or control assignments while the body runs.
Exercise
A metaclass defines __prepare__ to return a dict subclass that raises on duplicate keys. A class body defines size = 1 and, later in the same body, size = 2. At what point does the error occur, and why could a metaclass __new__ not detect the same mistake?
Show answer
The error occurs while the class body is running, at the second size assignment, because that assignment calls the custom mapping's __setitem__, which finds the key already present. By the time __new__ is called, the body has finished and the namespace holds only size = 2. The first value was overwritten, so there is no trace of the duplicate.