Does anyone got this weird outcome before?
>>> a == b
False
>>> list(sorted(a)) == list(sorted(b))
True
>>> set(list(a)) == set(list(b))
True
Where a and b above are set containing custom class instances.
This custom class inherited from MutableMapping with both __eq__() and __hash__() implemented as follows:
def to_json(self) -> dict:
# Code returning the data of this class
def __eq__(self, other):
if isinstance(other, Model):
return self.to_json() == other.to_json() and type(self) == type(other)
elif isinstance(other, MutableMapping):
return self.to_json() == other
else:
return False
def __hash__(self):
d = self.to_json()
hash_list = []
for k, v in d.items():
if isinstance(v, list):
v = tuple(v)
elif isinstance(v, dict):
v = tuple(v.items())
elif isinstance(v, Model):
v = hash(v)
hash_list.append((k, v))
return hash(tuple(hash_list))
I also test the hash code of these elements, it turns out it is the same. Below is my script to test:
>>> [hash(m) for m in a]
[-1696378346402890742, 3465342798672228497, 5576155172607749152]
>>> [hash(m) for m in b]
[-1696378346402890742, 3465342798672228497, 5576155172607749152]
I've found that there's some work to do with in, but I don't know what should I implement. I also don't know why this is its behavior.
>>> [(m in b) for m in a]
[False, False, False]
>>> [(m in b) for m in set(list(a))]
[False, False, False]
>>> [(m in set(list(b))) for m in a]
[True, True, True]
>>> [(m in set(list(b))) for m in set(list(b))]
[True, True, True]
Any fix that could potentially avoid/correct this weird behavior and the reason why this is how it works would be appreciated. Thanks!