Lesson 42 of 52Python under the hood
How Classes Are Made
Follow the class statement step by step, then use __init_subclass__, class decorators, __new__ and metaclasses only where each one fits.
Your team's reporting service supports CSV and JSON exports, and every new format means editing a big if fmt == ... chain in three places. Someone proposes that a new exporter should "just register itself" when you write the class. Another teammate opens Django's model code to see how class Order(models.Model) turns into a database table, and finds a metaclass. Frameworks do clever things at the moment a class is defined, not when it is used. This lesson shows you exactly what happens in that moment, and gives you a clear ladder of tools, from the simple one you should use most days to the metaclass you will rarely need but must be able to read.
Classes are objects, and type makes them
You saw in The Python Memory Model that everything is an object. Classes are no exception: a class is an object you can pass around, store in a dict and inspect at runtime. Every object has a type, so a class has a type too. For almost every class, that type is type. A class whose instances are classes is called a metaclass, and type is the default one.
Because type is a class, you can call it. With one argument it tells you an object's type. With three arguments it creates a new class: a name, a tuple of bases and a namespace dict.
Press Run (⌘ Enter) to see what happens.You will rarely call type(...) like that in real code. Its value is the mental model: a class statement is just a convenient way to gather a name, bases and a namespace, then call a metaclass with them.
What the class statement does, step by step
When Python executes a class statement, these steps run in order. Knowing them lets you predict exactly when your hooks fire and what they can see.
Python picks the metaclass: an explicit metaclass= keyword, otherwise the most derived metaclass among the bases. If two bases have unrelated metaclasses, this is where the metaclass conflict error comes from.
Run this trace and match each line to the tree.
Press Run (⌘ Enter) to see what happens.Three details from that output matter in practice. The class body runs once, at import time, which is why a slow call or a print in a class body happens on import. Base.__init_subclass__ did not run for Base itself, only for its subclasses. And the metaclass is inherited: Report never mentioned Meta, yet type(Report) is Meta.
Put these events in the order they happen when Python executes a class statement.
- Tap the steps below in the right order.
__init_subclass__: the modern first choice
Most problems that people used to solve with a metaclass only need one thing: run some code every time someone subclasses my class. Since Python 3.6, __init_subclass__ does exactly that, with no metaclass. It is an implicit classmethod on the parent, called with each new subclass and any keyword arguments written in the class line.
Here is the self-registering exporter from the introduction, with validation that runs at import time instead of in production.
Press Run (⌘ Enter) to see what happens.The habits worth copying:
- Always call
super().__init_subclass__(**kwargs). Another base class in a multiple-inheritance chain may have its own hook, and skippingsuper()silently disables it. - Use keyword-only arguments (
*, fmt=...) so the class line reads clearly. - Fail at definition time. A broken plugin now crashes on import, in CI, not on the first customer request that happens to use it.
One trap with registries: a subclass is only registered if its module is imported. If nothing imports exporters/xml.py, its class never runs and is never registered. Real plugin systems solve this with an explicit import list, a package scan with pkgutil, or packaging entry points (importlib.metadata.entry_points). Python's own entry_points mechanism is how tools such as pytest discover installed plugins.
What does this print?
class Base:
names = []
def __init_subclass__(cls, **kw):
super().__init_subclass__(**kw)
Base.names.append(cls.__name__)
class A(Base): pass
class B(A): pass
class C(Base): pass
print(Base.names)Class decorators: how @dataclass works
A class decorator is a function that takes the finished class and returns a class, usually the same one with extra methods attached. You saw them in Decorators ("Class decorators and frameworks"). The best-known one is @dataclass, and its core idea fits in a few lines: read the class annotations, then generate methods from them.
Press Run (⌘ Enter) to see what happens.The last line exposes the weakness of this toy. The generated __init__ has the signature (*args, **kwargs), so editors cannot autocomplete it and type checkers cannot check calls. The real dataclasses module avoids this by building the source text of an __init__ with the exact parameters and compiling it, so inspect.signature shows (self, name: str, email: str, active: bool = True). Type checkers do not run your decorator at all; they understand @dataclass through special rules, and third-party libraries opt into the same treatment with typing.dataclass_transform (3.11).
Notice inspect.get_annotations(cls) rather than cls.__annotations__. Since Python 3.14, annotations are evaluated lazily (more on that in What Changed in Python 3.11 to 3.15), and the annotationlib and inspect helpers are the supported way to read them, including when they contain forward references.
Prefer a class decorator over a metaclass when the change is a one-off transformation of one class. Decorators are explicit at the definition site, they compose by stacking, and they are not inherited, which is often what you want: a subclass of a dataclass is not a dataclass unless you decorate it too.
__new__ vs __init__
Creating an instance is two steps. Cls(...) calls type.__call__, which first calls Cls.__new__(Cls, ...) to create the object, then, if the result is an instance of Cls, calls obj.__init__(...) to initialise it. Most classes only need __init__. You need __new__ in two situations.
Subclassing immutable types. An int, str, float, tuple or frozenset has its value fixed at creation. By the time __init__ runs, it is too late to change it. Normalise or validate in __new__.
Controlling which object comes back: caching instances, returning an existing object, or returning a subclass. This is where the "singleton class" pattern lives, and it has a sharp edge.
Press Run (⌘ Enter) to see what happens.The singleton returned the same object, but __init__ ran again on every call and wiped its state. This is the bug in most hand-written singletons. In Python the idiomatic singleton is simply a module: modules are imported once and cached in sys.modules, so a module-level settings = Settings() is shared by every importer. If you need lazy creation, a function decorated with functools.cache returns the same object every time. Both are easier to replace in tests than a class that fights its own constructor.
__class_getitem__: how list[int] works
Writing list[int] looks like indexing a class. It is: subscripting a class calls its __class_getitem__ classmethod (3.7). For built-in containers, that returns a types.GenericAlias, a lightweight object that records the origin (list) and the arguments (int) and otherwise behaves like the original class.
Press Run (⌘ Enter) to see what happens.list[int] is for type checkers; at runtime it does not check anything, which is why list[int]([1, 2]) builds an ordinary list. A generic class declared with the 3.12 syntax class Repo[T] gets __class_getitem__ for free, as you saw in Type Hints. Write your own __class_getitem__ only for type-hint support in a library; using it for anything else confuses readers.
Metaclasses: when they are justified
A metaclass customises class creation for a class and every subclass of it, forever. That inheritance is both its power and its cost. Tim Peters put the rule well: if you wonder whether you need a metaclass, you don't. Reach for one only when the earlier tools cannot do the job:
- Changing how the class object itself behaves, not just its instances:
len(Colour), iteratingfor c in Colour, orColour["RED"]work becauseEnumTypedefines__len__,__iter__and__getitem__on the metaclass. You met it in Enums. - Controlling instance creation for a whole hierarchy by overriding the metaclass
__call__, asEnumTypedoes to turnColour("red")into a lookup. - Changing the namespace before the body runs with
__prepare__, for example recording definition order or rejecting duplicate names. - Framework declarative bases: Django's
ModelBaseand SQLAlchemy's declarative machinery collect field declarations and build table metadata.ABCMetatracks abstract methods and powersregister()for virtual subclasses, as in Inheritance and Composition.
The biggest practical problem is the metaclass conflict. A class has exactly one metaclass, and it must be a subclass of every base's metaclass. Mix bases from two libraries that each bring their own metaclass and class creation fails.
Press Run (⌘ Enter) to see what happens.The fix is a combined metaclass, which only works when the two metaclasses cooperate through super(). This is the main reason library authors avoid metaclasses now: every one they ship is a possible conflict for their users. __init_subclass__ has no such problem.
Handler to declare a route class attribute, and to fail at import time if it is missing. What is the simplest correct tool?Introspection and monkeypatching
You will meet a few more class-level tools in real code, mostly in frameworks and tests. Know them well enough to read them.
inspect answers questions about live objects. inspect.signature(f) gives parameters, kinds and defaults, and sig.bind(...) maps call arguments to parameters the way Python would. FastAPI and pytest both read signatures to decide what to inject. inspect.getmembers(obj, predicate) lists attributes, and inspect.get_annotations reads annotations safely.
types.SimpleNamespace is an object you can add attributes to freely, handy for quick config objects and test fakes. types.MethodType(func, obj) binds a function to one instance, doing by hand what the descriptor protocol does for functions on a class.
Monkeypatching means replacing an attribute on a module or class at runtime. It is legitimate in tests, where unittest.mock.patch or pytest's monkeypatch fixture do it and, crucially, undo it afterwards. In application code it creates action at a distance: a patched class behaves differently depending on whether some other module was imported first.
Press Run (⌘ Enter) to see what happens.Match each job to the tool that fits it best.
- metaclass
- The class of a class. It creates class objects; the default is
type. - type(name, bases, ns)
- The three-argument call that builds a class, which is what a class statement does under the hood.
- __prepare__
- A metaclass hook that returns the namespace dict the class body will fill.
- __init_subclass__
- A hook on a parent class that runs for every new subclass, with any class keyword arguments (3.6+).
- class decorator
- A function that receives a finished class and returns a class, as
@dataclassdoes. Not inherited. - __new__
- Creates the instance before
__init__runs. Needed for immutable subclasses and for returning existing objects. - metaclass conflict
- The
TypeErrorraised when bases have unrelated metaclasses, since a class can only have one.