Sub topic 10
Controlling the class body with __prepare__
This chapter assumes you know how a class statement becomes a call to a metaclass, and that you have written a basic metaclass with __new__. It covers __prepare__, the one hook that runs before the class body does.
Where __prepare__ fits
Most class-customization hooks run after the body has finished. __init_subclass__, __set_name__, class decorators and a metaclass's __new__ all see a finished namespace. __prepare__ runs first and chooses the object that collects the body's names.
The order for class C(Base, metaclass=M, flag=True): is:
- Python works out the metaclass
M. - It calls
M.__prepare__('C', (Base,), flag=True). The result is the namespace. - It runs the body with that namespace as the local scope. Each assignment,
defandclassinside the body stores a name into it. - It calls
M('C', (Base,), namespace, flag=True), which runs__new__and then__init__.
If you define no metaclass, Python uses type.__prepare__, which returns a plain empty dict. That is why ordinary class bodies behave like ordinary dictionaries.
The contract
__prepare__ has these requirements:
- It is a class method on the metaclass. It is called on the metaclass itself, before any class exists, so write
@classmethod. - Its signature is
__prepare__(mcls, name, bases, **kwargs). It receives the same class keyword arguments that__new__and__init__receive. - It returns a mapping. The body reads and writes names through that mapping.
- It is inherited. A subclass of a class whose metaclass defines
__prepare__also gets a prepared namespace.
The next example prints each stage. The metaclass takes a verbose keyword and removes it before calling type. This matters because type.__new__ forwards leftover keywords to __init_subclass__, and the default object.__init_subclass__ rejects them.
class Trace(type):
@classmethod
def __prepare__(mcls, name, bases, *, verbose=False, **kwargs):
print('prepare', name, verbose)
return super().__prepare__(name, bases, **kwargs)
def __new__(mcls, name, bases, namespace, *, verbose=False, **kwargs):
print('new', name, verbose)
return super().__new__(mcls, name, bases, namespace, **kwargs)
def __init__(cls, name, bases, namespace, *, verbose=False, **kwargs):
print('init', name, verbose)
super().__init__(name, bases, namespace, **kwargs)
class Demo(metaclass=Trace, verbose=True):
print('body runs')
x = 1The output is:
prepare Demo True
body runs
new Demo True
init Demo TrueThe prepare line comes before the body runs line, which shows that the namespace exists before the body executes.
Example: rejecting duplicate names
A normal class body silently lets a later definition replace an earlier one. A common cause is two methods with the same name, where the first becomes dead code. A custom mapping can turn that into an error at the moment of the second definition.
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: runThis works because every store in the class body goes through the namespace's __setitem__. The error is raised from inside the body, so the traceback points at the second def run. A check in __new__ could not do that, because the first run would already be gone by then.
The metaclass above defines only __prepare__, so type.__new__ builds the class from the dictionary as usual.
A gotcha: legitimate redefinition
Some Python idioms redefine a name on purpose:
- A property with a setter uses
@property def xfollowed by@x.setter def x. typing.overloadstacks severaldef fstubs before the real implementation.- Conditional definitions such as
if cond: def f ... else: def f ...define the name in two branches. Only one branch runs, so this one is fine.
NoDuplicateDict rejects the first two. If you apply a strict namespace to a class that uses them, you must allow the exceptions, for example by permitting a redefinition when the old and new values are both property objects.
Example: names that define themselves
Because the body looks names up in the namespace as well as storing them, __prepare__ can change what an undefined name means. dict calls __missing__ for absent keys, and the class body's name lookup honors that for dict subclasses. This namespace turns each bare name into the next integer:
import builtins
class AutoNamespace(dict):
def __init__(self):
super().__init__()
self._next = 0
self.names = []
def __missing__(self, key):
if key.startswith('_') or hasattr(builtins, key):
raise KeyError(key)
value = self._next
self._next += 1
self[key] = value
self.names.append(key)
return value
class AutoMeta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
return AutoNamespace()
def __new__(mcls, name, bases, namespace, **kwargs):
cls = super().__new__(mcls, name, bases, dict(namespace), **kwargs)
cls.members = tuple(namespace.names)
return cls
class Color(metaclass=AutoMeta):
red
green
blue
print(Color.members) # ('red', 'green', 'blue')
print(Color.green) # 1Each bare name such as red is a lookup that misses, so __missing__ assigns it a number and stores it. The guard in __missing__ matters. Without it, a name like print or __name__ would be captured as a member instead of falling through to builtins and module globals. Raising KeyError tells Python to continue its normal lookup.
The standard library's enum module relies on the same mechanism. Enum classes use a special namespace, and enum.auto() lets you ask for generated values.
What happens to the namespace afterward
The namespace is a temporary collection area. When type.__new__ builds the class, it copies the entries into a new internal dictionary. The class's __dict__ is a read-only view of that copy, not your custom mapping:
print(type(Color.__dict__).__name__) # mappingproxySeveral consequences follow:
- Your mapping's behavior stops at the end of the body. Setting
Color.red = 5later does not call your__setitem__. - Information that exists only on your mapping object, such as
namesabove, is lost unless__new__copies it onto the class. type.__new__requires the namespace argument to be adictor a subclass. If__prepare__returns another kind of mapping, the body still runs, but your__new__must convert it, for example withdict(namespace), before callingsuper().__new__.- Methods are not affected. Code inside a function body looks up names through normal function scoping, not through the class namespace. A custom
__getitem__or__missing__therefore only influences code written directly at class-body level.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting `@classmethod` | `TypeError` about a missing argument when the class statement runs | Decorate `__prepare__` with `@classmethod` |
| Returning `None` or forgetting `return` | `TypeError` or `TypeError: 'NoneType' object does not support item assignment` | Return a mapping |
| Not calling `super().__prepare__` when combining metaclasses | A parent metaclass's namespace behavior is lost | Call `super().__prepare__(name, bases, **kwargs)` and wrap or extend the result |
| Passing a non-`dict` mapping to `type.__new__` | `TypeError` that the namespace must be a dict | Convert with `dict(namespace)` in `__new__` |
| A `__missing__` that captures every name | Builtins and dunder names break inside the body | Raise `KeyError` for names that should fall through |
| Using `__prepare__` for something a later hook can do | Extra complexity with no gain | See the next section |
When __prepare__ is the right tool
__prepare__ is the narrowest of the class-creation hooks, and you should reach for it last. Use it only when the behavior must happen while the body runs:
- You need to intercept stores as they happen, such as duplicate detection with an error that points at the offending line.
- You need to change what unknown names mean, as in the enum-style example.
- You need to build up state, such as a count or a record of the order of stores, that the finished class cannot reconstruct.
If you only need to inspect the finished set of attributes, __init_subclass__ or a class decorator is simpler. They also avoid metaclass conflicts, which the next chapter covers. If you do use __prepare__, you have a metaclass, so every class that inherits from yours inherits that constraint as well.
You can also build a class with a prepared namespace without a class statement. types.new_class(name, bases, kwds, exec_body) calls __prepare__ for you and passes the namespace to exec_body. types.prepare_class(name, bases, kwds) returns the metaclass, the namespace and the remaining keywords so you can do each step yourself.
Exercise
A class body defines a property x and then redefines x with @x.setter. Why does NoDuplicateDict raise an error, and how would you change __setitem__ to allow it?
Show answer
The setter decorator rebinds the name x, so the body stores to x a second time, and __setitem__ sees the key already present. Allow it when both the existing value and the new value are property instances, for example if key in self and not (isinstance(self[key], property) and isinstance(value, property)): raise TypeError(...). Other duplicates still raise.
Exercise
In the Trace example, __prepare__ prints prepare Demo True before body runs appears. What does this ordering tell you about when you can use __prepare__ compared with __init_subclass__?
Show answer
__prepare__ runs before the body, so it can influence how the body executes, such as how names are stored or looked up. __init_subclass__ runs after the class is created, so it only sees the finished result and cannot change what happens during the body.
Exercise
You return a custom mapping from __prepare__ and, after the class is created, set Color.blue = 10. Does your mapping's __setitem__ run? Why or why not?
Show answer
No. type.__new__ copies the namespace into the class's own dictionary, and later attribute assignment on the class goes through type.__setattr__. The custom mapping only existed while the body ran.