Skip to content

Instantly share code, notes, and snippets.

@Jasata
Created December 28, 2019 08:29
Show Gist options
  • Save Jasata/2cb9bb2c4a52f5bb5b7246a898d2f535 to your computer and use it in GitHub Desktop.
Save Jasata/2cb9bb2c4a52f5bb5b7246a898d2f535 to your computer and use it in GitHub Desktop.
Dictionary with .default value
class DefaultDict(dict):
"""Returns DefaultDict.default value for missing key, or raises KeyError if default has not been set."""
def __missing__(self, key):
if getattr(self, 'default', None):
return self.default
raise KeyError(
f"Key '{key}' does not exist and default has not been set!"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment