Skip to main content

Special methods

Special methods are the protocol that the interpreter uses to implement built-in operations. A type implements an operation by defining a dunder method; the VM dispatches to that method through a slot on the type. This page is the complete table.

Source-of-record: Objects/typeobject.c (slot setup), the Objects/abstract.c abstract API, and the special method names index.

Slot tables

Every type has a flat C struct of "slot" function pointers. A Python dunder method on the class populates the matching slot; the VM calls the slot, never reads __dict__ directly. The five major slot tables are:

TablePrefixHolds
Type slotstp_General lifecycle, attribute, repr, etc.
Number methodsnb_+, -, *, /, integer protocols.
Sequence methodssq_len, getitem, contains, etc.
Mapping methodsmp_len, getitem, setitem for mappings.
Async methodsam___await__, __aiter__, __anext__.
Buffer methodsbf___buffer__, __release_buffer__.

Construction and destruction

MethodSlotWhen invoked
__new__(cls, *a, **k)tp_newConstruct a new instance. Class method.
__init__(self, *a, **k)tp_initInitialise the instance.
__del__(self)tp_finalizeFinalisation, before deallocation.
__init_subclass__(cls, **kw)-Called when a class is subclassed.
__set_name__(self, owner, name)-Called on descriptors during class creation.

Representation

MethodSlotOperation
__repr__(self)tp_reprrepr(x), fallback for str(x).
__str__(self)tp_strstr(x), print(x).
__bytes__(self)-bytes(x).
__format__(self, spec)-format(x, spec), f"{x:spec}".
__fspath__(self)-os.fspath(x).

Comparison

MethodSlotOperator
__lt__tp_richcompare (Py_LT)<
__le__tp_richcompare (Py_LE)<=
__eq__tp_richcompare (Py_EQ)==
__ne__tp_richcompare (Py_NE)!=
__gt__tp_richcompare (Py_GT)>
__ge__tp_richcompare (Py_GE)>=
__hash__(self)tp_hashhash(x). Mutable containers set this to None.
__bool__(self)nb_boolbool(x). Falls back to __len__.

Returning NotImplemented from a reflected comparison method tells the VM to try the other side.

Attribute access

MethodSlotUsed for
__getattr__(self, name)-Fallback when normal lookup fails.
__getattribute__(self, name)tp_getattroAlways invoked for x.name.
__setattr__(self, name, value)tp_setattrox.name = value.
__delattr__(self, name)tp_setattrodel x.name.
__dir__(self)-dir(x).

Descriptors

MethodSlotRole
__get__(self, obj, objtype=None)tp_descr_getAttribute read.
__set__(self, obj, value)tp_descr_setAttribute write.
__delete__(self, obj)tp_descr_setAttribute delete.

Defining __set__ or __delete__ makes the descriptor a data descriptor and gives it priority over instance __dict__.

Container protocols

Length

MethodSlotOperation
__len__(self)sq_length / mp_lengthlen(x). Result must be >=0.
__length_hint__(self)-operator.length_hint(x) for iterator sizing.

Item access

MethodSlotOperation
__getitem__(self, key)mp_subscript / sq_itemx[key]
__setitem__(self, key, value)mp_ass_subscript / sq_ass_itemx[key] = value
__delitem__(self, key)mp_ass_subscript / sq_ass_itemdel x[key]
__missing__(self, key)-dict.__getitem__ fallback for missing keys.

Iteration

MethodSlotOperation
__iter__(self)tp_iteriter(x), for x in obj.
__next__(self)tp_iternextnext(iter). Raises StopIteration.
__reversed__(self)-reversed(x).
__contains__(self, item)sq_containsitem in x.

Numeric protocols

Binary arithmetic

Each binary op has a forward, reflected, and in-place form:

OperatorForwardReflectedIn-place
+__add____radd____iadd__
-__sub____rsub____isub__
*__mul____rmul____imul__
/__truediv____rtruediv____itruediv__
//__floordiv____rfloordiv____ifloordiv__
%__mod____rmod____imod__
**__pow____rpow____ipow__
@__matmul____rmatmul____imatmul__
<<__lshift____rlshift____ilshift__
>>__rshift____rrshift____irshift__
&__and____rand____iand__
|__or____ror____ior__
^__xor____rxor____ixor__
divmod__divmod____rdivmod__-

__pow__ accepts a third modulus argument for pow(a, b, c).

Unary arithmetic and conversion

MethodSlotOperation
__neg__(self)nb_negative-x
__pos__(self)nb_positive+x
__abs__(self)nb_absoluteabs(x)
__invert__(self)nb_invert~x
__complex__(self)-complex(x).
__int__(self)nb_intint(x).
__float__(self)nb_floatfloat(x).
__index__(self)nb_indexoperator.index(x). Required for slice indices, hex(), etc.
__round__(self, ndigits=None)-round(x, ndigits).
__trunc__(self)-math.trunc(x).
__floor__(self)-math.floor(x).
__ceil__(self)-math.ceil(x).

Coroutines and async

MethodSlotOperation
__await__(self)am_awaitawait x. Returns an iterator.
__aiter__(self)am_aiterasync for x in obj. Returns async iterator.
__anext__(self)am_anextNext async-iteration value.
__aenter__(self)-async with enter.
__aexit__(self, et, ev, tb)-async with exit.

Context managers

MethodOperation
__enter__(self)with x as y: enter.
__exit__(self, exc_type, exc_val, exc_tb)with exit.

Generator and coroutine flow

MethodOperation
send(self, value)Resume a generator and send a value.
throw(self, type[, value[, tb]])Raise an exception inside the generator.
close(self)Raise GeneratorExit.

Pattern matching (PEP 634)

Attribute / methodRole
__match_args__Tuple of attribute names for positional class patterns.
__instancecheck__(cls, instance)isinstance(instance, cls).
__subclasscheck__(cls, subclass)issubclass(subclass, cls).

Reflection support

MethodOperation
__sizeof__(self)sys.getsizeof(x).
__dir__(self)dir(x).
__class_getitem__(cls, item)cls[item]. Class-level subscript (e.g. list[int]).
__instancecheck__(cls, obj)Custom isinstance.
__subclasscheck__(cls, sub)Custom issubclass.
__init_subclass__(cls, **kw)Customise subclass creation.

Class creation

MethodOperation
__prepare__(cls, name, bases, **kw)Returns the namespace mapping. Metaclass method.
__init_subclass__(cls, **kw)Run when a subclass is defined.
__set_name__(self, owner, name)Called on descriptors at class creation.
__class_getitem__(cls, item)Supports list[int].
__mro_entries__(self, bases)Hook to replace a base in __bases__.

Copying

The C-level slots do not implement copying; the protocol lives in copy.py:

MethodUsed by
__copy__(self)copy.copy.
__deepcopy__(self, memo)copy.deepcopy.
__reduce__(self)Pickling fallback.
__reduce_ex__(self, p)Versioned pickling hook.
__getstate__(self)Pickling state extraction.
__setstate__(self, s)Pickling state restoration.
__getnewargs__(self)Pickling __new__ args.
__getnewargs_ex__(self)Pickling __new__ args with kwargs.

Buffer protocol

MethodSlotRole
__buffer__(self, flags)bf_getbufferReturn a memoryview.
__release_buffer__(self, mv)bf_releasebufferRelease acquired buffer.

Call

MethodSlotOperation
__call__(self, *args, **kwargs)tp_callx(...).

Type-parameter protocols (PEP 695)

AttributeMeaning
__type_params__Tuple of TypeVar, TypeVarTuple, ParamSpec.
__typing_subst__Used by Generic during substitution.

Gopy status

Every dunder in CPython 3.14 dispatches to the same slot in gopy. The list above is exhaustive; if a method is reachable from CPython it is reachable from gopy unless flagged in Status.

Reference

  • Objects/typeobject.c. The slot-method wiring.
  • objects/typeobject.go. gopy's port.
  • Data model for the lookup rules.
  • Built-in types for which slots each type implements.