Created
September 26, 2012 20:12
-
-
Save dwf/3790284 to your computer and use it in GitHub Desktop.
A key-aware default dictionary implementation.
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 KeyAwareDefaultDict(dict): | |
""" | |
Like a standard library defaultdict, but pass the key | |
to the default factory. | |
""" | |
def __init__(self, default_factory=None): | |
self.default_factory = default_factory | |
def __getitem__(self, key): | |
if key not in self and self.default_factory is not None: | |
self[key] = val = self.default_factory(key) | |
return val | |
else: | |
raise KeyError(str(key)) | |
def test_key_aware_default_dict(): | |
a = KeyAwareDefaultDict(str) | |
assert a[5] == '5' | |
assert a[4] == '4' | |
assert a[(3, 2)] == '(3, 2)' | |
try: | |
b = KeyAwareDefaultDict() | |
b[5] | |
except KeyError: | |
return | |
assert False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment