Python Dunder Methods Cheat Sheet

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
__bases__Tuple of base classes of a class object
__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. This should return a bytes object
__call__Called when a given instance is “called” as a function
__ceil__Implement built-in function round() and math functions trunc(), floor() and ceil()
__class__Class to which a class instance belongs
__class_getitem__Return object representing the specialization of a generic class by type arguments found in key
__closure__None or tuple of cells that contain bindings for the free variables of a function
__code__Code object representing the compiled function body
__coerce__Converts x and y to the same numerical types
__complex__Implement the built-in functions complex() to create a new complex number
__contains__Tests whether the collection on which it is called contains the argument value
__concat__Returns a + b for sequences a and b
__defaults__Returns a tuple containing default argument values for those arguments that have, otherwise returns None
__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.
__delslice__Called to implement deletion of self[i:j]. Same notes for i and j as for __getslice__(). This method is deprecated.
__dict__The namespace supporting arbitrary function attributes.
__dir__Called when dir() is called on the object.
__div__The division operator (/) is implemented by these methods. The __truediv__() method is used when __future__.division is in effect, otherwise __div__() is used.
__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).
__doc__The function’s documentation string, or None if unavailable; not inherited by subclasses.
__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 functions complex(), int() and float().
__floor__(x, y)Implements behavior for math.floor(), i.e., rounding down to the nearest integer.
__floordiv__Implements a//b
__format__(self, specs)Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object.
__fspath__Return the file system representation of the path argument.
__ge__Return x is greater than or equal y
__get__Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access).
__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__(), the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError.
__getitem__Return the value of a at index b.
__getslice__Called to implement evaluation of self[i:j]. The returned object should be of the same type as self.
__globals__A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined.
__gt__Return x is greater than y
__hash__(self)Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict. __hash__() should return an integer.
__hex__Called to implement the built-in function hex(). Should return a string value.
__iadd__a = iadd(a, b) is equivalent to a += b.
__iand__a = iand(a, b) is equivalent to a &= b.
__iconcat__a = iconcat(a, b) is equivalent to a += b for a and b sequences.
__idiv__a = idiv(a, b) is equivalent to a /= b.
__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__(x)Return a converted to an integer.
__init__(self, …)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 containing class is subclassed. cls is then the new subclass.
__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 functions complex(), int() and float().
__invert__(x), __inv__(x)Return the bitwise inverse of the number obj.
__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. This method should return 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.
__kwdefaults__A dict containing defaults for keyword-only parameters.
__le__Returns true if x is lower than or equal y
__len__Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __bool__() method and whose __len__() method returns zero is considered to be false in a Boolean context.
__length_hint__Called to implement operator.length_hint(). Should return an estimated length for the object (which may be greater or less than the actual length).
__lshift__Return x shifted left by y.
__lt__(x, y)Returns true if x is less than 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.
__module__The name of the module the function was defined in, or None if unavailable.
__mro__This attribute is a tuple of classes that are considered when looking for base classes during method resolution.
__mul__Return a * b, for a and b numbers.
__name__The function’s name.
__ne__Rich comparison: x!=y and x<>y call x.__ne__(y)
__neg__Return obj negated (-obj).
__new__(x)Called to create a new instance of class cls.
__next__Return the next item from the container.
__nonzero__Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1.
__not__(x)Return the outcome of not x.
__oct__Returns the result of the oct() built-in function to compute the octal representation of an integer
__or__Return the bitwise or of a and b.
__pos__Return obj positive (+obj).
__pow__Return a ** b, for a and b numbers.
__qualname__The function’s qualified name.
__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.
__reduce__The __reduce__() method takes no argument and shall return either a string or preferably a tuple (the returned object is often referred to as the “reduce value”). If a string is returned, the string should be interpreted as the name of a global variable.
__reduce_ex__Alternatively, a __reduce_ex__() method may be defined. The only difference is this method should take a single integer argument, the protocol version.
__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 binary arithmetic 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 instance of the owner class to a new value, value.
__set_name__Called at the time the owning class owner is created. The descriptor has been assigned to name.
__setattr__Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary).
__setitem__Set the value of a at index b to c.
__setslice__Called to implement assignment to self[i:j]. Same notes for i and j as for __getslice__().
__sizeof__Returns the internal size in bytes for the given object
__slots__This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. __slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance.
__str__Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely 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__returns the 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 built-in function round() and math functions trunc(), floor() and ceil().
__unicode__Called to implement unicode() built-in; should return a Unicode object.
__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 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