Search code examples
pythonequalitypython-dataclassespython-class

Why are these 2 python class instance could equal to each other?


from dataclasses import dataclass

@dataclass
class ThreeDPoint:
    x: int | float
    y = 0.0
    z: int | float = 0.0

point_1 = ThreeDPoint(1.0,2)

point_3 = ThreeDPoint(1,2)
print(point_1 == point_3)

The result is true.

I ran it in python playground. The result said it is true. I think this dataclass module might play some magic trick inside but I am not sure what is exactly happening.


Solution

  • There is no magic trick. In Python, integer 1 and float 1.0 are the same

    > 1 == 1.0
    True
    

    On the other hand, type(1) is not the same as type(1.0)

    > type(1) == type(1.0)
    False
    

    If you would like the equality operator to behave the way you suggested (= returning False when x has the same value but different type), then you could define your own equality method for the class, like so:

    from dataclasses import dataclass
    
    
    @dataclass
    class ThreeDPoint:
        x: int | float
        y = 0.0
        z: int | float = 0.0
    
        def __eq__(self, other):
            for var, var_value in self.__dict__.items():
                try:
                    other_var_value = getattr(other, var)
                    if not (var_value == other_var_value and type(var_value) is type(other_var_value)):
                        return False
                except AttributeError:
                    return False
            return True
    
    
    point_1 = ThreeDPoint(1.0, 2)
    point_3 = ThreeDPoint(1, 2)
    print(point_1 == point_3)