Skip to content
Python

Python Dunder Methods: Make Your Objects Work Like Built-ins

Ihsan Ullah · 15 min read
Python Dunder Methods, Lesson 41 of the Python course: __len__, __eq__, __add__ and __str__

Python course · Module 8: OOP in Python · Lesson 41 of 63

Quick answer: Dunder methods (short for “double underscore”, also called magic or special methods) are methods like __len__, __eq__ and __add__ that Python calls for you. When you write len(cart), Python runs cart.__len__(); a == b runs a.__eq__(b); a + b first tries a.__add__(b). By writing these methods in your class, your objects work with len(), in, [], for loops, comparisons, sorted() and +, just like lists and dictionaries.

In this lesson you will learn:

  • what dunder methods are and how Python uses them
  • how __len__, __contains__, __getitem__ and __iter__ make a class act like a container
  • how __eq__ works, and why it makes objects unhashable
  • how __lt__ and functools.total_ordering make objects sortable
  • how __add__ and NotImplemented work for operators

Before you start: finish Lesson 40, Python Inheritance and super(): Reuse and Extend Classes. You already wrote two dunder methods, __str__ and __repr__, in Lesson 38. All examples were run on Linux with Python 3.14.6 and gave exactly the same output on Python 3.15.2, the newest release on python.org.

What are dunder methods in Python?

Built-in objects support many operations: you can ask a list for its len(), check "pen" in a dictionary, or add two strings with +. A new class supports almost none of this. Here is our shopping cart with no dunder methods:

class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        self.items[name] = (price, quantity)


a = ShoppingCart("Amna")
a.add_item("pen", 1.5, 4)
b = ShoppingCart("Amna")
b.add_item("pen", 1.5, 4)

print(a == b)
tests = [lambda: len(a), lambda: "pen" in a, lambda: a["pen"], lambda: a + b]
for test in tests:
    try:
        test()
    except TypeError as err:
        print("TypeError:", err)
False
TypeError: object of type 'ShoppingCart' has no len()
TypeError: argument of type 'ShoppingCart' is not a container or iterable
TypeError: 'ShoppingCart' object is not subscriptable
TypeError: unsupported operand type(s) for +: 'ShoppingCart' and 'ShoppingCart'
  • a == b is False, although both carts hold the same items. By default, == on objects only checks if they are the same object, like is from Lesson 9. The data model docs say: “By default, object implements __eq__() by using is“.
  • len(), in, [] and + all fail with TypeError. (The lambdas in the loop, from Lesson 25, just let us test four operations in one loop.)

Each of these operations has a special method behind it. The data model calls this “Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.” You never call the dunder method yourself. You write len(cart), and Python calls __len__.

__len__ and truth value: len(cart) and if cart

class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        self.items[name] = (price, quantity)

    def __len__(self):
        return len(self.items)


cart = ShoppingCart("Amna")
print(len(cart), bool(cart))
if not cart:
    print("Your cart is empty")

cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
print(len(cart), bool(cart))
0 False
Your cart is empty
2 True
  • len(cart) now returns the number of different items: 0, then 2.
  • We did not write __bool__, yet bool(cart) changed from False to True. The docs explain: when __bool__ is not defined, “__len__() is called, if it is defined, and the object is considered true if its result is nonzero.”
  • So if not cart: works the same way as for an empty list (truthiness was in Lesson 8).

Make a container: __contains__, __getitem__ and __iter__

Three more methods make the cart feel like a dictionary of items:

class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        self.items[name] = (price, quantity)

    def __len__(self):
        return len(self.items)

    def __contains__(self, name):
        return name in self.items

    def __getitem__(self, name):
        return self.items[name]

    def __iter__(self):
        return iter(self.items)


cart = ShoppingCart("Amna")
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)

print("pen" in cart, "bag" in cart)
print(cart["pen"])
for name in cart:
    price, quantity = cart[name]
    print(f"{name}: {quantity} x {price}")
print(list(cart), sorted(cart))

try:
    cart["bag"]
except KeyError as err:
    print("KeyError:", err)
True False
(1.5, 4)
pen: 4 x 1.5
notebook: 1 x 3.0
['pen', 'notebook'] ['notebook', 'pen']
KeyError: 'bag'
  • "pen" in cart calls __contains__, which the docs say should “return true if item is in self, false otherwise”.
  • cart["pen"] calls __getitem__, which is “called to implement subscription, that is, self[subscript]“. We pass the work on to the dictionary, so a missing item raises the same KeyError: 'bag' that a dictionary gives in Lesson 17.
  • for name in cart calls __iter__, which returns an iterator. iter(self.items) gives one over the item names. Now list(cart) and sorted(cart) work too. Lesson 44 explains iterators in detail.

Notice that each method is one short line that hands the job to self.items. That is very common: your class looks simple from outside and uses a built-in type inside.

__eq__: when are two carts equal?

You decide what “equal” means for your class. We say two carts are equal when they hold the same items, even if the owners differ:

class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        self.items[name] = (price, quantity)

    def __eq__(self, other):
        if not isinstance(other, ShoppingCart):
            return NotImplemented
        return self.items == other.items


a = ShoppingCart("Amna")
a.add_item("pen", 1.5, 4)
b = ShoppingCart("Bilal")
b.add_item("pen", 1.5, 4)

print(a == b, a != b, a is b)
b.add_item("notebook", 3.0)
print(a == b, a != b)
print(a == "pen")

print(ShoppingCart.__hash__)
try:
    carts = {a, b}
except TypeError as err:
    print("TypeError:", err)
True False False
False True
False
None
TypeError: cannot use 'ShoppingCart' as a set element (unhashable type: 'ShoppingCart')
  • a == b is now True, but a is b is still False: equal, but two separate objects.
  • We did not write __ne__, yet != works. The docs say: “For __ne__(), by default it delegates to __eq__() and inverts the result”.
  • a == "pen" gave False instead of crashing, because __eq__ returned NotImplemented for anything that is not a cart. The docs say a comparison method “may return the singleton NotImplemented if it does not implement the operation for a given pair of arguments”. Python then tries the other side, and when neither side can compare them, == falls back to is, which gives False.
  • ShoppingCart.__hash__ became None, so the carts cannot go into a set. The docs: “A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None.”

Why? Sets and dictionary keys need a hash value that never changes, and the docs require that “objects which compare equal have the same hash value”. Our carts can change their items, so equal carts could later become different. Leaving them unhashable is the safe choice for objects that change. This longer error message (“cannot use … as a set element”) is from the improved error messages in Python 3.14; Lesson 18 showed the same rule for lists.

__lt__ and total_ordering: sort your objects

< calls __lt__ (“less than”). With it, sorted(), min() and max() work. We compare carts by their total:

class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        self.items[name] = (price, quantity)

    def total(self):
        return sum(price * quantity for price, quantity in self.items.values())

    def __lt__(self, other):
        if not isinstance(other, ShoppingCart):
            return NotImplemented
        return self.total() < other.total()

    def __repr__(self):
        return f"ShoppingCart({self.owner!r})"


amna, bilal, sara = ShoppingCart("Amna"), ShoppingCart("Bilal"), ShoppingCart("Sara")
amna.add_item("pen", 1.5, 4)        # 6.0
bilal.add_item("bag", 20.0)         # 20.0
sara.add_item("notebook", 3.0, 3)   # 9.0

print(amna < bilal, amna > bilal)
print(sorted([bilal, sara, amna]))
print(max([bilal, sara, amna]))

try:
    print(amna <= bilal)
except TypeError as err:
    print("TypeError:", err)
True False
[ShoppingCart('Amna'), ShoppingCart('Sara'), ShoppingCart('Bilal')]
ShoppingCart('Bilal')
TypeError: '<=' not supported between instances of 'ShoppingCart' and 'ShoppingCart'
  • sorted() put the carts in order of their totals: 6.0, 9.0, 20.0, using only <.
  • amna > bilal worked without __gt__. The docs explain that “__lt__() and __gt__() are each other’s reflection”: Python ran bilal < amna instead.
  • <= failed. It needs __le__ (or __ge__ on the other side).

Writing all six comparison methods is boring. The functools.total_ordering decorator does it for you: “The class must define one of __lt__(), __le__(), __gt__(), or __ge__(). In addition, the class should supply an __eq__() method.”

from functools import total_ordering


@total_ordering
class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        self.items[name] = (price, quantity)

    def total(self):
        return sum(price * quantity for price, quantity in self.items.values())

    def __eq__(self, other):
        if not isinstance(other, ShoppingCart):
            return NotImplemented
        return self.total() == other.total()

    def __lt__(self, other):
        if not isinstance(other, ShoppingCart):
            return NotImplemented
        return self.total() < other.total()


amna, bilal = ShoppingCart("Amna"), ShoppingCart("Bilal")
amna.add_item("pen", 1.5, 4)   # 6.0
bilal.add_item("bag", 20.0)    # 20.0
print(amna <= bilal, amna >= bilal, amna == bilal)
True False False

Here __eq__ compares totals too. total_ordering builds <= from < and ==, so both must use the same rule, or the results stop making sense.

__add__: make + work

a + b first tries a.__add__(b). To be exact, the docs say Python calls type(a).__add__(a, b): it looks the method up on the class, not on the single object. We make + merge two carts into a new cart:

class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        if name in self.items:
            quantity += self.items[name][1]
        self.items[name] = (price, quantity)

    def __add__(self, other):
        if not isinstance(other, ShoppingCart):
            return NotImplemented
        merged = ShoppingCart(f"{self.owner} + {other.owner}")
        for cart in (self, other):
            for name, (price, quantity) in cart.items.items():
                merged.add_item(name, price, quantity)
        return merged


amna = ShoppingCart("Amna")
amna.add_item("pen", 1.5, 4)
bilal = ShoppingCart("Bilal")
bilal.add_item("pen", 1.5, 2)
bilal.add_item("bag", 20.0)

family = amna + bilal
print(family.owner, family.items)
print(amna.items)

try:
    amna + 5
except TypeError as err:
    print("TypeError:", err)
Amna + Bilal {'pen': (1.5, 6), 'bag': (20.0, 1)}
{'pen': (1.5, 4)}
TypeError: unsupported operand type(s) for +: 'ShoppingCart' and 'int'
  • The pens were combined (4 + 2 = 6) and the bag was added, in a new cart called Amna + Bilal.
  • amna.items did not change. Like + on lists and strings, __add__ should return a new object and leave both sides alone.
  • amna + 5 returned NotImplemented, so Python gave the normal error: unsupported operand type(s) for +: 'ShoppingCart' and 'int'. The docs say an arithmetic method “should return NotImplemented” if it does not support the arguments. Because the two sides have different types, Python then tries the right side’s reflected method (here int.__radd__), and raises TypeError when that also returns NotImplemented.

A complete example: a cart that works like a built-in

Here is everything in one class. Methods can use each other: __str__ calls len(self), and __add__ loops with for name in cart.

class ShoppingCart:
    """A shopping cart that works with len(), in, [], for, ==, <, + and print()."""

    def __init__(self, owner):
        self.owner = owner
        self.items = {}

    def add_item(self, name, price, quantity=1):
        if name in self.items:
            quantity += self.items[name][1]
        self.items[name] = (price, quantity)

    def total(self):
        return sum(price * quantity for price, quantity in self.items.values())

    # text
    def __repr__(self):
        return f"ShoppingCart({self.owner!r})"

    def __str__(self):
        return f"{self.owner}'s cart: {len(self)} items, total {self.total():.2f}"

    # container behaviour
    def __len__(self):
        return len(self.items)

    def __contains__(self, name):
        return name in self.items

    def __getitem__(self, name):
        return self.items[name]

    def __iter__(self):
        return iter(self.items)

    # comparing and adding
    def __eq__(self, other):
        if not isinstance(other, ShoppingCart):
            return NotImplemented
        return self.items == other.items

    def __lt__(self, other):
        if not isinstance(other, ShoppingCart):
            return NotImplemented
        return self.total() < other.total()

    def __add__(self, other):
        if not isinstance(other, ShoppingCart):
            return NotImplemented
        merged = ShoppingCart(f"{self.owner} + {other.owner}")
        for cart in (self, other):
            for name in cart:
                price, quantity = cart[name]
                merged.add_item(name, price, quantity)
        return merged


amna = ShoppingCart("Amna")
amna.add_item("pen", 1.5, 4)
amna.add_item("notebook", 3.0)
bilal = ShoppingCart("Bilal")
bilal.add_item("bag", 20.0)

print(amna)
print(len(amna), "pen" in amna, amna["notebook"])
print(amna == bilal, amna < bilal)
family = amna + bilal
print(family)
print(sorted([family, bilal, amna]))
Amna's cart: 2 items, total 9.00
2 True (3.0, 1)
False True
Amna + Bilal's cart: 3 items, total 29.00
[ShoppingCart('Amna'), ShoppingCart('Bilal'), ShoppingCart('Amna + Bilal')]
Python dunder methods map from Lesson 41: len(amna) calls __len__ and gives 2, "pen" in amna calls __contains__, amna == bilal calls __eq__, amna < bilal calls __lt__ and amna + bilal calls __add__ for a 29.00 cart.
You use the normal operators and functions; Python calls the matching dunder method on your object.
  • len(amna) is 2, "pen" in amna is True, and amna["notebook"] is (3.0, 1).
  • amna == bilal is False (different items), and amna < bilal is True (9.00 is less than 20.00).
  • amna + bilal made a 3-item cart worth 29.00, and sorted() placed it last.

We left out total_ordering here on purpose: __eq__ compares items but __lt__ compares totals, so <= built from them would mix two rules. Dunder methods are also inherited like any other method (Lesson 40), so a subclass of this cart gets all of them. In Lesson 42, dataclasses write __init__, __repr__ and __eq__ for you.

Try it yourself

Exercise 1: A playlist

Write a Playlist class with a name, a list of songs and an add() method. Add __len__, __contains__ and __str__ ("Study: 2 songs"). Show that an empty playlist is false.

Exercise 2: Money

Write a Money class with an amount. Add __eq__, __add__ (returns a new Money) and __repr__. Check that Money(1.5) + Money(3) == Money(4.5) is True, that Money(4.5) == 4.5 is False, and that Money(1) + 2 raises TypeError.

Exercise 3: Sortable products

Write a Product class with name and price, compared by price. Use total_ordering so that sorted(), max(), min() and <= all work.

Solutions

Solution 1

class Playlist:
    def __init__(self, name):
        self.name = name
        self.songs = []

    def add(self, song):
        self.songs.append(song)

    def __len__(self):
        return len(self.songs)

    def __contains__(self, song):
        return song in self.songs

    def __str__(self):
        return f"{self.name}: {len(self)} songs"


study = Playlist("Study")
print(study, bool(study))
study.add("Rain sounds")
study.add("Lo-fi beat")
print(study, bool(study))
print("Rain sounds" in study, "Fast beat" in study)
Study: 0 songs False
Study: 2 songs True
True False

__len__ alone makes an empty playlist false, and __str__ reuses len(self).

Solution 2

class Money:
    def __init__(self, amount):
        self.amount = amount

    def __eq__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return self.amount == other.amount

    def __add__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return Money(self.amount + other.amount)

    def __repr__(self):
        return f"Money({self.amount})"


price = Money(1.5) + Money(3)
print(price)
print(price == Money(4.5), price == 4.5)
try:
    Money(1) + 2
except TypeError as err:
    print("TypeError:", err)
Money(4.5)
True False
TypeError: unsupported operand type(s) for +: 'Money' and 'int'

Returning NotImplemented for other types gives False for == and the normal TypeError for +.

Solution 3

from functools import total_ordering


@total_ordering
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __eq__(self, other):
        if not isinstance(other, Product):
            return NotImplemented
        return self.price == other.price

    def __lt__(self, other):
        if not isinstance(other, Product):
            return NotImplemented
        return self.price < other.price

    def __repr__(self):
        return f"{self.name}({self.price})"


products = [Product("bag", 20.0), Product("pen", 1.5), Product("notebook", 3.0)]
print(sorted(products))
print(max(products), min(products))
print(Product("pen", 1.5) <= Product("ruler", 1.5))
[pen(1.5), notebook(3.0), bag(20.0)]
bag(20.0) pen(1.5)
True

total_ordering built <= from __lt__ and __eq__; both use the price, so a 1.50 pen is <= a 1.50 ruler.

Common mistakes

  • Returning the wrong type from __len__. It must return a whole number of 0 or more. Returning a total like 6.0 gives TypeError: 'float' object cannot be interpreted as an integer.
  • Using objects with __eq__ as dictionary keys. After you add __eq__, {cart: "Monday"} fails with TypeError: cannot use 'ShoppingCart' as a dict key (unhashable type: 'ShoppingCart'). Use a hashable key, such as the owner’s name.
  • No type check in __eq__. return self.items == other.items crashes on cart == "pen": AttributeError: 'str' object has no attribute 'items'. Check with isinstance() and return NotImplemented.
  • Changing self in __add__. self.items.update(other.items) followed by return self changes Amna’s own cart, and family is amna printed True. Build and return a new object.
  • A typo in the name. def __len(self): (no underscores at the end) is just a normal method, so len(cart) still says TypeError: object of type 'ShoppingCart' has no len().

Frequently asked questions

Why are they called dunder or magic methods?

“Dunder” is short for “double underscore”, because the names start and end with two underscores, like __init__. They are sometimes called magic methods because Python calls them automatically. The official docs call them special methods.

Should I call dunder methods directly?

Normally no. Write len(cart), a == b and a + b, and let Python call __len__, __eq__ and __add__. The operators also handle extra steps for you, such as trying the other side when you return NotImplemented. Inside a subclass, super().__init__() is the common exception.

What is the difference between __str__ and __repr__?

__str__ gives friendly text for users and is used by print(). __repr__ gives precise text for programmers, is used when you print a list of objects, and should look like the code that creates the object. Lesson 38 covers both with examples.

Summary

  • Dunder methods let Python’s operators and built-in functions work with your objects: len() calls __len__, in calls __contains__, [] calls __getitem__, for calls __iter__.
  • __len__ also decides truth: an object with length 0 is false.
  • __eq__ defines equality; != comes free, but the class becomes unhashable unless you also define __hash__.
  • __lt__ makes objects sortable; functools.total_ordering adds the other comparisons from __lt__ and __eq__.
  • Return NotImplemented for types you do not support, and make __add__ return a new object.

Next lesson

Next: Lesson 42, Python dataclasses: Write Classes With Less Code.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *