Trace Class Namespaces with __prepare__
Core idea
After selecting a metaclass, a class statement asks its prepare(name, bases, **kwargs) hook for the mapping in which the body executes. A metaclass can supply a mapping that records or validates assignments. The populated namespace then reaches the metaclass constructor. Normal type.new copies it into class storage. Methods do not treat the class namespace as an enclosing lexical function scope.
class Meta(type): @classmethod def __prepare__(mcls, name, bases, **kwargs): print('prepare', name) return {} def __new__(mcls, name, bases, ns, **kwargs): print('new', ns['code']) return super().__new__(mcls, name, bases, ns, **kwargs)class Record(metaclass=Meta): print('body') code = 'R7'print(Record.code)Preparation precedes body execution; new receives its completed mapping.
Reject duplicate public field names
class UniqueNames(dict): def __setitem__(self, key, value): if not key.startswith('_') and key in self: raise ValueError('duplicate ' + key) super().__setitem__(key, value)class Meta(type): @classmethod def __prepare__(mcls, name, bases, **kwargs): return UniqueNames()try: class Report(metaclass=Meta): title = 'first' title = 'second'except ValueError as exc: print(exc)Class-body assignments go through the custom mapping; the second public title is rejected before class creation finishes. This policy deliberately rejects normal repeated public definitions too.
Common mistake
When forwarding a class namespace to type.new, preserve classcell if present; dropping it can break zero-argument super in CPython. A custom non-dict mapping may need conversion to dict. Avoid custom namespaces when normal class-body order is sufficient.
Practice
Change the duplicate-name policy to record only names starting with field_. Define a class with two such fields and inspect the recorded order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Prepare and class namespaces
Check your understanding of prepare and class namespaces.
What is printed?
class M(type): @classmethod def __prepare__(m,n,b): return {'seed':3}class C(metaclass=M): value=seed+1print(C.value)What is printed?
class M(type): def __new__(m,n,b,ns): print(ns['x']); return super().__new__(m,n,b,ns)class C(metaclass=M): x=9When is __prepare__ called?
Which item must be preserved if present when forwarding a namespace to type.__new__ in CPython?