Created
December 28, 2019 08:29
-
-
Save Jasata/2cb9bb2c4a52f5bb5b7246a898d2f535 to your computer and use it in GitHub Desktop.
Dictionary with .default value
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 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