Skip to content

Instantly share code, notes, and snippets.

@mbarkhau
Last active December 18, 2015 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbarkhau/5785629 to your computer and use it in GitHub Desktop.
Save mbarkhau/5785629 to your computer and use it in GitHub Desktop.
Limited size dictionar with Random Eviction
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