Last active
December 18, 2015 12:49
-
-
Save mbarkhau/5785629 to your computer and use it in GitHub Desktop.
Limited size dictionar with Random Eviction
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 random import randint | |
class REDict(dict): | |
def __init__(self, maxsize, *args, **kwargs): | |
self._maxsize = maxsize | |
self._keys = [] | |
self._evict_cb = kwargs.pop('_evict_cb', None) | |
dict.__init__(self, *args, **kwargs) | |
def __setitem__(self, key, val): | |
if len(self._keys) >= self._maxsize: | |
i = randint(0, self._maxsize - 1) | |
old_k = self._keys[i] | |
old_v = self.pop(old_k) | |
if self._evict_cb: | |
self._evict_cb(old_k, old_v) | |
self._keys[i] = key | |
else: | |
self._keys.append(key) | |
dict.__setitem__(self, key, val) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment