TempCache is a Python utility that provides temporary file-based caching functionality. It’s designed to cache function results and arbitrary data using the system’s temporary directory.
pip install tempcache
An instance of the TempCache
class be used as a decorator
to automatically cache the results of a function.
from tempcache import TempCache
CACHE_MAX_AGE = 24 * 60 * 60 * 2 # two days
cache = TempCache("mycache", max_age=CACHE_MAX_AGE)
@cache
def long_running(...):
...
result = long_running(...)
You can also use a TempCache
object to cache a result
at the call site with the cache_result
method.
from tempcache import TempCache
CACHE_MAX_AGE = 24 * 60 * 60 * 2 # two days
cache = TempCache("mycache", max_age=CACHE_MAX_AGE)
def long_running(...):
...
result = cache.cache_result(long_running, ...)
In cases where the function or some of its arguments
are defined in the __main__
namespace or in a jupyter notebook
and cannot be pickled by pickle
you can use a different pickle module
like cloupickle
.
import cloudpickle
from tempcache import TempCache
CACHE_MAX_AGE = 24 * 60 * 60 * 2 # two days
cache = TempCache("mycache",
pickler=cloudpickle,
max_age=CACHE_MAX_AGE)
key = ...
# key object can be complex as long as it is pickle-able
item = cache.item_for_key(key)
# cache item for the given key whether it exists or not
# load item if it exists
if item.exists():
value = item.load()
# save item
item.save(value)
TempCache
ClassTempCache(name='tempcache', *, source=None, max_age=None, pickler=None)
Main cache utility class.
Parameters:
name
(str): Name of caching folder under tempdir (default: ‘tempcache’)source
(str, optional): Extra source information to differentiate key hashesmax_age
(int, optional): Maximum age in seconds (default: 7 days)pickler
(module, optional): Custom pickler module (default: pickle)Methods:
clear_items(all_items=False)
: Clear expired or all itemsitem_for_key(key)
: Get cache item for a specific keycache_result(func, *args, **kwargs)
: Cache function results__call__(func)
: Decorator interface for function cachingCacheItem
ClassCacheItem(path, *, pickler=None)
Represents a single cached item.
Methods:
exists()
: Check if item existsolder_than(whence)
: Check if item is older than given timestampnewer_than(whence)
: Check if item is newer than given timestampdelete()
: Delete the cached itemload()
: Load item contentssave(data)
: Save item contentstry_load()
: Load item contents, ignoring errorstry_save(data)
: Save item contents, ignoring errors