11/40
Part 2 of 7 · KeysLearn and do
Your own class must hash what it compares
Define __eq__ without __hash__, and Python makes your objects unhashable:
class OnlyEq:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
{OnlyEq("milk")}
TypeError: unhashable type: 'OnlyEq'
That's the safe outcome. The dangerous one is a __hash__ that disagrees with __eq__:
class Tag:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name.casefold() == other.name.casefold()
def __hash__(self):
# bug: hashes the raw name
return hash(self.name)
print(Tag("Milk") == Tag("milk"))
print(len({Tag("Milk"), Tag("milk")}))
Tag compares names with casefold but hashes the raw name. How many items does {Tag("Milk"), Tag("milk")} hold?
Pick one to see what it prints.
Pick an answer above to see the rest