I'm using this memoize decorator on a class and it is very effective. Now I'm ready to trade some of that speed for control over memory consumption. Ideally I'd be able to set a maximum; (eg: 2GB) but I guess I can trial and error a lot and settle for a maximum number of objects in the cache.
Anyone know of some ready-made code to do this? I guess I'd toss out the oldest in the cache to add the newest.
Or is there a more sensible way to do this?
Here's the routine I'm currently using:
def memoize(obj):
"""A decorator to cache advice objects using the advice key"""
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
key = args[0]
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
Seems sensible to give the max as an arg to the decorator like:
@memoize(max=2000)
class Foo(object):
...