ADR 0063: Operators on instances¶
Status: Final
Type: Feature
Created: 2026-10-14
Amends: 0023 and 0040, widening the dunder gate
Related-ADRs: 0032 (an instance's static class is its class), 0007 (a method that raises), 0024 (the result a method returns), 0038 (== with a C | None), 0065 (dispatch on a value of several classes). Provenance: the Shed Skin census (notes/measurements.md, 2026-10-14), where special methods stop 15 programs.
Context¶
The census's programs write vector classes with __add__, __sub__, __mul__ and __neg__ (chaos, pygmy, chull), accumulate with __iadd__ (bh), index a cube or a vector with __getitem__ and __setitem__ (rubik, bh), print with __str__ (seven programs), compare and sort instances, and key dicts by them. ADR 0040's rule is the frame: a special method lands only together with the positions that dispatch to it, because a definition accepted without its dispatch is a method CPython calls and the compiled program never does.
Decision¶
__str__ has __repr__'s exact shape, def __str__(self) -> str, and the positions that call str call it: print(x), str(x), f"{x}", f"{x!s}", "%s" % x and "{}".format(x). A class without one falls back to __repr__, as object.__str__ does, and methods holds inherited methods, so a __str__ in a base wins over a __repr__ in the subclass, as CPython's lookup does. repr(x), !r, %r and a list's elements still call __repr__, which no longer reaches it through str. __bytes__ is held to def __bytes__(self) -> bytes the same way, and bytes(x) calls it as str(x) calls __str__; bytes(x) of an instance of a class without one is refused, CPython's TypeError.
a OP b is a.__OP__(b) when a is an instance of a class the program defines, for + - * @ / // % ** & | ^ << >>. a OP= b is a.__iOP__(b), or a.__OP__(b) when the class has no in-place method. The result is bound to the target: a name, a field or a subscript. -a, +a and ~a are __neg__, __pos__ and __invert__. The call is an ordinary method call (0023's "Methods"), visible to the raiser fixpoint: the right operand is bound to the method's parameter and typed against it. An instance it returns is owned by the expression's site. When the value may be of several classes, the call dispatches on the instance's class at run time (0065).
The reflected methods (__radd__ and the rest) are not admitted. That is what makes the dispatch static. CPython tries b.__radd__(a) first when b's class is a proper subclass of a's that overrides it, and after a.__add__ returns NotImplemented; with no reflected method anywhere, the answer depends on a's class alone, which the compiler knows exactly (ADR 0032). So the compiler refuses 2 * v and p + q for a class without __add__, where CPython raises TypeError and mypy refuses them too.
x[k] is x.__getitem__(k) and x[k] = v is x.__setitem__(k, v), v evaluated before x and k, as CPython evaluates an assignment. x[k] += v is the two in turn. A slice is refused, since CPython passes a slice object, which has no value here. The positions CPython also reaches through __getitem__, iteration and in over an instance without __iter__, stay refused.
Each method's shape is fixed at the definition: (self, other) for a binary operator, (self) for a unary one, (self, key) and (self, key, value) for the item methods, and a declared result that is not None except for __setitem__. CPython binds what an operator returns, so an __iadd__ returning None would make the target None.
Equality and truth¶
Without __eq__, == is identity. A class that defines neither __eq__ nor __ne__ compares with CPython's object.__eq__: a == b is true when a and b are the same object, whatever their fields hold, so == and != between two instances lower to one pointer comparison. That is CPython's answer exactly, including for two instances of different classes. A C | None on either side takes the same fallback, None equal to None and to no instance. in, not in, count, index and remove on a list[C] compare each element with that ==, by identity. == between an instance and a value that is not one is refused as type confusion, as "a" == 1 is, and is stays refused for every type except in x is None (0038, A58).
With __eq__, == calls it (A168). A class may define __eq__(self, other) -> bool; a == b is a.__eq__(b) and a != b its negation, CPython's default __ne__. Both operands must be of one class with no subclass, since CPython calls a subclass's method first with the operands swapped; x == None is refused when x's class has an __eq__, since CPython passes it None. A list search calls no class's __eq__, so in, count, index and remove on a list of such instances stay refused.
A dataclass gets CPython's generated __eq__: the fields compared with == in declaration order and joined by and (True for none), as CPython 3.13 and later write it, when all fields are int, float, bool, str or bytes and the class defines no __eq__. == tests identity first, as CPython's method does, so d == d holds with a NaN field. A dataclass with a field of any other type gets no generated __eq__; == on it is refused where it is written, because methods are lowered whether called or not and an instance field's == can be refused. Identity would be wrong for a dataclass, which is why it never falls back to it.
An instance is true, in if p:, not p and bool(p). CPython asks __bool__, then __len__; no compiled class can define either, nor does a dataclass's expansion, so instances take object's answer: true.
Ordering¶
__lt__ (A167). A class may define __lt__(self, other) -> bool, and a < b on an instance is a.__lt__(b), dispatched as the arithmetic operators are. No reflected method is admitted, so a > b with only __lt__ stays refused; the other orderings are not admitted either.
sort and sorted over instances order by __lt__. CPython calls it in timsort's sequence, which is observable only through a comparison that has an effect or can raise. A sort is therefore admitted when each field read is always bound and non-optional and ends at an int, float, str or bool, and __lt__ has one of three shapes over chains of fields: return self.k < other.k, if self.k1 == other.k1: return self.k2 < other.k2 else: return self.k1 < other.k1, and return self.k1 < other.k1 or (self.k1 == other.k1 and self.k2 < other.k2) (the census's). Each shape is a lexicographic comparison of the keys, so the sort is a stable sort by the last key, then by each earlier one, with reverse applied to each pass, which keeps CPython's order for equal elements. All classes the list may hold must reach the same __lt__. Any other __lt__ is refused at the sort with the reason; a < b itself calls any __lt__. A NaN key falls under the divergence the runtime's sort already records: neither CPython's order nor this one is specified for it.
Hashing¶
An instance may be a key (A168). A class may define __hash__(self) -> int. A class body that defines __eq__ and not __hash__ makes the instances unhashable, as CPython sets __hash__ to None there, so they are refused as keys and elements as a dataclass's are.
The map runtime cannot call a compiled method, so the generated code looks up a key or a set element of a class with both. It calls __hash__ once, as CPython does, then tests each stored key of that hash for identity first and __eq__ after, which is CPython's order. The table holds the keys CPython's would. A dict keeps CPython's insertion order. The keys a probe meets are not the ones CPython's table meets, so __eq__ must be unable to raise or show an effect: a return of ==, !=, and, or and not over fields of the two parameters and accessors of the class, each field always bound. __hash__ must bind locals only and call only hash, str, len, range, abs, int, ord, min, max, bool and methods of the receiver under the same rule; it may raise, since CPython calls it the same number of times. Iterating or printing a set of instances stays refused (A133), and so do d.update(other) and a key of several classes.
hash() of an int, a bool, or a tuple of them (fixed, nested, or a tuple[int, ...]) lowers anywhere as CPython computes it, since none depends on the process. An int's hash is its magnitude modulo 2**61 - 1 with its sign, -1 spelled -2; a tuple's is xxHash rounds over the items' hashes. This is the value the program sees; a dict or a set hashes its keys with its own function (0058). hash() of a str is lowered only inside a __hash__; a call of x.__hash__() is refused. A str's hash is this runtime's (31 bits, so a __hash__'s sums stay in an int64). CPython's changes from one process to the next; only the dict or the set sees it.
Consequences¶
- The raiser walk gains an edge from each position that calls a special method implicitly to the methods of that name. The missing edge was older than this decision: a
__repr__that raised insideprint(p)lost its exception (notes/accept-then-wrong.md§50). x[f()] += 1evaluatesf()once, for a list or a dict as for an instance; it calledftwice before (§51).- Still refused, each with CPython's reason: the reflected methods, the orderings other than
__lt__,__len__,__bool__,__contains__,__iter__and__abs__. - sudoku1, which keys a dict by
hashcode * 17 + hash(tuple(row)), compiles and computes CPython's keys.hash()of a tuple is CPython's; the running value passes 64 bits and grows (0075). (a + b).xis refused, with the other attributes of expressions (the census root that plan B2 mostly lifts).
Alternatives considered¶
- Admitting the reflected methods.
a OP bwould then need CPython's subclass-first rule andNotImplementedas a value, for no program in the census. - Desugaring
a += btoa = a + b. It is wrong for a class with__iadd__, which mutates in place and may return something else. - Lowering
x[k] = vwithkbeforev. It is the order of the read, and differs from CPython's when either has an effect.