> built 2026-09-15 11:46 UTC from 4ad3b6f (master) · front 0.1.101. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# front

Compile a Python function’s configuration into a runnable UI (web app, CLI, GUI…) without writing framework glue by hand.

To install: `pip install front`

## Quick example

`front` itself is not a UI framework: it’s the core library concrete `front` frameworks (e.g. [streamlitfront](https://github.com/i2mint/streamlitfront/)) build on. A minimal in-memory framework, whose “app” is a container rendering each function’s docstring:

```python
from collections.abc import Callable
from front import SpecMakerBase, APP_KEY, OBJ_KEY, RENDERING_KEY, ELEMENT_KEY, AppMaker
from front.elements import FrontContainerBase, FrontComponentBase
from front.util import dflt_trans


class App(FrontContainerBase):
    def render(self):
        return {child.name: child() for child in self.children}


class Doc(FrontComponentBase):
    def render(self):
        return self.obj.__doc__


class SpecMaker(SpecMakerBase):
    @property
    def _dflt_convention(self):
        return {
            APP_KEY: {'title': 'Untitled'},
            OBJ_KEY: {'trans': dflt_trans},
            RENDERING_KEY: {ELEMENT_KEY: App, Callable: {ELEMENT_KEY: Doc}},
        }


def foo(a, b):
    "Adds a and b."
    return a + b


app_maker = AppMaker(spec_maker_factory=SpecMaker)
app = app_maker.mk_app([foo], config={APP_KEY: {'title': 'My App'}})
app.name
# 'My App'
app()
# {'foo': 'Adds a and b.'}
```

## The three-step workflow

1. `SpecMakerBase.mk_spec` compiles a short-language configuration (plus a convention of defaults) into a long-language `FrontSpec` (`app_spec`, `obj_spec`, `rendering_spec`).
2. `ElementTreeMaker.mk_tree` builds a composite tree of `FrontElementBase` elements from the rendering spec: a root container (e.g. `FrontContainerBase`) with one child per object, built from `FrontComponentBase`/`InputBase`/`OutputBase` subclasses.
3. `AppMaker.mk_app` chains the two and returns the root element, callable as the app.

To implement a concrete `front` framework, subclass `SpecMakerBase` to supply the concrete element classes as the default convention, and hand it to `AppMaker` (see the example above, and [streamlitfront](https://github.com/i2mint/streamlitfront/) for a real one).

## Crudifying functions

`Crudifier`/`prepare_for_crude_dispatch` (in `front.crude`) let functions with complex arguments (objects that don’t fit in a text box or URL) be dispatched through string keys into stores instead — the “CRUD-Execution” pattern. `front.dag` applies the same crudification to the variable nodes of a `meshed` DAG.

## Docs

[Rendered documentation](https://i2mint.github.io/front/) · [flat `front.md`](https://i2mint.github.io/front/front.md) for a single-file view.

<!-- epythet:agentic-readme:start -->

## For AI agents

`front` publishes its documentation in forms made for coding agents. If you are one, start here.

**The documentation, machine-readable**: [`llms.txt`](https://i2mint.github.io/front/llms.txt) indexes every page; [`front.md`](https://i2mint.github.io/front/front.md) is the whole documentation in one file; every page has a `.md` twin; [`objects.inv`](https://i2mint.github.io/front/objects.inv) maps symbols to URLs.

If you are a control freak, the rest of this README is written for you, starting at the top of the page.

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


# _autosummary/front.app_maker.html.md

# front.app_maker

The `AppMaker` orchestrator that turns a configuration into a front app.

Consumes a short-language configuration plus a convention, compiles it into a
nested [`FrontSpec`](_autosummary/front.types.html.md#front.types.FrontSpec) (the long language) via a spec maker,
builds the composite tree of front elements, and assembles the runnable app.

### Classes

| [`AppMaker`](_autosummary/front.app_maker.html.md#front.app_maker.AppMaker)(spec_maker_factory[, ...])   | Orchestrator that turns objects plus a configuration into a runnable front app.   |
|----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------|

### *class* front.app_maker.AppMaker(spec_maker_factory, element_tree_maker_factory=<class 'front.elements.tree_maker_base.ElementTreeMaker'>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Orchestrator that turns objects plus a configuration into a runnable front app.

Main class of front, doing the following:

1. Consume the configuration (short language) to produce a specification object
   (long language) using the provided spec maker. The specification is a nested
   structure which contains 3 sub-specification objects: “obj”, “rendering” and “app”.
2. Transform the input objects using the “trans” function from the “obj”
   specification (uses front.util.dflt_trans by default).
3. Build a composite tree of Front elements based on the “rendering” specification.
4. Build an app from the composite tree and “app” specification.

A concrete front framework subclasses `SpecMakerBase` (to supply its default
convention, including the concrete element classes) and hands that class to
`AppMaker`. Below, a minimal in-memory framework whose “app” is a container
that renders each function’s docstring:

```pycon
>>> from collections.abc import Callable
>>> from front import SpecMakerBase, APP_KEY, OBJ_KEY, RENDERING_KEY, ELEMENT_KEY
>>> from front.elements import FrontContainerBase, FrontComponentBase
>>> from front.util import dflt_trans
>>>
>>> class App(FrontContainerBase):
...     def render(self):
...         return {child.name: child() for child in self.children}
>>> class Doc(FrontComponentBase):
...     def render(self):
...         return self.obj.__doc__
>>> class SpecMaker(SpecMakerBase):
...     @property
...     def _dflt_convention(self):
...         return {
...             APP_KEY: {'title': 'Untitled'},
...             OBJ_KEY: {'trans': dflt_trans},
...             RENDERING_KEY: {ELEMENT_KEY: App, Callable: {ELEMENT_KEY: Doc}},
...         }
>>> def foo(a, b):
...     "Adds a and b."
...     return a + b
>>> app_maker = AppMaker(spec_maker_factory=SpecMaker)
>>> app = app_maker.mk_app([foo], config={APP_KEY: {'title': 'My App'}})
>>> app.name
'My App'
>>> app()
{'foo': 'Adds a and b.'}
```

Anything the config doesn’t say comes from the convention:

```pycon
>>> app_maker.mk_app([foo]).name
'Untitled'
```

#### SEE ALSO
`front.spec_maker_base.SpecMakerBase`: compiles config + convention into the spec.
`front.elements.ElementTreeMaker`: builds the element tree from the rendering spec.

#### mk_app(objs, config=None, convention=None)

Make a front application exposing `objs`: the entry point of `AppMaker`.

* **Parameters:**
  * **objs** ([`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – The objects that the user of the resulting
    application will be interacting with. Only callables are supported for now.
  * **config** (`Union`[[`None`](https://docs.python.org/3/builtins/constants.html#None), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[], [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)]]) – The configuration of the resulting application.
  * **convention** (`Union`[[`None`](https://docs.python.org/3/builtins/constants.html#None), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[], [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)]]) – The convention used to complete the configuration by
    providing default values for everything that is not specified in the
    configuration. Defaults to the spec maker’s `_dflt_convention`.
* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)
* **Returns:**
  The root element of the app tree, named after the app’s title.
* **Raises:**
  [**NotImplementedError**](https://docs.python.org/3/builtins/exceptions.html#NotImplementedError) – If an object in `objs` is not callable.


# _autosummary/front.base.html.md

# front.base

Base functions for front dispatching: `prepare_for_dispatch` chains the wrappers a UI needs.

### Functions

| `prepare_for_dispatch`([func, ...])   | Prepare `func` for dispatch: crudify, annotate cruded params with Enums, fix defaults.   |
|---------------------------------------|------------------------------------------------------------------------------------------|


# _autosummary/front.crude.html.md

# front.crude

Crudify functions: let complex arguments be specified by string keys into stores.

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/front.crude.html.md#front.crude.auto_key)(\*args, \*\*kwargs)                     | Make a str key from arguments.                                                                        |
|---------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------|
| [`auto_key_from_arguments`](_autosummary/front.crude.html.md#front.crude.auto_key_from_arguments)(\*args, \*\*kwargs)      | Make a str key from arguments.                                                                        |
| [`auto_key_from_time`](_autosummary/front.crude.html.md#front.crude.auto_key_from_time)(\*args[, \_\_format])         | Make a str key with current timestamp (ignoring arguments).                                           |
| [`crudify_based_on_names`](_autosummary/front.crude.html.md#front.crude.crudify_based_on_names)(func, \*[, ...])          | Crudify `func` from general, name-keyed `param_to_mall_map` and `output_store` specs.                 |
| [`keys_to_values_if_non_mapping_iterable`](_autosummary/front.crude.html.md#front.crude.keys_to_values_if_non_mapping_iterable)(d)        | Turn a non-mapping iterable into an identity dict; pass mappings through; None gives `{}`.            |
| [`mk_mall_of_dill_stores`](_autosummary/front.crude.html.md#front.crude.mk_mall_of_dill_stores)([store_names, rootdir])   | Make a mall of `DillFiles` stores, one sub-directory of `rootdir` per store name.                     |
| `prepare_for_crude_dispatch`([func, ...])                                                         | Wrap `func` into something that is ready for CRUDE dispatch.                                          |
| [`simple_mall_dispatch_core_func`](_autosummary/front.crude.html.md#front.crude.simple_mall_dispatch_core_func)(key, action, ...) | Explore a mall from a UI: list its stores, list a store's keys, or get a value.                       |
| `store_on_output`([func, store, ...])                                                             | Wrap `func` with an extra `save_name_param` argument that saves the output under that key in a store. |

### Classes

| [`Crudifier`](_autosummary/front.crude.html.md#front.crude.Crudifier)([param_to_mall_map, mall, ...])   | Convenience class to make crudify (i.e. map/source inputs of) functions.                 |
|----------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|
| [`DillFiles`](_autosummary/front.crude.html.md#front.crude.DillFiles)(\*args[, delete_func])            | Local files store that serializes values with dill (or pickle if dill is not installed). |

### *class* front.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`

Convenience class to make crudify (i.e. map/source inputs of) functions.

See [https://github.com/i2mint/front/issues/21](https://github.com/i2mint/front/issues/21).

`prepare_for_crude_dispatch` works well if you want to crudify a single function,
but if you’re trying to crudify multiple functions according to a specific fixed
convention, using it directly would involve too much boilerplate.

`Crudifier` is one the tools we offer to reduce this boilerplate.

Here are a few examples of how to use it.

```pycon
>>> def foo(x, y):
...     return x + y
...
>>> def bar(a, x):
...     return a * x
```

Let’s say we want `x` to be sourced by the `x_store` mapping listed in the
`mall`. We can make a `crudify` function like this:

```pycon
>>> crudify = Crudifier(
...     param_to_mall_map={'x': 'x_store'}, mall={'x_store': {'stored_two': 2, 'stored_four': 4}}
... )
```

And apply it to any function containing a argumennt named `x`:

```pycon
>>> from inspect import signature
>>> crudified_foo = crudify(foo)
>>> str(signature(crudified_foo))  # note how x has now a Literal annotation showing what the valid str inputs are
"(x: Literal['stored_two', 'stored_four'], y)"
>>> crudified_foo('stored_two', 3)  # -> 2 + 3
5
>>> crudified_bar = crudify(bar)
>>> str(signature(crudified_bar))
"(a, x: Literal['stored_two', 'stored_four'])"
>>> crudified_bar(3, 'stored_two')  # -> 3 * 2
6
```

If the argument names correspond to `mall` key, the first `param_to_mall_map`
argument can be specified a list of arguments, or even a space-separated string of
these argument names. In the following, the `'x y'` is equivalent to
`['x', 'y']`, which is equivalent to `{'x': 'x', 'y', 'y'}`.

```pycon
>>> crudify = Crudifier('x y', mall={'x': {'stored_two': 2, 'stored_four': 4}, 'y': {'three': 3}})
>>> f = crudify(foo)
>>> str(signature(f))  # note that both x and y have a str annotation now
"(x: Literal['stored_two', 'stored_four'], y: Literal['three'])"
>>> f('stored_two', 'three')
5
```

This allows you to do things like partialize, to fix the mall, and only have to
specify the param_to_mall_map when you want to crudify.
In the following, note the `verbose=False` which tells the crudification not to
issue any warning when it sees we have keys in our `mall` that are not arguments
of the function.

```pycon
>>> from functools import partial
>>>
>>> mall = {
...     'x': {'stored_two': 2}, 'y': {'three': 3}, 'fall_back_store': {'zebra': 11}
... }
>>> Crudify = partial(Crudifier, mall=mall, verbose=False)
>>> f = Crudify('x')(foo)
>>> f('stored_two', 3)
5
>>> f = Crudify('x y')(foo)
>>> f('stored_two', 'three')
5
>>> b = Crudify({'a': 'fall_back_store'})(bar)
>>> b('zebra', 3)
33
```

This callable object, or something like it, can then be used in a recursive
transformer such a the front rendering process to indicate that a function should
be crudified, and how.

For example, say we had a mini-language where this

```pycon
>>> config = {
...     foo: {
...         'preprocesses': Crudify('x y'),
...         'whatevs': 42
...     },
...     bar: {
...         'blahblah': 24
...     }
... }
```

should be preprocessed in such a way that adds a `'func'` key to each item of
`config` which contains a transformed function if a `preprocesses` function
or list of functions is specified, or the original function itself otherwise.
The following would implement this:

```pycon
>>> from typing import Iterable
>>> from i2 import Pipe
>>>
>>> def _ensure_iterable(v):
...     if not isinstance(v, Iterable):
...         v = [v]
...     return v
...
>>> def prepare(config):
...     for func, specs in config.items():
...         if (processes := specs.get('preprocesses', None)) is not None:
...             preprocess = Pipe(*_ensure_iterable(processes))
...             _func = preprocess(func)
...         else:
...             _func = func
...         specs = dict(specs, func=_func)
...         yield func, specs
```

```pycon
>>> prepared_configs = dict(prepare(config))
```

Now get the `func` value under `foo`, and see that it has been crudified:

```pycon
>>> processed_foo = prepared_configs[foo]['func']
>>> processed_foo('stored_two', 'three')
5
```

### *class* front.crude.DillFiles(\*args, delete_func=None, \*\*kwargs)

Bases: `Store`

Local files store that serializes values with dill (or pickle if dill is not installed).

#### 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`.

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

Make a str key from arguments.

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

```pycon
>>> auto_key_from_arguments(1,2,c=3,d=4)
'1,2,c=3,d=4'
>>> auto_key_from_arguments(1,2)
'1,2'
>>> auto_key_from_arguments(c=3,d=4)
'c=3,d=4'
>>> auto_key_from_arguments()
''
```

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

Make a str key from arguments.

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

```pycon
>>> auto_key_from_arguments(1,2,c=3,d=4)
'1,2,c=3,d=4'
>>> auto_key_from_arguments(1,2)
'1,2'
>>> auto_key_from_arguments(c=3,d=4)
'c=3,d=4'
>>> auto_key_from_arguments()
''
```

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

Make a str key with current timestamp (ignoring arguments).

* **Parameters:**
  **\_\_format** ([`Number`](https://docs.python.org/3/library/numbers.html#numbers.Number) | [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)) – When a number, will be used as a multiplier of current utc time
* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

```pycon
>>> auto_key_from_time()
'1_669_724_787_630_906'
```

But `auto_key_from_time` is really meant to be used with `functools.partial` to
parametrize its `__format`, such as:

```pycon
>>> from functools import partial
>>>
>>> time_in_ms = partial(auto_key_from_time, __format=1e3)
>>> normal_format = partial(auto_key_from_time, __format='%Y-%m-%d %H:%M:%S')
>>> modulo_1000 = partial(auto_key_from_time, __format=lambda x: int(x % 1000))
>>>
>>> time_in_ms()
'1_669_724_787_641'
>>> normal_format()
'2022-11-29 12:26:27'
>>> modulo_1000()
'788'
```

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

Crudify `func` from general, name-keyed `param_to_mall_map` and `output_store` specs.

Meant to apply one crudification convention to many functions: the specs are
looked up per argument by `(func, arg_name)`, `(func_name, arg_name)`,
`"func_name.arg_name"` then `arg_name` (first match wins), and the output
store by `func` then `func_name`.

* **Parameters:**
  * **func** – The function to crudify.
  * **param_to_mall_map** – Mapping from those argument keys to mall keys.
  * **output_store** – Mapping from `func` or its name to an output store.
  * **crudifier** – The callable doing the crudification, given
    `(func, param_to_mall_map=..., output_store=...)`.
* **Returns:**
  The crudified function, or `func` itself if no spec matched.

```pycon
>>> from functools import partial
>>> def foo(x, y):
...     return x + y
>>> def bar(a, x):
...     return a * x
>>> general_crudifier = partial(
...     crudify_based_on_names,
...     param_to_mall_map={'x': 'x_store'},
...     crudifier=partial(prepare_for_crude_dispatch, mall={'x_store': {'stored_two': 2, 'stored_four': 4}})
... )
>>>
>>> foo, bar = map(general_crudifier, [foo, bar])
>>>
>>> foo('stored_two', 10)
12
>>> bar(4, 'stored_four')
16
```

### front.crude.keys_to_values_if_non_mapping_iterable(d)

Turn a non-mapping iterable into an identity dict; pass mappings through; None gives `{}`.

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

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

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

Make a mall of `DillFiles` stores, one sub-directory of `rootdir` per store name.

`store_names` can be a space-separated string. `rootdir` defaults to a
stable `"crude"` subdirectory of the system temp directory (the same path
on every call, not a fresh one).

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

Explore a mall from a UI: list its stores, list a store’s keys, or get a value.

This function is only meant to be a helper to give a UI (GUI,
CLI…) mall-exploration capabilities. Namely:

- `list(mall)`: list the keys of a mall. This is achieved with args:
  `(key=None, action=None, store_name=None, mall=mall)`
- `mall[store_name]`: get a store. Achieved by:
  `(key=None, action=None, store_name=store_name, mall=mall)`
- `list(mall[store_name])`: list keys of a store (of the mall). Achieved by:
  `(key=None, action='list', store_name=store_name, mall=mall)`
- `list(filter(key, mall[store_name]))`: list keys of a store (of the mall)
  according to a substring filter. (only keys that have `key` as substring)
  `(key=key, action='list', store_name=store_name, mall=mall)`
- `mall[store_name][key]`:  get the value/data of a store for `key`
  `(key=key, action='get', store_name=store_name, mall=mall)`

* **Parameters:**
  * **key** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The key
  * **action** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – ‘list’ (to list keys of a store) or ‘get’ (to get the value of
    `key` in the store (named `store_name`)
  * **store_name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Store name to look up in mall. If not given, the function will
    output the mall keys (which are valid store names)
  * **mall** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]) – dict of stores (Mapping interface to data)
* **Returns:**

```pycon
>>> mall = {
...     'english': {'one': 1, 'two': 2, 'three': 3},
...     'french': {'un': 1, 'deux': 2},
... }
```

List the keys of a mall:

```pycon
>>> simple_mall_dispatch_core_func(None, None, None, mall=mall)
['english', 'french']
```

Get a store

```pycon
>>> simple_mall_dispatch_core_func(None, None, store_name='english', mall=mall)
{'one': 1, 'two': 2, 'three': 3}
```

List keys of a store (of the mall):

```pycon
>>> simple_mall_dispatch_core_func(
...     None, action='list', store_name='english', mall=mall
... )
['one', 'two', 'three']
```

List keys of a store (of the mall) according to a substring filter:

```pycon
>>> simple_mall_dispatch_core_func(
...     'e', action='list', store_name='english', mall=mall
... )
['one', 'three']
```

```pycon
>>> simple_mall_dispatch_core_func(
...     'two', action='get', store_name='english', mall=mall
... )
2
```


# _autosummary/front.dag.html.md

# front.dag

Crudify the variable nodes of a `meshed` DAG.

Crudifying a var node of a DAG means: the function producing it stores its
output in a store and returns the key, and the functions consuming it take that
key and fetch the value from the same store. The stores live in a mall (a
mapping of store names to stores).

Main entry points:

- `crudify_func_nodes`: a copy of the DAG whose func nodes are crudified.
- `crudify_funcs`: just the (crudified) functions of those func nodes.

See below one of the dags that will often be used in this module’s doctests:

```pycon
>>> from meshed.makers import code_to_dag
>>> @code_to_dag
... def dag():
...     x = foo(a, b)
...     y = bar(x, greeting)
...     z = confuser(a, w=x)  # note the w=x to test non-trivial binding
>>> print(dag.dot_digraph_ascii())
```

```text
   ┌──────────┐
┌▶ │ confuser │ ◀──    a
│  └──────────┘
│    │                │
│    │                │
│    ▼                ▼
│                   ┌─────┐
│       z           │ foo │ ◀──  b
│                   └─────┘
│                     │
│                     │
│                     ▼
│
└──────────────────    x

                      │
                      │
                      ▼
                    ┌─────┐
     greeting   ──▶ │ bar │
                    └─────┘
                      │
                      │
                      ▼

                       y
```

### Functions

| [`crudify_func_nodes`](_autosummary/front.dag.html.md#front.dag.crudify_func_nodes)(var_nodes, dag[, ...])   | Crudifies the given `var_nodes` in the `dag`.                                             |
|----------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|
| [`crudify_funcs`](_autosummary/front.dag.html.md#front.dag.crudify_funcs)(var_nodes, dag[, ...])        | Like `crudify_func_nodes`, but return the list of (crudified) functions, not a DAG.       |
| [`fnodes_to_var_node_crude_specs`](_autosummary/front.dag.html.md#front.dag.fnodes_to_var_node_crude_specs)(fnodes)      | Yield `(var, func, bind)` triples of the given func nodes.                                |
| [`group_kvs_into_dict`](_autosummary/front.dag.html.md#front.dag.group_kvs_into_dict)(kvs)                    | Group `(key, value)` pairs into a `{key: [values]}` dict, keeping order.                  |
| [`simple_namer`](_autosummary/front.dag.html.md#front.dag.simple_namer)(name, \*[, prefix, suffix])    | Wrap `name` with a `prefix` and `suffix`; the default store namer uses `suffix='_store'`. |

### Classes

| [`VarNodeRole`](_autosummary/front.dag.html.md#front.dag.VarNodeRole)(\*values)   | (Var)Node roles.   |
|--------------------------------------------------------------------------|--------------------|

### *class* front.dag.VarNodeRole(\*values)

Bases: [`Enum`](https://docs.python.org/3/library/enum.html#enum.Enum)

(Var)Node roles.

When a `VarNode` is used to source the arguments of a `FuncNode`, it’s playing
a `VarNodeRole.argument` role.

When a `VarNode` is used to store the return value of a `FuncNode`, it’s playing
a `VarNodeRole.return_value` role.

Most `VarNode``s play both roles during a ``DAG` computation.

### front.dag.crudify_func_nodes(var_nodes, dag, var_node_name_to_store_name=functools.partial(<function simple_namer>, suffix='_store'), \*, mall=None, include_stores_attribute=False, save_name_param='save_name')

Crudifies the given `var_nodes` in the `dag`.

Crudifying a var node means crudifying it’s `FuncNode` neighbors,
i.e. telling the function that outputs to the `VarNode` (if any) to save it’s
output in a store and (additionally) return the key it saved it too instead of the
value itself, and telling any consumers of the var node to use that key as it’s
argument instead, retrieving the value from said store.

```pycon
>>> from meshed import DAG, FuncNode
>>> from inspect import signature
>>> def foo(a, b):  return a + b
>>> def bar(x, y):  return  x * y
>>> dag = DAG([
...     FuncNode(foo, name='foo', out='foo_output'),
...     FuncNode(bar, bind={'y': 'foo_output'})
... ])
```

Let’s crudify `'foo_output'`. We don’t need to specify a mall, since
`crudify_func_nodes` will make one for us.
But in order to get access to it, to see what the function is doing, let’s define
a mall with a single store (a dictionary), named `'foo_output_store'`
(note that the map between `var_node` string name and
store name is controlled by the `var_node_name_to_store_name` argument)

```pycon
>>> store = dict()
>>> mall = {'foo_output_store': store}
>>> new_dag = crudify_func_nodes(['foo_output'], dag, mall=mall)
```

The `new_dag` will have the same global behavior:

```pycon
>>> assert dag(2, 3, 4) == new_dag(2, 3, 4) == 20
```

Notice though, that the `foo` node will have an extra argument, `save_name`,
which is the name of the store to save the output to:

```pycon
>>> print(new_dag.synopsis_string())
a,b,save_name -> foo -> foo_output
foo_output,x -> bar_ -> bar
```

This difference will be reflected in the signature of the `new_dag`:

```pycon
>>> print(str(signature(dag)))
(a, b, x)
>>> print(str(signature(new_dag)))
(a, b, x, save_name: str = '')
```

Let’s have a closer look at the functions that `dag` and `new_dag` are
using. The functions of the `dag` are the original functions we specified,
behaving normally:

```pycon
>>> dag.func_nodes[0].func(2, 3)
5
>>> dag.func_nodes[1].func(4, 5)
20
```

But the first function of `new_dag` outputs `'bar_last_output'` instead of `5`.

```pycon
>>> new_dag.func_nodes[0].func(2, 3)
'bar_last_output'
```

Where did the `5` go? In the mall!

```pycon
>>> mall
{'foo_output_store': {'bar_last_output': 5}}
```

So that `5` has been stored under the `'bar_last_output'` key.
Further, the second function’s second argument will no longer work with numbers,
but with string keys, and use that same store to retrieve the value it needs for
the underlying function:

```pycon
>>> new_dag.func_nodes[1].func(4, 'bar_last_output')
20
```

This `'bar_last_output'` was only the default value that is used if
`save_name` is not given. If we give it a different name, the value will be
stored under that name instead:

```pycon
>>> new_dag.func_nodes[0].func(20, 22, save_name='my_save_name')
'my_save_name'
>>> mall
{'foo_output_store': {'bar_last_output': 5, 'my_save_name': 42}}
```

* **Parameters:**
  * **var_nodes** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – The `VarNodes` we want to crudify
  * **dag** (`DAG`) – The dag that contains these var_nodes
  * **var_node_name_to_store_name** – The function to use to make a store for a given
    var_node name. If you have an explicit mapping `m` for this, just use `m.get`
  * **mall** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]] | [`None`](https://docs.python.org/3/builtins/constants.html#None)) – A `mall` (store of stores, i.e. mapping of mappings) whose keys are
    store names, and values are the actual stores.
  * **include_stores_attribute** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Whether the crudified functions should have an
    attribute containing a pointer to the stores involved
  * **save_name_param** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – The name that the “save as” parameter should appear as.
* **Returns:**

### front.dag.crudify_funcs(var_nodes, dag, var_node_name_to_store_name=functools.partial(<function simple_namer>, suffix='_store'), \*, mall=None, include_stores_attribute=False, save_name_param='save_name')

Like `crudify_func_nodes`, but return the list of (crudified) functions, not a DAG.

See `crudify_func_nodes` for the meaning of the arguments.

### front.dag.fnodes_to_var_node_crude_specs(fnodes)

Yield `(var, func, bind)` triples of the given func nodes.

### front.dag.group_kvs_into_dict(kvs)

Group `(key, value)` pairs into a `{key: [values]}` dict, keeping order.

```pycon
>>> group_kvs_into_dict([('a', 1), ('b', 2), ('a', 3)])
{'a': [1, 3], 'b': [2]}
```

### front.dag.simple_namer(name, , prefix='', suffix='')

Wrap `name` with a `prefix` and `suffix`; the default store namer uses `suffix='_store'`.

```pycon
>>> simple_namer('x', suffix='_store')
'x_store'
```


# _autosummary/front.data_binding.html.md

# front.data_binding

Data-binding primitives that connect front element values to a backing state store.

A [`BoundData`](_autosummary/front.data_binding.html.md#front.data_binding.BoundData) wraps a keyed slot in a [`State`](_autosummary/front.state.html.md#front.state.State) so an
element can read and write its current value through a single object. The
`ValueNotSet` / `Empty` sentinels distinguish “no value yet” from a
deliberate empty value.

### Classes

| [`Binder`](_autosummary/front.data_binding.html.md#front.data_binding.Binder)(front_state)   | Expose keys of `front_state` as attributes (or items) that are `BoundData` handles.   |
|------------------------------------------------------------------------|---------------------------------------------------------------------------------------|
| [`BoundData`](_autosummary/front.data_binding.html.md#front.data_binding.BoundData)(id, state)  | A read/write handle on one key (`id`) of a state mapping.                             |

### *class* front.data_binding.Binder(front_state)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Expose keys of `front_state` as attributes (or items) that are `BoundData` handles.

Reading an unknown attribute creates a handle for that key (without writing to
the state); assigning to it creates the handle and writes the value.

```pycon
>>> state = {}
>>> b = Binder(state)
>>> b.foo.get()
ValueNotSet
>>> b.foo = 42
>>> b.foo(), state
(42, {'foo': 42})
>>> b['bar'] = 'hi'
>>> state
{'foo': 42, 'bar': 'hi'}
```

#### SEE ALSO
`front.state.mk_binder`: a descriptor-based variant with an allow-list of names.

#### bound_data_factory

alias of [`BoundData`](_autosummary/front.data_binding.html.md#front.data_binding.BoundData)

### *class* front.data_binding.BoundData(id, state)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A read/write handle on one key (`id`) of a state mapping.

`get` returns `ValueNotSet` while the key is absent; `set` writes through
to the state. Calling the instance is the same as `get`.

```pycon
>>> state = {}
>>> bound = BoundData('x', state)
>>> bound.get()
ValueNotSet
>>> bound.set(3)
>>> bound(), state
(3, {'x': 3})
```

#### SEE ALSO
`Binder`: makes `BoundData` handles on demand, as attributes.

#### get()

Return the value stored under `id`, or `ValueNotSet`.

#### set(value)

Write `value` under `id` in the state.


# _autosummary/front.elements.elements.html.md

# front.elements.elements

Abstract base classes for the composite tree of front UI elements.

Front elements (containers, inputs, outputs, etc.) are arranged in a tree
mirroring the rendering specification. This module defines the base
`FrontElementBase` and `FrontContainerBase` classes that concrete frontends
(e.g. streamlit) subclass to provide their own rendering.

### Functions

| [`mk_element_from_spec`](_autosummary/front.elements.elements.html.md#front.elements.elements.mk_element_from_spec)(spec)          | Instantiate the element factory found under `ELEMENT_KEY` with the other keys.       |
|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
| [`mk_input_element_specs`](_autosummary/front.elements.elements.html.md#front.elements.elements.mk_input_element_specs)(obj, inputs) | Make one input element spec per parameter of `obj`, from a type-keyed `inputs` spec. |

### Classes

| [`BooleanInputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.BooleanInputBase)([obj, name, display, ...])      | Boolean input (checkbox-like); values are cast with `bool`, defaulting to False.              |
|---------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------|
| [`ExecContainerBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.ExecContainerBase)(obj, inputs, output[, ...])    | Container that executes `obj` with the values of its input children.                          |
| [`FileUploaderBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FileUploaderBase)([obj, name, display, ...])      | File upload input, restricted to the given file `type` (extension(s)) if any.                 |
| [`FloatInputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FloatInputBase)([obj, name, display, ...])        | Float input with optional bounds and `step`; values are cast with `float`, defaulting to 0.0. |
| [`FrontComponentBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontComponentBase)([obj, name, display])         | A leaf element the user interacts with (an input, an output, a text section).                 |
| [`FrontContainerBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontContainerBase)([obj, name, display])         | An element with children, each built from a keyword argument holding an element spec.         |
| [`FrontElementBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontElementBase)([obj, name, display])           | Base of every front element: a renderable node of the element tree.                           |
| [`FrontElementSpec`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontElementSpec)                                 |                                                                                               |
| [`InputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.InputBase)([obj, name, display, input_key, ...])  | Base of input components: a value bound to state under `input_key`.                           |
| [`IntInputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.IntInputBase)([obj, name, display, ...])          | Integer input with optional bounds; values are cast with `int`, defaulting to 0.              |
| [`KwargsInputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.KwargsInputBase)([obj, name, display, ...])       | Input for a `**kwargs` parameter, with one sub-input per name in `func_sig`.                  |
| [`MultiSourceInputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.MultiSourceInputBase)([obj, name, display, ...])  | An input whose value can come from several child input components.                            |
| [`NumberInputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.NumberInputBase)([obj, name, display, ...])       | Base of numeric inputs, with an optional display `format`.                                    |
| [`OutputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.OutputBase)([obj, name, display])                 | Base of output components; `output` is set by the executing container before render.          |
| [`SelectorBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.SelectorBase)([obj, name, display, ...])          | Input choosing one value among `options` (a sequence, or a callable returning one).           |
| [`TextInputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.TextInputBase)([obj, name, display, ...])         | Text input; the view value defaults to the empty string.                                      |
| [`TextSectionBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.TextSectionBase)(content[, kind, obj, name, ...]) | A component displaying text `content` of a given `kind` (e.g. "text", "markdown").            |

### *class* front.elements.elements.BooleanInputBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False)

Bases: [`InputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.InputBase)

Boolean input (checkbox-like); values are cast with `bool`, defaulting to False.

### *class* front.elements.elements.ExecContainerBase(obj, inputs, output, name=None, display=True, auto_submit=False, on_submit=None)

Bases: [`FrontContainerBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontContainerBase)

Container that executes `obj` with the values of its input children.

Builds one input child per parameter of `obj` (see `mk_input_element_specs`)
plus an `output` child. `_submit` calls `obj` with the collected inputs,
hands the result to the first `OutputBase` child and renders it, then calls
`on_submit` with the result if given. Concrete subclasses implement `render`
and `_noneable` (how an optional input is presented).

### *class* front.elements.elements.FileUploaderBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False, type=None, accept_multiple_files=False)

Bases: [`InputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.InputBase)

File upload input, restricted to the given file `type` (extension(s)) if any.

### *class* front.elements.elements.FloatInputBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False, format=None, min_value=None, max_value=None, step=None)

Bases: [`NumberInputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.NumberInputBase)

Float input with optional bounds and `step`; values are cast with `float`, defaulting to 0.0.

### *class* front.elements.elements.FrontComponentBase(obj=None, name=None, display=True)

Bases: [`FrontElementBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontElementBase)

A leaf element the user interacts with (an input, an output, a text section).

### *class* front.elements.elements.FrontContainerBase(obj=None, name=None, display=True, \*\*kwargs)

Bases: [`FrontElementBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontElementBase)

An element with children, each built from a keyword argument holding an element spec.

Every extra keyword argument is a child spec: the key becomes the child’s
`name` (unless the spec overrides it) and the container’s `obj` is passed
down. Concrete containers define the layout in `render`.

```pycon
>>> from dataclasses import dataclass
>>> @dataclass
... class Hello(FrontElementBase):
...     def render(self):
...         return f"hello {self.name}"
>>> class Box(FrontContainerBase):
...     def render(self):
...         return [child() for child in self.children]
>>> box = Box(name='box', greeting={ELEMENT_KEY: Hello, 'name': 'you'}, other={ELEMENT_KEY: Hello})
>>> box()
['hello you', 'hello other']
```

### *class* front.elements.elements.FrontElementBase(obj=None, name=None, display=True)

Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC)

Base of every front element: a renderable node of the element tree.

Subclasses implement `render`. Calling the element runs the lifecycle
`pre_render` → `render` → `post_render` when `display` is truthy, and
does nothing (returns None) otherwise. `name` and `display` may be given
as callables of `obj`; they are resolved at construction.

```pycon
>>> from dataclasses import dataclass
>>> @dataclass
... class Hello(FrontElementBase):
...     def render(self):
...         return f"hello {self.name}"
>>> Hello(name='world')()
'hello world'
>>> Hello(obj=len, name=lambda obj: obj.__name__)()
'hello len'
>>> Hello(name='hidden', display=False)() is None
True
```

#### SEE ALSO
`FrontContainerBase`: an element with children.
`FrontComponentBase`: a leaf element the user interacts with.

#### post_render(render_result)

Hook run on the result of `render`; returns it unchanged by default.

#### pre_render()

Hook run before `render`; does nothing by default.

#### *abstractmethod* render()

Render the element with the concrete UI framework; must be overridden.

### *class* front.elements.elements.FrontElementSpec

Bases: [`TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict)

### *class* front.elements.elements.InputBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False)

Bases: [`FrontComponentBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontComponentBase)

Base of input components: a value bound to state under `input_key`.

`obj` is the `inspect.Parameter` the input feeds. At construction, `value`
is wrapped in a `BoundData` made by `bound_data_factory` (unless it already
is one), and seeded with the given value or the parameter’s default if nothing
is set yet. Two companion keys, `view_key` and `none_key`, hold the widget’s
displayed value and its “is None” toggle.

* **Raises:**
  [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If `bound_data_factory` is None when a `BoundData` is needed.

#### *property* none_key *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

`"{input_key}_none"`.

* **Type:**
  State key of the “value is None” toggle

#### on_change()

Call `on_value_change` with the current view value, if both are set.

#### post_render(render_result)

Store the rendered (widget) value in the bound state and return it.

#### *property* view_key *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

`"{input_key}_view"`.

* **Type:**
  State key of the widget’s displayed value

### *class* front.elements.elements.IntInputBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False, format=None, min_value=None, max_value=None)

Bases: [`NumberInputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.NumberInputBase)

Integer input with optional bounds; values are cast with `int`, defaulting to 0.

### *class* front.elements.elements.KwargsInputBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False, inputs=None, func_sig=None)

Bases: [`InputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.InputBase)

Input for a `**kwargs` parameter, with one sub-input per name in `func_sig`.

#### pre_render()

Make `self.get_kwargs`, a function with signature `func_sig` returning its kwargs.

### *class* front.elements.elements.MultiSourceInputBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False, \*\*kwargs)

Bases: [`InputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.InputBase)

An input whose value can come from several child input components.

Extra keyword arguments are child input specs; each child shares this input’s
`input_key`, `value` and binding settings.

### *class* front.elements.elements.NumberInputBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False, format=None)

Bases: [`InputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.InputBase)

Base of numeric inputs, with an optional display `format`.

### *class* front.elements.elements.OutputBase(obj=None, name=None, display=True)

Bases: [`FrontComponentBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontComponentBase)

Base of output components; `output` is set by the executing container before render.

### *class* front.elements.elements.SelectorBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False, options=None)

Bases: [`InputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.InputBase)

Input choosing one value among `options` (a sequence, or a callable returning one).

If no options are given and the parameter is annotated with a `Literal`, the
literal’s values are the options.

#### pre_render()

Resolve the options and pre-select the current view value (or the first option).

### *class* front.elements.elements.TextInputBase(obj=None, name=None, display=True, input_key=None, value=ValueNotSet, on_value_change=None, bound_data_factory=None, is_noneable=False, disabled=False, type=None)

Bases: [`InputBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.InputBase)

Text input; the view value defaults to the empty string.

### *class* front.elements.elements.TextSectionBase(content, kind='text', obj=None, name=None, display=True, \*\*kwargs)

Bases: [`FrontComponentBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontComponentBase)

A component displaying text `content` of a given `kind` (e.g. “text”, “markdown”).

`content` and `kind` may be callables of `obj`, resolved at construction.
Extra keyword arguments are kept in `self.kwargs` for the concrete renderer.

### front.elements.elements.mk_element_from_spec(spec)

Instantiate the element factory found under `ELEMENT_KEY` with the other keys.

```pycon
>>> from dataclasses import dataclass
>>> @dataclass
... class Hello(FrontElementBase):
...     def render(self):
...         return f"hello {self.name}"
>>> mk_element_from_spec({ELEMENT_KEY: Hello, 'name': 'x'})()
'hello x'
```

* **Raises:**
  [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError) – If `spec` has no `ELEMENT_KEY`.

### front.elements.elements.mk_input_element_specs(obj, inputs)

Make one input element spec per parameter of `obj`, from a type-keyed `inputs` spec.

`inputs` maps parameter types (and/or parameter names) to element specs; the
`DEFAULT_INPUT_KEY` entry is merged under every type entry. Each parameter’s
spec is looked up by its annotation (or the type of its default), with an
`Optional[X]` annotation or a `None` default marking it as `is_noneable`.
Unions of more than one non-None type are not supported.

```pycon
>>> def foo(a: int, b='hi', c: float = None):
...     pass
>>> specs = mk_input_element_specs(
...     foo, {DEFAULT_INPUT_KEY: {'disabled': False}, int: {'min_value': 0}}
... )
>>> list(specs)
['a', 'b', 'c']
>>> {k: v for k, v in specs['a'].items() if k != 'obj'}
{'disabled': False, 'min_value': 0, 'input_key': 'foo_a', 'is_noneable': False}
>>> specs['c']['is_noneable']
True
```

* **Raises:**
  [**NotImplementedError**](https://docs.python.org/3/builtins/exceptions.html#NotImplementedError) – If a parameter is annotated with a Union of several
  non-None types.


# _autosummary/front.elements.html.md

# front.elements

Front UI elements: bases, tree maker, and component implementer helpers.

### Modules

| [`elements`](_autosummary/front.elements.elements.html.md#module-front.elements.elements)               | Abstract base classes for the composite tree of front UI elements.                     |
|--------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|
| [`implementation`](_autosummary/front.elements.implementation.html.md#module-front.elements.implementation)   | Helpers for binding concrete UI component factories to front element classes.          |
| [`tree_maker_base`](_autosummary/front.elements.tree_maker_base.html.md#module-front.elements.tree_maker_base) | `ElementTreeMaker`: builds the composite tree of front elements from a rendering spec. |


# _autosummary/front.elements.implementation.html.md

# front.elements.implementation

Helpers for binding concrete UI component factories to front element classes.

`implement_component` is a small factory that produces a `render`-able
front element class from any callable component factory (e.g. a Streamlit
widget), wiring the factory’s keyword arguments to the element’s attributes.

### Functions

| [`implement_component`](_autosummary/front.elements.implementation.html.md#front.elements.implementation.implement_component)(base_cls, component_factory)   | Make a `base_cls` subclass whose `render` calls `component_factory` with the element's attributes.   |
|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------|

### front.elements.implementation.implement_component(base_cls, component_factory, input_value_callback=None, \*\*input_mapping)

Make a `base_cls` subclass whose `render` calls `component_factory` with the element’s attributes.

For each keyword-able parameter of `component_factory`, the element attribute
of the same name (or of the name given in `input_mapping`) is passed, unless
it is None; callable attributes are called first. The value returned by the
factory is handed to `input_value_callback(value, element)` if given, and
returned.

```pycon
>>> from dataclasses import dataclass
>>> from front.elements import FrontComponentBase
>>> def widget(label, value=0):
...     return f"{label}={value}"
>>> @dataclass
... class LabelBase(FrontComponentBase):
...     label: str = None
...     value: int = 0
>>> Component = implement_component(LabelBase, widget)
>>> Component(label='n', value=7)()
'n=7'
```

With `input_mapping`, the factory’s `label` is fed from the element’s `name`:

```pycon
>>> seen = []
>>> Component = implement_component(
...     LabelBase, widget, input_value_callback=lambda v, el: seen.append(v), label='name'
... )
>>> Component(name='count', value=2)()
'count=2'
>>> seen
['count=2']
```


# _autosummary/front.elements.tree_maker_base.html.md

# front.elements.tree_maker_base

`ElementTreeMaker`: builds the composite tree of front elements from a rendering spec.

The tree is then walked by [`AppMaker`](_autosummary/front.app_maker.html.md#front.app_maker.AppMaker) to produce the
runnable app. Concrete frontends typically don’t override this — they supply
their own element classes via the rendering specification.

### Classes

| [`ElementTreeMaker`](_autosummary/front.elements.tree_maker_base.html.md#front.elements.tree_maker_base.ElementTreeMaker)()   | Build the composite tree of front elements from a compiled rendering spec.   |
|-----------------------------------------------------------------------|------------------------------------------------------------------------------|

### *class* front.elements.tree_maker_base.ElementTreeMaker

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Build the composite tree of front elements from a compiled rendering spec.

The rendering specification maps `ELEMENT_KEY` to the root container factory,
and types (or names) of the objects to render to their element specs. The
resulting tree is rendered by calling its root, which renders each element
recursively.

```pycon
>>> from collections.abc import Callable
>>> from front.elements import FrontContainerBase, FrontComponentBase, ELEMENT_KEY
>>> class App(FrontContainerBase):
...     def render(self):
...         return {child.name: child() for child in self.children}
>>> class Doc(FrontComponentBase):
...     def render(self):
...         return self.obj.__doc__
>>> def foo(a, b):
...     "Adds a and b."
...     return a + b
>>> rendering_spec = {ELEMENT_KEY: App, Callable: {ELEMENT_KEY: Doc}}
>>> tree = ElementTreeMaker().mk_tree([foo], rendering_spec)
>>> type(tree).__name__, [type(child).__name__ for child in tree.children]
('App', ['Doc'])
>>> tree()
{'foo': 'Adds a and b.'}
```

#### SEE ALSO
`front.app_maker.AppMaker`: calls `mk_tree` with the compiled spec.

#### mk_tree(front_objs, rendering_spec)

Build the composite tree: the entry point of `ElementTreeMaker`.

* **Parameters:**
  * **front_objs** ([`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – The objects to render after transformation (see AppMaker).
  * **rendering_spec** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)) – The rendering spec of the application, compiled from
    the given configuration.
    This nested object contains information on how an object should be rendered
    based on its type (general spec that can be reused for several objects) or
    its name (specific spec for a single object). Both specs can be used for a
    single objects. In that case, the spec that will be used for this object
    will be a combination between those two specs (any value in the specific
    spec overwrites the value in the general spec for any key that they could
    have in common).
* **Return type:**
  [`FrontContainerBase`](_autosummary/front.elements.elements.html.md#front.elements.elements.FrontContainerBase)
* **Returns:**
  The root container, with one child element per object.
* **Raises:**
  [**KeyError**](https://docs.python.org/3/builtins/exceptions.html#KeyError) – If `rendering_spec` has no `ELEMENT_KEY` (root factory).


# _autosummary/front.html.md

# front

Dispatching python functions as webservices, docker containers, and GUIs.

`front` is the core library that concrete UI frameworks (e.g. `streamlitfront`)
build on: it compiles a configuration into a specification (`SpecMakerBase`),
builds a tree of UI elements from it (`ElementTreeMaker`) and assembles the app
(`AppMaker`). `Crudifier` and `prepare_for_crude_dispatch` make functions
with complex arguments operable through string keys into stores.

Consider these three functions:

```pycon
>>> def foo(a: int = 0, b: int = 0, c=0):
...     'This is foo. It computes something'
...     return (a * b) + c
>>> def bar(x, greeting='hello'):
...     'bar greets its input'
...     return f'{greeting} {x}'
>>> def confuser(a: int = 0, x: float = 3.14):
...     return (a ** 2) * x
```

The objective here is to be able to do this:

```pycon
>>> app = dispatch_funcs([foo, bar, confuser], ...)
```

getting a deployable app that allows the user to operate with these three wonderful
functions. The ellipses (`...`) are there to indicate that we may want to specify
the kind of app we want (web-service, GUI, CLI…) as well as particular configurations
for the latter.

### Modules

| [`app_maker`](_autosummary/front.app_maker.html.md#module-front.app_maker)             | The `AppMaker` orchestrator that turns a configuration into a front app.                                                                           |
|-----------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
| [`base`](_autosummary/front.base.html.md#module-front.base)                       | Base functions for front dispatching: `prepare_for_dispatch` chains the wrappers a UI needs.                                                       |
| [`crude`](_autosummary/front.crude.html.md#module-front.crude)                     | Crudify functions: let complex arguments be specified by string keys into stores.                                                                  |
| [`dag`](_autosummary/front.dag.html.md#module-front.dag)                         | Crudify the variable nodes of a `meshed` DAG.                                                                                                      |
| [`data_binding`](_autosummary/front.data_binding.html.md#module-front.data_binding)       | Data-binding primitives that connect front element values to a backing state store.                                                                |
| [`elements`](_autosummary/front.elements.html.md#module-front.elements)               | Front UI elements: bases, tree maker, and component implementer helpers.                                                                           |
| [`py2pydantic`](_autosummary/front.py2pydantic.html.md#module-front.py2pydantic)         | Bridge between plain Python functions and pydantic v2 models.                                                                                      |
| [`spec_maker_base`](_autosummary/front.spec_maker_base.html.md#module-front.spec_maker_base) | Base classes and conventions for building a [`FrontSpec`](_autosummary/front.types.html.md#front.types.FrontSpec) from a configuration. |
| [`state`](_autosummary/front.state.html.md#module-front.state)                     | Stateful storage protocols and `Forbidden` errors used by front data bindings.                                                                     |
| [`tools`](_autosummary/front.tools.html.md#module-front.tools)                     | Tools using front, or useful when using front.                                                                                                     |
| [`types`](_autosummary/front.types.html.md#module-front.types)                     | Type aliases and lightweight dataclasses shared across front modules.                                                                              |
| [`util`](_autosummary/front.util.html.md#module-front.util)                       | Signature and mapping utilities shared by the front modules.                                                                                       |


# _autosummary/front.py2pydantic.html.md

# front.py2pydantic

Bridge between plain Python functions and pydantic v2 models.

Given a Python function, produce a pydantic input model whose fields mirror
the function’s signature (names, annotations, defaults), and an “opyrator”-
style wrapper that takes a single pydantic model instance and dispatches
to the underlying function.

Useful for auto-generating forms, validators, and JSON-schema descriptions
of arbitrary callables — the core trick behind front’s app-from-function
dispatch.

```pycon
>>> from i2.tests.objects_for_testing import formula1
>>> pyd_input_model = func_to_pyd_input_model_cls(formula1)
>>> pyd_input_model.__name__
'formula1'
>>> from i2 import Sig
>>> Sig(formula1)
<Sig (w, /, x: float, y=1, *, z: int = 1)>
>>> Sig(pyd_input_model)
<Sig (*, w: Any, x: float, y: int = 1, z: int = 1) -> None>
```

```pycon
>>> pyd_func = func_to_pyd_func(formula1)
>>> input_model_instance = pyd_input_model(w=1, x=2)
>>> input_model_instance
formula1(w=1, x=2.0, y=1, z=1)
>>> pyd_func(input_model_instance)
3.0
>>> formula1(1, x=2)  # can't say w=1 because w is position only
3
```

### Functions

| [`func_to_pyd_func`](_autosummary/front.py2pydantic.html.md#front.py2pydantic.func_to_pyd_func)(func[, dflt_type])           | Get an 'opyrator' function from a python function: one taking a single pydantic model input.   |
|------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------|
| [`func_to_pyd_input_model_cls`](_autosummary/front.py2pydantic.html.md#front.py2pydantic.func_to_pyd_input_model_cls)(func[, ...])      | Get a pydantic model of the arguments of a python function.                                    |
| [`func_to_pyd_model_specs`](_autosummary/front.py2pydantic.html.md#front.py2pydantic.func_to_pyd_model_specs)(func[, dflt_type])    | Helper function to get field info from python signature parameters.                            |
| [`pyd_func_ingress_template`](_autosummary/front.py2pydantic.html.md#front.py2pydantic.pyd_func_ingress_template)(...)                | Turn a pydantic model instance into the `(args, kwargs)` of `wrapped_func_sig`.                |
| [`pydantic_egress`](_autosummary/front.py2pydantic.html.md#front.py2pydantic.pydantic_egress)(output)                       | Wrap `output` in an `Output` model with a single `output_val` field of its type.               |
| [`pydantic_model_from_type`](_autosummary/front.py2pydantic.html.md#front.py2pydantic.pydantic_model_from_type)(mytype[, name, ...]) | Make a pydantic model with one required field `field_name` of type `mytype`.                   |

### front.py2pydantic.func_to_pyd_func(func, dflt_type=typing.Any)

Get an ‘opyrator’ function from a python function: one taking a single pydantic model input.

The output model is not yet applied: the wrapped function returns what `func` returns.

### front.py2pydantic.func_to_pyd_input_model_cls(func, dflt_type=typing.Any, , name=None, warn_when_changing_names=True)

Get a pydantic model of the arguments of a python function.

```pycon
>>> def foo(a, b: int, c: bool=False):
...     ...
>>> obj = func_to_pyd_input_model_cls(foo)
>>> obj.model_json_schema() == (
... {
...     'title': 'foo',
...     'type': 'object',
...     'properties': {
...         'a': {'title': 'A'},
...         'b': {'title': 'B', 'type': 'integer'},
...         'c': {'title': 'C', 'default': False, 'type': 'boolean'}
...     },
...     'required': ['a', 'b']
... })
True
```

If some argument names of the function conflict with attribute names of BaseModel,
these will be capitalized to resolve the conflict.

```pycon
>>> def bar(x, copy, schema):
...     ...
>>> obj2 = func_to_pyd_input_model_cls(bar, warn_when_changing_names=False)
>>> obj2.model_json_schema() == (
... {
...     'title': 'bar',
...     'type': 'object',
...     'properties': {
...         'x': {'title': 'X'},
...         'COPY': {'title': 'Copy'},
...         'SCHEMA': {'title': 'Schema'}},
...     'required': ['x', 'COPY', 'SCHEMA']
... })
True
```

### front.py2pydantic.func_to_pyd_model_specs(func, dflt_type=typing.Any)

Helper function to get field info from python signature parameters.

Each spec is a `(type, default)` tuple suitable for pydantic v2’s
`create_model`. For unannotated parameters the type is inferred from
the default value’s type when a default is present, otherwise
`dflt_type` (`Any` by default) is used with `...` (required).

### front.py2pydantic.pyd_func_ingress_template(input_model_instance, wrapped_func_sig)

Turn a pydantic model instance into the `(args, kwargs)` of `wrapped_func_sig`.

```pycon
>>> from i2 import Sig
>>> from i2.tests.objects_for_testing import formula1
>>> model = func_to_pyd_input_model_cls(formula1)(w=1, x=2)
>>> pyd_func_ingress_template(model, Sig(formula1))
((1,), {'x': 2.0, 'y': 1, 'z': 1})
```

### front.py2pydantic.pydantic_egress(output)

Wrap `output` in an `Output` model with a single `output_val` field of its type.

```pycon
>>> pydantic_egress(3)
Output(output_val=3)
```

### front.py2pydantic.pydantic_model_from_type(mytype, name='Output', field_name='result')

Make a pydantic model with one required field `field_name` of type `mytype`.

```pycon
>>> Model = pydantic_model_from_type(int)
>>> Model(result=2)
Output(result=2)
```


# _autosummary/front.spec_maker_base.html.md

# front.spec_maker_base

Base classes and conventions for building a [`FrontSpec`](_autosummary/front.types.html.md#front.types.FrontSpec) from a configuration.

A spec maker is the “short language → long language” compiler of front: it
consumes a user configuration plus a convention (defaults) and emits the
nested `app` / `obj` / `rendering` specification consumed by
[`AppMaker`](_autosummary/front.app_maker.html.md#front.app_maker.AppMaker).

### Classes

| [`SpecMakerBase`](_autosummary/front.spec_maker_base.html.md#front.spec_maker_base.SpecMakerBase)()   | Compile a user configuration (short language) into a `FrontSpec` (long language).   |
|--------------------------------------------------------------------|-------------------------------------------------------------------------------------|

### *class* front.spec_maker_base.SpecMakerBase

Bases: [`ABC`](https://docs.python.org/3/library/abc.html#abc.ABC)

Compile a user configuration (short language) into a `FrontSpec` (long language).

The configuration is merged over a convention (the defaults), then the
class-keyed entries of the rendering specification are completed along the
class hierarchy, so that a spec for a subclass inherits the spec of its bases.

To do so, the “mk_spec” method first merges the configuration with the convention,
then does the following for the rendering specification:
Let’s consider we have three classes A, B and C with C extends B and B extends A
(A <- B <- C). If the rendering configuration contains the following:

```default
{
    A: {
        'a': {...}
    },
    B: {
        'b': {...}
    },
    C: {
        'c': {...}
    },
}
```

The resulting rendering specification will be:

```default
{
    A: {
        'a': {...}
    },
    B: {
        'a': {...},
        'b': {...}
    },
    C: {
        'a': {...},
        'b': {...},
        'c': {...}
    },
}
```

This abstract class needs to be overloaded in every concrete front framework with
a concrete implementation for the “_dflt_convention” property, which will return
the convention after injecting the concrete element factories in it.

```pycon
>>> from front import APP_KEY, OBJ_KEY, RENDERING_KEY
>>> from front.util import dflt_trans
>>> class A: pass
>>> class B(A): pass
>>> class C(B): pass
>>> class SpecMaker(SpecMakerBase):
...     @property
...     def _dflt_convention(self):
...         return {
...             APP_KEY: {'title': 'Untitled'},
...             OBJ_KEY: {'trans': dflt_trans},
...             RENDERING_KEY: {A: {'a': 1}, B: {'b': 2}, C: {'c': 3}},
...         }
>>> spec = SpecMaker().mk_spec({APP_KEY: {'title': 'Demo'}})
>>> spec.app_spec
{'title': 'Demo'}
>>> spec.rendering_spec[C]
{'a': 1, 'b': 2, 'c': 3}
>>> spec.rendering_spec[B]
{'a': 1, 'b': 2}
```

#### SEE ALSO
`front.app_maker.AppMaker`: consumes the spec this class produces.
`front.util.deep_merge`: the merge used for config over convention.

#### mk_spec(config, convention=None)

Merge `config` over `convention` and complete class-keyed rendering specs.

* **Parameters:**
  * **config** (`Union`[[`None`](https://docs.python.org/3/builtins/constants.html#None), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[], [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)]]) – The user configuration: a mapping, a callable returning one,
    or None (empty).
  * **convention** (`Union`[[`None`](https://docs.python.org/3/builtins/constants.html#None), [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[], [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)]]) – The defaults. If None, `self._dflt_convention` is used.
* **Return type:**
  [`FrontSpec`](_autosummary/front.types.html.md#front.types.FrontSpec)
* **Returns:**
  A `FrontSpec` with `app_spec`, `obj_spec` and `rendering_spec`.


# _autosummary/front.state.html.md

# front.state

Stateful storage protocols and `Forbidden` errors used by front data bindings.

Defines the [`State`](_autosummary/front.state.html.md#front.state.State) wrapper and the `GetterSetter` / `StateType`
protocols an app’s backing store must satisfy, plus a small hierarchy of
`Forbidden*` exceptions raised when a write breaks the configured policy.

### Functions

| [`mk_binder`](_autosummary/front.state.html.md#front.state.mk_binder)([state, allowed_ids, ...])   | Make a `Binder` class (or instance) whose attributes read and write a state mapping.   |
|-----------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|

### Classes

| [`BoundVal`](_autosummary/front.state.html.md#front.state.BoundVal)(key, \*[, value_not_set])     | Descriptor reading and writing `key` in the owner's `_state` mapping.        |
|-----------------------------------------------------------------------------------------|------------------------------------------------------------------------------|
| [`DFLT_BOUND_VAL_FACTORY`](_autosummary/front.state.html.md#front.state.DFLT_BOUND_VAL_FACTORY)                 |                                                                              |
| [`GetterSetter`](_autosummary/front.state.html.md#front.state.GetterSetter)(\*args, \*\*kwargs)       | The type of an object `obj` supporting `v = obj[k]` and `obj[k] = v`.        |
| [`HasState`](_autosummary/front.state.html.md#front.state.HasState)(\*args, \*\*kwargs)           | An object with a `_state` mutable mapping, as `BoundVal` descriptors expect. |
| [`IsInstanceOf`](_autosummary/front.state.html.md#front.state.IsInstanceOf)(class_or_tuple)           | A picklable `isinstance` predicate: `IsInstanceOf(int)(3)` is True.          |
| [`State`](_autosummary/front.state.html.md#front.state.State)(state[, condition_for_key, ...]) | A write-policing wrapper around a key-value `state` (any `GetterSetter`).    |

### Exceptions

| [`ConditionNotMet`](_autosummary/front.state.html.md#front.state.ConditionNotMet)    | Raised when a value doesn't meet the condition set for its key.          |
|---------------------------------------------------------------------|--------------------------------------------------------------------------|
| [`Forbidden`](_autosummary/front.state.html.md#front.state.Forbidden)          | Base of the errors raised when an operation is not allowed.              |
| [`ForbiddenOverwrite`](_autosummary/front.state.html.md#front.state.ForbiddenOverwrite) | Raised when writing a different value to an existing key is not allowed. |
| [`ForbiddenWrite`](_autosummary/front.state.html.md#front.state.ForbiddenWrite)     | Raised when writing to a key is not allowed.                             |

### *class* front.state.BoundVal(key, , value_not_set=ValueNotSet)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Descriptor reading and writing `key` in the owner’s `_state` mapping.

Reading returns `value_not_set` (`ValueNotSet` by default) while the key
is absent.

```pycon
>>> class Obj:
...     _state = {}
...     x = BoundVal('x')
>>> obj = Obj()
>>> obj.x
ValueNotSet
>>> obj.x = 5
>>> obj.x, Obj._state
(5, {'x': 5})
>>> Obj.x
BoundVal('x')
```

### *exception* front.state.ConditionNotMet

Bases: [`ValueError`](https://docs.python.org/3/builtins/exceptions.html#ValueError)

Raised when a value doesn’t meet the condition set for its key.

### front.state.DFLT_BOUND_VAL_FACTORY

alias of [`BoundVal`](_autosummary/front.state.html.md#front.state.BoundVal)

### *exception* front.state.Forbidden

Bases: [`Exception`](https://docs.python.org/3/builtins/exceptions.html#Exception)

Base of the errors raised when an operation is not allowed.

### *exception* front.state.ForbiddenOverwrite

Bases: [`Forbidden`](_autosummary/front.state.html.md#front.state.Forbidden)

Raised when writing a different value to an existing key is not allowed.

### *exception* front.state.ForbiddenWrite

Bases: [`Forbidden`](_autosummary/front.state.html.md#front.state.Forbidden)

Raised when writing to a key is not allowed.

### *class* front.state.GetterSetter(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

The type of an object `obj` supporting `v = obj[k]` and `obj[k] = v`.

### *class* front.state.HasState(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

An object with a `_state` mutable mapping, as `BoundVal` descriptors expect.

### *class* front.state.IsInstanceOf(class_or_tuple)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A picklable `isinstance` predicate: `IsInstanceOf(int)(3)` is True.

### *class* front.state.State(state, condition_for_key=(), forbidden_writes=(), forbidden_overwrites=())

Bases: [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)

A write-policing wrapper around a key-value `state` (any `GetterSetter`).

Reads and the other `MutableMapping` operations forward to `state`. Writes
are checked first: keys in `forbidden_writes` can never be written; keys in
`forbidden_overwrites` can be written once (re-writing the same value is
allowed); a key in `condition_for_key` only accepts values for which its
predicate is true (a type there means `isinstance`).

```pycon
>>> state = State(
...     state={},
...     forbidden_writes={'foo'},
...     forbidden_overwrites={'apple'},
...     condition_for_key={'apple': list, 'carrot': lambda x: x > 10},
... )
>>> state['apple'] = [4, 2]
>>> state['apple'] = [4, 2]  # same value again: fine
>>> state['apple'] = [1]
Traceback (most recent call last):
...
front.state.ForbiddenOverwrite: Not allowed to write under this key more than once: apple
>>> state['foo'] = 1
Traceback (most recent call last):
...
front.state.ForbiddenWrite: Not allowed to write on foo
>>> state['carrot'] = 10
Traceback (most recent call last):
...
front.state.ConditionNotMet: The value for the carrot key must satisfy condition <function <lambda> at 0x...>
>>> state['carrot'] = 11
>>> dict(state)
{'apple': [4, 2], 'carrot': 11}
```

* **Raises:**
  * [**ForbiddenWrite**](_autosummary/front.state.html.md#front.state.ForbiddenWrite) – On writing a key of `forbidden_writes`.
  * [**ForbiddenOverwrite**](_autosummary/front.state.html.md#front.state.ForbiddenOverwrite) – On writing a different value to an existing key of
    `forbidden_overwrites`.
  * [**ConditionNotMet**](_autosummary/front.state.html.md#front.state.ConditionNotMet) – On writing a value that fails the key’s condition.

#### get(k, default=None)

Return `state[k]` if `k` is in the state, else `default`.

### front.state.mk_binder(state=None, allowed_ids=None, bound_val_factory=<class 'front.state.BoundVal'>)

Make a `Binder` class (or instance) whose attributes read and write a state mapping.

Returns a class when `state` is None, and an instance bound to `state`
otherwise. With `allowed_ids`, only those names are bound (as `bound_val_factory`
descriptors); without, any identifier is bound on first access.

```pycon
>>> Binder = mk_binder()
>>> d = dict()
>>> b = Binder(d)
```

If I ask for `b.foo` (or any valid python identifier I want) it’ll be inserted
as an “descriptor” attribute of `Binder`, but it’s  value will be special value
`ValueNotSet`.

```pycon
>>> b.foo
ValueNotSet
>>> 'foo' in dir(Binder)
True
```

Let’s set the value of `foo`:

```pycon
>>> b.foo = 42
>>> b.foo
42
```

So `b.foo` is now set, but the real point is that this assignment was “registered”
in the state we give the `Binder`:

```pycon
>>> d
{'foo': 42}
```

Wanna see that again?

```pycon
>>> b.foo = "I'm bound"
>>> b.foo
"I'm bound"
>>> d
{'foo': "I'm bound"}
```

And same with `b.bar`:

```pycon
>>> b.bar
ValueNotSet
>>> b.bar = "me too"
>>> b.bar
'me too'
>>> d
{'foo': "I'm bound", 'bar': 'me too'}
```

A `Binder` will also have some useful mapping methods that are linked to the
underlying `state`.

```pycon
>>> Binder = mk_binder(allowed_ids=['the', 'variables', 'I', 'want'])
>>> state = dict()
>>> b = Binder(state)
>>> list(b)
[]
>>> b.want  # I see a want, but no value is set
ValueNotSet
>>> list(b)  # list still gives me nothing
[]
>>> b.want = 42  # but if I set a value for want
>>> list(b)  # I see want in the list
['want']
>>> 'want' in b  # I can do this too
True
>>> 'not_in_there' in b
False
>>> 'variables' in b  # 'variables' not "there" because not set
False
```


# _autosummary/front.tools.html.md

# front.tools

Tools using front, or useful when using front.

### Classes

| [`FactoryFedSizedIterableContainer`](_autosummary/front.tools.html.md#front.tools.FactoryFedSizedIterableContainer)(...)   | A sized iterable container over the items of `iterable_factory()`, re-called on every use.   |
|------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|
| [`SizedIterableContainer`](_autosummary/front.tools.html.md#front.tools.SizedIterableContainer)()                | An object with `__len__`, `__iter__` and `__contains__` methods.                             |
| [`ValuesStore`](_autosummary/front.tools.html.md#front.tools.ValuesStore)(seq)                        | A mapping view of a sequence where the items of the sequence are both keys and values.       |

### *class* front.tools.FactoryFedSizedIterableContainer(iterable_factory)

Bases: [`SizedIterableContainer`](_autosummary/front.tools.html.md#front.tools.SizedIterableContainer)

A sized iterable container over the items of `iterable_factory()`, re-called on every use.

```pycon
>>> c = FactoryFedSizedIterableContainer(lambda: range(3))
>>> list(c), len(c), 2 in c, 5 in c
([0, 1, 2], 3, True, False)
```

### *class* front.tools.SizedIterableContainer

Bases: [`Sized`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sized), [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable), [`Container`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Container)

An object with `__len__`, `__iter__` and `__contains__` methods.

### *class* front.tools.ValuesStore(seq)

Bases: `KvReader`

A mapping view of a sequence where the items of the sequence are both keys and values.

```pycon
>>> vs = ValuesStore([1, 2, 3])
>>> list(vs)
[1, 2, 3]
>>> vs[1]
1
>>> len(vs)
3
>>> 4 in vs
False
```


# _autosummary/front.types.html.md

# front.types

Type aliases and lightweight dataclasses shared across front modules.

Centralizes the names used in spec compilation (`Configuration`,
`Convention`, `Map`) and the structured [`FrontSpec`](_autosummary/front.types.html.md#front.types.FrontSpec) consumed by
[`AppMaker`](_autosummary/front.app_maker.html.md#front.app_maker.AppMaker).

### Classes

| [`FrontSpec`](_autosummary/front.types.html.md#front.types.FrontSpec)(app_spec, obj_spec, rendering_spec)   | The compiled specification: `app_spec`, `obj_spec` and `rendering_spec` dicts.   |
|--------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|

### *class* front.types.FrontSpec(app_spec, obj_spec, rendering_spec)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The compiled specification: `app_spec`, `obj_spec` and `rendering_spec` dicts.


# _autosummary/front.util.html.md

# front.util

Signature and mapping utilities shared by the front modules.

Two families live here: signature rewriting (`inject_enum_annotations`,
`annotate_func_arguments`) used to make functions dispatchable by a UI, and
small mapping helpers (`deep_merge`, `subdict`, `normalize_map`) used by
the spec compilation.

```pycon
>>> deep_merge({'a': {'x': 1, 'y': 2}, 'b': 1}, {'a': {'y': 20}, 'c': 3})
{'a': {'x': 1, 'y': 20}, 'b': 1, 'c': 3}
```

### Functions

| [`annotate_func_arguments`](_autosummary/front.util.html.md#front.util.annotate_func_arguments)(func, \*[, ...])   | Add annotations to the arguments of `func`, by argument name or by default-value type.         |
|---------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------|
| [`deep_merge`](_autosummary/front.util.html.md#front.util.deep_merge)(a, b)                           | Merge `b` into `a` recursively (values of `b` win), returning a new dict.                      |
| [`dflt_name_trans`](_autosummary/front.util.html.md#front.util.dflt_name_trans)(obj)                       | Default display name: `obj` (or its name) with underscores as spaces, title-cased.             |
| [`dflt_trans`](_autosummary/front.util.html.md#front.util.dflt_trans)(objs)                           | Default `obj` transformation: ensure every object has a `__name__`, returning a list.          |
| [`get_value`](_autosummary/front.util.html.md#front.util.get_value)(obj, \*args, \*\*kwargs)         | Return `obj(*args, **kwargs)` if `obj` is callable, else `obj` itself.                         |
| [`identity`](_autosummary/front.util.html.md#front.util.identity)(x)                                | Return `x` unchanged.                                                                          |
| [`incremental_str_maker`](_autosummary/front.util.html.md#front.util.incremental_str_maker)([str_format])        | Make a function that will produce a (incrementally) new string at every call.                  |
| `inject_enum_annotations`([func, ...])                                                      | Annotate chosen arguments of `func` with Enums of their allowed values.                        |
| [`iterable_to_enum`](_autosummary/front.util.html.md#front.util.iterable_to_enum)(iterable[, name])         | Make an `Enum` whose member names are `str(value)` for each value of `iterable`.               |
| [`normalize_map`](_autosummary/front.util.html.md#front.util.normalize_map)(map)                         | Resolve a `Map` (mapping, callable returning one, or None) to a mapping; None gives `{}`.      |
| [`obj_name`](_autosummary/front.util.html.md#front.util.obj_name)(func)                             | Get the name of a callable, or make one (`UnnamedObjectNNN`) for lambdas and nameless objects. |
| [`subdict`](_autosummary/front.util.html.md#front.util.subdict)(d[, keys])                         | Get a sub-dict of Mapping `d`, with only those keys that are both in `keys` and `d`.           |
| `unnamed_obj`()                                                                             |                                                                                                |

### front.util.annotate_func_arguments(func, , ignore_existing_annot=False, annot_for_argname=(), annot_for_dflt_type=(), dflt_annot)

Add annotations to the arguments of `func`, by argument name or by default-value type.

* **Parameters:**
  * **func** ([`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)) – The function whose args we want to annotate
  * **ignore_existing_annot** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – Set to True to ignore existing annots.
  * **annot_for_argname** (`Union`[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)], [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]]) – Annotation for specific argnames
  * **annot_for_dflt_type** (`Union`[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`type`](https://docs.python.org/3/builtins/functions.html#type), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)], [`Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`type`](https://docs.python.org/3/builtins/functions.html#type), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]]) – Annotation for specific types. Arg defaults will be
    compared (with `isinstance(dflt_val, types)`) to types and the annotation
    (value) of the the first matching type (key) will be injected
  * **dflt_annot** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Default annotation to use if no match found earlier.
    The default is `inspect.Parameter.empty`, which means “don’t annotate”.
    If you want all your params to be annotated no matter what, you might consider
    `typing.Any`, or in the case of command line interfaces, `str`.
* **Returns:**
  A wrapped function with the desired signature changes, if any changes
  need to be made, or the same function untouched if not.

```pycon
>>> from inspect import signature
>>> from functools import partial
>>> from typing import Any
>>>
>>>
>>> def foo(a, b, c, aa: int=1, bb: int=1.0, cc: int=None, aaa=1, bbb=1.0, ccc=None):
...     pass
...
```

If nothing changes, you just get back the same function:

```pycon
>>> assert str(signature(annotate_func_arguments(foo))) == (
...     "(a, b, c, "
...     "aa: int = 1, bb: int = 1.0, cc: int = None, "
...     "aaa=1, bbb=1.0, ccc=None)"
... )
```

In the following:

- `b: str` through the argname rule, but `bb` (as well as `aa` and `bb`)
  didn’t change because `ignore_existing_annot=False` by default.
- `aaa: float` (even though default is `1`) and `ccc: 'NoneAnnot'` because of
  the `annot_for_dflt_type` rules.

```pycon
>>> annotator = partial(
...     annotate_func_arguments,
...     annot_for_argname = {'b': str, 'bb': str},
...     # don't confuse following with dict(int=float), which means {'int': float}
...     annot_for_dflt_type = {int: float, type(None): 'NoneAnnot'},
... )
>>>
>>> wrapped_func = annotator(foo)
>>> assert str(signature(wrapped_func)) == (
... "(a, b: str, c, "
... "aa: int = 1, bb: int = 1.0, cc: int = None, "
... "aaa: float = 1, bbb=1.0, ccc: 'NoneAnnot' = None)"
... )
```

See in the following what happens if we ask the default annotation to be `Any` and
`ignore_existing_annot=True`:

```pycon
>>> another_annotator = partial(
...     annotator,  # use the previous one, but...
...     dflt_annot=Any,  # and specify a default annotation
...     ignore_existing_annot=True  # now ignore any existing annotations
... )
>>>
>>> wrapped_func = another_annotator(foo)
>>> assert str(signature(wrapped_func)) == (
... "(a: Any, b: str, c: Any, "
... "aa: float = 1, bb: str = 1.0, cc: 'NoneAnnot' = None, "
... "aaa: float = 1, bbb: Any = 1.0, ccc: 'NoneAnnot' = None)"
... )
```

### front.util.deep_merge(a, b)

Merge `b` into `a` recursively (values of `b` win), returning a new dict.

Nested mappings present in both are merged; any other value in `b` replaces
the one in `a`. Neither input is modified.

```pycon
>>> deep_merge({'a': {'x': 1, 'y': 2}, 'b': 1}, {'a': {'y': 20, 'z': 30}, 'c': 3})
{'a': {'x': 1, 'y': 20, 'z': 30}, 'b': 1, 'c': 3}
```

### front.util.dflt_name_trans(obj)

Default display name: `obj` (or its name) with underscores as spaces, title-cased.

```pycon
>>> dflt_name_trans('my_func_name')
'My Func Name'
```

### front.util.dflt_trans(objs)

Default `obj` transformation: ensure every object has a `__name__`, returning a list.

Objects are passed through `copy.copy`, which returns functions unchanged, so
a lambda’s `__name__` is set on the lambda itself (to an `UnnamedObjectNNN`
name).

### front.util.get_value(obj, \*args, \*\*kwargs)

Return `obj(*args, **kwargs)` if `obj` is callable, else `obj` itself.

```pycon
>>> get_value(lambda: 3), get_value(3), get_value(lambda a, b: a + b, 1, 2)
(3, 3, 3)
```

### front.util.identity(x)

Return `x` unchanged.

### front.util.incremental_str_maker(str_format='{:03.f}')

Make a function that will produce a (incrementally) new string at every call.

### front.util.iterable_to_enum(iterable, name='CustomEnum')

Make an `Enum` whose member names are `str(value)` for each value of `iterable`.

```pycon
>>> E = iterable_to_enum([1, 'two'])
>>> list(E)
[<CustomEnum.1: 1>, <CustomEnum.two: 'two'>]
>>> E['1'].value
1
```

### front.util.normalize_map(map)

Resolve a `Map` (mapping, callable returning one, or None) to a mapping; None gives `{}`.

* **Return type:**
  [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)

```pycon
>>> normalize_map(None), normalize_map({'a': 1}), normalize_map(lambda: {'b': 2})
({}, {'a': 1}, {'b': 2})
```

### front.util.obj_name(func)

Get the name of a callable, or make one (`UnnamedObjectNNN`) for lambdas and nameless objects.

### front.util.subdict(d, keys=None)

Get a sub-dict of Mapping `d`, with only those keys that are both in `keys` and `d`.

Note that the dict will be ordered as `keys` are, so can be used for reordering
a Mapping.

```pycon
>>> subdict({'a': 1, 'b': 2, 'c': 3, 'd': 4}, keys=['b', 'a', 'd'])
{'b': 2, 'a': 1, 'd': 4}
```


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-09-15 11:46 UTC** from commit <a href="https://github.com/i2mint/front/commit/4ad3b6fe9223519bd4f1b5f95959a90a38d12c10"><code>4ad3b6f</code></a> on branch <code>master</code>, for **front 0.1.101** (from <code>pyproject.toml</code>).

#### WARNING
The documentation and the package may be misaligned:

- The documented version (0.1.101) is behind the latest release on PyPI (0.1.102): `pip install front` gives newer code than these docs describe.

## Source

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

## Continuous integration

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

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.11  |
| Sphinx   | 9.1.0   |
| docutils | 0.22.4  |
| Python   | 3.12.14 |

## Configuration as resolved

|               |                                                                   |
|---------------|-------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>pydata_sphinx_theme</code>) |
| accent        | <code>#23691d</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/front/0.1.102/">0.1.102</a>, newer than the documented version (0.1.101).

## Reproduce

```bash
git clone https://github.com/i2mint/front && cd front
git checkout 4ad3b6fe9223519bd4f1b5f95959a90a38d12c10
pip install "epythet==0.2.11"
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

| [`front`](_autosummary/front.html.md#module-front)   | Dispatching python functions as webservices, docker containers, and GUIs.   |
|-----------------------------------------------------------------------|-----------------------------------------------------------------------------|


