Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python caching library?

Tags:

python

caching

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?

like image 441
Stavros Korokithakis Avatar asked Oct 12 '22 04:10

Stavros Korokithakis


People also ask

Does Python have a cache?

Python offers built-in possibilities for caching, from a simple dictionary to a more complete data structure such as functools. lru_cache . The latter can cache any item using a Least-Recently Used algorithm to limit the cache size. Those data structures are, however, by definition local to your Python process.

Does Python cache imports?

Python caches all imported modules This all happened because Python caches modules. In Python, every module that is imported is stored in a dictionary called sys.

What is cache library?

Cache library (CacheLib) is a C++ library for accessing and managing cache data. It is a thread-safe API that enables developers to build and customize scalable, concurrent caches.


2 Answers

From Python 3.2 you can use the decorator @lru_cache from the functools library. It's a Least 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)
like image 84
Genma Avatar answered Oct 13 '22 16:10

Genma


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)
like image 55
Corbin March Avatar answered Oct 13 '22 16:10

Corbin March