Created
July 23, 2022 00:14
-
-
Save sterliakov/042bc5c3598217add267a5de497ba2b4 to your computer and use it in GitHub Desktop.
Example of unexpected results with mutable hashable objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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