Created
October 21, 2016 17:15
-
-
Save rlkelly/da88ec58008db8fa94a5259dc9713d72 to your computer and use it in GitHub Desktop.
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): | |
def __new__(cls, default_value): | |
new_instance = super(DefaultDict, cls).__new__(cls, default_value) | |
return new_instance | |
def __init__(self, default_value): | |
self.default_value = default_value | |
super(DefaultDict, self).__init__() | |
def __getitem__(self, item): | |
if item not in self: | |
self[item] = self.default_value | |
return self.default_value | |
def __repr__(self): | |
return 'DefaultDict <default %s> %s' % (self.default_value, dict.__repr__(self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment