Search code examples
pythonpython-dataclasses

Different dataclass object show equal


I have a simple dataclass with 3 member variables. When I create two different objects for the class and check for equality it always comes out True even if the values for the member variables is different.

Data Class:

@dataclass(init=False)
class DiagCodes:
    __slots__ = ["indx_nbr", "diag_cd", "diag_typ_cd"]

    def __init__(
        self,
        indx_nbr: Optional[int] = None,
        diag_cd: Optional[str] = None,
        diag_typ_cd: Optional[str] = None,
    ) -> None:

        self.indx_nbr = indx_nbr
        self.diag_cd = diag_cd
        self.diag_typ_cd = diag_typ_cd

if __name__ == "__main__":
    dc = DiagCodes(1)
    dc_empty = DiagCodes()

    print(dc == dc_empty)

Output:

True

Shouldn't the output come out as false with the default implementation of __eq__ function of the dataclass?

The python version I am working on is Python 3.8.10


Solution

  • You're not really using the functionality of dataclasses here. The dataclass decorator looks for class variables with type annotations (called fields) of which you have none.

    The default __eq__ for dataclasses compares each of it's fields. Since you don't any any fields, the equality returns true.

    Try the following (note you could remove init=False and the hand written __init__ method):

    @dataclass(init=False)
    class DiagCodes:
        __slots__ = ["indx_nbr", "diag_cd", "diag_typ_cd"]
    
        indx_nbr: Optional[int]
        diag_cd: Optional[int]
        diag_typ_cd: Optional[str]
        
        def __init__(
            self,
            indx_nbr: Optional[int] = None,
            diag_cd: Optional[str] = None,
            diag_typ_cd: Optional[str] = None,
        ) -> None:
    
            self.indx_nbr = indx_nbr
            self.diag_cd = diag_cd
            self.diag_typ_cd = diag_typ_cd