Python Dunder Methods Cheat Sheet

Rate this post

When searching for a list of dunder methods with explanations, i.e., a cheat sheet on Python magic methods, I only found a couple of resources all over the web—each covering only a fraction of dunder methods. So, here’s my collection of 127 dunder methods (also called “magic methods”) from those sources, sorted alphabetically. I provide the data in three forms.

Python Dunder Methods Table with Explanation

NameDescription
__abs__Absolute value of a given argument
__add__Addition x + y for x and y arguments
__aenter__Like __enter__() but must return an awaitable
__aexit__Like __exit__() but must return an awaitable
__aiter__Returns an asynchronous iterator
__and__Bitwise “AND” of a and b
__anext__Return an awaitable as the next value of the iterator argument
__annotations__A dict containing annotations (values) associated to parameter names (keys)
__await__Return an iterator to implement awaitable objects
__bool__Truth value testing for built-in bool() returning False or True. If undefined, call __len__()
__bytes__Called by bytes() to compute a byte-string representation of an object. Must return a bytes object.
__call__Called when a given instance is called as a function
__ceil__Implement math function ceil()
__complex__Implement the built-in functions complex() to create a new complex number
__contains__Implements the Python in operator to check membership.
__del__Called when the instance is about to be destroyed
__delattr__Delete an attribute
__delete__Delete the attribute on an instance of the owner class.
__delitem__Remove the value of the first argument at index as defined in second argument.
__dir__Called when dir(x) is called on object x.
__div__The division operator (/) in Python 2 is implemented by this dunder method. For Python 3, the __truediv__() method is used instead.
__divmod__Implements the divmod() built-in method. Python’s built-in divmod(a, b) function takes two integer or float numbers a and b as input arguments and returns a tuple (a // b, a % b).
__enter__Enter the runtime context related to this object.
__eq__Rich comparison: x==y calls x.__eq__(y)
__exit__Exit the runtime context related to this object.
__float__Called to implement the built-in function float().
__floor__Implements behavior for math.floor(), i.e., rounding down to the nearest integer.
__floordiv__Implements a//b
__format__ The Python __format__() method implements the built-in format() function as well as the string.format() method. So, when you call format(x, spec) or string.format(spec), Python attempts to call x.__format__(spec). The return value is a string.
__ge__Return whether x is greater than or equal y
__get__Called on the attribute type to get a class attribute or instance attribute of the owner class.
__getattr__Called when the default attribute access fails with an AttributeError
__getattribute__Called unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(), this method won’t be called unless __getattribute__() either calls it explicitly or raises an AttributeError.
__getitem__Return the value of a at index b.
__gt__Returns the result of the greater than operation x > y
__hash__Called by built-in function hash(), should return an integer.
__hex__Does not work for Python 3. Use __index__() instead.
__iadd__a = iadd(a, b) is equivalent to a += b.
__iand__a = iand(a, b) is equivalent to a &= b.
__idiv__a = idiv(a, b) is equivalent to a /= b in Python 2. In Python 3, this is replaced by __itruediv__.
__ifloordiv__a = ifloordiv(a, b) is equivalent to a //= b.
__ilshift__a = ilshift(a, b) is equivalent to a <<= b.
__imatmul__a = imatmul(a, b) is equivalent to a @= b.
__imod__a = imod(a, b) is equivalent to a %= b.
__import__Import a library by name. For example, to import the NumPy library dynamically, you could run __import__('numpy').
__imul__a = imul(a, b) is equivalent to a *= b.
__index__Returns the object converted to an integer. This is used for many built-in functions such as oct(), hex(), or bin().
__init__Called after the instance has been created (by __new__()), but before it is returned to the caller.
__init_subclass__This method is called whenever the class defining it is subclassed.
__instancecheck__Return True if instance should be considered a direct or indirect instance of class. If defined, called to implement isinstance(instance, class).
__int__Called to implement the built-in function int().
__invert__(x)Return the bitwise inverse ~x of the number x.
__ior__a = ior(a, b) is equivalent to a |= b.
__ipow__a = ipow(a, b) is equivalent to a **= b.
__irshift__a = irshift(a, b) is equivalent to a >>= b.
__isub__a = isub(a, b) is equivalent to a -= b.
__iter__This method is called when an iterator is required for a container. It returns a new iterator object that can iterate over all the objects in the container.
__itruediv__a = itruediv(a, b) is equivalent to a /= b.
__ixor__a = ixor(a, b) is equivalent to a ^= b.
__le__Returns True if the former is less than or equal to the latter argument, i.e., x <= y
__len__Called to implement the built-in function len(). Returns the length of the object >= 0. An object that doesn’t define __bool__() is considered False if its __len__() method returns zero.
__lshift__Return x shifted left by y.
__lt__Returns the result of the less than operation x < y
__matmul__Return a @ b.
__missing__Called by dict.__getitem__() to implement self[key] for dict subclasses when key is not in the dictionary.
__mod__Return x % y.
__mul__Return a * b, for a and b numbers.
__ne__Rich comparison: x!=y and x<>y call x.__ne__(y)
__neg__Return x negated (-x).
__new__Called to create a new instance of a given class cls.
__next__Return the next item from the container.
__oct__Does not work for Python 3. Use __index__() instead.
__or__Return the bitwise or of a and b.
__pow__Return a ** b, for a and b numbers.
__radd__Called to implement the binary arithmetic operation + with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rand__Called to implement the binary arithmetic operation & (__and__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rdiv__Called to implement the binary arithmetic operation / (__div__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rdivmod__Called to implement the binary arithmetic operation divmod() with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__repr__Called by the repr() built-in function to compute the “official” string representation of an object.
__reversed__Called (if present) by the reversed() built-in to implement reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order.
__rfloordiv__Called to implement the binary arithmetic operation // (__floordiv__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rlshift__Called to implement the binary arithmetic operation << (__lshift__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rmatmul__Called to implement the matmul operation @ (__matmul__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rmod__Called to implement the binary arithmetic operation % (__mod__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rmul__Called to implement the binary arithmetic operation * (__mul__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__ror__Called to implement the binary arithmetic operation | (__or__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__round__Called to implement the built-in function round() and math functions trunc(), floor() and ceil().
__rpow__Called to implement the arithmetic multiplication operation ** (__pow__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rrshift__Called to implement the binary arithmetic operation >> (__rshift__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rshift__Return a shifted right by b, i.e., a >> b.
__rsub__Called to implement the binary arithmetic operation – (__sub__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rtruediv__Called to implement the binary arithmetic operation / (__truediv__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__rxor__Called to implement the binary arithmetic operation ^ (__xor__) with reflected (swapped) operands. Only called if the left operand does not support the corresponding operation and the operands are of different types.
__set__Called to set the attribute on an instance of the owner class to a new value.
__set_name__Called at the time the owning class owner is created. The descriptor has been assigned to name.
__setattr__Called when you assign an attribute via setattr() instead of the normal mechanism of storing the value in the instance dictionary.
__setitem__Set a given element at a given index to a new value.
__sizeof__Returns the internal size in bytes for the given object
__str__Called by str(object) and the built-in functions format() and print() to compute the “informal” or printable string representation of an object.
__sub__Return a - b.
__subclasscheck__Return true if subclass should be considered a (direct or indirect) subclass of class. If defined, called to implement issubclass(subclass, class).
__subclasses__Finds all subclasses of a given class.
__truediv__Return a / b where 2/3 is .66 rather than 0. This is also known as “true” division.
__trunc__Called to implement the math.trunc() function.
__xor__Return the bitwise exclusive or of a and b.
Table: List of Dunder Methods with Explanations

To get the list of sources used to create this table, please scroll down to the end of the article.

Python Special Attributes

Python has multiple special attributes that are defined per default for each class such as __name__, __module__, __dict__, __bases__, __doc__, and __annotations__.

AttributeTypeDescription
__name__strThe name of the class
__module__str The string name of the module where the class is defined
__dict__dictThe dictionary with the namespace of the class
__bases__tupleA tuple with base classes of this class
__doc__str or NoneThe documentation of the class as a string. If no documentation is defined, None.
__annotations__dictA dictionary with variable annotations in this class

You can find them explained here:

Python Dunder Methods — One Method Per Line

__abs__
__add__
__aenter__
__aexit__
__aiter__
__and__
__anext__
__await__
__bool__
__bytes__
__call__
__ceil__
__class__
__class_getitem__
__cmp__
__coerce__
__complex__
__contains__
__del__
__delattr__
__delete__
__delitem__
__delslice__
__dict__
__dir__
__div__
__divmod__
__enter__
__eq__
__exit__
__float__
__floor__
__floordiv__
__format__
__fspath__
__ge__
__get__
__getattr__
__getattribute__
__getitem__
__getnewargs__
__getslice__
__gt__
__hash__
__hex__
__iadd__
__iand__
__idiv__
__ifloordiv__
__ilshift__
__imatmul__
__imod__
__import__
__imul__
__index__
__init__
__init_subclass__
__instancecheck__
__int__
__invert__
__ior__
__ipow__
__irshift__
__isub__
__iter__
__itruediv__
__ixor__
__le__
__len__
__length_hint__
__long__
__lshift__
__lt__
__matmul__
__metaclass__
__missing__
__mod__
__mro__
__mul__
__ne__
__neg__
__new__
__next__
__nonzero__
__oct__
__or__
__pos__
__pow__
__prepare__
__radd__
__rand__
__rcmp__
__rdiv__
__rdivmod__
__reduce__
__reduce_ex__
__repr__
__reversed__
__rfloordiv__
__rlshift__
__rmatmul__
__rmod__
__rmul__
__ror__
__round__
__rpow__
__rrshift__
__rshift__
__rsub__
__rtruediv__
__rxor__
__set__
__set_name__
__setattr__
__setitem__
__setslice__
__sizeof__
__slots__
__str__
__sub__
__subclasscheck__
__subclasses__
__truediv__
__trunc__
__unicode__
__weakref__
__xor__

Python Dunder Methods as a List of Strings

In case you need them as a Python list for copy&paste, here it is:

['__abs__', '__add__', '__aenter__', '__aexit__', '__aiter__', '__and__', '__anext__', '__await__', '__bool__', '__bytes__', '__call__', '__ceil__', '__class__', '__class_getitem__', '__cmp__', '__coerce__', '__complex__', '__contains__', '__del__', '__delattr__', '__delete__', '__delitem__', '__delslice__', '__dict__', '__dir__', '__div__', '__divmod__', '__enter__', '__eq__', '__exit__', '__float__', '__floor__', '__floordiv__', '__format__', '__fspath__', '__ge__', '__get__', '__getattr__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__import__', '__imul__', '__index__', '__init__', '__init_subclass__', '__instancecheck__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__length_hint__', '__long__', '__lshift__', '__lt__', '__matmul__', '__metaclass__', '__missing__', '__mod__', '__mro__', '__mul__', '__ne__', '__neg__', '__new__', '__next__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__prepare__', '__radd__', '__rand__', '__rcmp__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__set__', '__set_name__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__slots__', '__str__', '__sub__', '__subclasscheck__', '__subclasses__', '__truediv__', '__trunc__', '__unicode__', '__weakref__', '__xor__']

References and Sources