Skip to content

Commit 0e862fb

Browse files
Document pickling instances with lru_cache decorated methods.
After a cached instance method is called, the per-instance cache is stored as a non-picklable functools._lru_cache_wrapper attribute on the instance, so pickling the instance fails. Document overriding __getstate__ to drop attributes whose names begin with _lru_cache_ (or the method specific _lru_cache_<name>_ prefix), with the caches recreated lazily after unpickling.
1 parent 73dca57 commit 0e862fb

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

‎docs/bundled.rst‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,35 @@ single shared cache.
112112
>>> fibonacci.cache_parameters()
113113
{'maxsize': 128, 'typed': False}
114114

115+
Because the per-instance cache is stored as an attribute on the instance, an
116+
instance whose cached method has been called holds a
117+
``functools._lru_cache_wrapper`` object in its ``__dict__``, and that object
118+
is not picklable. If instances of the class need to be pickled, override
119+
``__getstate__`` to drop the cache attributes from the pickled state. The
120+
cache attribute names all begin with ``_lru_cache_``, so filtering on that
121+
prefix excludes every per-instance cache. The caches are recreated lazily on
122+
the next call after unpickling.
123+
124+
::
125+
126+
class MyClass:
127+
128+
@wrapt.lru_cache
129+
def compute(self, x):
130+
return x * 2
131+
132+
def __getstate__(self):
133+
return {
134+
key: value
135+
for key, value in self.__dict__.items()
136+
if not key.startswith("_lru_cache_")
137+
}
138+
139+
To target the cache for a particular method rather than all of them, filter
140+
on the more specific ``_lru_cache_<name>_`` prefix, where ``<name>`` is the
141+
method name. For example, ``_lru_cache_compute_`` matches only the cache for
142+
the ``compute`` method above.
143+
115144
Thread Synchronization
116145
----------------------
117146

0 commit comments

Comments
 (0)