Special methods (“dunder” methods, for d ouble under score) let your objects work with Python syntax and built-ins: len(x), x[i], a + b, with x:, for item in x. Python calls them for you; you rarely call them yourself.
I want to…
Use…
Example
show an object clearly in logs and the REPL
__repr__
Money(1349, 'USD')
show friendly text to users
__str__
13.49 USD
support format specs in f-strings
__format__(self, spec)
f"{price:,.2f}"
compare by value
__eq__; return NotImplemented for other types
Money(5) == Money(5)
use objects as dict keys or in sets
__hash__ from the same fields as __eq__
hash((self.cents, self.currency))
sort, min(), max()
__lt__ + __eq__ + @functools.total_ordering
sorted(versions)
len(x)
__len__
len(playlist)
x[i], x[a:b], x["key"]
__getitem__; test isinstance(key, slice)
playlist[1:3]
x[k] = v, del x[k]
__setitem__, __delitem__
a mutable store
for item in x
__iter__ written as a generator
yield from self._items
item in x
__contains__
"ada" in team
control if x:
__bool__, or only __len__
empty is falsy
call an object like a function
__call__
retry(fetch)
set up and always clean up
__enter__ / __exit__
with Transaction(db):
async with x:
__aenter__ / __aexit__
an async DB session
a + b, a * k, a @ b
__add__, __mul__, __matmul__
v1 + v2
2 * v, sum(xs)
reflected __rmul__, __radd__
__rmul__ = __mul__
a += b in place
__iadd__, return self
a mutable accumulator
-v, abs(v)
__neg__, __abs__
abs(v1 - v2)
decline an operand type
return NotImplemented
Python tries the other side
a fallback for missing attributes
__getattr__
delegate to a wrapped object
block or check every assignment
__setattr__
a read-only object
reuse a validated attribute on many classes
a descriptor: __get__, __set__, __set_name__
price = Positive()
run code when a subclass is created
__init_subclass__
a plugin registry
Cls[int] in type hints
__class_getitem__ (or Generic / class C[T]:)
Box[int]
a dict with defaults for missing keys
subclass dict + __missing__
defaultdict, Counter
open(x), Path(x) on your object
__fspath__
a class that names a file
control copy / pickle
__copy__, __deepcopy__, __getstate__, __setstate__
drop an open socket before pickling
positional patterns in match
__match_args__
case Point(x, y):
write most of these for you
@dataclass
see data containers
Python looks special methods up on the class , not the instance. Each table reads: method → triggered by → example.
Method
Triggered by
Example
__new__(cls, *args)
Cls(...), first; creates and returns the object
subclass str, int, tuple; instance caching
__init__(self, *args)
Cls(...), after __new__; fills the object; returns None
self.cents = cents
__del__(self)
garbage collection; timing not guaranteed
rarely; use with for cleanup
__copy__(self)
copy.copy(x)
share or reset caches
__deepcopy__(self, memo)
copy.deepcopy(x)
copy nested state
__getstate__(self)
pickle.dumps(x), copy
drop an open file or lock
__setstate__(self, state)
pickle.loads(...), copy
reopen the resource
__reduce__(self)
pickle for objects that need custom rebuilding
return (Cls, (self.a,))
__reduce_ex__(self, protocol)
pickle, copy; tried before __reduce__
rarely overridden
__getnewargs_ex__(self), __getnewargs__(self)
unpickling a class whose __new__ needs arguments
return ((self.code,), {})
__post_init__(self)
a @dataclass __init__, after the fields are set (not a Python dunder)
see data containers
__sizeof__(self)
sys.getsizeof(x)
shallow size in bytes
Method
Triggered by
Example
__repr__(self)
repr(x), REPL echo, items inside containers, f"{x!r}", f"{x=}", logging %r
Money(1349, 'USD')
__str__(self)
str(x), print(x); f"{x}" through the default __format__; falls back to __repr__
13.49 USD
__format__(self, spec)
format(x, spec), f"{x:spec}", and f"{x}" with spec '' (the default object.__format__ calls str())
f"{m:.0f}"
__bytes__(self)
bytes(x)
a binary message
__bool__(self)
bool(x), if x:, while x:, and, or, not; falls back to __len__
zero money is falsy
__int__, __float__, __complex__
int(x), float(x), complex(x)
float(Money(250)) → 2.5
__index__(self)
x as an index or slice bound, range(x), bin(x), hex(x)
integer-like IDs
__round__(self, n=None)
round(x), round(x, n)
round money to cents
__trunc__, __floor__, __ceil__
math.trunc(x), math.floor(x), math.ceil(x)
numeric types
__fspath__(self)
os.fspath(x), open(x), Path(x)
Upload("a.csv") used as a path
Method
Triggered by
Reflection if NotImplemented
Example
__eq__(self, other)
a == b, x in list, list.index, list.count, list.remove
b.__eq__(a)
same fields
__ne__(self, other)
a != b; default inverts __eq__
b.__ne__(a)
rarely written
__lt__(self, other)
a < b, sorted(), list.sort(), min(), max(), heapq, bisect
b.__gt__(a)
older version
__le__(self, other)
a <= b
b.__ge__(a)
from @total_ordering
__gt__(self, other)
a > b
b.__lt__(a)
from @total_ordering
__ge__(self, other)
a >= b
b.__le__(a)
from @total_ordering
__hash__(self)
hash(x), set members, dict keys, functools.cache arguments
—
hash((self.major, self.minor))
Method
Triggered by
Example
__len__(self)
len(x); truth test when __bool__ is missing
len(playlist)
__getitem__(self, key)
x[key]; x[a:b] passes a slice; x[i, j] passes a tuple
playlist[0], grid[1, 2]
__setitem__(self, key, value)
x[key] = value
a settings store
__delitem__(self, key)
del x[key]
a settings store
__missing__(self, key)
d[key] on a dict subclass when the key is missing
defaultdict, Counter
__contains__(self, item)
item in x, item not in x; falls back to __iter__
21.5 in Range(19, 23)
__reversed__(self)
reversed(x); falls back to __len__ + __getitem__
newest first
__length_hint__(self)
operator.length_hint(x); list pre-sizing
lazy iterators
Method
Triggered by
Example
__iter__(self)
for, list(x), sum(x), zip(), *x, a, b = x, comprehensions
yield from self._items
__next__(self)
next(it); only on iterators; raise StopIteration at the end
generator objects
__aiter__(self)
async for item in x
a stream of messages
__anext__(self)
each step of async for; raise StopAsyncIteration
async generators
__await__(self)
await x
custom awaitables (rare)
Method
Triggered by
Example
__call__(self, *args)
x(...)
a stateful callback, a decorator class
__enter__(self)
the start of with x as name:; its result goes to name
open a transaction
__exit__(self, exc_type, exc, tb)
the end of the with block, also after an exception; return True to suppress
commit or roll back
__aenter__, __aexit__
async with x:
httpx.AsyncClient, DB sessions
Operator
Method
Reflected (x on the right)
In place
a + b
__add__
__radd__
a += b → __iadd__
a - b
__sub__
__rsub__
__isub__
a * b
__mul__
__rmul__
__imul__
a / b
__truediv__
__rtruediv__
__itruediv__
a // b
__floordiv__
__rfloordiv__
__ifloordiv__
a % b
__mod__
__rmod__
__imod__
divmod(a, b)
__divmod__
__rdivmod__
—
a ** b, pow(a, b)
__pow__
__rpow__
__ipow__
a @ b
__matmul__
__rmatmul__
__imatmul__
a & b
__and__
__rand__
__iand__
a | b
__or__
__ror__
__ior__
a ^ b
__xor__
__rxor__
__ixor__
a << b, a >> b
__lshift__, __rshift__
__rlshift__, __rrshift__
__ilshift__, __irshift__
Method
Triggered by
Example
__neg__(self)
-x
-Vector(1, 2)
__pos__(self)
+x
rarely; Decimal rounds to context
__abs__(self)
abs(x)
vector length
__invert__(self)
~x
NOT of a pandas mask, a flag set
Method
Triggered by
Example
__getattr__(self, name)
x.name when normal lookup fails
delegation proxies, lazy attributes
__getattribute__(self, name)
every x.name, before anything else
tracing; avoid overriding
__setattr__(self, name, value)
x.name = value, setattr()
read-only objects, change tracking
__delattr__(self, name)
del x.name, delattr()
block deletes
__dir__(self)
dir(x), tab completion
list dynamic attributes
__slots__ (a class attribute)
instance creation: fixed attribute names, no __dict__
memory per object
Method
Triggered by
Example
__get__(self, obj, objtype=None)
obj.attr when attr is a descriptor on the class; obj is None for Cls.attr
property, methods, cached_property
__set__(self, obj, value)
obj.attr = value; makes it a data descriptor that wins over vars(obj)
validated fields
__delete__(self, obj)
del obj.attr
rare
__set_name__(self, owner, name)
the owner class is created (after its body runs); tells the descriptor its attribute name
self.private = "_" + name
Method
Triggered by
Example
__init_subclass__(cls, **kwargs)
a subclass is created; keywords come from the class line
class Csv(Exporter, fmt="csv")
__class_getitem__(cls, item)
Cls[item]
list[int], Box[str]
__mro_entries__(self, bases)
a non-class object listed as a base
typing.NamedTuple
__instancecheck__, __subclasscheck__
isinstance(), issubclass(); defined on a metaclass
ABCs, Protocols
__subclasshook__(cls, sub)
issubclass() on an ABC
Sized accepts any class with __len__
__prepare__(name, bases)
before the class body runs; on a metaclass
enum collects members
__match_args__ (a class attribute)
positional class patterns in match
case Point(x, y):
__buffer__(self, flags) (3.12+)
memoryview(x)
binary data without copies
__release_buffer__(self, view) (3.12+)
the memoryview is released
free or unlock the buffer
Function in a module
Triggered by
Example
def __getattr__(name)
module.name (or from module import name) when the name is missing
lazy imports, a DeprecationWarning for an old name
def __dir__()
dir(module)
list the lazy names
Attribute
Holds
Example
obj.__dict__
the instance namespace (same as vars(obj))
{'cents': 1349}
obj.__class__
the class of the object (same as type(obj))
Money
Cls.__name__, Cls.__qualname__
the name; the dotted path inside the module
'Inner', 'Outer.Inner'
Cls.__module__
the module that defines it
'billing.money'
x.__doc__
the docstring
help(x) shows it
Cls.__mro__, Cls.__bases__
the lookup order; the direct parents
see inheritance
x.__annotations__
type hints of a class or a function (prefer typing.get_type_hints(x))
{'cents': <class 'int'>}
func.__wrapped__
the original function under a functools.wraps decorator
unwrap for tests
obj.__weakref__
the weak-reference slot
needed with __slots__ for weakref.ref(obj)
module.__file__, module.__name__
the file path; '__main__' when run as a script
if __name__ == "__main__":
def __init__ (self, cents: int , currency: str = "USD" ) -> None :
self .cents, self .currency = cents, currency
def __repr__ (self) -> str : # developers: looks like the constructor call
return f " {type ( self ). __name__} ( {self .cents !r } , {self .currency !r } )"
def __str__ (self) -> str : # users: readable
return f " {self .cents / 100 :.2f } {self .currency } "
def __format__ (self, spec: str ) -> str : # f"{m:,.0f}"
return f " {format ( self .cents / 100 , spec or '.2f' ) } {self .currency } "
def __bool__ (self) -> bool :
print (m, repr (m), [m]) # print -> str; inside containers -> repr
print ( f " { m } | { m !r } | { m :,.0f } | { m = } " )
print ( bool (Money( 0 )), "free" if not Money( 0 ) else "paid" )
1234.56 USD Money(123456, 'USD') [Money(123456, 'USD')]
1234.56 USD | Money(123456, 'USD') | 1,235 USD | m=Money(123456, 'USD')
Rule
Why
always write __repr__
str() falls back to it; nothing falls back to __str__
make the repr look like the constructor call
you can paste it into code
use !r for fields in a repr
strings keep their quotes
use type(self).__name__
subclasses show their own name
keep reprs short for big objects
show sizes and keys, not 10,000 rows
a custom __format__ must handle an empty spec
plain f"{x}" calls it with ''
without __format__
f"{x:>10}" raises TypeError: unsupported format string passed to X.__format__
from functools import total_ordering
@total_ordering # writes <=, > and >= from __eq__ and __lt__
def __init__ (self, text: str ) -> None :
self .parts = tuple ( int (p) for p in text.split( "." ))
def __repr__ (self) -> str :
return f "Version( { '.' .join( map ( str , self .parts)) !r } )"
def __eq__ (self, other: object ) -> bool :
if not isinstance (other, Version):
return NotImplemented # not False: let the other side answer
return self .parts == other.parts
def __lt__ (self, other: object ) -> bool :
if not isinstance (other, Version):
return self .parts < other.parts
def __hash__ (self) -> int : # the same fields as __eq__
vs = [Version(t) for t in [ "1.10.0" , "1.9.3" , "1.9.3" , "2.0" ]]
print ( sorted ( set (vs)), max (vs), Version( "1.10" ) >= Version( "1.9" ))
print (Version( "1.0" ) == "1.0" , Version( "1.0" ) in vs)
[Version('1.9.3'), Version('1.10.0'), Version('2.0')] Version('2.0') True
Class defines
== means
__hash__
Hashable?
neither
identity (is)
identity-based
yes
__eq__ only
your rule
set to None
no: TypeError: unhashable type
__eq__ and __hash__
your rule
your rule
yes, if the fields never change
__hash__ = None
inherited
None
no (says so on purpose)
The hash contract: a == b implies hash(a) == hash(b). Hash only fields that never change. @total_ordering needs __eq__ and one of __lt__, __le__, __gt__, __ge__; it does not check that they agree.
from collections.abc import Iterator
def __init__ (self, songs: list[ str ]) -> None :
self ._songs = list (songs)
def __repr__ (self) -> str :
return f "Playlist( {self ._songs !r } )"
def __len__ (self) -> int :
def __getitem__ (self, key: int | slice ) -> "str | Playlist" :
if isinstance (key, slice ):
return type ( self )( self ._songs[key]) # a slice keeps the class
return self ._songs[key] # IndexError comes from the list
def __iter__ (self) -> Iterator[ str ]:
yield from self ._songs # a fresh iterator for each loop
def __contains__ (self, song: object ) -> bool :
return isinstance (song, str ) and song.lower() in (s.lower() for s in self )
p = Playlist([ "Intro" , "Song A" , "Song B" , "Outro" ])
print ( len (p), p[ 0 ], p[ - 1 ], p[ 1 : 3 ], "song a" in p)
print ( list ( reversed (p)), [s.upper() for s in p][: 2 ], bool (p[ 4 :]))
4 Intro Outro Playlist(['Song A', 'Song B']) True
['Outro', 'Song B', 'Song A', 'Intro'] ['INTRO', 'SONG A'] False
Intro ['Song A', 'Song B', 'Outro']
Missing method
Python falls back to
__iter__
__getitem__(0), (1), … until IndexError
__contains__
a loop over __iter__ with ==
__bool__
__len__() != 0; with neither, always True
__reversed__
__len__ + __getitem__ from the end
__ne__
not __eq__
__radd__ etc.
TypeError: unsupported operand type(s)
For a full container, subclass collections.abc.Sequence or Mapping and write only the abstract methods (see ABC vs Protocol ).
def __init__ (self, func) -> None : # a decorator written as a class
self .func, self .calls = func, 0
def __call__ (self, * args, ** kwargs):
return self .func( * args, ** kwargs)
def slugify (text: str ) -> str :
return text.strip().lower().replace( " " , "-" )
def __init__ (self, store: dict[ str , int ]) -> None :
def __enter__ (self) -> dict[ str , int ]:
self ._backup = dict ( self .store) # snapshot
return self .store # bound to the name after "as"
def __exit__ (self, exc_type, exc, tb) -> bool :
if exc_type is not None : # an error in the block: roll back
self .store.update( self ._backup)
print ( "rolled back:" , exc)
return False # do not suppress the exception
print (slugify( "Hello World" ), slugify( " Python " ), slugify.calls, callable (slugify))
accounts = { "ada" : 100 , "bob" : 0 }
with Transaction(accounts) as acc:
raise RuntimeError ( "network down" )
hello-world python 2 True
rolled back: network down
__exit__ returns
Effect
None or False
an exception from the block propagates after cleanup
True
the exception is suppressed (use with care)
__exit__ does not run if __enter__ raises. For simple cases, @contextlib.contextmanager with try/finally around a yield is shorter.
def __init__ (self, * xs: float ) -> None :
def __repr__ (self) -> str :
return f "Vector {self .xs } "
def __add__ (self, other: object ) -> "Vector" :
if not isinstance (other, Vector):
return Vector( * (a + b for a, b in zip ( self .xs, other.xs, strict = True )))
def __radd__ (self, other: object ) -> "Vector" :
return self if other == 0 else self . __add__ (other) # sum() starts at 0
def __mul__ (self, k: object ) -> "Vector" :
if isinstance (k, bool ) or not isinstance (k, ( int , float )):
return Vector( * (a * k for a in self .xs))
__rmul__ = __mul__ # 2 * v: commutative, share the method
def __neg__ (self) -> "Vector" :
def __abs__ (self) -> float :
return math.hypot( * self .xs)
class Total : # a mutable accumulator: in-place operator returns self
def __init__ (self) -> None :
def __iadd__ (self, x: float ) -> "Total" :
v, w = Vector( 3 , 4 ), Vector( 1 , 1 )
print (v + w, 2 * v, - w, abs (v), sum ([v, w, w]))
Vector(4, 5) Vector(6, 8) Vector(-1, -1) 5.0 Vector(5, 6)
unsupported operand type(s) for +: 'Vector' and 'int'
How Python evaluates a + b:
If type(b) is a subclass of type(a) and overrides __radd__, try b.__radd__(a) first.
Otherwise call a.__add__(b). Any result except NotImplemented is the answer.
Then try b.__radd__(a).
If both return NotImplemented or are missing: TypeError: unsupported operand type(s) for +.
a += b tries a.__iadd__(b) first, then falls back to a = a + b. Immutable types (int, str, tuple) have no __iadd__, so += builds a new object.
def __init__ (self, target: object ) -> None :
self .calls: list[ str ] = []
def __getattr__ (self, name: str ) -> object : # only for names not found normally
if name.startswith( "__" ): # copy and pickle probe dunders before __init__
raise AttributeError (name)
return getattr ( vars ( self )[ "_target" ], name) # delegate; no recursion
def __init__ (self, ** fields: object ) -> None :
for k, v in fields.items():
object . __setattr__ ( self , k, v) # bypass our own __setattr__
def __setattr__ (self, name: str , value: object ) -> None :
raise AttributeError ( f " {type ( self ). __name__} is read-only: cannot set { name !r } " )
print (p.upper(), p.startswith( "He" ), p.calls) # p.calls itself is found normally
cfg = ReadOnly( host = "localhost" , port = 8000 )
except AttributeError as err:
HELLO True ['upper', 'startswith']
ReadOnly is read-only: cannot set 'port' 8000
Rule
Why
prefer __getattr__ to __getattribute__
__getattr__ runs only for missing names
inside __getattribute__, call object.__getattribute__(self, name)
self.x there recurses forever
inside __setattr__, write with object.__setattr__ or super().__setattr__
self.x = v there recurses forever
raise AttributeError for unknown names
hasattr() and getattr(obj, n, default) rely on it
guard __getattr__ for copy and pickle
they build the object without __init__; reading self._target there recurses
special methods bypass __getattr__
len(proxy) does not delegate; define __len__ explicitly
A descriptor is an object in a class body that controls access to one attribute. property, methods, classmethod, staticmethod and cached_property are all descriptors. Write your own to reuse one check on many attributes.
def __set_name__ (self, owner: type , name: str ) -> None : # runs at class creation
self .public, self .private = name, "_" + name
def __get__ (self, obj: object , objtype: type | None = None ) -> object :
if obj is None : # accessed on the class: return the descriptor itself
return getattr (obj, self .private)
def __set__ (self, obj: object , value: float ) -> None : # data descriptor
raise ValueError ( f " {self .public } must be > 0, got { value } " )
setattr (obj, self .private, value)
price = Positive() # one line per validated attribute
def __init__ (self, price: float , quantity: int ) -> None :
self .price = price # runs Positive.__set__
print (o.price, o.quantity, sorted ( vars (o)), type (Order.price). __name__ )
except ValueError as err:
9.99 3 ['_price', '_quantity'] Positive
quantity must be > 0, got 0
Kind
Defines
Precedence
data descriptor
__get__ and __set__ (or __delete__)
wins over vars(obj): property, Positive
non-data descriptor
__get__ only
vars(obj) wins: functions, cached_property (that is how it caches)
from typing import ClassVar
registry: ClassVar[dict[ str , type[ "Exporter" ]]] = {}
def __init_subclass__ (cls, * , fmt: str , ** kwargs: object ) -> None :
super (). __init_subclass__ ( ** kwargs)
Exporter.registry[fmt] = cls # runs once per subclass, at class creation
class CsvExporter ( Exporter , fmt = "csv" ):
class JsonExporter ( Exporter , fmt = "json" ):
def __class_getitem__ (cls, item: object ) -> str : # Box[int]
return f " {cls . __name__} [ {getattr (item, '__name__' , item) } ]"
print ({k: v. __name__ for k, v in Exporter.registry.items()}, Box[ int ], list[ int ])
{'csv': 'CsvExporter', 'json': 'JsonExporter'} Box[int] list[int]
In real code, write class Box[T]: (3.12+) or subclass typing.Generic[T] instead of a hand-written __class_getitem__.
Special methods on the instance. Symptom: obj.__len__ = lambda: 3 does not change len(obj). Fix: define it on the class.
__eq__ without __hash__. Symptom: TypeError: unhashable type in a set or as a dict key. Fix: add __hash__ over the same fields, or use @dataclass(frozen=True).
Hashing mutable fields. Symptom: an object “disappears” from a set after a change. Fix: hash only fields that never change.
NotImplementedError instead of NotImplemented. Symptom: a == b raises instead of returning False. Fix: return NotImplemented (a value), never raise it.
return False for unknown types in __eq__. Symptom: the other operand never gets a say. Fix: return NotImplemented.
print([x]) ignores __str__. Symptom: a list shows reprs. Fix: that is by design; write a good __repr__.
Wrong return types. Symptom: TypeError from len() or bool(). Fix: __len__ returns an int ≥ 0, __bool__ a bool, __repr__ a str.
__iter__ returns self without __next__. Symptom: TypeError: iter() returned non-iterator. Fix: write __iter__ as a generator.
One-shot iterator. Symptom: a second loop over the object is empty. Fix: return a fresh iterator from __iter__ on each call.
Slices return a plain list. Symptom: obj[1:3].method() fails. Fix: check isinstance(key, slice) and return type(self)(...).
sum() of custom objects. Symptom: TypeError: unsupported operand type(s) for +: 'int' and 'X'. Fix: __radd__ that accepts 0, or sum(xs, start=zero).
__exit__ returns True by accident. Symptom: every error in the with block vanishes. Fix: return None or False.
Recursion in __setattr__ or __getattribute__. Symptom: RecursionError. Fix: use object.__setattr__ / object.__getattribute__.
__getattr__ hides typos. Symptom: a misspelled attribute returns something instead of failing. Fix: raise AttributeError for names you do not handle.
__del__ for cleanup. Symptom: files or connections stay open. Fix: use a context manager.
Surprising operators. Symptom: readers cannot guess what pipeline + model does. Fix: overload only operators with an obvious meaning; use named methods otherwise.