tempcache

TempCache Documentation

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.

Installation

pip install tempcache

Basic Usage

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(...)

Caching results at the call site

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, ...)

Advanced usage

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)

API Reference

TempCache Class

TempCache(name='tempcache', *, source=None, max_age=None, pickler=None)

Main cache utility class.

Parameters:

Methods:

CacheItem Class

CacheItem(path, *, pickler=None)

Represents a single cached item.

Methods:

Features

Best Practices

Limitations