Python › Dataclasses & NamedTuples
How do you implement a custom __eq__ or __hash__ on a dataclass while still benefiting from its other auto-generated methods?
AdvancedAnswer
Pass eq=False (or hash appropriately) to @dataclass to SKIP auto-generating that specific method, then define your OWN __eq__ or __hash__ method in the class body — the decorator only generates methods you haven't disabled, letting you selectively override just the behavior you need custom logic for.
@dataclass(eq=False)
class CaseInsensitiveString:
value: str
def __eq__(self, other):
return isinstance(other, CaseInsensitiveString) and self.value.lower() == other.value.lower()
def __hash__(self):
return hash(self.value.lower())Real-world example Implementing case-insensitive equality for a dataclass wrapping a string, where the default field-by-field comparison wouldn't be correct.