Skip to main content

manager: add key_transforms to change how cache keys are stored

ID
00743a6
date
2026-11-26 22:16:34+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
b57f330
message
manager: add key_transforms to change how cache keys are stored

This allows you to transform arguments before using them in the cache
key, without changing how you call the function or what arguments it
receives.
changed files
7 files, 283 additions, 10 deletions

Changed files

CHANGELOG.md (1550 → 2793)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index d6a9bd5..38915fa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,34 @@
 # CHANGELOG
 
+## v1.2.0 - 2026-11-26
+
+Add the `key_transforms` parameter to `cache.register`, which allows you to transform arguments before using them in the cache key, without changing how you call the function or what arguments it receives.
+
+One of the design goals for funkycache is that you should be able to register a function for caching without making any changes to the function itself.
+Previously, expressing a different cache key from an argument meant creating an "inner function" that received the cache key arguments.
+For example:
+
+```python
+def read_markdown(path: Path) -> str:
+    return read_markdown_inner(path, path.stat().st_mtime, path.stat().st_size)
+
+
+@cache.register
+def read_markdown_inner(path: Path, mtime: float, size: int) -> str:
+    return path.read_text()
+```
+
+Now you can specify that transformation in `cache.register`, either with the built-in `pathstat` transform (which extends the cache key with a file's modification time and size, or a missing file marker), or with a custom function.
+
+```python
+@cache.register(key_transforms={"path": "pathstat"})
+def read_markdown(path: Path) -> str: ...
+
+
+@cache.register(key_transforms={"query": lambda q: q.strip().lower()})
+def search_docs(query: str) -> list[str]: ...
+```
+
 ## v1.1.0 - 2026-11-26
 
 To clarify that path dependencies include both files and folders, rename two parameters:

README.md (7252 → 8438)

diff --git a/README.md b/README.md
index 5553e47..253e838 100644
--- a/README.md
+++ b/README.md
@@ -39,6 +39,14 @@ funkycache is intended for deterministic functions which:
 
 If you use SQLite storage, your function must have a type hint which includes a return annotation.
 
+## Installation
+
+Install using pip:
+
+```console
+$ pip install funkycache
+```
+
 ## Examples
 
 ### Basic usage
@@ -194,6 +202,35 @@ For example, to double the cap from the default:
 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:
+
+```python
+@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.
+
+```python
+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
@@ -202,14 +239,6 @@ def count_upwards(max: int) -> Generator[int]: ...
 
 For more information about how funkycache works, read [my design notes][me-funkycache-intro].
 
-## Installation
-
-Install using pip:
-
-```console
-$ pip install funkycache
-```
-
 ## License
 
 This project is shared under the [MIT license](./LICENSE).

src/funkycache/functions.py (2105 → 2309)

diff --git a/src/funkycache/functions.py b/src/funkycache/functions.py
index 4e8f1bd..0240226 100644
--- a/src/funkycache/functions.py
+++ b/src/funkycache/functions.py
@@ -66,3 +66,11 @@ def canonical_func_name(func: Func) -> str:
     parts.append(getattr(func, "__qualname__", func.__name__))
 
     return "::".join(parts)
+
+
+def parameter_names(func: Func) -> set[str]:
+    """
+    Return the list of parameter names this function takes as input.
+    """
+    sig = inspect.signature(func)
+    return set(sig.parameters.keys())

src/funkycache/key.py (3999 → 6831)

diff --git a/src/funkycache/key.py b/src/funkycache/key.py
index 02db05d..199f188 100644
--- a/src/funkycache/key.py
+++ b/src/funkycache/key.py
@@ -6,14 +6,102 @@ A dict mapping can't be used as a hash key (in a python dict or
 an SQLite database), so we need to convert mappings to a string first.
 """
 
+from collections.abc import Callable
 import dataclasses
 import functools
 import json
-from typing import Any
+from pathlib import Path
+from typing import Any, Literal
 
 from pydantic import BaseModel, TypeAdapter
 import xxhash
 
+from .functions import Func, parameter_names
+
+
+# NAMED_KEY_TRANSFORMATIONS is a list of prebuilt key transformations
+# provided as part of the library.
+NamedKeyTransformation = Literal["pathstat"]
+
+# A KeyTransformation is a processing step applied to a key before
+# it's serialised into the cache key.
+#
+# This allows a caller to control if and how function arguments are
+# treated as equivalent. For example, they could declare that strings
+# inputs should be cached regardless of case, or that a Path should
+# be cached based on its mtime and size.
+KeyTransformationFunc = Callable[[Any], Any]
+
+KeyTransformation = KeyTransformationFunc | NamedKeyTransformation
+
+
+def pathstat(p: Path | str) -> Any:
+    """
+    When caching a file path, the modification time and size of the
+    file the path points to should be part of the cache key.
+    """
+    try:
+        return p, Path(p).stat().st_mtime, Path(p).stat().st_size
+    except FileNotFoundError:
+        return p, "<missing>", "<missing>"
+
+
+NAMED_KEY_TRANSFORMATIONS: dict[NamedKeyTransformation, KeyTransformationFunc] = {
+    "pathstat": pathstat,
+}
+
+
+class KeyTransformationException(ValueError):
+    """
+    Raised when there's an error during key transformation.
+    """
+
+
+def verify_key_transformations(
+    func: Func, transformations: dict[str, KeyTransformation]
+) -> None:
+    """
+    Verify a set of key transformations are appropriate for this function.
+    """
+    func_params = parameter_names(func)
+    for name in transformations:
+        if name not in func_params:
+            raise TypeError(
+                f"Key transformation for {name!r}, but {func.__name__} "
+                "has no argument by that name"
+            )
+        keytrans = transformations[name]
+        if isinstance(keytrans, str) and keytrans not in NAMED_KEY_TRANSFORMATIONS:
+            raise TypeError(f"Unrecognised key transformation: {keytrans!r}")
+
+
+def apply_key_transformations(
+    key: dict[str, Any], transformations: dict[str, KeyTransformation]
+) -> dict[str, Any]:
+    """
+    Apply a series of transformations to a cache key, and returns
+    the updated key. This modifies the original dict.
+
+    The caller is responsible for verifying the key transformations
+    beforehand.
+    """
+    for name, keytrans in transformations.items():
+        if isinstance(keytrans, str):
+            trans = NAMED_KEY_TRANSFORMATIONS[keytrans]  # type: ignore
+        else:
+            trans = keytrans
+
+        old_value = key[name]
+        try:
+            new_value = trans(old_value)
+        except Exception as exc:
+            raise KeyTransformationException(
+                f"error applying key transformation for {name}: {exc}"
+            ) from exc
+        key[name] = new_value
+
+    return key
+
 
 def encode_key_as_json(key: dict[str, Any]) -> str:
     """

src/funkycache/manager.py (21874 → 22913)

diff --git a/src/funkycache/manager.py b/src/funkycache/manager.py
index c8f9373..8c01b85 100644
--- a/src/funkycache/manager.py
+++ b/src/funkycache/manager.py
@@ -21,6 +21,12 @@ from warnings import deprecated
 import xxhash
 
 from .functions import Func, Params, ReturnType, canonical_func_name
+from .key import (
+    KeyTransformation,
+    apply_key_transformations,
+    verify_key_transformations,
+    KeyTransformationException,
+)
 from .storage import (
     CacheStorage,
     LazyCacheStorage,
@@ -153,6 +159,7 @@ class FunkyCache:
         *,
         paths: list[Path | str] | None = None,
         values: list[Any] | None = None,
+        key_transforms: dict[str, KeyTransformation] | None = None,
         max_memory: int | None = None,
     ) -> Callable[[Func], Func]: ...
 
@@ -163,6 +170,7 @@ class FunkyCache:
         *,
         files: list[Path | str] | None = None,
         values: list[Any] | None = None,
+        key_transforms: dict[str, KeyTransformation] | None = None,
         max_memory: int | None = None,
     ) -> Callable[[Func], Func] | Func: ...
 
@@ -173,6 +181,7 @@ class FunkyCache:
         files: list[Path | str] | None = None,
         paths: list[Path | str] | None = None,
         values: list[Any] | None = None,
+        key_transforms: dict[str, KeyTransformation] | None = None,
         max_memory: int | None = None,
     ) -> Callable[[Func], Func] | Func:
         """
@@ -217,6 +226,10 @@ class FunkyCache:
             if not is_generator and max_memory is not None:
                 raise TypeError("Do not set max_memory for a non-generator function")
 
+            # Check all the key transformations are suitable for this function.
+            if key_transforms is not None:
+                verify_key_transformations(func, key_transforms)
+
             # Check if we already have a cache for this function.
             #
             # We must do this before creating the storage, or we could have
@@ -239,6 +252,16 @@ class FunkyCache:
                 bound.apply_defaults()
                 key = bound.arguments
 
+                # Apply any key transformations. If this step fails, drop
+                # a warning and call the function directly; don't touch
+                # the cache.
+                if key_transforms:
+                    try:
+                        key = apply_key_transformations(key, key_transforms)
+                    except KeyTransformationException as e:
+                        warnings.warn(f"Error applying key transformation: {e}")
+                        return func(*args, **kwargs)
+
                 # We need to look up the CacheStorage in self._known_caches
                 # every time, in case it's changed since the last call.
                 storage = self._known_caches[func_name].storage

src/funkycache/version.py (55 → 55)

diff --git a/src/funkycache/version.py b/src/funkycache/version.py
index 7103e33..2762e7c 100644
--- a/src/funkycache/version.py
+++ b/src/funkycache/version.py
@@ -2,4 +2,4 @@
 The FunkyCache version.
 """
 
-__version__ = "1.1.0"
+__version__ = "1.2.0"

tests/test_manager.py (35600 → 38919)

diff --git a/tests/test_manager.py b/tests/test_manager.py
index fbac93e..3996f53 100644
--- a/tests/test_manager.py
+++ b/tests/test_manager.py
@@ -537,6 +537,102 @@ class FunkyCacheTestSuite(ABC):
             assert initial("apple") == "A"
             assert calls == {"apple": 2}
 
+    def test_key_transformation(self, cache: FunkyCache, tmp_path: Path) -> None:
+        """
+        The `key_transformations` parameter lets us modify a function's
+        arguments before using them in the cache key.
+        """
+        calls = Counter[Path]()
+
+        @cache.register(key_transforms={"path": lambda p: (p, p.stat().st_mtime)})
+        def read(path: Path) -> str:
+            calls[path] += 1
+            return path.read_text()
+
+        p = tmp_path / "greeting.txt"
+
+        p.write_text("hello world")
+        assert read(p) == "hello world"
+        assert calls == {p: 1}
+
+        p.write_text("bonjour monde")
+        assert read(p) == "bonjour monde"
+        assert calls == {p: 2}
+
+    def test_named_key_transformation(self, cache: FunkyCache, tmp_path: Path) -> None:
+        """
+        The `key_transformations` parameter lets us use the "pathstat"
+        named transformation.
+        """
+        calls = Counter[Path]()
+
+        @cache.register(key_transforms={"path": "pathstat"})
+        def read(path: Path) -> str:
+            calls[path] += 1
+            try:
+                return path.read_text()
+            except FileNotFoundError:
+                return "<does-not-exist>"
+
+        p = tmp_path / "greeting.txt"
+
+        assert read(p) == "<does-not-exist>"
+        assert calls == {p: 1}
+
+        p.write_text("hello world")
+        assert read(p) == "hello world"
+        assert calls == {p: 2}
+
+        p.write_text("bonjour monde")
+        assert read(p) == "bonjour monde"
+        assert calls == {p: 3}
+
+    def test_key_transformation_for_unrecognised_param(self, cache: FunkyCache) -> None:
+        """
+        Using a key transformation for a parameter that isn't in the
+        function's signature is an error.
+        """
+        with pytest.raises(TypeError, match="has no argument by that name"):
+
+            @cache.register(key_transforms={"path": "pathstat"})
+            def greet(name: str) -> str:  # pragma: no cover
+                return f"Hello {name}!"
+
+    def test_key_transformation_with_unrecognised_name(self, cache: FunkyCache) -> None:
+        """
+        Using a named key transformation for an unrecognised name is an error.
+        """
+        with pytest.raises(TypeError, match="Unrecognised key transformation"):
+
+            @cache.register(key_transforms={"name": "does_not_exist"})  # type: ignore
+            def greet(name: str) -> str:  # pragma: no cover
+                return f"Hello {name}!"
+
+    def test_exception_in_key_transformation_is_warning(
+        self, cache: FunkyCache
+    ) -> None:
+        """
+        If there's an exception in the key transformation, it's raised
+        as a warning and skips the cache.
+        """
+        calls = Counter[str]()
+
+        def explode(_: Any) -> Any:
+            raise ValueError("BOOM!")
+
+        @cache.register(key_transforms={"name": explode})
+        def greet(name: str) -> str:
+            calls[name] += 1
+            return f"Hello {name}!"
+
+        with pytest.warns(match="Error applying key transformation"):
+            assert greet("Alex") == "Hello Alex!"
+            assert calls == {"Alex": 1}
+
+        with pytest.warns(match="Error applying key transformation"):
+            assert greet("Alex") == "Hello Alex!"
+            assert calls == {"Alex": 2}
+
 
 R = TypeVar("R")