funkycache
A SQLite-backed cache for Python functions that tracks file dependencies.
funkycache is a Python function cache that tracks file dependencies. I use it in my static site generator to cache the output of expensive functions.
To cache the output of a function, create a FunkyCache instance, then apply the cache.register decorator. For example:
from funkycache import FunkyCache
cache = FunkyCache(storage="sqlite")
@cache.register(paths=["templates/base.html"])
def render_index(content: str) -> str:
with open("templates/base.html") as f:
template = f.read()
return template.replace("{{ content }}", content)
print(render_index()) # runs the function
print(render_index()) # cache hit, even in a new process
cache.notify_path_change("templates/base.html")
print(render_index()) # runs the function againWhen you register a function with funkycache, you can declare path or static values the function depends on. If those dependent values change, funkycache creates a fresh cache for the updated dependencies – so calls with those new dependencies won’t hit entries from the old state.
Requirements
funkycache is intended for deterministic functions which:
- Always return an identical output when given the same arguments, and
- Do not have side effects
If you use SQLite storage, your function must have a type hint which includes a return annotation.
Installation
Install using pip:
$ pip install funkycacheExamples
Basic usage
To cache the output of a function, create a FunkyCache instance, then use the register decorator on your function:
from funkycache import FunkyCache
cache = FunkyCache()
@cache.register
def fibonacci(n: int) -> int:
return fibonacci(n - 1) + fibonacci(n - 2) if n >= 2 else 1
print(fibonacci(10))The default storage is in memory, so results will only be persisted for the lifetime of the Python process.
Choosing your storage
There are two types of storage: in-memory and SQLite. Select which you’d like by passing the storage option to FunkyCache.
To use in-memory storage:
cache = FunkyCache(storage="memory")To use SQLite storage:
cache = FunkyCache(storage="sqlite")Choosing your SQLite directory
funkycache creates one SQLite database per cached function, all stored in the same directory. By default, it saves these databases in .funkycache.
You can choose a different directory by passing a root parameter to FunkyCache.
For example, to save these databases in .cache:
cache = FunkyCache(storage="sqlite", root=".cache")The root parameter can be a str or a Path.
Depending on an external file
If your function depends on a file or folder which is not an input to the function, you can declare that dependency by passing the paths parameter to cache.register.
For example, if your function depends on a template file, you can declare a dependency on the template:
@cache.register(paths=["templates/greeting.html"])
def render_greeting(name: str) -> str:
template = Path("templates/greeting.html").read_text()
return template.replace("{{ name }}", name)If you pass a file path, the contents of the file will be included in the input signature for that cache.
You can pass paths to files that do not exist, in which case their absence is recorded in the signature. If the file is later created, the input signature changes, and funkycache starts using a fresh cache rather than reusing entries from when the file was missing.
If you pass a folder path, the contents of every file under that folder will be included in the input signature.
The contents of each file are checked once, when you call cache.register.
If the contents of the file have changed since the previous run (for example, when you restart your Python program), funkycache computes a new input signature and uses a fresh cache for it.
funkycache does not monitor the filesystem for file changes.
The source file where a function is defined is always a dependency, and changes to that file will invalidate the cache.
Notifying funkycache of changes to an external file
If an external input file changes, you can notify funkycache by calling cache.notify_path_change on the FunkyCache instance.
For example:
cache.notify_path_change(changed_paths=["templates/greeting.html"])funkycache checks which registered functions depend on those paths, recomputes their input signatures, and switches affected functions to a fresh cache when the signature has changed.
Notification is advisory: it is a hint that something may have changed, but caches are only invalidated when the files they depend on actually change, so notifying about an unrelated or unchanged path is cheap and safe.
Depending on a static value
If your function depends on a static value which is not one of the inputs, you can declare a dependency on this value by passing the values parameter to cache.register.
For example, if your function depends on a third-party library, you could declare a dependency on the library version:
import pygments
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name
@cache.register(values=[pygments.__version__])
def apply_syntax_highlighting(src: str, lang: str) -> str:
lexer = get_lexer_by_name(lang)
formatter = HtmlFormatter()
return pygments.highlight(src, lexer, formatter)These values are expected to be static for the lifetime of a Python process; changing them requires restarting the process so funkycache can compute a new input signature.
Caching a generator
funkycache has a limited capacity to cache functions which return generators. It will attempt to materialise the generator output into a list, then store that list. This means it may consume a large number of items on the first call, before you call next() on the generator.
In this example, funkycache will collect all 10 items on the very first call:
from collections.abc import Generator
@cache.register
def count_upwards(max: int) -> Generator[int]:
i = 0
while i < max:
i += 1
print(f"computing item {i}")
yield i
numbers = count_upwards(10)There is a soft memory cap of 5MB, and if the generator output exceeds this size, the output will not be cached, and the function will be called every time for that input.
Changing the soft memory cap
Pass the max_memory parameter to cache.register to change the memory cap for cached generators.
For example, to double the cap from the default:
@cache.register(max_memory=10 * 1024 * 1024)
def count_upwards(max: int) -> Generator[int]: ...Transforming arguments for cache keys
Sometimes you want two calls with different argument values to share (or avoid sharing) a cache entry, without changing the inputs to your function.
Pass the key_transforms parameter to cache.register to transform arguments before using them in the cache key. This takes a dictionary mapping argument name to a transformation, which can either be a function you define, or one of funkycache’s built-in transformations.
For example, you can normalise case or whitespace:
@cache.register(key_transforms={"query": lambda q: q.strip().lower()})
def search_docs(query: str) -> list[str]: ...The built-in pathstat transform caches a path argument based on the file’s modification time and size, not just the path.
from pathlib import Path
@cache.register(key_transforms={"path": "pathstat"})
def read_markdown(path: Path) -> str:
return path.read_text()Key transformations only affect the cache key. The decorated function receives the original arguments unchanged. If a transform fails at call time, funkycache issues a warning and calls the underlying function directly without touching the cache.
Design
- Each function has an independent cache
- Cache keys are the function arguments, serialised as JSON and hashed using XXH64
- Cache values are the return value, serialised as JSON
For more information about how funkycache works, read my design notes.
License
This project is shared under the MIT license.