Skip to content

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.

20 min read0/4 questions

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.

Python
def greet(self): return f"hi, I am {self.name}" # Exactly what a class statement would buildPerson = type("Person", (object,), {"name": "ada", "greet": greet}) p = Person()print(p.greet())print(type(p).__name__, type(Person).__name__, type(type).__name__)print(isinstance(Person, type), Person.__mro__)
Output
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.

class Report(Base, table='reports'): ...
class statement1 find the metaclassmost derived metaclass of the bases, or metaclass=2 __prepare__returns the namespace dict3 run the class bodyevery def and assignment fills the namespace__set_name__on each attribute that defines it__init_subclass__on the parent classtype.__new__builds the class objectmetaclass __init__4 metaclass(name, bases, ns, **kwargs)5 class decoratorsapplied bottom up6 bind the name Reportin the enclosing scoperoot

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.

1/5

Run this trace and match each line to the tree.

Python
class Field: def __set_name__(self, owner, name): print(f"4. __set_name__: {name} on {owner.__name__}") class Meta(type): @classmethod def __prepare__(mcls, name, bases, **kw): print(f"1. __prepare__ for {name}, kwargs={kw}") return {} def __new__(mcls, name, bases, ns, **kw): print(f"3. Meta.__new__: body gave {sorted(k for k in ns if not k.startswith('__'))}") cls = super().__new__(mcls, name, bases, ns, **kw) print(f"6. type.__new__ returned {cls.__name__}") return cls def __init__(cls, name, bases, ns, **kw): print(f"7. Meta.__init__ for {name}") super().__init__(name, bases, ns, **kw) print("--- defining Base")class Base(metaclass=Meta): def __init_subclass__(cls, **kw): print(f"5. Base.__init_subclass__({cls.__name__}, {kw})") super().__init_subclass__() def decorate(cls): print(f"8. class decorator gets {cls.__name__}") return cls print("--- defining Report")@decorateclass Report(Base, table="reports"): print("2. class body runs") title = Field() def render(self): ... print("9. name bound:", Report.__name__, "made by", type(Report).__name__)
Output
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 it in order6 steps

Put these events in the order they happen when Python executes a class statement.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

__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.

Python
class Exporter: registry: dict[str, type["Exporter"]] = {} def __init_subclass__(cls, *, fmt: str | None = None, **kwargs): super().__init_subclass__(**kwargs) if fmt is None: # abstract helper class: skip return if fmt in Exporter.registry: raise TypeError(f"duplicate exporter for {fmt!r}") if not callable(getattr(cls, "export", None)): raise TypeError(f"{cls.__name__} must define export()") Exporter.registry[fmt] = cls @classmethod def for_format(cls, fmt: str) -> "Exporter": try: return cls.registry[fmt]() except KeyError: raise ValueError(f"no exporter for {fmt!r}; have {sorted(cls.registry)}") from None class CsvExporter(Exporter, fmt="csv"): def export(self, rows): return "\n".join(",".join(map(str, r)) for r in rows) class JsonExporter(Exporter, fmt="json"): def export(self, rows): import json return json.dumps(rows) rows = [[1, "ada"], [2, "bob"]]print(sorted(Exporter.registry))print(Exporter.for_format("csv").export(rows))print(Exporter.for_format("json").export(rows)) try: class Broken(Exporter, fmt="xml"): passexcept TypeError as e: print("TypeError:", e) try: class AnotherCsv(Exporter, fmt="csv"): def export(self, rows): ...except TypeError as e: print("TypeError:", e) try: Exporter.for_format("pdf")except ValueError as e: print("ValueError:", e)
Output
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 skipping super() 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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Python
import inspect def record(cls): """A tiny @dataclass: read the annotations, generate methods.""" fields = list(inspect.get_annotations(cls)) defaults = {f: cls.__dict__[f] for f in fields if f in cls.__dict__} def __init__(self, *args, **kwargs): values = dict(defaults) values.update(zip(fields, args)) values.update(kwargs) missing = [f for f in fields if f not in values] if missing: raise TypeError(f"missing: {', '.join(missing)}") for f in fields: setattr(self, f, values[f]) def __repr__(self): inner = ", ".join(f"{f}={getattr(self, f)!r}" for f in fields) return f"{cls.__name__}({inner})" def __eq__(self, other): if type(other) is not type(self): return NotImplemented return all(getattr(self, f) == getattr(other, f) for f in fields) cls.__init__, cls.__repr__, cls.__eq__ = __init__, __repr__, __eq__ cls.__hash__ = None # mutable and has __eq__: unhashable, like @dataclass return cls @recordclass User: name: str email: str active: bool = True u = User("ada", "ada@example.com")print(u)print(u == User("ada", "ada@example.com"), u == User("bob", "b@example.com"))try: User("ada")except TypeError as e: print("TypeError:", e)print(inspect.get_annotations(User))print(inspect.signature(User.__init__))
Output
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.

Python
class Celsius(float): def __new__(cls, degrees): if degrees < -273.15: raise ValueError("below absolute zero") return super().__new__(cls, round(degrees, 2)) def __init__(self, degrees): # too late to change the value: float is immutable print(" __init__ sees", float(self)) t = Celsius(21.456)print(t, type(t).__name__, t + 1) class Settings: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self): print(" __init__ runs again") self.values = {} a = Settings(); a.values["debug"] = Trueb = Settings()print(a is b, a.values)
Output
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.

Python
print(list[int], type(list[int]).__name__, list[int].__origin__, list[int].__args__)print(isinstance([1], list), list[int]([1, 2])) class Box: def __class_getitem__(cls, item): return f"Box of {item.__name__}" print(Box[int]) class Repo[T]: def __init__(self): self.items: list[T] = [] print(Repo[str], Repo.__type_params__)
Output
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), iterating for c in Colour, or Colour["RED"] work because EnumType defines __len__, __iter__ and __getitem__ on the metaclass. You met it in Enums.
  • Controlling instance creation for a whole hierarchy by overriding the metaclass __call__, as EnumType does to turn Colour("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 ModelBase and SQLAlchemy's declarative machinery collect field declarations and build table metadata. ABCMeta tracks abstract methods and powers register() 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.

Python
from abc import ABCMeta, ABC class PluginMeta(type): pass class Plugin(metaclass=PluginMeta): pass class Shape(ABC): # ABC's metaclass is ABCMeta pass try: class Circle(Shape, Plugin): passexcept TypeError as e: print("TypeError:", str(e)[:60] + "...") class ShapePluginMeta(ABCMeta, PluginMeta): pass class Circle(Shape, Plugin, metaclass=ShapePluginMeta): pass print(type(Circle).__name__, [m.__name__ for m in type(Circle).__mro__])
Output
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.

Quick check
You want every subclass of Handler to declare a route class attribute, and to fail at import time if it is missing. What is the simplest correct tool?
Need a nudge? A hint rules out a wrong answer.

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.

Python
import inspect, types def charge(amount: int, currency: str = "GBP", *, idempotency_key: str) -> dict: return {"amount": amount, "currency": currency, "key": idempotency_key} sig = inspect.signature(charge)for name, p in sig.parameters.items(): print(name, p.kind.name, p.default if p.default is not p.empty else "-")bound = sig.bind(500, idempotency_key="k-1")bound.apply_defaults()print(bound.arguments) class Order: def total(self): return 10 @property def tax(self): return 2 print([n for n, _ in inspect.getmembers(Order, inspect.isfunction)]) cfg = types.SimpleNamespace(region="eu-west-2", retries=3)cfg.timeout = 5print(cfg) o = Order()o.total = types.MethodType(lambda self: 99, o) # patch one instanceprint(o.total(), Order().total())
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/5 matched

Match each job to the tool that fits it best.

Choose an item, then its match on the other side.
Key terms
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 @dataclass does. Not inherited.
__new__
Creates the instance before __init__ runs. Needed for immutable subclasses and for returning existing objects.
metaclass conflict
The TypeError raised when bases have unrelated metaclasses, since a class can only have one.