Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created December 23, 2019 19:08
Show Gist options
  • Save luisenriquecorona/f0acc7f6743c5683109e29abdadc869e to your computer and use it in GitHub Desktop.
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.
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