Greetings, I'm trying to write a small script to audit my architecture library that is split between a file (YAML) and folder structure.
In order to not lose myself in nested dictionaries I've decided to try out my hand at dataclasses, but I've hit a particular problem, how to store them? Say I have the "Architect" class, I want to be able to has a set() but be able to retrieve the instance of the class if the hashed attribute is the same (the name) to be able to compare/update/join instances whether it's missing info from one side or the other.
@dataclass
class Architect:
name: str
based: Optional[str] = None
url: Optional[str] = None
def __hash__(self) -> int:
return hash(self.name)
def __eq__(self, other: object) -> bool:
if not isinstance(other, type(self)):
return False
else:
return self.name == other.name
architect = Architect(name=name)
if architect in architects:
old_instance = architects.get(architect)
The approach that I tried was mimicking the dict() builtin and always use hash() as the key for the item:
class RetrivableSet:
def __init__(self, iterable: Optional[Iterable[Hashable]] = None):
self.data: dict[Hashable, Hashable] = {}
if iterable is not None:
self.add(*iterable)
def __contains__(self, item: Hashable):
return hash(item) in self.data
def __getitem__(self, item: Hashable):
return self.data[hash(item)]
def get(self, item: Hashable) -> Hashable:
key = hash(item)
if key in self:
return self[key]
else:
return item
def add(self, item: Hashable):
self.data[hash(item)] = item
def remove(self, item: Hashable):
del self.data[hash(item)]
architects: RetrivableSet = RetrivableSet()
architects.add(architect)