Last active
August 29, 2015 14:22
-
-
Save bencharb/b65a292fa03165d7ddf3 to your computer and use it in GitHub Desktop.
SimpleCache capped dict
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 CappedDict(collections.OrderedDict): | |
default_max_size = 50 | |
def __init__(self, *args, **kwargs): | |
self.max_size = kwargs.pop('max_size', self.default_max_size) | |
super(CappedDict, self).__init__(*args, **kwargs) | |
def __setitem__(self, key, val): | |
if key not in self: | |
max_size = self.max_size-1 # so the dict is sized properly after adding a key | |
self._prune_dict(max_size) | |
super(CappedDict, self).__setitem__(key, val) | |
def update(self, **kwargs): | |
super(CappedDict, self).update(**kwargs) | |
self._prune_dict(self.max_size) | |
def _prune_dict(self, max_size): | |
if len(self) >= max_size: | |
diff = len(self) - max_size | |
for k in self.keys()[:diff]: | |
del self[k] | |
class SimpleCache(CappedDict): | |
def __init__(self, max_length=50): | |
super(SimpleCache, self).__init__(max_size=max_length) | |
def get_key(self, *args): | |
return format(args) | |
def get_cache(self, *args): | |
key = self.get_key(*args) | |
try: | |
return self[key] | |
except KeyError: | |
return | |
def set_cache(self, value, *args): | |
key = self.get_key(*args) | |
self[key] = value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment