ADR-0024: Keep class variables in globals and defaults in each instance¶
Status¶
Accepted
Date¶
2026-11-13
Context¶
CLS-11 asks for class variables, given a value in the class body. Python gives a value in a class body two meanings, and type checkers follow PEP 526 in telling them apart:
count = 0andcount: ClassVar[int] = 0declare a class variable: one value that the class holds and every instance reads through the class.size: int = 0declares an instance attribute whose default is the class's value: an instance that never assignssizereads the class's value, and one that assigns it has its own.@dataclass(CLS-05) reads these defaults.
In CPython both are attributes of the class object, and an instance reads the class's attribute when it has none of its own. A TyPy instance has a fixed layout (ADR-0012), so an attribute is either in every instance or in none.
Options considered¶
- CPython's lookup at run time. Each read of an attribute looks in the instance, then in the class. This needs a flag per attribute in each instance and a branch on every read.
- A class variable in static storage, a default copied into each
instance. A class variable is a module variable of the class's
module; an annotated default is copied into each new instance before
__init__runs. Writes that would make an instance and the class disagree are refused.
Decision¶
TyPy uses option 2.
- Class variables.
name = valueandname: ClassVar[T] = valuein a class body declare a class variable, held as a module variable of the class's module and given its value where theclassstatement runs, as CPython runs the class body.Class.nameandself.nameread it, andClass.name = valueassigns it, in any function. Assigning it through an instance, which in CPython gives that instance an attribute of its own, is refused. - Annotated defaults.
name: T = valuedeclares an instance attribute with a default. The default is held as a class variable, and each new instance starts with that value, the same object, before__init__runs, so a mutable default is shared as in CPython.Class.namereads the default; assigning it is refused, since in CPython instances that never assigned the attribute would read the new value. - Inheritance. A subclass reads its bases' class variables and starts its instances with its bases' defaults (ADR-0021).
Consequences¶
- Reading a class variable costs a load from static storage; reading an attribute with a default costs what any attribute costs.
- An instance is as large as before: a default takes the place its attribute takes anyway.
- Programs that give one instance its own value of a class variable, a
pattern type checkers also flag, are refused with a message that names
Class.name. - Separate compilation (ADR-0016) exports class variables as it exports module variables.
Related requirements¶
CLS-05, CLS-11, ADR-0012, ADR-0015, ADR-0016, ADR-0021.