weakref and memoizing

B

bearophileHUGS

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top