Skip to main content

README: expand with proper documentation and examples

ID
2b51625
date
2026-11-26 19:59:18+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
1cc4ab1
message
README: expand with proper documentation and examples
changed files
1 file, 169 additions, 16 deletions

Changed files

README.md (2072 → 7252)

diff --git a/README.md b/README.md
index 8d3e6ef..ff96b5e 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
 # funkycache
 
-funkycache is a disk-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.
@@ -12,34 +12,187 @@ from funkycache import FunkyCache
 cache = FunkyCache(storage="sqlite")
 
 
-@cache.register(files=["content/index.md", "templates/base.html"])
-def render_index() -> str:
-    page = Path("content/index.md").read_text()
-    template = Path("templates/base.html").read_text()
-    return template.replace("{{ content }}", page)
+@cache.register(files=["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("content/index.md")
+cache.notify_path_change("templates/base.html")
 
 print(render_index())  # runs the function again
 ```
 
 When you register a function with funkycache, you can declare path or static values the function depends on.
-If those dependent values change, the function's cache is invalidated, and the next call will rerun the function fresh.
+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.
 
-**Note:** funkycache does not watch the filesystem.
-It is your responsibility to notify it of changes to dependent files, or they will be noticed when the Python process restarts.
+## Requirements
 
-## Caching requirements
+funkycache is intended for deterministic functions which:
 
-To cache a function with funkycache, the function must:
+*   Always return an identical output when given the same arguments, and
+*   Do not have side effects
 
-*   Have a type hint with a return annotation
-*   Always return an identical result when given identical inputs
-*   Not have any side effects (for example, creating a file)
+If you use SQLite storage, your function must have a type hint which includes a return annotation.
+
+## Examples
+
+### Basic usage
+
+To cache the output of a function, create a `FunkyCache` instance, then use the `register` decorator on your function:
+
+```python
+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:
+
+```python
+cache = FunkyCache(storage="memory")
+```
+
+To use SQLite storage:
+
+```python
+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`:
+
+```python
+cache = FunkyCache(storage="sqlite", root=".cache")
+```
+
+The `root` parameter can be a str or a [Path][pydoc-pathlib].
+
+### 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 `files` parameter to `cache.register`.
+
+For example, if your function depends on a template file, you can declare a dependency on the template:
+
+```python
+@cache.register(files=["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:
+
+```python
+cache.notify_path_change(changed_files=["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:
+
+```python
+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:
+
+```python
+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:
+
+```python
+@cache.register(max_memory=10 * 1024 * 1024)
+def count_upwards(max: int) -> Generator[int]: ...
+```
 
 ## Design
 
@@ -62,4 +215,4 @@ $ pip install funkycache
 This project is shared under the [MIT license](./LICENSE).
 
 [me-funkycache-intro]: https://alexwlchan.net/2026/funkycache/
-[wiki-pure]: https://en.wikipedia.org/wiki/Pure_function
+[pydoc-pathlib]: https://docs.python.org/3/library/pathlib.html