'When do I need to add a hash to my own object, for example a python data class?
I find myself in one of two situations very often. I have a class, either a standard class
class myClass:
def __init__(self, x):
self.x = x
or a dataclasss
@dataclass(frozen=True)
class myClass:
x: float
Now, all I want is to be able to store these two classes as keys in a dictionary, such that the hash is on the instant of the object itself, so look-up will work if (and only if) I look-up using the exact same instant of the object that I stored as key.
I've read online a bit, and what confuses me is the __eq__ operator. I have no idea why that is relevant here. All I want is for dictionaries to remember the object by its id. So, my questions are
- do I need to add
def __hash__(self): return id(self)to any of those two objects above, or is this always implicit? - do I need to add
__eq__?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
