Created
December 23, 2019 19:08
-
-
Save luisenriquecorona/f0acc7f6743c5683109e29abdadc869e to your computer and use it in GitHub Desktop.
Underlying the way mappings deal with missing keys is the aptly named __missing__ method. This method is not defined in the base dict class, but dict is aware of it: if you subclass dict and provide a __missing__ method, the standard dict.__getitem__will call it whenever a key is not found, instead of raising KeyError.
This file contains hidden or 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 StrKeyDict0(dict): | |
def __missing__(self, key): | |
if isinstance(key, str): | |
raise KeyError(key) | |
return self[str(key)] | |
def get(self, key, default=None): | |
try: | |
return self[key] | |
except KeyError: | |
return default | |
def __contains__(self, key): | |
return key in self.keys() or str(key) in self.keys() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment