I have this dataclass:
from dataclasses import dataclass, field
from typing import List
@dataclass
class Person:
name: str
dob: str
friends: List['Person'] = field(default_factory=list, init=False)
name
and dob
are immutable and friends
is mutable. I want to generate a hash of each person object. Can I somehow specify which field to be included and excluded for generating the __hash__
method? In this case, name
and dob
should be included in generating the hash and friends
shouldn't. This is my attempt but it doesn't work
@dataclass
class Person:
name: str = field(hash=True)
dob: str = field(hash=True)
friends: List['Person'] = field(default_factory=list, init=False, hash=False)
>>> hash(Person("Mike", "01/01/1900"))
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
hash(Person("Mike", "01/01/1900"))
TypeError: unhashable type: 'Person'
I also can't find a way to set name
and dob
to be frozen. And I'd refrain from setting unsafe_hash
to True
, just by the sound of it. Any suggestions?
Also, is what I'm doing considered good practice? If not, can you suggest some alternatives?
Thank you
Edit: This is just a toy example and we can assume that the name and dob fields are unique.
Edit: I gave an example to demonstrate the error.