weakref and memoizing

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Jan 19 19:01:24 EST 2006


This is yet another memoize decorator, it's meant to be resilient (and
fast enough):
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466320

Like most memoize decorators it stores the pairs of data-result in
cache dictionary, but Garrett Rooney says:

it could be better if it used the new weak references from python 2.1.
The way it works now, the cached values will be stored forever, and
will never be garbage collected. This is fine if they are small, but if
they happen to be non trivial objects, the memory cost could be a
problem. If they are refered to with weak references, they can still be
garbage collected, as long as there are no strong references to them.

So maybe I can use a dict with weak values:
self._cache = weakref.WeakValueDictionary()
But the keys of such dict can't be ints and others. Maybe here someone
can suggest me if and how weak references can be used in this
situation.

Bye,
bearophile




More information about the Python-list mailing list