Skip to content

ADR 0023: Class instances

Status: Final Type: Feature Created: 2026-07-29 Amended-By: 0024 (lifetime: an instance is counted and released), 0032 (single inheritance), 0040 (__repr__), 0042 (class attributes, isinstance), 0063 (operators) Related-ADRs: 0035 (the header layout), 0065 (a value of several classes). Provenance: arbitrations A125, A144, A147, A149, A172.

Context

A class instance has reference semantics: self.x = 1 inside a method must be visible to the caller, and b = a must alias. That is CPython's rule, and the corpus programs with a class rely on it. An instance therefore cannot be a value copied into a parameter. It became the first POST type that is a heap object with identity, allocated by the program, with an owner to be decided (0024 decides it).

Decision

Layout

An instance is a pointer to a heap block of nslots eight-byte slots, one per field, in declaration order, pointing at field 0 with the header at a negative offset (0024/0035 define the header). Allocation is one zeroing call, so a slot is a defined zero before __init__ writes it; a zero-field class still gets one slot, so separate instances of it stay separate objects.

A field access is a runtime call (accessor pairs keyed on the field's wire type), and no IR instruction exists for it. The layout therefore lives in one C file that all three backends link, so no emitter has to agree with another about offsets. The ABI check also applies for free: a Str field read through the integer accessor is caught as a wire-type mismatch. The accessors take a slot index; the multiply belongs to the runtime, so a future narrower layout is a change to one C file. A Bool field is stored at Int64 width and narrowed on the way out, the one place wire type and declared type differ.

Fields, as a type checker types them

What a type checker infers, postpile infers (A144), and mypy types a field from whatever a method assigns it. So:

  1. The layout is every self.x = ... binding in every method of the class, at any depth, one slot per name, in order of first appearance, reading __init__ first and the other methods in source order; tuple targets holding self.x count. A subclass's own fields follow the base's (0032). A class-body annotation without a value (name: str, not a ClassVar, in a class that is not a dataclass) declares an instance field of that type, laid out before the fields the methods bind (A172), which is how mypy accepts a store from another class's method. CPython binds nothing at class level for it, so C.name stays refused as a class attribute. A class-body x = 0 is a class attribute (0042).
  2. A field's type is the type of the value its first binding assigns, for any value this compiler can lower: arithmetic, a call with a declared return, a constructor, another field, a container whose members are known, an empty container completed in the same method (0031). An annotation (self.x: int | None = None) declares it. A field bound to None takes its type from a later assignment in the same method, as a local does (A147). One type per field, so a later binding must be holdable in the first one's type (0004: an int is not widened to a float).
  3. Types come from the lowering, with mypy's deferral. An annotation, a literal or a parameter types a field where it is collected. Any other first binding leaves the field pending until a probe types it: the method holding that binding is lowered once and thrown away, with each field it first binds read and written as a local, so a local's inference serves a field unchanged. The probe of a script's top level that types the module globals (0060) is one probe among these. Probes run in rounds: one that uses a field or global still pending runs again once a round has typed more. A field that waits on itself through others is refused, asking for an annotation.
  4. A field __init__ may leave unbound gets a bound flag. A field __init__ does not bind before the instance escapes (a use of self other than storing a field or reading one already bound, a method call included, and the base's __init__ when that escapes) gets a flag slot, set by each store and tested at each read, which raises CPython's AttributeError: 'C' object has no attribute 'x'. AttributeError is in the exception vocabulary (0007). A function with a read that may raise it is a raiser. A field __init__ binds on all paths first, the common case, needs no flag and costs nothing.

Methods

A method lifts to an ordinary top-level function with the receiver as first parameter, typed as an instance of the class. Construction is a pair of calls (allocate, then __init__) and a method call is one. A method adds no call mechanism: the signature checks, the arity diagnostics (quoting Point.move) and the raiser analysis all apply as to any call. The raiser analysis resolves p.m() by name across all classes and over-approximates when classes share a method name: an unnecessary pending check costs a branch, a missing one swallows an exception.

The class surface spec §5.1 and §4.4 name lowers too:

  • @staticmethod is a method whose call passes no receiver, reached through an instance or through the class (A.f(...)).
  • @classmethod is a static method in each per-receiver copy (0032), with cls bound to that copy's class. cls(), cls.attr and cls.other() are then a construction, a class attribute and a static call, so Kelvin.freezing() builds a Kelvin through a method Temperature defines. typing.Self (PEP 673) is the receiver's class in the same copy.
  • @dataclass is expanded before collection into the __init__, __repr__ and __eq__ CPython writes (0063 for __eq__). Defaults must be literal scalars or strings; a dataclass base's fields come first. The __repr__ names the receiver in each copy, as __qualname__ does.
  • __slots__ lowers to nothing, since the layout is fixed at construction already, which is what __slots__ asks for. A literal list or tuple of names, or one name, is accepted. What CPython rejects is refused at compile time: a stored field that no __slots__ of a class's chain lists, when each class of the chain has one (CPython's AttributeError at the store), and a slot named like a method or a class attribute of the class (CPython's ValueError when the class is created).
  • A string annotation is the forward reference it spells (-> "Node"). A call whose declared result is an instance can be the base of a field read or method call (Node(1).bumped().v), decided from declarations, so nothing is evaluated twice. A string statement in a class body other than the docstring is evaluated and discarded, as CPython does.

The refusal boundary

What an instance cannot do refuses with the reason named. These refusals are decisions, each with its reason:

  • is, id(), __del__: is on instances would be one pointer comparison, yet it is refused: on ints and strs a is b is CPython-implementation-defined. An operator must not mean "identity" for one operand type and "no lowering" for another, so it becomes available for all types at once or for none. x is None asks another question and lowers (0038). All three also keep the cycle-collection options open (0024).
  • A special method lands only with every position that dispatches to it: a dunder is a protocol CPython dispatches to implicitly, and accepting a definition without lowering all dispatch positions would compile a method that is never called (0040 states the rule; 0063 lists what lowers).
  • New attributes at run time, or a decorator this ADR does not name: one way to reach a name, one layout, fixed at construction. Each of these changes the class in a way the lowering does not reproduce, so each is refused: super() in a static or class method, an instance method reached through the class, a dataclass option (frozen, order, ...), field(...), an out-of-order default. A dunder slot (__dict__ brings the dictionary back), a computed __slots__ and __slots__ on a dataclass are refused for the same reason.
  • Crossing boundaries: an instance is refused at task boundaries (mutable heap state is neither val nor handle; the whole memory model rests on the sendability rule), at the stable C ABI (a C caller has no accessors), and at the CPython callback boundary (no conversion exists). Array[Point] and Chan[Point] refuse with the same sentence.

What else is refused today is listed in the compatibility page.

Consequences

  • The layout question and the lifetime question stay separate: this ADR's accessors were byte-for-byte unchanged when the header grew a count, and again when it grew the descriptor.
  • Because accessors are checked runtime call, a category of backend disagreement (offset arithmetic) is unrepresentable.
  • Each refusal states a reason a reader can check is still true.
  • A read of an inherited field in a subclass's __init__ before its super().__init__() call raises CPython's AttributeError, as a read of any field not yet bound does. The class-attribute window of A125 (a class attribute shadowed by a field bound later) stays refused (0042).

Alternatives considered

  • Inline field access in the IR (a GetField/SetField instruction pair): rejected: the pair briefly existed without a producer, verifier rule or backend support, the trap a shared IR must avoid, and was removed in favour of the accessor calls.
  • Type-tagged instances, for the release walk: rejected, since the descriptor answers which slots hold references; see 0024's alternatives. The class number an instance holds serves dispatch only (0065).
  • Value-semantics structs: rejected: CPython's classes alias, so a copied "instance" would silently diverge on the first mutation.