Skip to content

Instantly share code, notes, and snippets.

@dwf
Created September 26, 2012 20:12
Show Gist options
  • Save dwf/3790284 to your computer and use it in GitHub Desktop.
Save dwf/3790284 to your computer and use it in GitHub Desktop.
A key-aware default dictionary implementation.
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