I made a hashable custom class to use as keys in a dictionary. I rewrote __repr__
to return some attributes combined in a string, the __hash__
to hash this string, and __eq__
to compare the __repr__
string of each object.
It seems like it should be possibile to lookup the object by that string alone. So far, that does not appear to be the case, at least looking up by string
, repr(string)
, and str(string)
.
Am I doing something wrong or is my scheme just not possible? Based on what I’ve been reading about dictionary lookup in Python, if the is
table comparison fails, it uses ==
, and so looking up a matching __repr__
string ought to work.
Answer:
I tried one more thing and it worked.
When I lookup the dictionary with the string, it uses the string’s __repr__
method, which adds quotations marks.
So changing the __eq__
method for the custom class from
return self.__repr__() == other.__repr__()
to
return self.__repr__() == other.__str__()
compares the object’s string against the unaltered string value.
This gives the same hash value, returns True
for ==
comparison, and works for dictionary lookup.