I have written a mapping to a mutable Set in Python. I've used it as a datastructure dealing with file hashes and map the hashes to duplicate files.
I want to apply type hints and have read a lot about Generics and that stuff. Finally, I am not able to solve it well and I ask help from the community:
How does one type annotate the code below correctly?
I know, I could inherit from collections.abc thereby taking advantage of some type hints. However, in the mixin of Mapping and MutableSet I would end up in ducktyped methods such as __iter__ that are difficut to trace (at least for me). Therefore I chose to write all necessary methods by hand.
I want to supply all possible types, so kind of
K = typing.TypeVar('K', bound = typing.Hashable)
should be involved. This is necessary for keys in a dict and members of a set. The code below just deals with Integers.
Thank you very much for your comments!
class MtoS():
def __init__(self, x = None):
self._hashlu= {}
if isinstance(x, list):
for t in x:
self.add(t)
elif x:
self.add(x)
def __ior__(self, other):
for i in other:
self.add(i)
return self
def __len__(self):
return sum([len(x) for x in self._hashlu.values()])
def add(self, item):
if item[0] not in self._hashlu:
self._hashlu[item[0]] = set()
self._hashlu[item[0]].add(item[1])
def __iter__(self):
for hash in self._hashlu.keys():
for file in sorted(self._hashlu[hash]):
yield hash, file
def __str__(self):
return(str(self._hashlu))
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self))
def __getitem__(self, key):
return self._hashlu[key]
if __name__ == "__main__":
m = MtoS([(1,2),(3,4)])
o = MtoS([(3,4),(3,5),(4,5),(4,6)])
print(m) # {1: {2}, 3: {4}}
print(m[1]) # {2}
m |= o
print(m) # {1: {2}, 3: {4, 5}, 4: {5, 6}}
print(len(m)) # 5