Search code examples
pythonenumspython-dataclasses

Counter-intuitive results when mixing dataclass and enum


A colleague of mine just tried mixing dataclass and enum, and got some weird result:

from dataclasses import dataclass 
from enum import Enum

@dataclass
class MyClass(Enum):
    A = 1
    B = 2
>>> MyClass.A == MyClass.B
True

While we quickly realized that the @dataclass was irrelevant here (a simple enum is fine), we are still wondering why MyClass is behaving this way.


Additional info/things we tried below:

>>> MyClass.A
MyClass()
>>> type(MyClass.A)
<enum 'MyClass'>
>>> type(MyClass)
<class 'enum.EnumMeta'>
>>> @dataclass
... class MyClass2(int):
...     A = 1
...     B = 2
... 
>>> 
>>> print(MyClass2.A == MyClass2.B)  # Works fine with 'int'
False

Solution

  • First observation: dataclass and Enum were not designed to work together.

    The specific issue you are experiencing:

    • dataclass replaces the __eq__ method
    • the dataclass __eq__ method is comparing the values of the dataclass fields
    • there are no dataclass fields
    • so they compare equal

    Enum's __eq__, on the other hand, knows to compare the .value of each member.