functions: extract function type hints and helpers
- ID
5f1bcb9- date
2026-11-26 20:09:30+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
2b51625- message
functions: extract function type hints and helpers This is a precursor to adding new functions for key transformations, and wanting to get inspection/reflection code out of the main flow.- changed files
4 files, 137 additions, 126 deletions
Changed files
src/funkycache/functions.py (0 → 2105)
diff --git a/src/funkycache/functions.py b/src/funkycache/functions.py
new file mode 100644
index 0000000..4e8f1bd
--- /dev/null
+++ b/src/funkycache/functions.py
@@ -0,0 +1,68 @@
+"""
+Types and helper methods for dealing with functions.
+"""
+
+import inspect
+from typing import ParamSpec, Protocol, TypeVar
+
+import xxhash
+
+
+Params = ParamSpec("Params")
+ReturnType = TypeVar("ReturnType")
+
+
+class Func[**Params, ReturnType](Protocol):
+ """
+ A function: that is, a callable that also exposes a __name__ attribute.
+
+ This is the type accepted by register(). It's deliberately narrower
+ than Callable, because the identifier for a cache is derived from
+ a function's __name__, __module__, and __qualname__.
+ """
+
+ def __call__(self, *args: Params.args, **kwargs: Params.kwargs) -> ReturnType: ... # noqa: D102
+
+ @property
+ def __name__(self) -> str: ... # noqa: D105
+
+
+def canonical_func_name(func: Func) -> str:
+ """
+ Return a canonical identifier for this function.
+
+ This should uniquely identify a function within a codebase,
+ and functions with the same name but in different files/classes
+ should get a different identifier.
+
+ This is used as the key in _known_caches and to identify SQLite caches
+ on disk.
+ """
+ parts = []
+
+ # Get the name of the module where this function is defined.
+ # For example, _canonical_name.__module__ is `funkycache.manager`.
+ #
+ # If this is unavailable, __module__ is None.
+ module = getattr(func, "__module__", "__main__")
+ parts.append(module or "<unknown>")
+
+ # If the function is in a script, __module__ is `__main__`, so
+ # include the XXH64 of the path to prevent collisions between
+ # identically-named functions in different script files.
+ #
+ # This code is tested, but coverage can't see it.
+ if module == "__main__": # pragma: no cover
+ parts.append(
+ xxhash.xxh64_hexdigest(
+ (inspect.getsourcefile(func) or "<unknown>").encode("utf8")
+ )
+ )
+
+ # Get the qualified name of the function.
+ #
+ # This is the "path" from a module's global scope to the function
+ # or method, which includes classes.
+ parts.append(getattr(func, "__qualname__", func.__name__))
+
+ return "::".join(parts)
src/funkycache/manager.py (21965 → 20322)
diff --git a/src/funkycache/manager.py b/src/funkycache/manager.py
index 979fcb0..521e820 100644
--- a/src/funkycache/manager.py
+++ b/src/funkycache/manager.py
@@ -14,20 +14,12 @@ import json
from pathlib import Path
import pickle
import typing
-from typing import (
- Any,
- cast,
- Literal,
- NamedTuple,
- overload,
- ParamSpec,
- Protocol,
- TypeVar,
-)
+from typing import Any, cast, Literal, NamedTuple, overload, TypeVar
import warnings
import xxhash
+from .functions import Func, Params, ReturnType, canonical_func_name
from .storage import (
CacheStorage,
LazyCacheStorage,
@@ -37,30 +29,14 @@ from .storage import (
)
-P = ParamSpec("P")
-R = TypeVar("R")
-
-
-class F[**P, R](Protocol):
- """
- A function: that is, a callable that also exposes a __name__ attribute.
-
- This is the type accepted by register(). It's deliberately narrower
- than Callable, because the identifier for a cache is derived from
- a function's __name__, __module__, and __qualname__.
- """
-
- def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... # noqa: D102
-
- @property
- def __name__(self) -> str: ... # noqa: D105
+StorageType = Literal["memory", "sqlite"]
-StorageType = Literal["memory", "sqlite"]
+V = TypeVar("V")
@dataclass
-class KnownCache[R]:
+class KnownCache[V]:
"""
Tracks the underlying storage for a single function.
@@ -70,7 +46,7 @@ class KnownCache[R]:
"""
storage: CacheStorage
- data_type: R
+ data_type: V
# func_name is the canonical name of the function, including
# module path and function name.
@@ -168,25 +144,25 @@ class FunkyCache:
atexit.register(self._close)
@overload
- def register[**P, R](self, func: F) -> F: ...
+ def register[**Params, ReturnType](self, func: Func) -> Func: ...
@overload
- def register[**P, R](
+ def register[**Params, ReturnType](
self,
*,
files: list[Path | str] | None = None,
values: list[Any] | None = None,
max_memory: int | None = None,
- ) -> Callable[[F], F]: ...
+ ) -> Callable[[Func], Func]: ...
- def register[**P, R](
+ def register[**Params, ReturnType](
self,
- func: F | None = None,
+ func: Func | None = None,
*,
files: list[Path | str] | None = None,
values: list[Any] | None = None,
max_memory: int | None = None,
- ) -> F:
+ ) -> Callable[[Func], Func] | Func:
"""
Cache the input/output of func.
@@ -203,7 +179,7 @@ class FunkyCache:
It's a soft cap, and may be slightly exceeded.
"""
- def decorator(func: F) -> F:
+ def decorator(func: Func) -> Func:
data_type = _data_type(func, self._storage)
dep_paths = _dep_paths(func, files=[Path(p) for p in (files or [])])
dep_values = values or []
@@ -227,7 +203,7 @@ class FunkyCache:
#
# We must do this before creating the storage, or we could have
# a dangling, unclosed storage hanging around.
- func_name = _canonical_name(func)
+ func_name = canonical_func_name(func)
if func_name in self._known_caches:
raise TypeError(f"Duplicate cache for {func_name}")
@@ -239,7 +215,7 @@ class FunkyCache:
)
@wraps(func)
- def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ def wrapper(*args: Params.args, **kwargs: Params.kwargs) -> ReturnType:
sig = inspect.signature(func)
bound = sig.bind(*args, **kwargs)
bound.apply_defaults()
@@ -252,7 +228,7 @@ class FunkyCache:
try:
cached_val = storage.get(key)
if is_generator:
- return cast(R, iter(cached_val))
+ return cast(ReturnType, iter(cached_val))
return cached_val
except KeyError:
pass
@@ -280,7 +256,8 @@ class FunkyCache:
"output will not be cached"
)
return cast(
- R, itertools.chain(iter(gen_result.list_value), new_value)
+ ReturnType,
+ itertools.chain(iter(gen_result.list_value), new_value),
)
try:
@@ -292,9 +269,9 @@ class FunkyCache:
pass
if is_generator:
- return cast(R, iter(new_value))
+ return cast(ReturnType, iter(new_value))
- return cast(R, new_value)
+ return cast(ReturnType, new_value)
return wrapper
@@ -305,15 +282,15 @@ class FunkyCache:
def _create_storage(
self,
func_name: str,
- data_type: R,
+ data_type: ReturnType,
input_sig: str,
- ) -> CacheStorage[R]:
+ ) -> CacheStorage[ReturnType]:
"""
Create a new instance of CacheStorage.
"""
match self._storage:
case "memory":
- return MemoryCacheStorage[R]()
+ return MemoryCacheStorage[ReturnType]()
case "sqlite":
# Remove path-unsafe names from the function name,
# and use this as the on-disk identifier.
@@ -329,7 +306,7 @@ class FunkyCache:
f.unlink()
return LazyCacheStorage(
- create_underlying=lambda: SQLiteCacheStorage[R](
+ create_underlying=lambda: SQLiteCacheStorage[ReturnType](
db_path, data_type=data_type
)
)
@@ -396,7 +373,7 @@ class FunkyCache:
known_cache.input_sig = new_input_sig
-def _data_type(func: F, storage: StorageType) -> Any:
+def _data_type(func: Func, storage: StorageType) -> Any:
"""
Based on a function's return annotation, look up the type of the
data we're going to cache.
@@ -458,48 +435,7 @@ def _data_type(func: F, storage: StorageType) -> Any:
return ret_annotation
-def _canonical_name(func: F) -> str:
- """
- Return a canonical identifier for this function.
-
- This should uniquely identify a function within a codebase,
- and functions with the same name but in different files/classes
- should get a different identifier.
-
- This is used as the key in _known_caches and to identify SQLite caches
- on disk.
- """
- parts = []
-
- # Get the name of the module where this function is defined.
- # For example, _canonical_name.__module__ is `funkycache.manager`.
- #
- # If this is unavailable, __module__ is None.
- module = getattr(func, "__module__", "__main__")
- parts.append(module or "<unknown>")
-
- # If the function is in a script, __module__ is `__main__`, so
- # include the XXH64 of the path to prevent collisions between
- # identically-named functions in different script files.
- #
- # This code is tested, but coverage can't see it.
- if module == "__main__": # pragma: no cover
- parts.append(
- xxhash.xxh64_hexdigest(
- (inspect.getsourcefile(func) or "<unknown>").encode("utf8")
- )
- )
-
- # Get the qualified name of the function.
- #
- # This is the "path" from a module's global scope to the function
- # or method, which includes classes.
- parts.append(getattr(func, "__qualname__", func.__name__))
-
- return "::".join(parts)
-
-
-def _dep_paths(func: F, files: list[Path]) -> set[Path]:
+def _dep_paths(func: Func, files: list[Path]) -> set[Path]:
"""
Get a list of all the absolute paths this function depends on.
"""
tests/test_functions.py (0 → 1079)
diff --git a/tests/test_functions.py b/tests/test_functions.py
new file mode 100644
index 0000000..1caa926
--- /dev/null
+++ b/tests/test_functions.py
@@ -0,0 +1,43 @@
+"""
+Tests for `funkycache.functions`.
+"""
+
+from pathlib import Path
+import subprocess
+import textwrap
+
+
+def test_canonical_name_varies_by_path(tmp_path: Path) -> None:
+ """
+ The canonical name of functions in the top-level of a script
+ varies by path.
+
+ For these functions, func.__module__ is __main__, so we need a way
+ to distinguish them to avoid cache collisions.
+ """
+ (tmp_path / "s1.py").write_text(
+ textwrap.dedent("""
+ from funkycache.functions import canonical_func_name
+
+ def greet(name: str) -> str:
+ return f"Hello {name}!"
+
+ print(canonical_func_name(greet))
+ """)
+ )
+
+ (tmp_path / "s2.py").write_text(
+ textwrap.dedent("""
+ from funkycache.functions import canonical_func_name
+
+ def greet(name: str) -> str:
+ return f"Hello {name}!"
+
+ print(canonical_func_name(greet))
+ """)
+ )
+
+ name1 = subprocess.check_output(["python3", (tmp_path / "s1.py")])
+ name2 = subprocess.check_output(["python3", (tmp_path / "s2.py")])
+
+ assert name1 != name2
tests/test_manager.py (33369 → 32412)
diff --git a/tests/test_manager.py b/tests/test_manager.py
index 5cbc0b4..1f7c438 100644
--- a/tests/test_manager.py
+++ b/tests/test_manager.py
@@ -981,39 +981,3 @@ class TestSQLiteFunkyCache(FunkyCacheTestSuite):
# Creating a cache entry creates the db
assert greet("Alex") == "Hello Alex!"
assert cache_root.exists()
-
-
-def test_canonical_name_varies_by_path(tmp_path: Path) -> None:
- """
- The canonical name of functions in the top-level of a script
- varies by path.
-
- For these functions, func.__module__ is __main__, so we need a way
- to distinguish them to avoid cache collisions.
- """
- (tmp_path / "s1.py").write_text(
- textwrap.dedent("""
- from funkycache.manager import _canonical_name
-
- def greet(name: str) -> str:
- return f"Hello {name}!"
-
- print(_canonical_name(greet))
- """)
- )
-
- (tmp_path / "s2.py").write_text(
- textwrap.dedent("""
- from funkycache.manager import _canonical_name
-
- def greet(name: str) -> str:
- return f"Hello {name}!"
-
- print(_canonical_name(greet))
- """)
- )
-
- name1 = subprocess.check_output(["python3", (tmp_path / "s1.py")])
- name2 = subprocess.check_output(["python3", (tmp_path / "s2.py")])
-
- assert name1 != name2