Skip to content

Instantly share code, notes, and snippets.

@sterliakov
Created July 23, 2022 00:14
Show Gist options
  • Save sterliakov/042bc5c3598217add267a5de497ba2b4 to your computer and use it in GitHub Desktop.
Save sterliakov/042bc5c3598217add267a5de497ba2b4 to your computer and use it in GitHub Desktop.
Example of unexpected results with mutable hashable objects
class MyDict(dict):
def __hash__(self):
return hash(frozenset(self))
key = MyDict(a=1)
mapping = {key: 'foo'}
key['b'] = 2
mapping[key] # KeyError: {'a': 1, 'b': 2}
# Do you expect that variable which you have added to dict would raise KeyError?
# And this may happen in another function, if you have passed key somewhere else in between
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment