Note

Python - Magic Method __eq__ - Implement custom object comparison


Understanding the Python __eq__ Magic Method / Dunder Method with Examples

Magic Method __eq__ specify what should be compared to determine equality between two class instances. So it means that the __eq__ magic method allows you to define custom behavior for the == operator.

This method is accepting argument (most often called other) that is a class instance that is being compared.


class MyClass:
    def __init__(self, my_int: int) -> None:
        self.my_int = my_int

    def __eq__(self, other: "MyClass") -> bool:
        return self.my_int == other.my_int


my_class_instance_1 = MyClass(1)
my_class_instance_2 = MyClass(1)

print(my_class_instance_1 == my_class_instance_2)  # True

my_class_instance_3 = MyClass(2)

print(my_class_instance_1 == my_class_instance_3)  # False

Output:

True
False

When to Use __eq__

Implementing __eq__ is especially useful for:

  • Data-centric Classes: Comparing data objects like products, users, or transactions.

  • Filtering Unique Elements: In sets or lists, where you want only unique instances of your object.

  • Unit Testing: Allowing direct comparison of instances in test assertions.


Here you can take a look at a more practical example. Product class where two products are considered equal only if they have the same name and price attributes:

class Product:
    def __init__(self, name: str, price: int) -> None:
        self.name = name
        self.price = price

    def __eq__(self, other: "Product") -> bool:
        return self.name == other.name and self.price == other.price

product_1 = Product("Laptop", 999)
product_2 = Product("Laptop", 999)
product_3 = Product("Smartphone", 699)

print(product_1 == product_2)  # True
print(product_1 == product_3)  # False

Output:

True
False

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: