I'm looking for a Python caching library but can't find anything so far. I need a simple dict
-like interface where I can set keys and their expiration and get them back cached. Sort of something like:
cache.get(myfunction, duration=300)
which will give me the item from the cache if it exists or call the function and store it if it doesn't or has expired. Does anyone know something like this?
From Python 3.2 you can use the decorator @lru_cache from the functools library. It's a Last Recently Used cache, so there is no expiration time for the items in it, but as a fast hack it's very useful.
from functools import lru_cache
@lru_cache(maxsize=256)
def f(x):
return x*x
for x in range(20):
print f(x)
for x in range(20):
print f(x)