Python › Metaclasses & Class Customization
What role does the class namespace dict play during class creation, and how can __prepare__ customize it?
IntermediateAnswer
During class body execution, Python populates a namespace mapping (by default a plain dict) with all the names defined in the class body (methods, class variables), which is then passed to the metaclass's __new__/__init__. A metaclass's __prepare__(mcs, name, bases) classmethod can return a custom mapping (like an OrderedDict or one that tracks definition order or rejects duplicate names) to control how that namespace behaves during class body execution.
class OrderedMeta(type):
@classmethod
def __prepare__(mcs, name, bases):
return {} # could return a custom ordered/tracking mapping
def __new__(mcs, name, bases, namespace):
cls = super().__new__(mcs, name, bases, namespace)
cls._field_order = list(namespace.keys())
return clsReal-world example An ORM metaclass uses __prepare__ with a custom mapping to preserve and later use the exact declaration order of model fields for generating a consistent database schema.