Sub topic 3
What happens when Python runs a class statement
This chapter assumes you can define classes with methods and inheritance, call super(), and write simple decorators. It also assumes you know what **kwargs does. By the end you will be able to list, in order, every step Python takes between the word class and the name being bound in your module. Later chapters hook into those steps one by one, so this chapter is the map.
A class statement is executable code
A class statement runs when the interpreter reaches it, just like an if or a for. It is not a declaration that the compiler processes ahead of time. It produces an object, and it binds that object to a name.
Consider this statement:
class Child(Base, metaclass=Meta, flag=True):
x = 1
def method(self):
return self.xPython treats it roughly as the following sequence. This is a simplified model, not literal source code.
bases = (Base,)
kwds = {"flag": True}
namespace = Meta.__prepare__("Child", bases, **kwds)
# the indented body runs here, with `namespace` acting as its local variables
cls = Meta("Child", bases, namespace, **kwds)
Child = clsTwo details are easy to miss. The body runs before the class exists, so code inside it cannot refer to the class yet. The class object is also built in one call at the end, from the finished namespace.
The steps in order
- Resolve the bases. Python evaluates the expressions in the parentheses. If a base is not a class but defines
__mro_entries__, that method is called and its result replaces the base. Generic aliases such asGeneric[T]rely on this. - Pick the metaclass. An explicit
metaclass=keyword is the starting candidate. Without one, Python uses the type of the first base, ortypeif there are no bases. It then checks the types of all bases and picks the most derived metaclass, meaning the one that is a subclass of all the others. If no such metaclass exists, you get a metaclass conflict (see the chapter on conflicts). - Prepare the namespace. Python calls
Meta.__prepare__(name, bases, **kwds). It returns the mapping used while the body runs.type.__prepare__returns an ordinary emptydict. - Run the body. The indented code executes with that mapping as its local scope. Every assignment and
defbecomes a key in the namespace. - Call the metaclass. Python calls
Meta(name, bases, namespace, **kwds). For a normal metaclass this callsMeta.__new__, which usually ends intype.__new__, and thenMeta.__init__on the result. - Inside
type.__new__. The class object is allocated and its__dict__is filled from the namespace. Then two hooks fire, in this order: __set_name__(owner, name)is called on every value in the namespace that defines it.__init_subclass__(**kwds)is called on the parent class, with the class keyword arguments.- Run
Meta.__init__. This happens after__new__has returned, so the class already exists and has been through both hooks above. - Apply decorators. If the statement has decorators, they run from the bottom up on the finished class. Their return value is what gets bound.
- Bind the name. The final object is assigned to
Childin the enclosing scope.
Each hook you will meet in this tutorial sits at one of these steps:
| Step | Hook | Who defines it |
|---|---|---|
| 3 | `__prepare__` | The metaclass |
| 5 | `__new__` and `__call__` of the metaclass | The metaclass |
| 6 | `__set_name__` | A descriptor or any attribute value in the body |
| 6 | `__init_subclass__` | A parent class |
| 7 | `__init__` | The metaclass |
| 8 | Class decorator | Any callable that takes a class |
Watching the order
The best way to remember the order is to print it. This script uses one metaclass, one parent class, one marker object and one decorator. Each prints a numbered line when it runs.
class TraceMeta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
print("1. __prepare__", name)
return super().__prepare__(name, bases, **kwargs)
def __new__(mcls, name, bases, namespace, **kwargs):
public = sorted(k for k in namespace if not k.startswith("__"))
print("3. Meta.__new__", name, public)
return super().__new__(mcls, name, bases, namespace, **kwargs)
def __init__(cls, name, bases, namespace, **kwargs):
print("5. Meta.__init__", name)
super().__init__(name, bases, namespace)
class Marker:
def __set_name__(self, owner, name):
print("4a. __set_name__", owner.__name__, name)
class Base(metaclass=TraceMeta):
def __init_subclass__(cls, **kwargs):
print("4b. __init_subclass__", cls.__name__)
super().__init_subclass__(**kwargs)
def decorate(cls):
print("6. class decorator", cls.__name__)
return cls
print("--- defining Child ---")
@decorate
class Child(Base):
print("2. class body runs")
marker = Marker()Running it prints the following. The first three lines come from creating Base, which uses the same metaclass.
1. __prepare__ Base
3. Meta.__new__ Base []
5. Meta.__init__ Base
--- defining Child ---
1. __prepare__ Child
2. class body runs
3. Meta.__new__ Child ['marker']
4a. __set_name__ Child marker
4b. __init_subclass__ Child
5. Meta.__init__ Child
6. class decorator ChildThree things stand out in this output:
__prepare__and the body run beforeMeta.__new__. By the time__new__is called, the namespace is already complete.__set_name__and__init_subclass__both fire insidetype.__new__, which is why they appear between the__new__and__init__lines.Basedid not trigger__init_subclass__. That hook is looked up on the parents of the new class. The parent ofBaseisobject, whose version does nothing.
Doing it by hand with types.new_class
The standard library exposes the whole protocol as a function. types.new_class(name, bases, kwds, exec_body) performs the steps above: it resolves bases, selects the metaclass, calls __prepare__, runs your body function against the namespace, and calls the metaclass.
import types
def fill(namespace):
namespace["greeting"] = "hello"
namespace["greet"] = lambda self: self.greeting
Greeter = types.new_class("Greeter", (), {}, fill)
print(Greeter().greet()) # hello
print(type(Greeter)) # <class 'type'>Compare this with calling type("Greeter", (), {...}) directly. A direct call to type skips base resolution, metaclass selection and __prepare__. It works for simple cases. When bases might have custom metaclasses or __mro_entries__, types.new_class is the correct tool.
The namespace is only a mapping until step 6
During the body, the namespace is just a mapping, and the class does not exist. Two consequences follow.
First, a descriptor in the body has no way to know its own name when it is created. marker = Marker() evaluates Marker() first, and only afterwards is the result stored under "marker". That is why __set_name__ exists. Python calls it after the class is built, with the owner and the name.
Second, the namespace is copied into the class. type.__new__ copies the contents of the mapping into a new dictionary. Changing the namespace object later does not change the class. If you want to alter the class contents from a metaclass, do it to the namespace before calling super().__new__, or use setattr on the class afterwards.
class Meta(type):
def __new__(mcls, name, bases, namespace, **kwargs):
namespace["added_before"] = 1 # becomes part of the class
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
namespace["added_after"] = 2 # ignored: the dict was copied
cls.added_with_setattr = 3 # works
return cls
class Demo(metaclass=Meta):
pass
print(hasattr(Demo, "added_before")) # True
print(hasattr(Demo, "added_after")) # False
print(hasattr(Demo, "added_with_setattr")) # TrueWhere super() and __class__ fit in
A method that calls zero-argument super() or mentions __class__ needs a reference to its own class. The class does not exist when the method is compiled. The compiler solves this by creating a hidden cell, and the class body stores it in the namespace under __classcell__. type.__new__ fills the cell with the new class.
This has one consequence for metaclass authors. If your __new__ builds a different namespace and drops __classcell__, or never reaches type.__new__, the cell stays empty. Since Python 3.8 this raises RuntimeError. Forward the original namespace, or copy it with all its keys, and the problem does not arise.
Edge cases and gotchas
- Errors in hooks. An exception raised inside
__init_subclass__propagates out of the class statement, and the name is never bound. A failure in__set_name__behaves the same way. Before Python 3.12 the exception from__set_name__was wrapped in aRuntimeError. From 3.12 the original exception is raised with a note added. - Hook order is fixed. Inside
type.__new__,__set_name__always runs before__init_subclass__. If your__init_subclass__inspects attributes, any descriptor already knows its name. __init__sees the finished class. Code in the metaclass__init__can rely on__init_subclass__having run. Code in the metaclass__new__before the call tosuper().__new__cannot.- Decorators run last. A decorator sees a fully initialized class and may return a different object. If it does, the name is bound to that object, and the original class is no longer reachable by name.
- The body is ordinary code. You can use loops, conditionals and function calls in it. It runs once, when the statement executes, and never again for subclasses.
- Subclasses repeat the process. Every subclass statement goes through all the steps again, using the metaclass inherited from its bases.
Summary of the model
A class statement is a function call in disguise. Python collects bases and keyword arguments, asks the metaclass for a namespace, fills it by running the body, and then calls the metaclass with the name, bases and namespace. Inside that call, type.__new__ creates the class and runs __set_name__ and then __init_subclass__. The metaclass __init__ follows, then any decorators, and finally the name is bound.
Exercise
A class Child(Base) has a decorator, a metaclass Meta with __new__ and __init__, a descriptor attribute with __set_name__, and a parent Base with __init_subclass__. List the order in which these five things run: the class body, Meta.__new__ being entered, __set_name__, __init_subclass__, and the decorator. Then say where Meta.__init__ and __prepare__ fall.
Show answer
The order is: __prepare__, class body, Meta.__new__ entered, then inside type.__new__ the __set_name__ call, then __init_subclass__ on Base, then Meta.__init__, and finally the decorator. __prepare__ comes before the body because it supplies the namespace the body writes into. Meta.__init__ comes after __init_subclass__ because it runs only once Meta.__new__ has returned the finished class.
Exercise
A metaclass __new__ calls super().__new__(mcls, name, bases, namespace) and then runs namespace["extra"] = 1. Will Cls.extra exist? Why or why not?
Show answer
No. type.__new__ copies the namespace into the class's own dictionary, so changes to the namespace afterwards do not reach the class. Add the key before calling super().__new__, or use setattr(cls, "extra", 1) after it.