Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Operator Overloading: How It Works

Learn how Python operator overloading works through dunder methods like __add__ and __eq__, including reflected operators, comparison behavior, and hashability.

~6 min readPython
#operator overloading#dunder methods#magic methods#python classes
A clean editorial illustration showing a Python class with plus and equals operator symbols, representing operator overloading.

Python operator overloading lets you define how operators like +, ==, and < behave for instances of your own classes. The mechanism is built on special methods whose names begin and end with double underscores, such as add, eq, and lt. When the interpreter sees an expression like a + b, it looks up the add method on the type of a and calls it with b as an argument. This lookup follows the normal attribute resolution rules, which means you can control operator behavior by defining these methods on a class.

How Operator Overloading Works in Python

The Python data model defines a fixed set of special methods that correspond to operators. Each operator maps to one or more methods. For example, the + operator maps to add and radd, and the == operator maps to eq. When you write a + b, Python first tries type(a).add(a, b). If that returns NotImplemented, it then tries type(b).radd(b, a). If both return NotImplemented, Python raises TypeError. This protocol is important because it allows both operands to participate in the operation, even when they are of different types.

A minimal example shows the pattern:

python
class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if not isinstance(other, Vector): return NotImplemented return Vector(self.x + other.x, self.y + other.y)

Here add checks the type of other. Returning NotImplemented instead of raising TypeError lets Python attempt the reflected operation on the other operand. If other also does not support the operation, Python raises a clear error. This is the correct way to handle incompatible types because it preserves the fallback behavior.

Implementing Arithmetic Operators with add and radd

For binary arithmetic operators, you often need both the forward and reflected versions. The reflected method is called when the left operand does not support the operation, or when it returns NotImplemented. Consider a class that represents a scalar multiplier:

python
class Scalar: def __init__(self, value): self.value = value def __mul__(self, other): if isinstance(other, (int, float)): return Scalar(self.value * other) return NotImplemented def __rmul__(self, other): if isinstance(other, (int, float)): return Scalar(other * self.value) return NotImplemented

Now both Scalar(3) * 5 and 5 * Scalar(3) work. The rmul method is essential when the left operand is a built-in type that does not know about Scalar. Without it, the expression 5 * Scalar(3) would raise TypeError.

The same pattern applies to subtraction, division, and modulo. For each binary operator, there is a corresponding reflected method: sub and rsub, truediv and rtruediv, mod and rmod. The decision to implement both depends on whether your class is likely to appear on the right side of an expression. If you only control the left operand, add may be enough. But for symmetry, implementing the reflected version is usually safer.

Comparison Operators and eq, lt, and Hashability

Comparison operators have their own set of methods. The eq method controls equality, and lt controls the less-than operator. In Python 3, if you define eq without defining ne, the default ne delegates to eq and inverts the result unless it returns NotImplemented. You only need to define ne if you want behavior different from that default. The other comparison methods le, gt, and ge are separate; Python does not infer them from lt and eq.

A common mistake is to define eq without also defining hash. In Python, if a class defines eq but not hash, its instances become unhashable. That means they cannot be used as dictionary keys or placed in a set. If you need equality semantics and also want to keep instances hashable, you must define hash explicitly. The hash value should be consistent with equality: if two objects compare equal, they must have the same hash.

python
class Point: def __init__(self, x, y): self.x = x self.y = y def __eq__(self, other): if not isinstance(other, Point): return NotImplemented return self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))

Defining hash as the hash of a tuple of the same fields keeps the invariant. If you do not need hashability, you can set hash = None to explicitly make the class unhashable, but that is rarely the right choice for value objects.

Unary Operators and neg, abs, and invert

Unary operators are simpler because they take only one operand. The methods are neg for unary minus, pos for unary plus, abs for the built-in abs() function, and invert for the bitwise NOT operator. These methods should return a new instance of the class, not modify the original.

python
class Temperature: def __init__(self, celsius): self.celsius = celsius def __neg__(self): return Temperature(-self.celsius) def __abs__(self): return Temperature(abs(self.celsius))

These methods are straightforward, but they still need to return NotImplemented when the operation is not applicable. For unary operators, there is no reflected variant, so returning NotImplemented causes Python to raise TypeError.

In-Place Operators and iadd: When to Implement Them

In-place operators like += and -= are handled by iadd, isub, and similar methods. For an expression like a += b, Python calls type(a).__iadd__ when it is defined; otherwise it falls back to __add__ (and the reflected method if needed) and reassigns the result to a. That fallback works, but it creates a new object instead of modifying the existing one.

The decision to implement iadd depends on whether your class is mutable. For immutable types like tuples, there is no in-place modification, so iadd is not meaningful. For mutable types, implementing iadd can avoid allocation overhead and preserve object identity.

python
class Buffer: def __init__(self, data): self.data = list(data) def __iadd__(self, other): if not isinstance(other, Buffer): return NotImplemented self.data.extend(other.data) return self

Notice that iadd returns self after modifying the object. If it returned a new instance, the semantics would be different. The in-place protocol expects the method to return the object that should be bound to the left-hand variable. Returning self is the common pattern for mutable containers.

Type Checking and Returning NotImplemented

One of the most important rules in operator overloading is to return NotImplemented, not raise TypeError, when the operation is unsupported. The NotImplemented singleton is a special value that tells the interpreter to try the reflected operation or raise TypeError if no method works. Raising TypeError inside a dunder method breaks the fallback protocol and can cause confusing behavior when both operands are custom types.

Another common mistake is to use type() checks instead of isinstance(). Because operator overloading often involves inheritance, isinstance() is more flexible and respects subclass relationships. If you have a subclass of Vector, isinstance(subclass_instance, Vector) is True, and the operation will work. Using type() would reject that subclass and return NotImplemented, which can lead to a TypeError unless the other operand's reflected method handles it.

Maintainability and Performance Considerations

Operator overloading can make code more readable, but it also adds a layer of indirection. Every operator call goes through the special method lookup, which is slightly slower than a direct method call. For most applications, the difference is negligible. However, if you are overloading operators for a class used in tight numerical loops, the overhead can add up. In such cases, consider whether the readability gain justifies the cost.

Maintainability is a more significant concern. Overloading too many operators can make a class difficult to reason about, especially if the semantics are not obvious. For example, overloading lt to compare objects by a non-obvious attribute can confuse readers. It is usually better to keep operator semantics aligned with the mathematical or domain meaning of the class. If an operator does not have a natural meaning, do not overload it.

Compatibility and Python Version Notes

The special-method protocol described here is stable in current Python 3 releases. One common legacy difference is ne: Python 2 did not derive ne from eq, which is why older code often defined it explicitly. In Python 3, the default ne delegates to eq and inverts the result unless it returns NotImplemented. Python 3 also uses truediv for / and floordiv for //; Python 2's div is no longer used. New code should target Python 3.

Another version-related detail is the use of index for integer-like objects. If you want your class to be usable in slicing or as an index, you need to implement index to return an integer. This method is still required in Python 3. It is not strictly an operator, but it affects how the object behaves in expressions like list[obj].

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.