skip to content

When a class uses `metaclass=Meta`, in what order do `__prepare__`, `__new__` and `__init__` run?

level: middleimportance: should knowfreq 40%

answer

  1. Four steps, not two
  2. Something runs before the class body
  3. The body needs a namespace to write into
  4. Ingredients first, finished class last
  5. prepare, body, __new__, __init__

basics

~20 s

Meta.__prepare__ runs first and returns the mapping the class body executes into. The body then runs, and the filled mapping is handed to Meta.__new__, which creates the class object, and finally to Meta.__init__, which configures it.

solid answer

~40 s

A `class` statement with `metaclass=Meta` executes in four steps. First Python calls `Meta.__prepare__(name, bases, **kwds)` — an implicit classmethod — and uses the mapping it returns as the namespace for the class body. Second, the class body runs, writing every name it defines into that mapping. Third, Python calls `Meta(name, bases, namespace, **kwds)`, which is `type.__call__` on the metaclass, so `Meta.__new__` runs and actually creates the class object. Fourth, `Meta.__init__` runs on that freshly built class. The result is bound to the class name. So `__new__` sees a namespace but no class yet, while `__init__` receives the finished class as `cls`. Any extra class keywords are forwarded to all three hooks and must be consumed before delegating to `type`.

code

python · 18 lines
python
class Meta(type):
    @classmethod
    def __prepare__(mcls, name, bases, **kwds):
        print("1 prepare", name, kwds)
        return {}

    def __new__(mcls, name, bases, namespace, **kwds):
        print("3 new", name, "has body names:", "value" in namespace)
        return super().__new__(mcls, name, bases, namespace)

    def __init__(cls, name, bases, namespace, **kwds):
        print("4 init", cls.__name__, "mro len:", len(cls.__mro__))
        super().__init__(name, bases, namespace)


class Service(metaclass=Meta, tag="x"):
    print("2 body runs")
    value = 1

go deeper

for a junior

You are unlikely to write a metaclass yet, but recognise metaclass= in a class header and know it means the class is being built by something other than type. Remember that the class body is ordinary code that runs once, at import.

for a middle

Be able to list the four steps in order and say what each hook receives: __prepare__ gets the name and bases and returns a mapping, __new__ gets the filled namespace, __init__ gets the finished class. Mention that __prepare__ is an implicit classmethod.

for a senior

Demonstrate hook selection under pressure: __new__ only when the class must be built differently, __init__ when you merely inspect or register. Be ready to debug a metaclass that leaks class keywords into type.__new__ or that mutates a namespace after the body already read from it.

for a principal

Own the readability cost. Every hook you occupy is code that runs for every subclass anyone ever writes, at import time, invisible at the definition site — so set the standard for when that power is justified and where such machinery is allowed to live.

Reading a `class` statement as a sequence of calls is the fastest way to make metaclasses stop feeling like magic. With `class Service(Base, metaclass=Meta, tag="x"):` the interpreter does this, in order. ## 1. Choose the metaclass If a `metaclass=` keyword is present, that is the candidate. Otherwise the candidate is `type`. Python then picks the **most derived** metaclass among the candidate and the metaclasses of all bases. If no single one is a subclass of all the others, class creation fails with a `TypeError` about a metaclass conflict — the reason a base class that carries a custom metaclass constrains everyone who inherits from it. ## 2. `__prepare__` builds the namespace Python calls `Meta.__prepare__(name, bases, **kwds)`. It is an implicit classmethod, so you must decorate it with `@classmethod` when you write it; forgetting that is the single most common mistake in a first metaclass. It must return a **mapping**, which becomes the namespace the class body will execute in. `type.__prepare__` simply returns a fresh `dict`. This is the only hook that sees definitions *as they happen*, so it is where you intercept the act of writing a name in a class body: rejecting duplicate method definitions, recording definition order, injecting names that are visible to the body without importing them. ## 3. The class body executes The compiler turned the body into a function; it now runs with that prepared mapping as its local namespace. Every `def`, every assignment, every nested statement writes into it. Nothing about the class object exists yet. ## 4. `__new__` creates the class, `__init__` configures it Python then calls `Meta(name, bases, namespace, **kwds)`. Because `Meta` is a class, calling it goes through `type(Meta).__call__` — normally `type.__call__` — which runs `Meta.__new__` and then, if the result is an instance of `Meta`, `Meta.__init__`. * `Meta.__new__(mcls, name, bases, namespace, **kwds)` receives the *ingredients*. This is where you mutate the namespace before the class exists, adjust the bases, or return something else entirely. It must eventually call `super().__new__(mcls, name, bases, namespace)` to get a real class. * `Meta.__init__(cls, name, bases, namespace, **kwds)` receives the **finished class** as its first argument. This is where you register the class, validate it, or set attributes on it. It cannot change what the class *is*, only what it holds. The rule of thumb: change the recipe in `__new__`, use the cake in `__init__`. If you only need to inspect or register, `__init__` is the gentler hook. ## Class keywords Extra keywords in the class header (`tag="x"` above) are forwarded to `__prepare__`, `__new__` and `__init__`. Your metaclass must consume them — pop them out of `**kwds` — before delegating, because `type.__new__` does not accept arbitrary keyword arguments and class creation fails with a `TypeError` if they leak through. ## Order matters in a way that surprises people Because `__prepare__` runs before the body, code in the body can see names that `__prepare__` seeded into the namespace. Because `__new__` runs after the body, it can never influence how a name in the body was evaluated — only what happens to it afterwards. And because `__init__` runs last, on a complete class, anything that must observe the fully formed class (its MRO, its inherited attributes) belongs there. ## Ordering of the namespace itself Before 3.6, returning a `collections.OrderedDict` from `__prepare__` was the standard trick for recording definition order. Since 3.6 the ordinary `dict` used by `type.__prepare__` already preserves insertion order, and the created class's `__dict__` reflects the body's order, so that idiom is obsolete. It remains correct through 3.14. ## When you need none of this Most real cases that reach for `__new__` want only "run some code for each subclass" or "transform this one class". The first is a subclass hook's job and the second is a class decorator's; both compose better than a metaclass, which every subclass then inherits. Knowing the four-step order is still worth it, because it is what lets you read someone else's metaclass and say precisely which of the four moments their code lives in — and that is what the interviewer is checking.

  • What happens if you forget to decorate `__prepare__` with `@classmethod`?
    Python calls it on the metaclass with `(name, bases)`, so an undecorated function receives the metaclass as `self` and the class name as `name` — every argument shifts by one. You usually get a confusing `TypeError` about argument counts, or worse, silently wrong values. `__prepare__` is documented as an implicit classmethod, so write the decorator explicitly.
  • Why should a metaclass consume extra class keywords rather than passing them through?
    Keywords in the class header are forwarded to `__prepare__`, `__new__` and `__init__`. `type.__new__` does not accept arbitrary keyword arguments, so leaking them through to `super().__new__` makes class creation fail with a `TypeError`. Pop what you understand out of `**kwds` in your own hooks and delegate with only `(mcls, name, bases, namespace)`.
  • If a metaclass only needs to register each class it creates, which hook should it use?
    `__init__`, because it receives the fully built class and cannot accidentally change what the class is. `__new__` is for altering the ingredients — rewriting the namespace, adjusting bases, returning a substitute. Choosing the weakest hook that does the job keeps the metaclass readable and keeps subclass creation predictable.

saying these in an interview costs you the question

  • Thinks the class body runs after `__new__`
  • Writes `__prepare__` without the `@classmethod` decorator
  • Says a metaclass `__init__` initialises instances of the class
  • Passes extra class keywords straight to `type.__new__`
  • Believes `__prepare__` must return an OrderedDict for ordering
  • Cannot say what `__new__` receives that `__init__` does not

context