From d2f03722e7422f52380ebd99a07eafca84ec7d28 Mon Sep 17 00:00:00 2001 From: Stephen Bailey Date: Mon, 23 Mar 2015 17:26:22 -0700 Subject: [PATCH] Fix CacheDict for pickling --- py/util/cachedict.py | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/py/util/cachedict.py b/py/util/cachedict.py index a12b6b1..236e813 100644 --- a/py/util/cachedict.py +++ b/py/util/cachedict.py @@ -3,15 +3,35 @@ """ class CacheDict(dict): - def __init__(self, n): + """ + A dictionary that keeps only the last n items added + """ + def __init__(self, n, d=None): + """ + Create CacheDict with n keys cached. + + If d is a dict, use that to initialize the key/value pairs + """ self._keys = [None,]*n self._current = -1 self._n = n + + if type(d) == dict: + for key, value in d.items(): + self[key] = value + + #- Needed by pickle to reconstruct the object. + #- Pickle tries to reconstruct the dictionary via __setitem__ before + #- filling in _keys, _current, _n. This allows it to create a new + #- object first to get those right, before calling __setitem__ + def __reduce__(self): + return type(self), (self._n, dict(self)) def __setitem__(self, key, value): + """Sets the key/value, possibly dropping an earlier cached key/value""" if key in self: return - + i = self._current = (self._current + 1) % self._n if self._keys[i] is not None: del self[self._keys[i]] @@ -19,4 +39,3 @@ def __setitem__(self, key, value): self._keys[i] = key dict.__setitem__(self, key, value) - \ No newline at end of file