Course contentsShow
← Python
Lesson 663 of 1,06010. Advanced Language FeaturesFree lesson

Controlling Class Namespace with __prepare__

Learners will utilize the __prepare__ method to return a custom dictionary-like object that tracks the order and definition of class members.

In this lesson, you will learn how to use the __prepare__ method to intercept and customize the creation of a class's internal namespace before the class body is even executed.

Why __prepare__?

Normally, when you define a class, Python creates a standard dict to store its members. However, sometimes you need more control—such as tracking the order in which members are defined, preventing duplicate names, or automatically wrapping methods. Since the class body execution happens after the namespace is created but before the class object is instantiated, __prepare__ acts as the factory for the object that stores these definitions.

Capturing Definition Order

If you want your class to remember the order in which attributes are defined, you can provide an OrderedDict (or a regular dict in modern Python versions) via a metaclass. Here is how you implement it:

from collections import OrderedDict

class OrderedMeta(type):
    @classmethod
    def __prepare__(mcs, name, bases):
        # We return an OrderedDict to capture insertion order
        return OrderedDict()

    def __new__(mcs, name, bases, namespace):
        # namespace is now an OrderedDict
        return super().__new__(mcs, name, bases, namespace)

class MyClass(metaclass=OrderedMeta):
    first = 1
    second = 2
    third = 3

# We can inspect the namespace of the created class
print(list(MyClass.__dict__.keys()))
# Output: ['__module__', 'first', 'second', 'third', '__dict__', ...]

How it Works

When Python sees a metaclass with __prepare__, it calls this static method before the class body is executed. The dictionary returned by __prepare__ is passed as the namespace argument to the metaclass's __new__ and __init__ methods. By returning a specialized mapping, you gain full control over how attribute names are stored and validated during the class construction phase. This is an essential tool for building declarative frameworks where the sequence of definitions matters as much as the values themselves.

Key Takeaway: The __prepare__ method allows you to define a custom namespace container at the metaclass level, enabling you to track, filter, or manipulate attributes while the class body is being parsed.