> built 2026-11-23 09:42 UTC from bd7707a (master) · larder 0.0.11. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# larder — connect functions to stores

Connect functions to stores - fetch inputs & persist outputs.

```bash
pip install larder
```

This package provides small utilities to “CRUD-ify” function inputs and outputs: let callers refer to any complex Python objects (functions, tables, etc.) by string keys stored in simple mappings (a “mall”), and to persist outputs into stores. The code is intentionally tiny and dependency-light; it contains three practical pieces you will use together or separately:

- `crude.py` — helpers to wrap functions so they read inputs from stores and
  persist outputs (decorators, factory wrappers, simple file-backed helpers).
  (Note: “crude” stands for “CRUD Execution”)
- `dog.py` — a small Data Operation Graph (DOG) plus an async variant (ADOG)
  which route operation outputs into the appropriate data store.

## Why this exists

Many UIs and service layers cannot pass rich Python objects (functions, in-memory tables, model objects) directly. Instead they pass lightweight keys that reference objects stored in a session or filesystem. `larder` gives you the plumbing to map those keys back into real Python values before calling your functions, and to persist outputs back into stores under predictable keys.

This makes it easy to:

- Drive computations from a GUI or web API using human-friendly string keys.
- Persist outputs (results, embeddings, cluster indices) alongside data.
- Swap stores (in-memory dicts, file-backed stores) without changing
  the wrapped business logic.

## Key concepts and patterns

- Decorator-as-factory: `store_on_output` and `prepare_for_crude_dispatch` can
  be used either as plain decorators or as factories that accept configuration
  and return a decorator. This lets you write `@store_on_output` or
  `@store_on_output("name", store=...)`.
- Signature reflection: wrappers use `i2.Sig` to keep function signatures
  transparent (so wrapped functions still show sensible parameter lists).
- Mall pattern: a `mall` is a mapping {store_name: store}, where `store` is a
  mapping-like object. It can be a plain dict or a file-backed store (see
  `DillFiles` in `crude.py`).
- Sync/async compatibility: wrappers work for both synchronous and
  asynchronous functions where applicable (the code checks for coroutine
  functions and dispatches accordingly).

## Short working examples (taken from the tests)

These examples are simplified extracts from the package tests so you can quickly try the patterns that are covered by tests in `larder/tests`.

1. Persisting a function’s output (sync)

```python
from larder import store_on_output

output_store = {}


@store_on_output("result", store=output_store)
def add(a, b):
    return a + b


res = add(2, 3)
assert res == 5
assert output_store["result"] == 5
```

Why useful: attach simple persistence to pure functions without changing the function body. Use cases: caching, background result pickling, lightweight audit logs.

(2) DOG example (minimal)

```python
from typing import Callable, Iterable, NewType
from larder import DOG

# DOG routes an operation's output to the store whose `type` matches the
# operation signature's RETURN type, so the store types must be distinct.
Segment = NewType("Segment", str)
Embedding = NewType("Embedding", list)
Segments = Iterable[Segment]
Embeddings = Iterable[Embedding]

data_stores = {
    "segments": {"type": Segments, "store": {"s1": ["a", "b"]}},
    "embeddings": {"type": Embeddings, "store": {}},
}
# the signature's return type (Embeddings) selects the output store
operation_signatures = {"embedder": Callable[[Segments], Embeddings]}
operation_implementations = {
    "embedder": {"simple": lambda segs: [[ord(c) for c in s] for s in segs]}
}

dog = DOG(
    operation_signatures=operation_signatures,
    data_stores=data_stores,
    operation_implementations=operation_implementations,
)
out_store, out_key = dog.call(
    operation_implementations["embedder"]["simple"], ["hello"]
)
assert out_store == "embeddings"
```

## API reference (main interfaces)

Below are the most important functions and classes you will use. The list is concise but mentions the main options; consult the code for advanced knobs.

```text
crude.store_on_output(save_name_or_func=None, *, store=None, store_multi_values=False,
											save_name_param='save_name', add_store_to_func_attr='output_store',
											empty_name_callback=None, auto_namer=None, output_trans=None)
```

- Use: decorate functions so their return value is optionally persisted.
- Important args:
  - save_name_or_func: if used as `@store_on_output('name', ...)` this is the
    fixed save name, otherwise used as plain decorator.
  - store: mapping-like object where outputs are saved (default: in-memory dict).
  - store_multi_values: when True, expects the function to return an iterable
    and stores each item individually (requires `auto_namer` and
    `save_name_param=None`).
  - save_name_param: name of the (keyword-only) parameter used to pass
    a save name at call-time (default ‘save_name’). If None, call-time naming
    is disabled.
  - auto_namer(arguments=…, output=…): a callable used to compute names.
  - output_trans(save_name=…, output=…, arguments=…): optional callable
    to post-process results (return value of wrapped function replaced by
    output_trans return).

crude.prepare_for_crude_dispatch(func=None, \*, param_to_mall_map=None, mall=None,
include_stores_attribute=False, output_store=None,
store_multi_values=False, save_name_param=’save_name’,
empty_name_callback=None, auto_namer=None, output_trans=None,
verbose=True)

- Use: wrap a function so specified parameters are fetched from mall stores
  before calling, and optionally attach `store_on_output` behavior to persist
  outputs.
- Important args:
  - param_to_mall_map: mapping of function parameter names -> mall store keys.
  - mall: the mall mapping (store_name -> store mapping object).
  - output_store: either a store object or a store-name in the mall to persist
    outputs.

crude.DillFiles(root)

- File-backed store that pickles objects. Useful for simple persistence of
  Python objects without setting up a database.

larder.wip.input_sourcing.source_variables(\*\*config)

- Use: decorate functions to resolve specific parameters from stores.
- Important args in `config` for each parameter name:
  - resolver: callable(value, store_key, mall) | async callable
  - store_key: name of the store in the mall
  - mode: ‘hybrid’ (default) or ‘store_only’ (raise error if key missing)
  - condition: callable(value) -> bool to decide whether to resolve
  - ingress: optional transformer when resolving parameterized values
- The decorator also accepts `mall` (callable or mapping) and `egress`
  (post-processing of the function result).

larder.wip.input_sourcing.resolve_data(data, store_key, mall)

- Simple helper that returns mall[store_key][data] when `data` is a key.

larder.wip.input_sourcing._get_function_from_store(key, store_key, mall)

- Async helper that returns a function stored under `store_key`; supports
  parameterized function descriptors like `{'name': {'multiplier': 2}}`.

larder.wip.input_wire.input_wiring(func, global_param_to_store, mall=None)

- Use: wrap a function so named parameters are fetched from mall stores using
  a mapping `global_param_to_store` (param -> store_name). The mall object is
  expected to expose callable attributes returning mapping-like stores.

larder.dog.DOG(operation_signatures, data_stores, operation_implementations, sourced_argnames=None)

- Use: small orchestration helper that determines where operation outputs
  should be stored based on declared return types and stores mapping.
- ADOG: async variant that wraps operations with an async compute wrapper and
  file-backed stores when needed.

## How to run the tests that back these examples

Run the package tests (they contain the full examples):

```bash
cd /path/to/proj/i/larder/larder
pytest -q
```

## Notes and next steps

- The package is intentionally small and meant as a focused toolbox rather
  than a full-blown orchestration framework. You can plug any mapping-like
  store into the mall (in-memory dicts, `DillFiles`, or custom file stores).
- If you want, I can add a tiny example script under `examples/` that shows a
  small end-to-end flow (upload -> compute -> persist) using `DillFiles`.

If you’d like the README changed in tone, length, or to include additional examples (FastAPI, background workers, or real file-backed stores), say which example and I will add it.

‘’’ pip install larder ‘’’

## Work-in-Progress

We’re working on some alternatives to crude. Less complete, but simpler. The idea is maybe to one day refactor `crude.py` to start with simpler functions that implement the most frequent use cases, and then add layers that extend it’s functionality, all the way to our current `crude.py` coverage.

- `wip/input_sourcing.py` — the `source_variables` decorator that resolves
  function arguments from a mall (useful for APIs and FastAPI endpoints).
- `wip/input_wire.py` — a small `input_wiring` helper that binds function
  parameters to values from a dependency-injector style mall.

**Resolve arguments from a mall using `source_variables`**

```python
from larder.wip.input_sourcing import source_variables, mock_mall


@source_variables(
    segments={"resolver": lambda v, sk, mall: mall[sk].get(v), "store_key": "segments"},
)
def embed_text(segments, embedder):
    return embedder(segments)


# mock_mall['segments']['greeting'] == 'hello' and mock_mall['embedders']['default'] exists
result = embed_text(segments="greeting", embedder=mock_mall["embedders"]["default"])
```

Why useful: API endpoints receive simple keys (or direct values). The decorator transparently resolves keys to Python objects before the handler runs. Use cases include FastAPI endpoints, CLI wrappers, and simple webhooks.

**Simple input wiring (dependency-injector style)**

```python
from larder.wip.input_wire import input_wiring


# stores are zero-arg callables returning their data (dependency-injector style);
# a bare `lambda: ...` class attribute would become a bound method, so use a class
class Store:
    def __init__(self, data):
        self._data = data

    def __call__(self):
        return self._data


class MockMall:
    def __init__(self):
        self.store1 = Store({"x": 10})
        self.store2 = Store({"y": 5})


def add(a, b, c):
    return a + b * c


wrapped = input_wiring(
    add, global_param_to_store={"a": "store1", "b": "store2"}, mall=MockMall()
)
res = wrapped("x", "y", 2)  # resolves 'x' -> 10, 'y' -> 5
assert res == 20
```

Why useful: small bridge to dependency-injection style stores. Helpful when tests or apps already expose stores via an object with callable attributes.

<p class="epythet-aggregates">This documentation as a single file: <a href="larder.md">larder.md</a> (Markdown, for agents).</p>


# _autosummary/larder.crude.html.md

# larder.crude

CRUDE stands for CRUD-Execution.
It is a method to solve the problem of dealing with complex python objects in an
environment that doesn’t natively support these.

The method’s trick is to allow the complex object’s that we “crudified” to be controlled
via a string key that references the complex object, via a “store” which maps
these string keys to the actual physical object.
This store could be a python dictionary (so in RAM) or any persisting storage system
(files, DB) that is given a `typing.Mapping` interface
(see [https://i2mint.github.io/dol/](https://i2mint.github.io/dol/) or [https://i2mint.github.io/py2store](https://i2mint.github.io/py2store) for
tools to do so).

Take, for instance, a GUI that allows a user to compute some descriptive statistics
of the columns of a table.
The inputs are a table, and one of the following statistics function:
`statistics.mean`, `statistics.median`, or `statistics.stdev`.

Python functions are not a type natively handled by GUI, so what can we do?
We can stick a layer between our `compute_stats(stats_func, table)` function
and our GUI, endowed with a
`{"mean": statistics.mean`, “median”: statistics.median, “std”: statistics.stdev}\`\`
mapping. We expose the string keys to the GUI, and map them to the functions before
calling `compute_stats`.

In the case of the `table`, we’d probably add a means for the GUI user to upload
tables (say from `.csv` or `.xlsx` files), storing them under a name of their
choice, then pointing to said table via the name, when they want to execute a
`compute_stats(stats_func, table)`.

These are examples of what we call “crudifying” variables or functions.

Here we therefore offer tools to do this sort of thing;
wrap functions so that the complex arguments can be specified through a string key
that points to the actual python object (which is stored in a session’s memory or
persisted in some fashion).

### Functions

| [`auto_key`](_autosummary/larder.crude.html.md#larder.crude.auto_key)(\*args, \*\*kwargs)                     | Build a string key from a call's positional and keyword arguments.              |
|---------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------|
| [`auto_key_from_arguments`](_autosummary/larder.crude.html.md#larder.crude.auto_key_from_arguments)(\*args, \*\*kwargs)      | Build a string key from a call's positional and keyword arguments.              |
| [`auto_key_from_time`](_autosummary/larder.crude.html.md#larder.crude.auto_key_from_time)(\*args[, \_\_format])         | Make a string key from the current UTC time.                                    |
| [`crudify_based_on_names`](_autosummary/larder.crude.html.md#larder.crude.crudify_based_on_names)(func, \*[, ...])          | Crudify `func` by matching its parameter names against name-keyed maps.         |
| [`keys_to_values_if_non_mapping_iterable`](_autosummary/larder.crude.html.md#larder.crude.keys_to_values_if_non_mapping_iterable)(d)        | Normalize `d` to a mapping: a non-mapping iterable becomes `{x: x}`.            |
| [`mk_mall_of_dill_stores`](_autosummary/larder.crude.html.md#larder.crude.mk_mall_of_dill_stores)([store_names, rootdir])   | Make a mall (dict of stores) of dill-backed file stores, one per name.          |
| `prepare_for_crude_dispatch`([func, ...])                                                         | Adapt a function for "crude" dispatch: source string-key arguments from a mall. |
| [`simple_mall_dispatch_core_func`](_autosummary/larder.crude.html.md#larder.crude.simple_mall_dispatch_core_func)(key, action, ...) | Dispatch a CRUD-ish read against a mall: list stores, list/get keys.            |
| `store_on_output`([save_name_or_func, store, ...])                                                | Decorate a function so its return value is (optionally) persisted to a store.   |

### Classes

| [`Crudifier`](_autosummary/larder.crude.html.md#larder.crude.Crudifier)([param_to_mall_map, mall, ...])   | A reusable, configured `prepare_for_crude_dispatch` as a dataclass.   |
|----------------------------------------------------------------------------------------------|-----------------------------------------------------------------------|
| [`DillFiles`](_autosummary/larder.crude.html.md#larder.crude.DillFiles)(\*args[, delete_func, ...])       | A `dol.Files` store that serializes values with `dill` (pickle++).    |

### *class* larder.crude.Crudifier(param_to_mall_map=None, mall=None, include_stores_attribute=False, output_store=None, store_multi_values=False, save_name_param='save_name', empty_name_callback=None, auto_namer=None, output_trans=None, verbose=True)

Bases: `_Crudifier`

A reusable, configured `prepare_for_crude_dispatch` as a dataclass.

Holds the crudification options (`param_to_mall_map`, `output_store`,
…) as fields, so one configured instance can crudify many functions:
`crudify = Crudifier(mall=mall, param_to_mall_map=...); crudify(func)`.

### *class* larder.crude.DillFiles(\*args, delete_func=None, write_open_kwargs=None, write_func=None, \*\*kwargs)

Bases: `Store`

A `dol.Files` store that serializes values with `dill` (pickle++).

#### is_valid_key(k, \*args, \_\_name='is_valid_key', \*\*kwargs)

`is_valid_key` on the inner key – see `mk_relative_path_store`.

#### validate_key(k, \*args, \_\_name='validate_key', \*\*kwargs)

`validate_key` on the inner key – see `mk_relative_path_store`.

### larder.crude.auto_key(\*args, \*\*kwargs)

Build a string key from a call’s positional and keyword arguments.

```pycon
>>> auto_key_from_arguments(1, 2, a=3)
'1,2,a=3'
>>> auto_key_from_arguments(a=1, b=2)
'a=1,b=2'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### larder.crude.auto_key_from_arguments(\*args, \*\*kwargs)

Build a string key from a call’s positional and keyword arguments.

```pycon
>>> auto_key_from_arguments(1, 2, a=3)
'1,2,a=3'
>>> auto_key_from_arguments(a=1, b=2)
'a=1,b=2'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### larder.crude.auto_key_from_time(\*args, \_\_format=1000000.0, \*\*kwargs)

Make a string key from the current UTC time.

`__format` controls the rendering: a number multiplies the UTC seconds
(default `1e6` → microseconds as a grouped integer string), a `strftime`
format string formats the time, and a callable is passed the UTC seconds.
Ignores `*args`/`**kwargs` so it can be dropped in as an auto-namer.

```pycon
>>> auto_key_from_time(__format=lambda utc_seconds: 'fixed-key')
'fixed-key'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### larder.crude.crudify_based_on_names(func, \*, param_to_mall_map=(), output_store=(), crudifier=<class 'larder.crude.Crudifier'>)

Crudify `func` by matching its parameter names against name-keyed maps.

Looks each parameter up in `param_to_mall_map` (and the output in
`output_store`) by the function object, its name, `name.arg`, or the
bare arg name — so a single name-indexed config can crudify many functions.
Returns `func` unchanged when nothing matches.

### larder.crude.keys_to_values_if_non_mapping_iterable(d)

Normalize `d` to a mapping: a non-mapping iterable becomes `{x: x}`.

A mapping (or `None`) is returned as a dict unchanged; an iterable of
items is turned into an identity mapping.

```pycon
>>> keys_to_values_if_non_mapping_iterable(['a', 'b'])
{'a': 'a', 'b': 'b'}
>>> keys_to_values_if_non_mapping_iterable(None)
{}
>>> keys_to_values_if_non_mapping_iterable({'a': 1})
{'a': 1}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### larder.crude.mk_mall_of_dill_stores(store_names=collections.abc.Iterable[str], rootdir=None)

Make a mall (dict of stores) of dill-backed file stores, one per name.

`store_names` may be an iterable of names or a space-separated string;
each store persists under `rootdir/<name>` (a temp dir by default).

### larder.crude.simple_mall_dispatch_core_func(key, action, store_name, mall)

Dispatch a CRUD-ish read against a mall: list stores, list/get keys.

With no `store_name`, returns the mall’s store names. With a store but no
`action`, returns the store. `action='list'` returns the keys
containing `key` (a substring filter); `action='get'` returns
`store[key]`.

```pycon
>>> mall = {'s1': {'apple': 1, 'apricot': 2, 'banana': 3}}
>>> sorted(simple_mall_dispatch_core_func(None, None, None, mall))
['s1']
>>> simple_mall_dispatch_core_func('ap', 'list', 's1', mall)
['apple', 'apricot']
>>> simple_mall_dispatch_core_func('banana', 'get', 's1', mall)
3
```


# _autosummary/larder.dog.html.md

# larder.dog

DOG (Data Operation Graph)

### Classes

| [`ADOG`](_autosummary/larder.dog.html.md#larder.dog.ADOG)(operation_signatures, data_stores, ...)   | Asynchronous DOG: like [`DOG`](_autosummary/larder.dog.html.md#larder.dog.DOG) but runs operations via `async_compute`.   |
|-------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------|
| [`DOG`](_autosummary/larder.dog.html.md#larder.dog.DOG)(operation_signatures, data_stores, ...)    | Synchronous DAG-of-operations executor over typed data stores.                                                         |

### *class* larder.dog.ADOG(operation_signatures, data_stores, operation_implementations, , base_path=None, ttl_seconds=3600, serialization=SerializationFormat.JSON, middleware=None, sourced_argnames=None)

Bases: `_DOG`

Asynchronous DOG: like [`DOG`](_autosummary/larder.dog.html.md#larder.dog.DOG) but runs operations via `async_compute`.

Adds caching/persistence knobs (`ttl_seconds`, `serialization`,
`middleware`) and a `base_path` for the async result stores; otherwise
the operation/store/signature model is the same as [`DOG`](_autosummary/larder.dog.html.md#larder.dog.DOG).

#### call(func_impl, \*args, \*\*kwargs)

Run `func_impl` via its cached async wrapper, persisting the output.

Returns `(store_name, output_key)`; raises `ValueError` if no store
matches the operation’s return type.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### *class* larder.dog.DOG(operation_signatures, data_stores, operation_implementations, sourced_argnames=None)

Bases: `_DOG`

Synchronous DAG-of-operations executor over typed data stores.

Given `operation_signatures` (`Callable[[In], Out]` per operation),
`data_stores` (each tagged with a `type`), and
`operation_implementations`, [`call()`](_autosummary/larder.dog.html.md#larder.dog.DOG.call) runs an implementation, sources
any string-key arguments from the stores, and persists the output to the
store whose `type` matches the operation’s return type. A runnable
example is in the README (“DOG example”).

#### call(func_impl, \*args, \*\*kwargs)

Run `func_impl`, persist its output, and return `(store_name, key)`.

Raises `ValueError` if no store matches the operation’s return type.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/larder.html.md

# larder

larder: Connect functions to stores - fetch inputs & persist outputs

### Modules

| [`crude`](_autosummary/larder.crude.html.md#module-larder.crude)   | CRUDE stands for CRUD-Execution.   |
|------------------------------------------------------------------------------|------------------------------------|
| [`dog`](_autosummary/larder.dog.html.md#module-larder.dog)       | DOG (Data Operation Graph)         |


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-11-23 09:42 UTC** from commit <a href="https://github.com/i2mint/larder/commit/bd7707a3f29876a09f4bcbfc01c292ba330a0caa"><code>bd7707a</code></a> on branch <code>master</code>, for **larder 0.0.11** (from <code>pyproject.toml</code>).

#### NOTE
Nothing suggests a mismatch: the tree was clean at the commit above, and the documented version is the one on PyPI.

## Source

|                     |                                                                                                                                                      |
|---------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/i2mint/larder/commit/bd7707a3f29876a09f4bcbfc01c292ba330a0caa"><code>bd7707a3f29876a09f4bcbfc01c292ba330a0caa</code></a> |
| Branch              | <code>master</code>                                                                                                                                  |
| Tags at this commit | none                                                                                                                                                 |
| Working tree        | clean                                                                                                                                                |
| Remote              | <code>https://github.com/i2mint/larder</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>i2mint/larder</code>                                                                 |
| Run          | <a href="https://github.com/i2mint/larder/actions/runs/45149308089">45149308089</a>        |
| Ref          | <code>refs/heads/master</code>                                                             |
| Event commit | <code>bd7707a3f29876a09f4bcbfc01c292ba330a0caa</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.25  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                   |
|---------------|-------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>sphinxawesome_theme</code>) |
| accent        | <code>#006b2b</code>                                              |
| api_generator | <code>autosummary</code>                                          |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code>  |
| agent_outputs | <code>true</code>                                                 |
| aggregates    | <code>md</code>                                                   |
| ai_artifacts  | <code>true</code>                                                 |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/larder/0.0.11/">0.0.11</a>, the same as the documented version.

## Reproduce

```bash
git clone https://github.com/i2mint/larder && cd larder
git checkout bd7707a3f29876a09f4bcbfc01c292ba330a0caa
pip install "epythet==0.2.25"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# api.html.md

# API reference

| [`larder`](_autosummary/larder.html.md#module-larder)   | larder: Connect functions to stores - fetch inputs & persist outputs   |
|-------------------------------------------------------------------------|------------------------------------------------------------------------|


