Sub topic 3
What happens when Python runs a class statement
This chapter assumes you can define classes and use inheritance, call super(), write simple decorators, and pass **kwargs. It also assumes you know that type(name, bases, namespace) builds a class, which the previous chapter covered. Here you will see that a class statement is a sequence of steps, and which hook runs at each step.
A class statement is a call
This statement:
class Child(Base, flag=True):
x = 1runs roughly like this:
ns = meta.__prepare__('Child', (Base,), flag=True)
exec_body_into(ns) # runs "x = 1" with ns as the local namespace
Child = meta('Child', (Base,), ns, flag=True)Here meta is the metaclass Python chose for the class. If you wrote no metaclass, it is type. The class body is ordinary code that runs once, at definition time, and every name it assigns lands in the namespace mapping.
The steps in order
- Resolve bases. If a base is not a class but defines
__mro_entries__, Python substitutes the real bases. You rarely need this. - Choose the metaclass. An explicit
metaclass=is used unless a base has a more derived metaclass. The chapter on conflicts covers this rule. - Prepare the namespace. Python calls
meta.__prepare__(name, bases, **kwargs). It returns an emptydictby default. - Run the body. The body's assignments and
defstatements fill the namespace. - Call the metaclass.
meta(name, bases, namespace, **kwargs)callsmeta.__new__and thenmeta.__init__. - Inside
type.__new__: the class object is created. Then Python calls__set_name__on every attribute that defines it. Then it calls__init_subclass__on the parent class. - Apply decorators and bind the name. Class decorators run on the result, and the final object is assigned to the name
Child.
__set_name__ and __init_subclass__ run inside type.__new__. So they run before the metaclass __init__ and before any decorator.
Watching the order
This metaclass prints a line from each hook. The example uses a plain Base class and a Child subclass.
class TraceMeta(type):
@classmethod
def __prepare__(mcls, name, bases, **kwargs):
print('1 prepare', name)
return {}
def __new__(mcls, name, bases, ns, **kwargs):
print('3 new', name)
return super().__new__(mcls, name, bases, ns, **kwargs)
def __init__(cls, name, bases, ns, **kwargs):
print('5 init', name)
super().__init__(name, bases, ns, **kwargs)
class Marker:
def __set_name__(self, owner, name):
print('4a set_name', name)
class Base(metaclass=TraceMeta):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print('4b init_subclass', cls.__name__)
print('--- defining Child ---')
class Child(Base):
print('2 body runs')
tag = Marker()Running it prints:
1 prepare Base
3 new Base
5 init Base
--- defining Child ---
1 prepare Child
2 body runs
3 new Child
4a set_name tag
4b init_subclass Child
5 init ChildTwo details are worth noticing. First, Base does not print 4b, because __init_subclass__ runs on the parent when a subclass is created, never for the class that defines it. Second, Child never named a metaclass, yet TraceMeta ran for it, because it inherited Base's metaclass.
Common errors
- Expecting hooks on the defining class.
__init_subclass__and__set_name__do not tell you about the class that holds the code. They tell you about later subclasses and about attributes assigned in a class body. - Reading the finished class too early. In
__new__before you callsuper().__new__, the class does not exist yet. Only the namespace does. - Forgetting to forward keyword arguments. Any
**kwargsfrom the class line reach__prepare__,__new__,__init__, and__init_subclass__. If a hook drops them, the next hook sees nothing. - Assuming decorators run early. A class decorator sees a class that is already fully built, with hooks already run.
Exercise
A class Child(Base) is defined, where Base defines __init_subclass__ and Child defines an attribute whose class has __set_name__. Which runs first for Child: the attribute's __set_name__ or Base.__init_subclass__? Which of these two runs before the metaclass __init__?
Show answer
__set_name__ runs first, then Base.__init_subclass__. Both run inside type.__new__, so both run before the metaclass __init__.
Exercise
Why does Base not print 4b init_subclass in the trace example?
Show answer
__init_subclass__ is called on the parent when a subclass is created. Base is not a subclass of a class with that hook, so only Child triggers it.