Last active
August 29, 2015 14:16
-
-
Save bheklilr/6d6956800e65b6323bc7 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
from collections import OrderedDict, MutableMapping, ItemsView | |
class ordereddefaultdictwithkey(MutableMapping, ItemsView): | |
def __init__(self, factory_func): | |
self.__factory_func = factory_func | |
self.__dict = OrderedDict() | |
def __len__(self): | |
return len(self.__dict) | |
def __delitem__(self, key): | |
del self.__dict[key] | |
def __setitem__(self, key, value): | |
self.__dict[key] = value | |
def __iter__(self): | |
return iter(self.__dict) | |
def __getitem__(self, key): | |
if key not in self.__dict: | |
val = self.__factory_func(key) | |
self.__dict[key] = val | |
return val | |
else: | |
return self.__dict[key] | |
def __contains__(self, key): | |
return key in self.__dict | |
def __repr__(self): | |
return '{}({},{})'.format(self.__class__.__name__, repr(self.__factory_func), repr(list(self.iteritems()))) | |
## Example | |
import time | |
def long_computation(name): | |
time.sleep(1) | |
return len(name) | |
def another_computation(length): | |
time.sleep(1) | |
return '*' * length | |
a = ordereddefaultdictwithkey(lambda key: long_computation(key)) | |
b = ordereddefaultdictwithkey(lambda key: another_computation(a[key])) | |
b['test'] | |
b['foobarbaz'] | |
print 'a is' | |
print a | |
print 'b is' | |
print b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment