Is there a Python caching library?

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?


Solution 1:

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)

Solution 2:

Take a look at Beaker:

  • Home Page
  • Caching Documentation
  • Good quick-start article about using Beaker with Django (but useful in any other apps too)

Solution 3:

You might also take a look at the Memoize decorator. You could probably get it to do what you want without too much modification.

Solution 4:

No one has mentioned shelve yet. https://docs.python.org/2/library/shelve.html

It isn't memcached, but looks much simpler and might fit your need.