> built 2026-11-21 17:39 UTC from 4b5c863 (master) · embody 0.1.11. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# embody

**Structural Object Embodiment for Python** - Transform skeletal templates into fully realized, type-safe objects through recursive hydration.

[![Documentation](https://img.shields.io/badge/docs-i2mint-blue)](https://i2mint.github.io/embody/)
[![PyPI version](https://img.shields.io/pypi/v/embody.svg)](https://pypi.org/project/embody/)
[![Python](https://img.shields.io/pypi/pyversions/embody.svg)](https://pypi.org/project/embody/)

## What is Embody?

Embody is a powerful library for **templated object generation** that goes beyond simple string formatting. It provides **structural embodiment** - the recursive hydration of nested data structures with type preservation, cycle detection, and intelligent traversal strategies.

### Key Features

- **🎯 Type Preservation**: Variables like `${count}` preserve their types (int, bool, list, dict) instead of converting everything to strings
- **🔄 Multiple Strategies**: Choose between recursive visitor, compiled path, or iterative stack traversal
- **🎨 Multiple Syntaxes**: Support for `${var}`, `{var}`, and `[[var]]` template syntaxes
- **🛡️ Cycle Detection**: Automatically detect and prevent circular references
- **📍 Path Addressing**: Access nested data via JSON Pointer, dot notation, or tuple paths
- **🗺️ Mapping Interfaces**: Uniform interfaces for attribute access, flattening, and path-based operations
- **⚡ Performance**: Auto-selects optimal strategy based on template complexity
- **🔒 Type Safety**: Full integration with Pydantic and other validation libraries

## Installation

```bash
pip install embody
```

## Quick Start

### Basic Usage

```python
from embody import embody

# Simple template embodiment
template = {"name": "${name}", "age": "${age}", "greeting": "Hello ${name}!"}

result = embody(template, {"name": "Alice", "age": 30})
# {'name': 'Alice', 'age': 30, 'greeting': 'Hello Alice!'}
```

### Type Preservation

Unlike traditional templating, embody preserves types:

```python
template = {
    "count": "${num}",  # Will be int, not string!
    "active": "${flag}",  # Will be bool
    "items": "${list}",  # Will be list
    "message": "Count: ${num}",  # Will be string (interpolation)
}

result = embody(template, {"num": 42, "flag": True, "list": [1, 2, 3]})

assert isinstance(result["count"], int)  # True - type preserved!
assert isinstance(result["active"], bool)  # True
assert isinstance(result["items"], list)  # True
```

### Nested Structures

Embody handles deep nesting naturally:

```python
template = {
    "user": {
        "profile": {
            "name": "${name}",
            "settings": {"theme": "${theme}", "notifications": "${notify}"},
        }
    }
}

result = embody(template, {"name": "Bob", "theme": "dark", "notify": True})
```

## Advanced Features

### Context with Resolvers

```python
from embody import Context
import datetime

ctx = Context({"now": lambda: datetime.datetime.now(), "user": "Alice"})

# Callables are invoked on access
print(ctx["now"])  # Current time
print(ctx["user"])  # 'Alice'
```

### Mapping Interfaces

```python
from embody.mappings import AttributeMapping, PathMapping

# Attribute access (Box pattern)
attr_map = AttributeMapping({"user": {"name": "Alice"}})
print(attr_map.user.name)  # 'Alice'

# Path-based access
path_map = PathMapping({"a": {"b": {"c": 42}}})
print(path_map["a.b.c"])  # Dot notation
print(path_map["/a/b/c"])  # JSON Pointer
print(path_map[("a", "b", "c")])  # Tuple path
```

### Path Addressing

```python
from embody.paths import JSONPointer, resolve_path

data = {"users": [{"name": "Alice"}, {"name": "Bob"}]}

# JSON Pointer (RFC 6901)
ptr = JSONPointer("/users/0/name")
print(ptr.resolve(data))  # 'Alice'

# Convenience function
print(resolve_path(data, "users.0.name"))  # 'Alice'
```

### Traversal Strategies

```python
from embody import Embodier

template = {"data": "${value}"}

# Recursive visitor (default, best for one-off templates)
embodier1 = Embodier(template, strategy="recursive")

# Compiled path (best for repeated embodiment)
embodier2 = Embodier(template, strategy="compiled")

# Auto-select based on template complexity
embodier3 = Embodier(template, strategy="auto")

result = embodier1({"value": 42})
```

## Examples

### Configuration Management

```python
from embody import embody
import os

config_template = {
    "database": {"host": "${db_host}", "port": "${db_port}", "name": "${db_name}"},
    "api": {"base_url": "${api_url}", "timeout": "${timeout}"},
}

config = embody(
    config_template,
    {
        "db_host": os.getenv("DB_HOST", "localhost"),
        "db_port": int(os.getenv("DB_PORT", "5432")),
        "db_name": "myapp",
        "api_url": "https://api.example.com",
        "timeout": 30,
    },
)
```

### API Response Templates

```python
from embody import Embodier

response_template = {
    "status": "success",
    "data": {"user_id": "${id}", "name": "${name}", "timestamp": "${ts}"},
}

embodier = Embodier(response_template, strategy="compiled")

# Efficiently generate many responses
for user in users:
    response = embodier({"id": user.id, "name": user.name, "ts": datetime.now()})
```

## Backwards Compatibility

The original `Templater` API is fully preserved:

```python
from embody.templater import Templater

template = {"hello": "{name}", "how are you": ["{verb}", 2, "{name} and {verb} again"]}

g = Templater.template_func(template=template)
result = g(name="NAME", verb="VERB")
# {'hello': 'NAME', 'how are you': ['VERB', 2, 'NAME and VERB again']}
```

## Documentation

- [Full Documentation](https://i2mint.github.io/embody/)
- [Advanced Examples]()
- [API Reference](https://i2mint.github.io/embody/api/)

## Contributing

Contributions are welcome! Please see our [contributing guidelines]().

## License

Apache License 2.0 - see [LICENSE]() file for details.

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


# _autosummary/embody.base.html.md

# embody.base

Core classes for embody: Context, Template, and Embodier.

This module provides the foundational classes for the embody framework,
implementing the pattern: obj = embody(template, parameters).

### Functions

| [`embody`](_autosummary/embody.base.html.md#embody.base.embody)(template[, params])   | Convenience function for template embodiment.   |
|-------------------------------------------------------------------------------|-------------------------------------------------|

### Classes

| [`Context`](_autosummary/embody.base.html.md#embody.base.Context)([params, parent, resolvers, auto_call])   | Parameter store for template embodiment with support for resolvers.   |
|----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------|
| [`Embodier`](_autosummary/embody.base.html.md#embody.base.Embodier)(template[, strategy, syntax, ...])       | Main class for embodying templates with parameters.                   |
| [`TemplateWrapper`](_autosummary/embody.base.html.md#embody.base.TemplateWrapper)(template[, syntax, check_cycles]) | Wrapper for template data with introspection capabilities.            |

### Exceptions

| [`MissingParameterError`](_autosummary/embody.base.html.md#embody.base.MissingParameterError)   | Raised when a required template parameter is missing.   |
|--------------------------------------------------------------------------|---------------------------------------------------------|

### *class* embody.base.Context(params=None, parent=None, resolvers=None, auto_call=True)

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

Parameter store for template embodiment with support for resolvers.

The Context holds parameters for substitution and supports:

- Hierarchical scoping (global → local overrides)
- Resolver functions (lazy evaluation)
- Callable values that are invoked on access

### Examples

```pycon
>>> ctx = Context({'name': 'Alice', 'age': 30})
>>> ctx['name']
'Alice'
```

```pycon
>>> import datetime
>>> ctx = Context({'now': lambda: datetime.datetime.now()})
>>> ctx['now']
datetime.datetime(...)
```

```pycon
>>> ctx = Context({'base': 10}, parent={'base': 5, 'other': 20})
>>> ctx['base']  # Local overrides parent
10
>>> ctx['other']  # Falls back to parent
20
```

#### child(params=None)

Create a child context with this context as parent.

* **Parameters:**
  **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for the child context
* **Return type:**
  [`Context`](_autosummary/embody.base.html.md#embody.base.Context)
* **Returns:**
  New Context with this as parent

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

Get a parameter with a default value.

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

#### register_resolver(name, func)

Register a named resolver function.

* **Parameters:**
  * **name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Name of the resolver
  * **func** ([`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)) – Callable that returns the resolved value

### Examples

```pycon
>>> import os
>>> ctx = Context()
>>> ctx.register_resolver('env', lambda: os.environ.get('USER', 'unknown'))
```

#### to_dict()

Convert to a plain dictionary (resolving all values).

* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]
* **Returns:**
  Dictionary with all parameters resolved

#### update(params)

Create a new context with updated parameters.

* **Parameters:**
  **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters to add/override
* **Return type:**
  [`Context`](_autosummary/embody.base.html.md#embody.base.Context)
* **Returns:**
  New Context with updated parameters

### *class* embody.base.Embodier(template, strategy='auto', syntax='dollar_brace', strict=False, check_cycles=True, key_collision='error')

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

Main class for embodying templates with parameters.

This is the primary API for the embody framework. It supports:

- Multiple traversal strategies (recursive, compiled, auto)
- Multiple syntax styles
- Strict or lenient parameter checking
- Cycle detection

### Examples

```pycon
>>> template = {'greeting': 'Hello ${name}', 'age': '${age}'}
>>> embodier = Embodier(template)
>>> embodier({'name': 'Alice', 'age': 30})
{'greeting': 'Hello Alice', 'age': 30}
```

```pycon
>>> template = {'count': '${num}'}
>>> embodier = Embodier(template)
>>> embodier({'num': 42})  # Type preserved
{'count': 42}
```

#### get_signature()

Get the list of parameters required by the template.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  List of parameter names

### *exception* embody.base.MissingParameterError

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

Raised when a required template parameter is missing.

### *class* embody.base.TemplateWrapper(template, syntax='dollar_brace', check_cycles=True)

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

Wrapper for template data with introspection capabilities.

This class wraps template data and provides methods to:

- Extract variable dependencies
- Detect cycles
- Parse and validate the template structure

### Examples

```pycon
>>> template = TemplateWrapper({'name': '${user}', 'age': '${years}'})
>>> sorted(template.get_dependencies())
['user', 'years']
```

#### get_dependencies()

Extract all template variables from the template.

* **Return type:**
  [`set`](https://docs.python.org/3/builtins/stdtypes.html#set)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Set of variable names used in the template

#### validate_params(params)

Check which template dependencies are missing from params.

* **Parameters:**
  **params** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict), [`Context`](_autosummary/embody.base.html.md#embody.base.Context)]) – Parameters to check against
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  List of missing parameter names

### embody.base.embody(template, params=None, \*\*kwargs)

Convenience function for template embodiment.

This is the main entry point for simple embodiment use cases.

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – The template to embody
  * **params** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict), [`Context`](_autosummary/embody.base.html.md#embody.base.Context)]) – Parameters for substitution
  * **\*\*kwargs** – Additional parameters or config options
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object

### Examples

```pycon
>>> embody({'name': '${name}'}, {'name': 'Alice'})
{'name': 'Alice'}
```

```pycon
>>> embody({'count': '${n}'}, {'n': 42})
{'count': 42}
```

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


# _autosummary/embody.graphviz_template.html.md

# embody.graphviz_template

Graphviz templates


# _autosummary/embody.html.md

# embody

Generate templated objects with advanced structural embodiment features.

This package provides powerful tools for template-based object generation,
supporting:

- Multiple syntax styles (${var}, {var}, [[var]])
- Type-preserving substitution
- Multiple traversal strategies (recursive, compiled, iterative)
- Cycle detection
- Mapping interfaces with various access patterns
- Path-based addressing (JSON Pointer, dot notation, tuple paths)

Basic usage:

```pycon
>>> from embody import embody
>>> template = {'name': '${name}', 'age': '${age}'}
>>> result = embody(template, {'name': 'Alice', 'age': 30})
>>> result
{'name': 'Alice', 'age': 30}
```

Advanced usage:

```pycon
>>> from embody import Embodier, Context
>>> template = {'greeting': 'Hello ${name}', 'count': '${num}'}
>>> embodier = Embodier(template, syntax='dollar_brace', strict=True)
>>> embodier({'name': 'Alice', 'num': 42})
{'greeting': 'Hello Alice', 'count': 42}
```

### Functions

| [`embody`](_autosummary/embody.html.md#embody.embody)(template[, params])                      | Convenience function for template embodiment.                              |
|--------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------|
| [`get_engine`](_autosummary/embody.html.md#embody.get_engine)([strategy])                          | Get an embodiment engine by name.                                          |
| [`substitute`](_autosummary/embody.html.md#embody.substitute)(template, params[, syntax, strict])  | Perform type-preserving substitution on a template value.                  |
| [`extract_template_vars`](_autosummary/embody.html.md#embody.extract_template_vars)(template[, syntax])       | Extract all template variable names from a string.                         |
| [`is_exact_match`](_autosummary/embody.html.md#embody.is_exact_match)(template[, syntax])              | Check if template is exactly one variable placeholder (no other text).     |
| [`flatten_dict`](_autosummary/embody.html.md#embody.flatten_dict)(nested_dict[, separator, ...])     | Flatten a nested dictionary into a single-level dictionary with path keys. |
| [`unflatten_dict`](_autosummary/embody.html.md#embody.unflatten_dict)(flat_dict[, separator])          | Unflatten a dictionary with path keys into a nested structure.             |
| [`flatten_to_tuples`](_autosummary/embody.html.md#embody.flatten_to_tuples)(obj[, parent_path])           | Flatten a nested structure using tuple paths (unambiguous).                |
| [`unflatten_from_tuples`](_autosummary/embody.html.md#embody.unflatten_from_tuples)(flat_dict)                | Unflatten a dictionary with tuple paths into a nested structure.           |
| [`detect_cycle`](_autosummary/embody.html.md#embody.detect_cycle)(obj[, visited, path])              | Detect cycles in a nested data structure.                                  |
| [`get_by_path`](_autosummary/embody.html.md#embody.get_by_path)(obj, path[, separator, default])    | Get a value from a nested structure by path.                               |
| [`set_by_path`](_autosummary/embody.html.md#embody.set_by_path)(obj, path, value[, separator, ...]) | Set a value in a nested structure by path (modifies in place).             |
| [`max_depth`](_autosummary/embody.html.md#embody.max_depth)(obj[, current_depth])                 | Calculate the maximum depth of a nested structure.                         |
| [`count_template_markers`](_autosummary/embody.html.md#embody.count_template_markers)(obj[, syntax])           | Count the number of template markers in a nested structure.                |
| [`as_mapping`](_autosummary/embody.html.md#embody.as_mapping)(data[, style])                       | Convert data to a Mapping with the specified style.                        |
| [`parse_path`](_autosummary/embody.html.md#embody.parse_path)(path[, format])                      | Parse a path in various formats.                                           |
| [`resolve_path`](_autosummary/embody.html.md#embody.resolve_path)(data, path[, default, format])     | Resolve a path against data.                                               |
| [`set_path`](_autosummary/embody.html.md#embody.set_path)(data, path, value[, format, ...])      | Set a value at a path.                                                     |

### Classes

| [`Embodier`](_autosummary/embody.html.md#embody.Embodier)(template[, strategy, syntax, ...])       | Main class for embodying templates with parameters.                  |
|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|
| [`Context`](_autosummary/embody.html.md#embody.Context)([params, parent, resolvers, auto_call])   | Parameter store for template embodiment with support for resolvers.  |
| [`TemplateWrapper`](_autosummary/embody.html.md#embody.TemplateWrapper)(template[, syntax, check_cycles]) | Wrapper for template data with introspection capabilities.           |
| `Templater`()                                                                                      |                                                                      |
| [`RecursiveVisitorEngine`](_autosummary/embody.html.md#embody.RecursiveVisitorEngine)([syntax, strict, ...])     | Dynamic traversal strategy using the Visitor pattern.                |
| [`CompiledPathEngine`](_autosummary/embody.html.md#embody.CompiledPathEngine)(\*args, \*\*kwargs)            | Pre-compiled path-based traversal strategy.                          |
| [`IterativeStackEngine`](_autosummary/embody.html.md#embody.IterativeStackEngine)([syntax, strict, ...])       | Iterative stack-based traversal strategy.                            |
| [`SubstitutionSyntax`](_autosummary/embody.html.md#embody.SubstitutionSyntax)()                              | Defines the syntax patterns for template variable substitution.      |
| [`EmbodiedMapping`](_autosummary/embody.html.md#embody.EmbodiedMapping)(data)                             | Read-only Mapping wrapper for embodied objects with lazy evaluation. |
| [`LazyEmbodiedMapping`](_autosummary/embody.html.md#embody.LazyEmbodiedMapping)(template, params, embodier)   | Lazy Mapping that embodies values on access.                         |
| [`FlatMapping`](_autosummary/embody.html.md#embody.FlatMapping)(data[, separator])                    | Mapping with flattened nested structure for path-based access.       |
| [`AttributeMapping`](_autosummary/embody.html.md#embody.AttributeMapping)(data)                            | Mapping that allows attribute access (Box pattern).                  |
| [`FrozenMapping`](_autosummary/embody.html.md#embody.FrozenMapping)(data)                               | Immutable Mapping wrapper.                                           |
| [`MutableEmbodiedMapping`](_autosummary/embody.html.md#embody.MutableEmbodiedMapping)(data)                      | Mutable Mapping wrapper for embodied objects.                        |
| [`PathMapping`](_autosummary/embody.html.md#embody.PathMapping)(data[, separator])                    | Mapping supporting multiple path access styles.                      |
| [`JSONPointer`](_autosummary/embody.html.md#embody.JSONPointer)(pointer)                              | JSON Pointer implementation (RFC 6901).                              |
| [`DotPath`](_autosummary/embody.html.md#embody.DotPath)(path[, separator])                        | Dot notation path handler (e.g., 'user.address.city').               |
| [`TuplePath`](_autosummary/embody.html.md#embody.TuplePath)(parts)                                  | Tuple-based path (unambiguous, e.g., ('user', 'address', 'city')).   |

### Exceptions

| [`MissingParameterError`](_autosummary/embody.html.md#embody.MissingParameterError)   | Raised when a required template parameter is missing.             |
|--------------------------------------------------------------------------|-------------------------------------------------------------------|
| [`KeyCollisionError`](_autosummary/embody.html.md#embody.KeyCollisionError)       | Raised when dynamic keys resolve to the same value.               |
| [`CycleError`](_autosummary/embody.html.md#embody.CycleError)              | Raised when a circular reference is detected in a data structure. |
| [`PathNotFoundError`](_autosummary/embody.html.md#embody.PathNotFoundError)       | Raised when a path doesn't exist in a data structure.             |
| [`InvalidPathError`](_autosummary/embody.html.md#embody.InvalidPathError)        | Raised when a path is malformed or invalid.                       |

### *class* embody.AttributeMapping(data)

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

Mapping that allows attribute access (Box pattern).

Allows accessing dictionary keys as attributes for more fluid syntax.

### Examples

```pycon
>>> data = {'user': {'name': 'Alice', 'age': 30}}
>>> attr_map = AttributeMapping(data)
>>> attr_map.user.name
'Alice'
>>> attr_map.user.age
30
>>> attr_map['user']['name']  # Still works as dict
'Alice'
```

#### to_dict()

Convert back to plain dictionary.

* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)
* **Returns:**
  Plain dictionary

### *class* embody.CompiledPathEngine(\*args, \*\*kwargs)

Bases: [`BaseEmbodimentEngine`](_autosummary/embody.strategies.html.md#embody.strategies.BaseEmbodimentEngine)

Pre-compiled path-based traversal strategy.

This engine flattens the template into a path map, performs substitutions,
and then reconstructs the structure. It’s best for:

- Templates embodied repeatedly (e.g., API responses)
- Static templates with known structure
- Performance-critical paths

The compilation happens once, then embodiment is a linear scan.

### Examples

```pycon
>>> engine = CompiledPathEngine()
>>> template = {'a': {'b': '${x}'}, 'c': '${y}'}
>>> compiled = engine.compile(template)
>>> engine.embody_compiled(compiled, {'x': 1, 'y': 2})
{'a': {'b': 1}, 'c': 2}
```

#### compile(template)

Compile a template into a flat path map.

* **Parameters:**
  **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Template to compile
* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)
* **Returns:**
  Compiled template data

### Examples

```pycon
>>> engine = CompiledPathEngine()
>>> template = {'a': {'b': '${x}'}}
>>> compiled = engine.compile(template)
>>> compiled['flat']
{('a', 'b'): '${x}'}
```

#### embody(template, params)

Embody a template (compiles on first use, caches compilation).

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Template to embody
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for substitution
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object

#### embody_compiled(compiled, params)

Embody a pre-compiled template.

* **Parameters:**
  * **compiled** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)) – Compiled template from compile()
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for substitution
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object

### *class* embody.Context(params=None, parent=None, resolvers=None, auto_call=True)

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

Parameter store for template embodiment with support for resolvers.

The Context holds parameters for substitution and supports:

- Hierarchical scoping (global → local overrides)
- Resolver functions (lazy evaluation)
- Callable values that are invoked on access

### Examples

```pycon
>>> ctx = Context({'name': 'Alice', 'age': 30})
>>> ctx['name']
'Alice'
```

```pycon
>>> import datetime
>>> ctx = Context({'now': lambda: datetime.datetime.now()})
>>> ctx['now']
datetime.datetime(...)
```

```pycon
>>> ctx = Context({'base': 10}, parent={'base': 5, 'other': 20})
>>> ctx['base']  # Local overrides parent
10
>>> ctx['other']  # Falls back to parent
20
```

#### child(params=None)

Create a child context with this context as parent.

* **Parameters:**
  **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for the child context
* **Return type:**
  [`Context`](_autosummary/embody.base.html.md#embody.base.Context)
* **Returns:**
  New Context with this as parent

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

Get a parameter with a default value.

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

#### register_resolver(name, func)

Register a named resolver function.

* **Parameters:**
  * **name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Name of the resolver
  * **func** ([`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)) – Callable that returns the resolved value

### Examples

```pycon
>>> import os
>>> ctx = Context()
>>> ctx.register_resolver('env', lambda: os.environ.get('USER', 'unknown'))
```

#### to_dict()

Convert to a plain dictionary (resolving all values).

* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]
* **Returns:**
  Dictionary with all parameters resolved

#### update(params)

Create a new context with updated parameters.

* **Parameters:**
  **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters to add/override
* **Return type:**
  [`Context`](_autosummary/embody.base.html.md#embody.base.Context)
* **Returns:**
  New Context with updated parameters

### *exception* embody.CycleError

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

Raised when a circular reference is detected in a data structure.

### *class* embody.DotPath(path, separator='.')

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

Dot notation path handler (e.g., ‘user.address.city’).

### Examples

```pycon
>>> data = {'user': {'address': {'city': 'NYC'}}}
>>> path = DotPath('user.address.city')
>>> path.resolve(data)
'NYC'
```

#### resolve(data, default=None)

Resolve the path against data.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to resolve against
  * **default** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Default value if resolution fails
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Resolved value or default

#### to_json_pointer()

Convert to a JSON Pointer.

* **Return type:**
  [`JSONPointer`](_autosummary/embody.paths.html.md#embody.paths.JSONPointer)
* **Returns:**
  JSONPointer instance

### *class* embody.EmbodiedMapping(data)

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

Read-only Mapping wrapper for embodied objects with lazy evaluation.

This wrapper provides a Mapping interface around an embodied object,
with support for lazy embodiment (values materialized on access).

### Examples

```pycon
>>> from embody import embody
>>> template = {'name': '${name}', 'age': '${age}'}
>>> params = {'name': 'Alice', 'age': 30}
>>> # Embody eagerly first
>>> data = embody(template, params)
>>> mapping = EmbodiedMapping(data)
>>> mapping['name']
'Alice'
>>> len(mapping)
2
```

### *class* embody.Embodier(template, strategy='auto', syntax='dollar_brace', strict=False, check_cycles=True, key_collision='error')

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

Main class for embodying templates with parameters.

This is the primary API for the embody framework. It supports:

- Multiple traversal strategies (recursive, compiled, auto)
- Multiple syntax styles
- Strict or lenient parameter checking
- Cycle detection

### Examples

```pycon
>>> template = {'greeting': 'Hello ${name}', 'age': '${age}'}
>>> embodier = Embodier(template)
>>> embodier({'name': 'Alice', 'age': 30})
{'greeting': 'Hello Alice', 'age': 30}
```

```pycon
>>> template = {'count': '${num}'}
>>> embodier = Embodier(template)
>>> embodier({'num': 42})  # Type preserved
{'count': 42}
```

#### get_signature()

Get the list of parameters required by the template.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  List of parameter names

### *class* embody.FlatMapping(data, separator='.')

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

Mapping with flattened nested structure for path-based access.

Allows accessing nested values using dot notation as single keys.

### Examples

```pycon
>>> nested = {'user': {'name': 'Alice', 'age': 30}}
>>> flat = FlatMapping(nested)
>>> flat['user.name']
'Alice'
>>> flat['user.age']
30
>>> list(flat.keys())
['user.name', 'user.age']
```

#### get_nested(\*path_parts)

Get a value by path components.

* **Parameters:**
  **\*path_parts** – Path components
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Value at path

### Examples

```pycon
>>> nested = {'a': {'b': {'c': 42}}}
>>> flat = FlatMapping(nested)
>>> flat.get_nested('a', 'b', 'c')
42
```

### *class* embody.FrozenMapping(data)

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

Immutable Mapping wrapper.

Provides a frozen (immutable) view of a dictionary.

### Examples

```pycon
>>> data = {'a': 1, 'b': 2}
>>> frozen = FrozenMapping(data)
>>> frozen['a']
1
>>> # Modifications to original don't affect frozen (deep copy)
>>> data['c'] = 3
>>> 'c' in frozen
False
```

### *exception* embody.InvalidPathError

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

Raised when a path is malformed or invalid.

### *class* embody.IterativeStackEngine(syntax='dollar_brace', strict=False, key_collision='error')

Bases: [`BaseEmbodimentEngine`](_autosummary/embody.strategies.html.md#embody.strategies.BaseEmbodimentEngine)

Iterative stack-based traversal strategy.

This engine uses an explicit stack instead of recursion, which is more
memory-efficient for very deep structures and avoids Python’s recursion limit.

Best for:

- Very deeply nested structures (>100 levels)
- When recursion depth is a concern

#### embody(template, params)

Embody using iterative stack-based traversal.

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Template to embody
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for substitution
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object

### *class* embody.JSONPointer(pointer)

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

JSON Pointer implementation (RFC 6901).

JSON Pointer defines a string syntax for identifying a specific value
within a JSON document. Example: /foo/bar/0 refers to the first element
of the ‘bar’ array in the ‘foo’ object.

### Examples

```pycon
>>> data = {'foo': {'bar': [1, 2, 3]}}
>>> ptr = JSONPointer('/foo/bar/0')
>>> ptr.resolve(data)
1
```

```pycon
>>> data = {'user': {'name': 'Alice', 'age': 30}}
>>> JSONPointer('/user/name').resolve(data)
'Alice'
```

#### *classmethod* from_parts(parts)

Create a JSON Pointer from path components.

* **Parameters:**
  **parts** ([`List`](https://docs.python.org/3/library/typing.html#typing.List)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – List of path components
* **Return type:**
  [`JSONPointer`](_autosummary/embody.paths.html.md#embody.paths.JSONPointer)
* **Returns:**
  JSONPointer instance

### Examples

```pycon
>>> ptr = JSONPointer.from_parts(['foo', 'bar', '0'])
>>> ptr.pointer
'/foo/bar/0'
```

#### resolve(data, default=None)

Resolve the pointer against data.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to resolve against
  * **default** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Default value if resolution fails
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Resolved value or default

### Examples

```pycon
>>> data = {'a': {'b': [1, 2, 3]}}
>>> JSONPointer('/a/b/1').resolve(data)
2
>>> JSONPointer('/a/x').resolve(data, default='not found')
'not found'
```

#### set(data, value, create_intermediate=False)

Set a value at the pointer location.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to modify (in place)
  * **value** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Value to set
  * **create_intermediate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, create intermediate structures
* **Raises:**
  [**InvalidPathError**](_autosummary/embody.html.md#embody.InvalidPathError) – If path cannot be set

### Examples

```pycon
>>> data = {'a': {'b': {}}}
>>> JSONPointer('/a/b/c').set(data, 42)
>>> data
{'a': {'b': {'c': 42}}}
```

### *exception* embody.KeyCollisionError

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

Raised when dynamic keys resolve to the same value.

### *class* embody.LazyEmbodiedMapping(template, params, embodier)

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

Lazy Mapping that embodies values on access.

This is useful for large templates where you only need to access
a subset of values. Values are embodied on-demand and cached.

### Examples

```pycon
>>> from embody import Embodier
>>> template = {'a': '${x}', 'b': '${y}', 'c': '${z}'}
>>> params = {'x': 1, 'y': 2, 'z': 3}
>>> embodier = Embodier(template)
>>> lazy = LazyEmbodiedMapping(template, params, embodier)
>>> lazy['a']  # Only 'a' is embodied
1
```

### *exception* embody.MissingParameterError

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

Raised when a required template parameter is missing.

### *class* embody.MutableEmbodiedMapping(data)

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

Mutable Mapping wrapper for embodied objects.

Provides full MutableMapping interface for modifying embodied results.

### Examples

```pycon
>>> data = {'a': 1, 'b': 2}
>>> mutable = MutableEmbodiedMapping(data)
>>> mutable['c'] = 3
>>> mutable['a'] = 10
>>> del mutable['b']
>>> dict(mutable)
{'a': 10, 'c': 3}
```

#### freeze()

Convert to an immutable FrozenMapping.

* **Return type:**
  [`FrozenMapping`](_autosummary/embody.mappings.html.md#embody.mappings.FrozenMapping)
* **Returns:**
  Frozen version of this mapping

### *class* embody.PathMapping(data, separator='.')

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

Mapping supporting multiple path access styles.

Supports:

- Regular dict access: mapping[‘key’]
- Dot notation: mapping[‘a.b.c’]
- Tuple paths: mapping[(‘a’, ‘b’, ‘c’)]
- JSON Pointer: mapping[‘/a/b/c’]

### Examples

```pycon
>>> data = {'a': {'b': {'c': 42}}}
>>> pm = PathMapping(data)
>>> pm['a.b.c']
42
>>> pm[('a', 'b', 'c')]
42
>>> pm['/a/b/c']  # JSON Pointer
42
>>> pm['a']  # Regular access
{'b': {'c': 42}}
```

### *exception* embody.PathNotFoundError

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

Raised when a path doesn’t exist in a data structure.

### *class* embody.RecursiveVisitorEngine(syntax='dollar_brace', strict=False, key_collision='error')

Bases: [`BaseEmbodimentEngine`](_autosummary/embody.strategies.html.md#embody.strategies.BaseEmbodimentEngine)

Dynamic traversal strategy using the Visitor pattern.

This engine recursively walks the template structure at runtime,
visiting each node and performing substitutions. It’s best for:

- One-off templates
- Dynamic templates with conditional logic
- Templates where structure changes based on parameters

### Examples

```pycon
>>> engine = RecursiveVisitorEngine()
>>> template = {'greeting': 'Hello ${name}', 'count': '${num}'}
>>> engine.embody(template, {'name': 'Alice', 'num': 42})
{'greeting': 'Hello Alice', 'count': 42}
```

#### embody(template, params, visited=None)

Recursively embody a template.

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Template to embody
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for substitution
  * **visited** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Set`](https://docs.python.org/3/library/typing.html#typing.Set)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]]) – Set of visited object IDs (for cycle detection)
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object
* **Raises:**
  [**CycleError**](_autosummary/embody.html.md#embody.CycleError) – If a circular reference is detected

### *class* embody.SubstitutionSyntax

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

Defines the syntax patterns for template variable substitution.

#### *classmethod* get_pattern(syntax='dollar_brace')

Get the regex pattern for the specified syntax.

* **Parameters:**
  **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – One of ‘dollar_brace’, ‘brace’, ‘double_bracket’
* **Return type:**
  [`Pattern`](https://docs.python.org/3/library/typing.html#typing.Pattern)
* **Returns:**
  Compiled regex pattern

### Examples

```pycon
>>> pattern = SubstitutionSyntax.get_pattern('dollar_brace')
>>> pattern.findall('${name} is ${age}')
['name', 'age']
```

### *class* embody.TemplateWrapper(template, syntax='dollar_brace', check_cycles=True)

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

Wrapper for template data with introspection capabilities.

This class wraps template data and provides methods to:

- Extract variable dependencies
- Detect cycles
- Parse and validate the template structure

### Examples

```pycon
>>> template = TemplateWrapper({'name': '${user}', 'age': '${years}'})
>>> sorted(template.get_dependencies())
['user', 'years']
```

#### get_dependencies()

Extract all template variables from the template.

* **Return type:**
  [`set`](https://docs.python.org/3/builtins/stdtypes.html#set)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Set of variable names used in the template

#### validate_params(params)

Check which template dependencies are missing from params.

* **Parameters:**
  **params** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict), [`Context`](_autosummary/embody.base.html.md#embody.base.Context)]) – Parameters to check against
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  List of missing parameter names

### *class* embody.TuplePath(parts)

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

Tuple-based path (unambiguous, e.g., (‘user’, ‘address’, ‘city’)).

### Examples

```pycon
>>> data = {'user': {'address': {'city': 'NYC'}}}
>>> path = TuplePath(('user', 'address', 'city'))
>>> path.resolve(data)
'NYC'
```

#### resolve(data, default=None)

Resolve the path against data.

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

#### to_json_pointer()

Convert to a JSON Pointer.

* **Return type:**
  [`JSONPointer`](_autosummary/embody.paths.html.md#embody.paths.JSONPointer)

### embody.as_mapping(data, style='basic')

Convert data to a Mapping with the specified style.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to wrap
  * **style** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Style of mapping (‘basic’, ‘attribute’, ‘flat’, ‘path’, ‘frozen’)
* **Return type:**
  [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)
* **Returns:**
  Mapping instance

### Examples

```pycon
>>> data = {'user': {'name': 'Alice'}}
>>> m = as_mapping(data, 'attribute')
>>> m.user.name
'Alice'
```

```pycon
>>> m = as_mapping(data, 'flat')
>>> m['user.name']
'Alice'
```

### embody.count_template_markers(obj, syntax='dollar_brace')

Count the number of template markers in a nested structure.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Object to count markers in
  * **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Template syntax to look for
* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)
* **Returns:**
  Number of template markers found

### Examples

```pycon
>>> count_template_markers({'a': '${x}', 'b': '${y}'})
2
>>> count_template_markers(['${a}', 'literal', '${b} and ${c}'])
3
```

### embody.detect_cycle(obj, visited=None, path=None)

Detect cycles in a nested data structure.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – The object to check for cycles
  * **visited** ([`Set`](https://docs.python.org/3/library/typing.html#typing.Set)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Set of object IDs already visited
  * **path** ([`List`](https://docs.python.org/3/library/typing.html#typing.List)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Current path in the structure (for error reporting)
* **Raises:**
  [**CycleError**](_autosummary/embody.html.md#embody.CycleError) – If a cycle is detected
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### Examples

```pycon
>>> d = {'a': 1, 'b': [2, 3]}
>>> detect_cycle(d)  # No cycle, returns None
```

```pycon
>>> circular = {'a': 1}
>>> circular['self'] = circular
>>> try:
...     detect_cycle(circular)
... except CycleError as e:
...     print("Cycle detected")
Cycle detected
```

### embody.embody(template, params=None, \*\*kwargs)

Convenience function for template embodiment.

This is the main entry point for simple embodiment use cases.

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – The template to embody
  * **params** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict), [`Context`](_autosummary/embody.base.html.md#embody.base.Context)]) – Parameters for substitution
  * **\*\*kwargs** – Additional parameters or config options
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object

### Examples

```pycon
>>> embody({'name': '${name}'}, {'name': 'Alice'})
{'name': 'Alice'}
```

```pycon
>>> embody({'count': '${n}'}, {'n': 42})
{'count': 42}
```

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

### embody.extract_template_vars(template, syntax='dollar_brace')

Extract all template variable names from a string.

* **Parameters:**
  * **template** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Template string containing variables
  * **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Variable syntax to use
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  List of variable names found in the template

### Examples

```pycon
>>> extract_template_vars('Hello ${name}, you are ${age} years old')
['name', 'age']
>>> extract_template_vars('Hello {name}', syntax='brace')
['name']
```

### embody.flatten_dict(nested_dict, separator='.', parent_key='')

Flatten a nested dictionary into a single-level dictionary with path keys.

* **Parameters:**
  * **nested_dict** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Nested dictionary to flatten
  * **separator** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – String to use for separating path components
  * **parent_key** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Key of the parent (used in recursion)
* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]
* **Returns:**
  Flattened dictionary with path keys

### Examples

```pycon
>>> d = {'a': {'b': {'c': 1}}, 'd': 2}
>>> flatten_dict(d)
{'a.b.c': 1, 'd': 2}
```

```pycon
>>> d = {'user': {'name': 'Alice', 'age': 30}}
>>> flatten_dict(d)
{'user.name': 'Alice', 'user.age': 30}
```

```pycon
>>> d = {'items': [1, 2, 3]}
>>> flatten_dict(d)
{'items.0': 1, 'items.1': 2, 'items.2': 3}
```

### embody.flatten_to_tuples(obj, parent_path=())

Flatten a nested structure using tuple paths (unambiguous).

This avoids the ambiguity of string separators. A tuple path like
(‘a’, ‘b’, 0) is unambiguous, while ‘a.b.0’ could mean multiple things
if keys contain dots.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Object to flatten
  * **parent_path** ([`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple)) – Current path as tuple
* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]
* **Returns:**
  Dictionary mapping tuple paths to values

### Examples

```pycon
>>> d = {'a': {'b': [1, 2]}}
>>> flatten_to_tuples(d)
{('a', 'b', 0): 1, ('a', 'b', 1): 2}
```

### embody.get_by_path(obj, path, separator='.', default=None)

Get a value from a nested structure by path.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Nested structure
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple)]) – Path as string or tuple
  * **separator** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Separator for string paths
  * **default** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Default value if path not found
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Value at the path, or default if not found

### Examples

```pycon
>>> d = {'a': {'b': {'c': 42}}}
>>> get_by_path(d, 'a.b.c')
42
>>> get_by_path(d, ('a', 'b', 'c'))
42
>>> get_by_path(d, 'a.b.x', default='not found')
'not found'
```

### embody.get_engine(strategy='recursive', \*\*kwargs)

Get an embodiment engine by name.

* **Parameters:**
  * **strategy** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Name of strategy (‘recursive’, ‘compiled’, ‘iterative’)
  * **\*\*kwargs** – Arguments to pass to engine constructor
* **Return type:**
  [`BaseEmbodimentEngine`](_autosummary/embody.strategies.html.md#embody.strategies.BaseEmbodimentEngine)
* **Returns:**
  Embodiment engine instance

### Examples

```pycon
>>> engine = get_engine('recursive', syntax='brace')
>>> isinstance(engine, RecursiveVisitorEngine)
True
```

### embody.is_exact_match(template, syntax='dollar_brace')

Check if template is exactly one variable placeholder (no other text).

This is crucial for type preservation. If the template is exactly ${var},
we should return the raw value, not convert it to a string.

* **Parameters:**
  * **template** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Template string to check
  * **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Variable syntax to use
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Variable name if exact match, None otherwise

### Examples

```pycon
>>> is_exact_match('${name}')
'name'
>>> is_exact_match('Hello ${name}')
```

```pycon
>>> is_exact_match('${count}')
'count'
```

### embody.max_depth(obj, current_depth=0)

Calculate the maximum depth of a nested structure.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Object to measure
  * **current_depth** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Current depth (used in recursion)
* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)
* **Returns:**
  Maximum depth

### Examples

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

### embody.parse_path(path, format='auto')

Parse a path in various formats.

* **Parameters:**
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`List`](https://docs.python.org/3/library/typing.html#typing.List)]) – Path in any supported format
  * **format** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Format hint (‘auto’, ‘json_pointer’, ‘dot’, ‘tuple’)
* **Return type:**
  [`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`JSONPointer`](_autosummary/embody.paths.html.md#embody.paths.JSONPointer), [`DotPath`](_autosummary/embody.paths.html.md#embody.paths.DotPath), [`TuplePath`](_autosummary/embody.paths.html.md#embody.paths.TuplePath)]
* **Returns:**
  Path object

### Examples

```pycon
>>> parse_path('/user/name')
<embody.paths.JSONPointer object at ...>
```

```pycon
>>> parse_path('user.name')
<embody.paths.DotPath object at ...>
```

```pycon
>>> parse_path(('user', 'name'))
<embody.paths.TuplePath object at ...>
```

### embody.resolve_path(data, path, default=None, format='auto')

Resolve a path against data.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to resolve against
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`List`](https://docs.python.org/3/library/typing.html#typing.List)]) – Path in any supported format
  * **default** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Default value if resolution fails
  * **format** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Format hint
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Resolved value or default

### Examples

```pycon
>>> data = {'user': {'name': 'Alice', 'age': 30}}
>>> resolve_path(data, '/user/name')
'Alice'
>>> resolve_path(data, 'user.age')
30
>>> resolve_path(data, ('user', 'name'))
'Alice'
```

### embody.set_by_path(obj, path, value, separator='.', create_intermediate=True)

Set a value in a nested structure by path (modifies in place).

* **Parameters:**
  * **obj** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)) – Nested structure to modify
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple)]) – Path as string or tuple
  * **value** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Value to set
  * **separator** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Separator for string paths
  * **create_intermediate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, create intermediate dicts/lists as needed
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### Examples

```pycon
>>> d = {}
>>> set_by_path(d, 'a.b.c', 42)
>>> d
{'a': {'b': {'c': 42}}}
```

### embody.set_path(data, path, value, format='auto', create_intermediate=True)

Set a value at a path.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to modify
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`List`](https://docs.python.org/3/library/typing.html#typing.List)]) – Path in any supported format
  * **value** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Value to set
  * **format** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Format hint
  * **create_intermediate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, create intermediate structures

### Examples

```pycon
>>> data = {}
>>> set_path(data, '/user/name', 'Alice')
>>> data
{'user': {'name': 'Alice'}}
```

### embody.substitute(template, params, syntax='dollar_brace', strict=False)

Perform type-preserving substitution on a template value.

This is the core substitution function. It handles:

1. Exact match: ${var} -> returns params[‘var’] with type preserved
2. Partial match: “Count is ${var}” -> string interpolation
3. Non-string templates: returned unchanged

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – The template value (can be any type)
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Dictionary of parameters for substitution
  * **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Variable syntax to use
  * **strict** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, raise KeyError for missing variables
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  The substituted value with type preservation

### Examples

```pycon
>>> substitute('${count}', {'count': 42})
42
>>> substitute('Count: ${count}', {'count': 42})
'Count: 42'
>>> substitute('${active}', {'active': True})
True
>>> substitute('${items}', {'items': [1, 2, 3]})
[1, 2, 3]
>>> substitute(42, {})
42
```

### embody.unflatten_dict(flat_dict, separator='.')

Unflatten a dictionary with path keys into a nested structure.

* **Parameters:**
  * **flat_dict** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Flattened dictionary with path keys
  * **separator** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – String used for separating path components
* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]
* **Returns:**
  Nested dictionary structure

### Examples

```pycon
>>> flat = {'a.b.c': 1, 'd': 2}
>>> unflatten_dict(flat)
{'a': {'b': {'c': 1}}, 'd': 2}
```

```pycon
>>> flat = {'items.0': 'a', 'items.1': 'b'}
>>> unflatten_dict(flat)
{'items': ['a', 'b']}
```

### embody.unflatten_from_tuples(flat_dict)

Unflatten a dictionary with tuple paths into a nested structure.

* **Parameters:**
  **flat_dict** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Dictionary with tuple paths as keys
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Nested structure (dict or list)

### Examples

```pycon
>>> flat = {('a', 'b', 0): 1, ('a', 'b', 1): 2}
>>> unflatten_from_tuples(flat)
{'a': {'b': [1, 2]}}
```

### Modules

| [`base`](_autosummary/embody.base.html.md#module-embody.base)                           | Core classes for embody: Context, Template, and Embodier.                                                      |
|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------|
| [`graphviz_template`](_autosummary/embody.graphviz_template.html.md#module-embody.graphviz_template) | Graphviz templates                                                                                             |
| [`mappings`](_autosummary/embody.mappings.html.md#module-embody.mappings)                   | Mapping interface wrappers for embodied objects.                                                               |
| [`naming`](_autosummary/embody.naming.html.md#module-embody.naming)                       | This module is about generating, validating, and operating on (parametrized) fields (i.e. stings, e.g. paths). |
| [`paths`](_autosummary/embody.paths.html.md#module-embody.paths)                         | Path addressing for nested data structures.                                                                    |
| [`strategies`](_autosummary/embody.strategies.html.md#module-embody.strategies)               | Traversal strategies for template embodiment.                                                                  |
| [`substitution`](_autosummary/embody.substitution.html.md#module-embody.substitution)           | Pattern matching and type-preserving substitution logic for templates.                                         |
| [`templater`](_autosummary/embody.templater.html.md#module-embody.templater)                 | Base objects for definding templates                                                                           |
| [`templating`](_autosummary/embody.templating.html.md#module-embody.templating)               | Making templates for various objects                                                                           |
| [`util`](_autosummary/embody.util.html.md#module-embody.util)                           | Utility functions for embody: flattening, unflattening, and cycle detection.                                   |


# _autosummary/embody.mappings.html.md

# embody.mappings

Mapping interface wrappers for embodied objects.

This module provides wrappers that convert nested structures into
uniform Mapping interfaces, supporting:

- Lazy evaluation
- Attribute access (Box pattern)
- Flat path-based access
- Immutability (frozen objects)

### Functions

| [`as_mapping`](_autosummary/embody.mappings.html.md#embody.mappings.as_mapping)(data[, style])   | Convert data to a Mapping with the specified style.   |
|------------------------------------------------------------------------------|-------------------------------------------------------|

### Classes

| [`AttributeMapping`](_autosummary/embody.mappings.html.md#embody.mappings.AttributeMapping)(data)                          | Mapping that allows attribute access (Box pattern).                  |
|--------------------------------------------------------------------------------------------------|----------------------------------------------------------------------|
| [`EmbodiedMapping`](_autosummary/embody.mappings.html.md#embody.mappings.EmbodiedMapping)(data)                           | Read-only Mapping wrapper for embodied objects with lazy evaluation. |
| [`FlatMapping`](_autosummary/embody.mappings.html.md#embody.mappings.FlatMapping)(data[, separator])                  | Mapping with flattened nested structure for path-based access.       |
| [`FrozenMapping`](_autosummary/embody.mappings.html.md#embody.mappings.FrozenMapping)(data)                             | Immutable Mapping wrapper.                                           |
| [`LazyEmbodiedMapping`](_autosummary/embody.mappings.html.md#embody.mappings.LazyEmbodiedMapping)(template, params, embodier) | Lazy Mapping that embodies values on access.                         |
| [`MutableEmbodiedMapping`](_autosummary/embody.mappings.html.md#embody.mappings.MutableEmbodiedMapping)(data)                    | Mutable Mapping wrapper for embodied objects.                        |
| [`PathMapping`](_autosummary/embody.mappings.html.md#embody.mappings.PathMapping)(data[, separator])                  | Mapping supporting multiple path access styles.                      |

### *class* embody.mappings.AttributeMapping(data)

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

Mapping that allows attribute access (Box pattern).

Allows accessing dictionary keys as attributes for more fluid syntax.

### Examples

```pycon
>>> data = {'user': {'name': 'Alice', 'age': 30}}
>>> attr_map = AttributeMapping(data)
>>> attr_map.user.name
'Alice'
>>> attr_map.user.age
30
>>> attr_map['user']['name']  # Still works as dict
'Alice'
```

#### to_dict()

Convert back to plain dictionary.

* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)
* **Returns:**
  Plain dictionary

### *class* embody.mappings.EmbodiedMapping(data)

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

Read-only Mapping wrapper for embodied objects with lazy evaluation.

This wrapper provides a Mapping interface around an embodied object,
with support for lazy embodiment (values materialized on access).

### Examples

```pycon
>>> from embody import embody
>>> template = {'name': '${name}', 'age': '${age}'}
>>> params = {'name': 'Alice', 'age': 30}
>>> # Embody eagerly first
>>> data = embody(template, params)
>>> mapping = EmbodiedMapping(data)
>>> mapping['name']
'Alice'
>>> len(mapping)
2
```

### *class* embody.mappings.FlatMapping(data, separator='.')

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

Mapping with flattened nested structure for path-based access.

Allows accessing nested values using dot notation as single keys.

### Examples

```pycon
>>> nested = {'user': {'name': 'Alice', 'age': 30}}
>>> flat = FlatMapping(nested)
>>> flat['user.name']
'Alice'
>>> flat['user.age']
30
>>> list(flat.keys())
['user.name', 'user.age']
```

#### get_nested(\*path_parts)

Get a value by path components.

* **Parameters:**
  **\*path_parts** – Path components
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Value at path

### Examples

```pycon
>>> nested = {'a': {'b': {'c': 42}}}
>>> flat = FlatMapping(nested)
>>> flat.get_nested('a', 'b', 'c')
42
```

### *class* embody.mappings.FrozenMapping(data)

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

Immutable Mapping wrapper.

Provides a frozen (immutable) view of a dictionary.

### Examples

```pycon
>>> data = {'a': 1, 'b': 2}
>>> frozen = FrozenMapping(data)
>>> frozen['a']
1
>>> # Modifications to original don't affect frozen (deep copy)
>>> data['c'] = 3
>>> 'c' in frozen
False
```

### *class* embody.mappings.LazyEmbodiedMapping(template, params, embodier)

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

Lazy Mapping that embodies values on access.

This is useful for large templates where you only need to access
a subset of values. Values are embodied on-demand and cached.

### Examples

```pycon
>>> from embody import Embodier
>>> template = {'a': '${x}', 'b': '${y}', 'c': '${z}'}
>>> params = {'x': 1, 'y': 2, 'z': 3}
>>> embodier = Embodier(template)
>>> lazy = LazyEmbodiedMapping(template, params, embodier)
>>> lazy['a']  # Only 'a' is embodied
1
```

### *class* embody.mappings.MutableEmbodiedMapping(data)

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

Mutable Mapping wrapper for embodied objects.

Provides full MutableMapping interface for modifying embodied results.

### Examples

```pycon
>>> data = {'a': 1, 'b': 2}
>>> mutable = MutableEmbodiedMapping(data)
>>> mutable['c'] = 3
>>> mutable['a'] = 10
>>> del mutable['b']
>>> dict(mutable)
{'a': 10, 'c': 3}
```

#### freeze()

Convert to an immutable FrozenMapping.

* **Return type:**
  [`FrozenMapping`](_autosummary/embody.mappings.html.md#embody.mappings.FrozenMapping)
* **Returns:**
  Frozen version of this mapping

### *class* embody.mappings.PathMapping(data, separator='.')

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

Mapping supporting multiple path access styles.

Supports:

- Regular dict access: mapping[‘key’]
- Dot notation: mapping[‘a.b.c’]
- Tuple paths: mapping[(‘a’, ‘b’, ‘c’)]
- JSON Pointer: mapping[‘/a/b/c’]

### Examples

```pycon
>>> data = {'a': {'b': {'c': 42}}}
>>> pm = PathMapping(data)
>>> pm['a.b.c']
42
>>> pm[('a', 'b', 'c')]
42
>>> pm['/a/b/c']  # JSON Pointer
42
>>> pm['a']  # Regular access
{'b': {'c': 42}}
```

### embody.mappings.as_mapping(data, style='basic')

Convert data to a Mapping with the specified style.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to wrap
  * **style** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Style of mapping (‘basic’, ‘attribute’, ‘flat’, ‘path’, ‘frozen’)
* **Return type:**
  [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)
* **Returns:**
  Mapping instance

### Examples

```pycon
>>> data = {'user': {'name': 'Alice'}}
>>> m = as_mapping(data, 'attribute')
>>> m.user.name
'Alice'
```

```pycon
>>> m = as_mapping(data, 'flat')
>>> m['user.name']
'Alice'
```


# _autosummary/embody.naming.html.md

# embody.naming

This module is about generating, validating, and operating on (parametrized) fields
(i.e. stings, e.g. paths).

### Functions

| [`dict_to_namedtuple`](_autosummary/embody.naming.html.md#embody.naming.dict_to_namedtuple)(d[, namedtuple_obj])           |                                                                                                                                                                                                                      |
|----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`get_fields_from_template`](_autosummary/embody.naming.html.md#embody.naming.get_fields_from_template)(template)                | Get list from {item} items of template string                                                                                                                                                                        |
| `mk_capture_patterns`(mapping_dict)                                                                |                                                                                                                                                                                                                      |
| `mk_extract_pattern`(template[, format_dict, ...])                                                 |                                                                                                                                                                                                                      |
| `mk_format_mapping_dict`(format_dict, ...[, sep])                                                  |                                                                                                                                                                                                                      |
| [`mk_kwargs_trans`](_autosummary/embody.naming.html.md#embody.naming.mk_kwargs_trans)(\*\*trans_func_for_key)           | Make a dict transformer from functions that depends solely on keys (of the dict to be transformed) Used to easily make process_kwargs and process_info_dict arguments for LinearNaming.                              |
| `mk_named_capture_patterns`(mapping_dict)                                                          |                                                                                                                                                                                                                      |
| [`mk_pattern_from_template_and_format_dict`](_autosummary/embody.naming.html.md#embody.naming.mk_pattern_from_template_and_format_dict)(...)     | Make a compiled regex to match template :type template:  :param template: A format string :type format_dict:  :param format_dict: A dict whose keys are template fields and values are regex strings to capture them |
| `mk_prefix_templates_dicts`(template)                                                              |                                                                                                                                                                                                                      |
| [`mk_store_from_path_format_store_cls`](_autosummary/embody.naming.html.md#embody.naming.mk_store_from_path_format_store_cls)([store, ...]) | Wrap a store (instance or class) that uses string keys to make it into a store that uses a specific key format.                                                                                                      |
| [`mk_tupled_store_from_path_format_store_cls`](_autosummary/embody.naming.html.md#embody.naming.mk_tupled_store_from_path_format_store_cls)([...]) | Wrap a store (instance or class) that uses string keys to make it into a store that uses a specific key format.                                                                                                      |
| [`namedtuple_to_dict`](_autosummary/embody.naming.html.md#embody.naming.namedtuple_to_dict)(nt)                            |                                                                                                                                                                                                                      |
| `template_to_pattern`(mapping_dict, template)                                                      |                                                                                                                                                                                                                      |
| [`update_fields_of_namedtuple`](_autosummary/embody.naming.html.md#embody.naming.update_fields_of_namedtuple)(nt, \*[, ...])        | Replace fields of namedtuple                                                                                                                                                                                         |
| [`validate_kwargs`](_autosummary/embody.naming.html.md#embody.naming.validate_kwargs)(kwargs_to_validate, ...[, ...])   | Utility to validate a dict.                                                                                                                                                                                          |

### Classes

| [`BigDocTest`](_autosummary/embody.naming.html.md#embody.naming.BigDocTest)()                             |                                                                                             |
|-------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------|
| [`KeyMapNames`](_autosummary/embody.naming.html.md#embody.naming.KeyMapNames)                              |                                                                                             |
| [`KeyMaps`](_autosummary/embody.naming.html.md#embody.naming.KeyMaps)(key_of_id, id_of_key)            |                                                                                             |
| [`LinearNaming`](_autosummary/embody.naming.html.md#embody.naming.LinearNaming)                             |                                                                                             |
| `NamingInterface`([params, validation_funs, ...])                                         |                                                                                             |
| [`ParametricKeyStore`](_autosummary/embody.naming.html.md#embody.naming.ParametricKeyStore)(store[, keymap])      |                                                                                             |
| [`PartialFormatter`](_autosummary/embody.naming.html.md#embody.naming.PartialFormatter)()                       | A string formatter that won't complain if the fields are only partially formatted.          |
| [`StoreWithDictKeys`](_autosummary/embody.naming.html.md#embody.naming.StoreWithDictKeys)(store[, keymap])       |                                                                                             |
| [`StoreWithNamedTupleKeys`](_autosummary/embody.naming.html.md#embody.naming.StoreWithNamedTupleKeys)(store[, keymap]) |                                                                                             |
| [`StoreWithTupleKeys`](_autosummary/embody.naming.html.md#embody.naming.StoreWithTupleKeys)(store[, keymap])      |                                                                                             |
| `StrTupleDict`(template[, format_dict, ...])                                              |                                                                                             |
| [`StrTupleDictWithPrefix`](_autosummary/embody.naming.html.md#embody.naming.StrTupleDictWithPrefix)(template[, ...])  | Converting from and to strings, tuples, and dicts, but with partial "prefix" specs allowed. |

### *class* embody.naming.BigDocTest

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

```pycon
>>>
>>> e_name = BigDocTest.mk_e_naming()
>>> u_name = BigDocTest.mk_u_naming()
>>> e_sref = 's3://bucket-GROUP/example/files/USER/SUBUSER/2017-01-24/1485272231982_1485261448469'
>>> u_sref = "s3://uploads/GROUP/upload/files/USER/2017-01-24/SUBUSER/a_file.wav"
>>> u_name_2 = "s3://uploads/ANOTHER_GROUP/upload/files/ANOTHER_USER/2017-01-24/SUBUSER/a_file.wav"
>>>
>>> ####### is_valid(self, name): ######
>>> e_name.is_valid(e_sref)
True
>>> e_name.is_valid(u_sref)
False
>>> u_name.is_valid(u_sref)
True
>>>
>>> ####### is_valid_prefix(self, name): ######
>>> e_name.is_valid_prefix('s3://bucket-')
True
>>> e_name.is_valid_prefix('s3://bucket-GROUP')
False
>>> e_name.is_valid_prefix('s3://bucket-GROUP/example/')
False
>>> e_name.is_valid_prefix('s3://bucket-GROUP/example/files')
False
>>> e_name.is_valid_prefix('s3://bucket-GROUP/example/files/')
True
>>> e_name.is_valid_prefix('s3://bucket-GROUP/example/files/USER/SUBUSER/2017-01-24/')
True
>>> e_name.is_valid_prefix('s3://bucket-GROUP/example/files/USER/SUBUSER/2017-01-24/0_0')
True
>>>
>>> ####### info_dict(self, name): ######
>>> e_name.info_dict(e_sref)  # see that utc_ms args were cast to ints
{'group': 'GROUP', 'user': 'USER', 'subuser': 'SUBUSER', 'day': '2017-01-24', 's_ums': 1485272231982, 'e_ums': 1485261448469}
>>> u_name.info_dict(u_sref)  # returns None (because self was made for example!
{'group': 'GROUP', 'user': 'USER', 'day': '2017-01-24', 'subuser': 'SUBUSER', 'filename': 'a_file.wav'}
>>> # but with a u_name, it will work
>>> u_name.info_dict(u_sref)
{'group': 'GROUP', 'user': 'USER', 'day': '2017-01-24', 'subuser': 'SUBUSER', 'filename': 'a_file.wav'}
>>>
>>> ####### extract(self, item, name): ######
>>> e_name.extract('group', e_sref)
'GROUP'
>>> e_name.extract('user', e_sref)
'USER'
>>> u_name.extract('group', u_name_2)
'ANOTHER_GROUP'
>>> u_name.extract('user', u_name_2)
'ANOTHER_USER'
>>>
#
# >>> ####### mk_prefix(self, *args, **kwargs): ######
# >>> e_name.mk_prefix()
# 's3://bucket-'
# >>> e_name.mk_prefix(group='GROUP')
# 's3://bucket-GROUP/example/files/'
# >>> e_name.mk_prefix(group='GROUP', user='USER')
# 's3://bucket-GROUP/example/files/USER/'
# >>> e_name.mk_prefix(group='GROUP', user='USER', subuser='SUBUSER')
# 's3://bucket-GROUP/example/files/USER/SUBUSER/'
# >>> e_name.mk_prefix(group='GROUP', user='USER', subuser='SUBUSER', day='0000-00-00')
# 's3://bucket-GROUP/example/files/USER/SUBUSER/0000-00-00/'
# >>> e_name.mk_prefix(group='GROUP', user='USER', subuser='SUBUSER', day='0000-00-00',
# ... s_ums=1485272231982)
# 's3://bucket-GROUP/example/files/USER/SUBUSER/0000-00-00/1485272231982_'
# >>> e_name.mk_prefix(group='GROUP', user='USER', subuser='SUBUSER', day='0000-00-00',
# ... s_ums=1485272231982, e_ums=1485261448469)
# 's3://bucket-GROUP/example/files/USER/SUBUSER/0000-00-00/1485272231982_1485261448469'
# >>>
# >>> u_name.mk_prefix()
# 's3://uploads/'
# >>> u_name.mk_prefix(group='GROUP')
# 's3://uploads/GROUP/upload/files/'
# >>> u_name.mk_prefix(group='GROUP', user='USER')
# 's3://uploads/GROUP/upload/files/USER/'
# >>> u_name.mk_prefix(group='GROUP', user='USER', day='DAY')
# 's3://uploads/GROUP/upload/files/USER/DAY/'
# >>> u_name.mk_prefix(group='GROUP', user='USER', day='DAY')
# 's3://uploads/GROUP/upload/files/USER/DAY/'
# >>> u_name.mk_prefix(group='GROUP', user='USER', day='DAY', subuser='SUBUSER')
# 's3://uploads/GROUP/upload/files/USER/DAY/SUBUSER/'
# >>>
# >>> ####### mk(self, *args, **kwargs): ######
# >>> e_name.mk(group='GROUP', user='USER', subuser='SUBUSER', day='0000-00-00',
# ...             s_ums=1485272231982, e_ums=1485261448469)
# 's3://bucket-GROUP/example/files/USER/SUBUSER/0000-00-00/1485272231982_1485261448469'
# >>> e_name.mk(group='GROUP', user='USER', subuser='SUBUSER', day='from_s_ums',
# ...             s_ums=1485272231982, e_ums=1485261448469)
# 's3://bucket-GROUP/example/files/USER/SUBUSER/2017-01-24/1485272231982_1485261448469'
# >>>
# >>> ####### replace_name_elements(self, *args, **kwargs): ######
# >>> name = 's3://bucket-redrum/example/files/oopsy@domain.com/ozeip/2008-11-04/1225779243969_1225779246969'
# >>> e_name.replace_name_elements(name, user='NEW_USER', group='NEW_GROUP')
# 's3://bucket-NEW_GROUP/example/files/NEW_USER/ozeip/2008-11-04/1225779243969_1225779246969'
```

### embody.naming.KeyMapNames

alias of [`KeyMaps`](_autosummary/embody.naming.html.md#embody.naming.KeyMaps)

### *class* embody.naming.KeyMaps(key_of_id, id_of_key)

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

#### id_of_key

Alias for field number 1

#### key_of_id

Alias for field number 0

### embody.naming.LinearNaming

alias of [`StrTupleDictWithPrefix`](_autosummary/embody.naming.html.md#embody.naming.StrTupleDictWithPrefix)

### *class* embody.naming.ParametricKeyStore(store, keymap=None)

Bases: `Store`

### *class* embody.naming.PartialFormatter

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

A string formatter that won’t complain if the fields are only partially formatted.
But note that you will lose the spec part of your template (e.g. in {foo:1.2f}, you’ll loose the 1.2f
if not foo is given – but {foo} will remain).

```pycon
>>> partial_formatter = PartialFormatter()
>>> str_template = 'foo:{foo} bar={bar} a={a} b={b:0.02f} c={c}'
>>> partial_formatter.format(str_template, bar="BAR", b=34)
'foo:{foo} bar=BAR a={a} b=34.00 c={c}'
```

#### NOTE
If you only need a formatting function (not the transformed formatting string), a simpler solution may be:

```text
import functools
format_str = functools.partial(str_template.format, bar="BAR", b=34)
```

See [https://stackoverflow.com/questions/11283961/partial-string-formatting](https://stackoverflow.com/questions/11283961/partial-string-formatting) for more options and discussions.

### *class* embody.naming.StoreWithDictKeys(store, keymap=None)

Bases: [`ParametricKeyStore`](_autosummary/embody.naming.html.md#embody.naming.ParametricKeyStore)

### *class* embody.naming.StoreWithNamedTupleKeys(store, keymap=None)

Bases: [`ParametricKeyStore`](_autosummary/embody.naming.html.md#embody.naming.ParametricKeyStore)

### *class* embody.naming.StoreWithTupleKeys(store, keymap=None)

Bases: [`ParametricKeyStore`](_autosummary/embody.naming.html.md#embody.naming.ParametricKeyStore)

### *class* embody.naming.StrTupleDictWithPrefix(template, format_dict=None, process_kwargs=None, process_info_dict=None, named_tuple_type_name='NamedTuple', sep='/')

Bases: `StrTupleDict`

Converting from and to strings, tuples, and dicts, but with partial “prefix” specs allowed.

* **Parameters:**
  * **template** (([`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list))) – The string format template
  * **format_dict** – A {field_name: field_value_format_regex, …} dict
  * **process_kwargs** – A function taking the field=value pairs and producing a dict of processed
    {field: value,…} dict (where both fields and values could have been processed.
    This is useful when we need to process (format, default, etc.) fields, or their values,
    according to the other fields of values in the collection.
    A specification of {field: function_to_process_this_value,…} wouldn’t allow the full powers
    we are allowing here.
  * **process_info_dict** – A sort of converse of format_dict.
    This is a {field_name: field_conversion_func, …} dict that is used to convert info_dict values
    before returning them.
  * **name_separator** – Used

```pycon
>>> ln = StrTupleDictWithPrefix('/home/{user}/fav/{num}.txt',
...                   format_dict={'user': '[^/]+', 'num': r'\d+'},
...                   process_info_dict={'num': int},
...                   sep='/'
...                  )
>>> ln.mk('USER', num=123)  # making a string (with args or kwargs)
'/home/USER/fav/123.txt'
>>> ####### prefix methods #######
>>> ln.is_valid_prefix('/home/USER/fav/')
True
>>> ln.is_valid_prefix('/home/USER/fav/12')  # False because too long
False
>>> ln.is_valid_prefix('/home/USER/fav')  # False because too short
False
>>> ln.is_valid_prefix('/home/')  # True because just right
True
>>> ln.is_valid_prefix('/home/USER/fav/123.txt')  # full path, so output same as is_valid() method
True
>>>
>>> ln.mk_prefix('ME')
'/home/ME/fav/'
>>> ln.mk_prefix(user='YOU', num=456)  # full specification, so output same as same as mk() method
'/home/YOU/fav/456.txt'
```

#### is_valid_prefix(s)

Check if name is a valid prefix.

* **Parameters:**
  **s** – a string (that might or might not be a valid prefix)
* **Returns:**
  True iff name is a valid prefix

### embody.naming.dict_to_namedtuple(d, namedtuple_obj=None)

```pycon
>>> from collections import namedtuple
>>> NT = namedtuple('MyTuple', ('foo', 'hello'))
>>> nt = NT(1, 42)
>>> nt
MyTuple(foo=1, hello=42)
>>> d = namedtuple_to_dict(nt)
>>> d
{'foo': 1, 'hello': 42}
>>> dict_to_namedtuple(d)
NamedTupleFromDict(foo=1, hello=42)
>>> dict_to_namedtuple(d, nt)
MyTuple(foo=1, hello=42)
```

### embody.naming.get_fields_from_template(template)

Get list from {item} items of template string

* **Parameters:**
  **template** – a “template” string (a string with {item} items
  – the kind that is used to mark token for str.format)
* **Returns:**
  a list of the token items of the string, in the order they appear

```pycon
>>> get_fields_from_template('this{is}an{example}of{a}template')
['is', 'example', 'a']
```

### embody.naming.mk_kwargs_trans(\*\*trans_func_for_key)

Make a dict transformer from functions that depends solely on keys (of the dict to be transformed)
Used to easily make process_kwargs and process_info_dict arguments for LinearNaming.

### embody.naming.mk_pattern_from_template_and_format_dict(template, format_dict=None, sep='/')

Make a compiled regex to match template
:type template: 
:param template: A format string
:type format_dict: 
:param format_dict: A dict whose keys are template fields and values are regex strings to capture them

* **Returns:**
  a compiled regex

```pycon
>>> import os
>>> p = mk_pattern_from_template_and_format_dict('{here}/and/{there}')
>>> if os.name == 'nt':  # for windows
...     assert p == re.compile('(?P<here>[^\\\\]+)/and/(?P<there>[^\\\\]+)')
... else:
...     assert p == re.compile('(?P<here>[^/]+)/and/(?P<there>[^/]+)')
>>> p = mk_pattern_from_template_and_format_dict('{here}/and/{there}', {'there': r'\d+'})
>>> if os.name == 'nt':  # for windows
...     assert p == re.compile(r'(?P<here>[^\\]+)/and/(?P<there>\d+)')
... else:
...     assert p == re.compile(r'(?P<here>[^/]+)/and/(?P<there>\d+)')
>>> type(p)
<class 're.Pattern'>
>>> p.match('HERE/and/1234').groupdict()
{'here': 'HERE', 'there': '1234'}
```

### embody.naming.mk_store_from_path_format_store_cls(store=None, \*, subpath='', store_cls_kwargs=None, key_type=<function namedtuple>, keymap=<class 'embody.naming.StrTupleDict'>, keymap_kwargs=None, name=None, \_\_module_\_=None, \_\_name_\_=None, \_\_qualname_\_=None, \_\_doc_\_=None, \_\_annotations_\_=None, \_\_defaults_\_=None, \_\_kwdefaults_\_=None)

Wrap a store (instance or class) that uses string keys to make it into a store that uses a specific key format.

* **Parameters:**
  * **store** – The instance or class to wrap
  * **subpath** – The subpath (defining the subset of the data pointed at by the URI
  * **store_cls_kwargs** – # if store is a class, the kwargs that you would have given the store_cls to make itself
  * **key_type** – The key type you want to interface with:
    dict, tuple, namedtuple, str or ‘dict’, ‘tuple’, ‘namedtuple’, ‘str’
  * **keymap** – # the keymap instance or class you want to use to map keys
  * **keymap_kwargs** – # if keymap is a cls, the kwargs to give it (besides the subpath)
  * **name** – The name to give the class the function will make here
* **Returns:**
  An instance of a wrapped class

### Example

```text
# Get a (session, bt) indexed LocalJsonStore
s = mk_store_from_path_format_store_cls(LocalJsonStore,
                                               os.path.join(root_dir, 'd'),
                                               subpath='{session}/d/{bt}',
                                               keymap_kwargs=dict(process_info_dict={'session': int, 'bt': int}))
```

### embody.naming.mk_tupled_store_from_path_format_store_cls(store=None, \*, subpath='', store_cls_kwargs=None, key_type=<function namedtuple>, keymap=<class 'embody.naming.StrTupleDict'>, keymap_kwargs=None, name=None, \_\_module_\_=None, \_\_name_\_=None, \_\_qualname_\_=None, \_\_doc_\_=None, \_\_annotations_\_=None, \_\_defaults_\_=None, \_\_kwdefaults_\_=None)

Wrap a store (instance or class) that uses string keys to make it into a store that uses a specific key format.

* **Parameters:**
  * **store** – The instance or class to wrap
  * **subpath** – The subpath (defining the subset of the data pointed at by the URI
  * **store_cls_kwargs** – # if store is a class, the kwargs that you would have given the store_cls to make itself
  * **key_type** – The key type you want to interface with:
    dict, tuple, namedtuple, str or ‘dict’, ‘tuple’, ‘namedtuple’, ‘str’
  * **keymap** – # the keymap instance or class you want to use to map keys
  * **keymap_kwargs** – # if keymap is a cls, the kwargs to give it (besides the subpath)
  * **name** – The name to give the class the function will make here
* **Returns:**
  An instance of a wrapped class

### Example

```text
# Get a (session, bt) indexed LocalJsonStore
s = mk_store_from_path_format_store_cls(LocalJsonStore,
                                               os.path.join(root_dir, 'd'),
                                               subpath='{session}/d/{bt}',
                                               keymap_kwargs=dict(process_info_dict={'session': int, 'bt': int}))
```

### embody.naming.namedtuple_to_dict(nt)

```pycon
>>> from collections import namedtuple
>>> NT = namedtuple('MyTuple', ('foo', 'hello'))
>>> nt = NT(1, 42)
>>> nt
MyTuple(foo=1, hello=42)
>>> d = namedtuple_to_dict(nt)
>>> d
{'foo': 1, 'hello': 42}
```

### embody.naming.update_fields_of_namedtuple(nt, , name_of_output_type=None, remove_fields=(), \*\*kwargs)

Replace fields of namedtuple

```pycon
>>> from collections import namedtuple
>>> NT = namedtuple('NT', ('a', 'b', 'c'))
>>> nt = NT(1,2,3)
>>> nt
NT(a=1, b=2, c=3)
>>> update_fields_of_namedtuple(nt, c=3000)  # replacing a single field
NT(a=1, b=2, c=3000)
>>> update_fields_of_namedtuple(nt, c=3000, a=1000)  # replacing two fields
NT(a=1000, b=2, c=3000)
>>> update_fields_of_namedtuple(nt, a=1000, c=3000)  # see that the original order doesn't change
NT(a=1000, b=2, c=3000)
>>> update_fields_of_namedtuple(nt, b=2000, d='hello')  # replacing one field and adding a new one
UpdatedNT(a=1, b=2000, c=3, d='hello')
>>> # Now let's try controlling the name of the output type, remove fields, and add new ones
>>> update_fields_of_namedtuple(nt, name_of_output_type='NewGuy', remove_fields=('a', 'c'), hello='world')
NewGuy(b=2, hello='world')
```

### embody.naming.validate_kwargs(kwargs_to_validate, validation_dict, validation_funs=None, all_kwargs_should_be_in_validation_dict=False, ignore_misunderstood_validation_instructions=False)

Utility to validate a dict. It’s main use is to validate function arguments (expressing the validation checks
in validation_dict) by doing validate_kwargs(locals()), usually in the beginning of the function
(to avoid having more accumulated variables than we need in locals())

* **Parameters:**
  * **kwargs_to_validate** – as the name implies…
  * **validation_dict** – A dict specifying what to validate. Keys are usually name of variables (when feeding
    locals()) and values are dicts, themselves specifying check:check_val pairs where check is a string that
    points to a function (see validation_funs argument) and check_val is an object that the kwargs_to_validate
    value will be checked against.
  * **validation_funs** – A dict of check:check_function(val, check_val) where check_function is a function returning
    True if val is valid (with respect to check_val).
  * **all_kwargs_should_be_in_validation_dict** – If True, will raise an error if kwargs_to_validate contains
    keys that are not in validation_dict.
  * **ignore_misunderstood_validation_instructions** – If True, will raise an error if validation_dict contains
    a key that is not in validation_funs (safer, since if you mistype a key in validation_dict, the function will
    tell you so!
* **Returns:**
  True if all the validations passed.

```pycon
>>> validation_dict = {
...     'system': {
...         'be in': {'darwin', 'linux'}
...     },
...     'fv_version': {
...         'be a': int,
...         'be at least': 5
...     }
... }
>>> validate_kwargs({'system': 'darwin'}, validation_dict)
True
>>> try:
...     validate_kwargs({'system': 'windows'}, validation_dict)
... except AssertionError as e:
...     assert str(e).startswith('system must be in')  # omitting the set because inconsistent order
>>> try:
...     validate_kwargs({'fv_version': 9.9}, validation_dict)
... except AssertionError as e:
...     print(e)
fv_version must be a <class 'int'>
>>> try:
...     validate_kwargs({'fv_version': 4}, validation_dict)
... except AssertionError as e:
...     print(e)
fv_version must be at least 5
>>> validate_kwargs({'fv_version': 6}, validation_dict)
True
```


# _autosummary/embody.paths.html.md

# embody.paths

Path addressing for nested data structures.

This module provides utilities for working with paths in nested structures,
supporting:

- JSON Pointer (RFC 6901)
- Dot notation
- Tuple paths
- Path parsing and resolution

### Functions

| [`parse_path`](_autosummary/embody.paths.html.md#embody.paths.parse_path)(path[, format])                  | Parse a path in various formats.   |
|----------------------------------------------------------------------------------------------|------------------------------------|
| [`resolve_path`](_autosummary/embody.paths.html.md#embody.paths.resolve_path)(data, path[, default, format]) | Resolve a path against data.       |
| [`set_path`](_autosummary/embody.paths.html.md#embody.paths.set_path)(data, path, value[, format, ...])  | Set a value at a path.             |

### Classes

| [`DotPath`](_autosummary/embody.paths.html.md#embody.paths.DotPath)(path[, separator])   | Dot notation path handler (e.g., 'user.address.city').             |
|-------------------------------------------------------------------------------|--------------------------------------------------------------------|
| [`JSONPointer`](_autosummary/embody.paths.html.md#embody.paths.JSONPointer)(pointer)         | JSON Pointer implementation (RFC 6901).                            |
| [`TuplePath`](_autosummary/embody.paths.html.md#embody.paths.TuplePath)(parts)             | Tuple-based path (unambiguous, e.g., ('user', 'address', 'city')). |

### Exceptions

| [`InvalidPathError`](_autosummary/embody.paths.html.md#embody.paths.InvalidPathError)   | Raised when a path is malformed or invalid.   |
|---------------------------------------------------------------------|-----------------------------------------------|

### *class* embody.paths.DotPath(path, separator='.')

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

Dot notation path handler (e.g., ‘user.address.city’).

### Examples

```pycon
>>> data = {'user': {'address': {'city': 'NYC'}}}
>>> path = DotPath('user.address.city')
>>> path.resolve(data)
'NYC'
```

#### resolve(data, default=None)

Resolve the path against data.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to resolve against
  * **default** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Default value if resolution fails
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Resolved value or default

#### to_json_pointer()

Convert to a JSON Pointer.

* **Return type:**
  [`JSONPointer`](_autosummary/embody.paths.html.md#embody.paths.JSONPointer)
* **Returns:**
  JSONPointer instance

### *exception* embody.paths.InvalidPathError

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

Raised when a path is malformed or invalid.

### *class* embody.paths.JSONPointer(pointer)

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

JSON Pointer implementation (RFC 6901).

JSON Pointer defines a string syntax for identifying a specific value
within a JSON document. Example: /foo/bar/0 refers to the first element
of the ‘bar’ array in the ‘foo’ object.

### Examples

```pycon
>>> data = {'foo': {'bar': [1, 2, 3]}}
>>> ptr = JSONPointer('/foo/bar/0')
>>> ptr.resolve(data)
1
```

```pycon
>>> data = {'user': {'name': 'Alice', 'age': 30}}
>>> JSONPointer('/user/name').resolve(data)
'Alice'
```

#### *classmethod* from_parts(parts)

Create a JSON Pointer from path components.

* **Parameters:**
  **parts** ([`List`](https://docs.python.org/3/library/typing.html#typing.List)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – List of path components
* **Return type:**
  [`JSONPointer`](_autosummary/embody.paths.html.md#embody.paths.JSONPointer)
* **Returns:**
  JSONPointer instance

### Examples

```pycon
>>> ptr = JSONPointer.from_parts(['foo', 'bar', '0'])
>>> ptr.pointer
'/foo/bar/0'
```

#### resolve(data, default=None)

Resolve the pointer against data.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to resolve against
  * **default** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Default value if resolution fails
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Resolved value or default

### Examples

```pycon
>>> data = {'a': {'b': [1, 2, 3]}}
>>> JSONPointer('/a/b/1').resolve(data)
2
>>> JSONPointer('/a/x').resolve(data, default='not found')
'not found'
```

#### set(data, value, create_intermediate=False)

Set a value at the pointer location.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to modify (in place)
  * **value** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Value to set
  * **create_intermediate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, create intermediate structures
* **Raises:**
  [**InvalidPathError**](_autosummary/embody.paths.html.md#embody.paths.InvalidPathError) – If path cannot be set

### Examples

```pycon
>>> data = {'a': {'b': {}}}
>>> JSONPointer('/a/b/c').set(data, 42)
>>> data
{'a': {'b': {'c': 42}}}
```

### *class* embody.paths.TuplePath(parts)

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

Tuple-based path (unambiguous, e.g., (‘user’, ‘address’, ‘city’)).

### Examples

```pycon
>>> data = {'user': {'address': {'city': 'NYC'}}}
>>> path = TuplePath(('user', 'address', 'city'))
>>> path.resolve(data)
'NYC'
```

#### resolve(data, default=None)

Resolve the path against data.

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

#### to_json_pointer()

Convert to a JSON Pointer.

* **Return type:**
  [`JSONPointer`](_autosummary/embody.paths.html.md#embody.paths.JSONPointer)

### embody.paths.parse_path(path, format='auto')

Parse a path in various formats.

* **Parameters:**
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`List`](https://docs.python.org/3/library/typing.html#typing.List)]) – Path in any supported format
  * **format** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Format hint (‘auto’, ‘json_pointer’, ‘dot’, ‘tuple’)
* **Return type:**
  [`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`JSONPointer`](_autosummary/embody.paths.html.md#embody.paths.JSONPointer), [`DotPath`](_autosummary/embody.paths.html.md#embody.paths.DotPath), [`TuplePath`](_autosummary/embody.paths.html.md#embody.paths.TuplePath)]
* **Returns:**
  Path object

### Examples

```pycon
>>> parse_path('/user/name')
<embody.paths.JSONPointer object at ...>
```

```pycon
>>> parse_path('user.name')
<embody.paths.DotPath object at ...>
```

```pycon
>>> parse_path(('user', 'name'))
<embody.paths.TuplePath object at ...>
```

### embody.paths.resolve_path(data, path, default=None, format='auto')

Resolve a path against data.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to resolve against
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`List`](https://docs.python.org/3/library/typing.html#typing.List)]) – Path in any supported format
  * **default** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Default value if resolution fails
  * **format** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Format hint
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Resolved value or default

### Examples

```pycon
>>> data = {'user': {'name': 'Alice', 'age': 30}}
>>> resolve_path(data, '/user/name')
'Alice'
>>> resolve_path(data, 'user.age')
30
>>> resolve_path(data, ('user', 'name'))
'Alice'
```

### embody.paths.set_path(data, path, value, format='auto', create_intermediate=True)

Set a value at a path.

* **Parameters:**
  * **data** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Data to modify
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`List`](https://docs.python.org/3/library/typing.html#typing.List)]) – Path in any supported format
  * **value** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Value to set
  * **format** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Format hint
  * **create_intermediate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, create intermediate structures

### Examples

```pycon
>>> data = {}
>>> set_path(data, '/user/name', 'Alice')
>>> data
{'user': {'name': 'Alice'}}
```


# _autosummary/embody.strategies.html.md

# embody.strategies

Traversal strategies for template embodiment.

This module provides different strategies for traversing and embodying templates:

- RecursiveVisitorEngine: Dynamic traversal using the Visitor pattern
- CompiledPathEngine: Pre-compiled path-based traversal for performance

### Functions

| [`get_engine`](_autosummary/embody.strategies.html.md#embody.strategies.get_engine)([strategy])   | Get an embodiment engine by name.   |
|---------------------------------------------------------------------------|-------------------------------------|

### Classes

| [`BaseEmbodimentEngine`](_autosummary/embody.strategies.html.md#embody.strategies.BaseEmbodimentEngine)([syntax, strict, ...])   | Base class for embodiment engines.                    |
|------------------------------------------------------------------------------------------------|-------------------------------------------------------|
| [`CompiledPathEngine`](_autosummary/embody.strategies.html.md#embody.strategies.CompiledPathEngine)(\*args, \*\*kwargs)        | Pre-compiled path-based traversal strategy.           |
| [`IterativeStackEngine`](_autosummary/embody.strategies.html.md#embody.strategies.IterativeStackEngine)([syntax, strict, ...])   | Iterative stack-based traversal strategy.             |
| [`RecursiveVisitorEngine`](_autosummary/embody.strategies.html.md#embody.strategies.RecursiveVisitorEngine)([syntax, strict, ...]) | Dynamic traversal strategy using the Visitor pattern. |

### Exceptions

| [`KeyCollisionError`](_autosummary/embody.strategies.html.md#embody.strategies.KeyCollisionError)   | Raised when dynamic keys resolve to the same value.   |
|----------------------------------------------------------------------|-------------------------------------------------------|

### *class* embody.strategies.BaseEmbodimentEngine(syntax='dollar_brace', strict=False, key_collision='error')

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

Base class for embodiment engines.

#### embody(template, params)

Embody a template with parameters.

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – The template to embody
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for substitution
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object

### *class* embody.strategies.CompiledPathEngine(\*args, \*\*kwargs)

Bases: [`BaseEmbodimentEngine`](_autosummary/embody.strategies.html.md#embody.strategies.BaseEmbodimentEngine)

Pre-compiled path-based traversal strategy.

This engine flattens the template into a path map, performs substitutions,
and then reconstructs the structure. It’s best for:

- Templates embodied repeatedly (e.g., API responses)
- Static templates with known structure
- Performance-critical paths

The compilation happens once, then embodiment is a linear scan.

### Examples

```pycon
>>> engine = CompiledPathEngine()
>>> template = {'a': {'b': '${x}'}, 'c': '${y}'}
>>> compiled = engine.compile(template)
>>> engine.embody_compiled(compiled, {'x': 1, 'y': 2})
{'a': {'b': 1}, 'c': 2}
```

#### compile(template)

Compile a template into a flat path map.

* **Parameters:**
  **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Template to compile
* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)
* **Returns:**
  Compiled template data

### Examples

```pycon
>>> engine = CompiledPathEngine()
>>> template = {'a': {'b': '${x}'}}
>>> compiled = engine.compile(template)
>>> compiled['flat']
{('a', 'b'): '${x}'}
```

#### embody(template, params)

Embody a template (compiles on first use, caches compilation).

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Template to embody
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for substitution
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object

#### embody_compiled(compiled, params)

Embody a pre-compiled template.

* **Parameters:**
  * **compiled** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)) – Compiled template from compile()
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for substitution
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object

### *class* embody.strategies.IterativeStackEngine(syntax='dollar_brace', strict=False, key_collision='error')

Bases: [`BaseEmbodimentEngine`](_autosummary/embody.strategies.html.md#embody.strategies.BaseEmbodimentEngine)

Iterative stack-based traversal strategy.

This engine uses an explicit stack instead of recursion, which is more
memory-efficient for very deep structures and avoids Python’s recursion limit.

Best for:

- Very deeply nested structures (>100 levels)
- When recursion depth is a concern

#### embody(template, params)

Embody using iterative stack-based traversal.

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Template to embody
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for substitution
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object

### *exception* embody.strategies.KeyCollisionError

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

Raised when dynamic keys resolve to the same value.

### *class* embody.strategies.RecursiveVisitorEngine(syntax='dollar_brace', strict=False, key_collision='error')

Bases: [`BaseEmbodimentEngine`](_autosummary/embody.strategies.html.md#embody.strategies.BaseEmbodimentEngine)

Dynamic traversal strategy using the Visitor pattern.

This engine recursively walks the template structure at runtime,
visiting each node and performing substitutions. It’s best for:

- One-off templates
- Dynamic templates with conditional logic
- Templates where structure changes based on parameters

### Examples

```pycon
>>> engine = RecursiveVisitorEngine()
>>> template = {'greeting': 'Hello ${name}', 'count': '${num}'}
>>> engine.embody(template, {'name': 'Alice', 'num': 42})
{'greeting': 'Hello Alice', 'count': 42}
```

#### embody(template, params, visited=None)

Recursively embody a template.

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Template to embody
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Parameters for substitution
  * **visited** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Set`](https://docs.python.org/3/library/typing.html#typing.Set)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]]) – Set of visited object IDs (for cycle detection)
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Embodied object
* **Raises:**
  [**CycleError**](_autosummary/embody.html.md#embody.CycleError) – If a circular reference is detected

### embody.strategies.get_engine(strategy='recursive', \*\*kwargs)

Get an embodiment engine by name.

* **Parameters:**
  * **strategy** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Name of strategy (‘recursive’, ‘compiled’, ‘iterative’)
  * **\*\*kwargs** – Arguments to pass to engine constructor
* **Return type:**
  [`BaseEmbodimentEngine`](_autosummary/embody.strategies.html.md#embody.strategies.BaseEmbodimentEngine)
* **Returns:**
  Embodiment engine instance

### Examples

```pycon
>>> engine = get_engine('recursive', syntax='brace')
>>> isinstance(engine, RecursiveVisitorEngine)
True
```


# _autosummary/embody.substitution.html.md

# embody.substitution

Pattern matching and type-preserving substitution logic for templates.

This module provides the core substitution functionality for embody, supporting
multiple syntaxes (${var}, {var}) with type preservation.

### Functions

| [`extract_template_vars`](_autosummary/embody.substitution.html.md#embody.substitution.extract_template_vars)(template[, syntax])        | Extract all template variable names from a string.                     |
|---------------------------------------------------------------------------------------------------|------------------------------------------------------------------------|
| [`is_exact_match`](_autosummary/embody.substitution.html.md#embody.substitution.is_exact_match)(template[, syntax])               | Check if template is exactly one variable placeholder (no other text). |
| [`safe_format`](_autosummary/embody.substitution.html.md#embody.substitution.safe_format)(template, \*\*params)                | Safely format a string, leaving undefined placeholders unchanged.      |
| [`substitute`](_autosummary/embody.substitution.html.md#embody.substitution.substitute)(template, params[, syntax, strict])   | Perform type-preserving substitution on a template value.              |
| [`substitute_all_syntaxes`](_autosummary/embody.substitution.html.md#embody.substitution.substitute_all_syntaxes)(template, params[, ...]) | Apply substitution for multiple syntax styles.                         |

### Classes

| [`SafeFormatter`](_autosummary/embody.substitution.html.md#embody.substitution.SafeFormatter)()      | A string formatter that doesn't raise errors for missing keys.   |
|-----------------------------------------------------------------------|------------------------------------------------------------------|
| [`SubstitutionSyntax`](_autosummary/embody.substitution.html.md#embody.substitution.SubstitutionSyntax)() | Defines the syntax patterns for template variable substitution.  |

### *class* embody.substitution.SafeFormatter

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

A string formatter that doesn’t raise errors for missing keys.

### *class* embody.substitution.SubstitutionSyntax

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

Defines the syntax patterns for template variable substitution.

#### *classmethod* get_pattern(syntax='dollar_brace')

Get the regex pattern for the specified syntax.

* **Parameters:**
  **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – One of ‘dollar_brace’, ‘brace’, ‘double_bracket’
* **Return type:**
  [`Pattern`](https://docs.python.org/3/library/typing.html#typing.Pattern)
* **Returns:**
  Compiled regex pattern

### Examples

```pycon
>>> pattern = SubstitutionSyntax.get_pattern('dollar_brace')
>>> pattern.findall('${name} is ${age}')
['name', 'age']
```

### embody.substitution.extract_template_vars(template, syntax='dollar_brace')

Extract all template variable names from a string.

* **Parameters:**
  * **template** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Template string containing variables
  * **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Variable syntax to use
* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  List of variable names found in the template

### Examples

```pycon
>>> extract_template_vars('Hello ${name}, you are ${age} years old')
['name', 'age']
>>> extract_template_vars('Hello {name}', syntax='brace')
['name']
```

### embody.substitution.is_exact_match(template, syntax='dollar_brace')

Check if template is exactly one variable placeholder (no other text).

This is crucial for type preservation. If the template is exactly ${var},
we should return the raw value, not convert it to a string.

* **Parameters:**
  * **template** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Template string to check
  * **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Variable syntax to use
* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]
* **Returns:**
  Variable name if exact match, None otherwise

### Examples

```pycon
>>> is_exact_match('${name}')
'name'
>>> is_exact_match('Hello ${name}')
```

```pycon
>>> is_exact_match('${count}')
'count'
```

### embody.substitution.safe_format(template, \*\*params)

Safely format a string, leaving undefined placeholders unchanged.

* **Parameters:**
  * **template** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Template string
  * **\*\*params** – Parameters for substitution
* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)
* **Returns:**
  Formatted string

### Examples

```pycon
>>> safe_format('Hello {name}, you are {age}', name='Alice')
'Hello Alice, you are {age}'
```

### embody.substitution.substitute(template, params, syntax='dollar_brace', strict=False)

Perform type-preserving substitution on a template value.

This is the core substitution function. It handles:

1. Exact match: ${var} -> returns params[‘var’] with type preserved
2. Partial match: “Count is ${var}” -> string interpolation
3. Non-string templates: returned unchanged

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – The template value (can be any type)
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Dictionary of parameters for substitution
  * **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Variable syntax to use
  * **strict** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, raise KeyError for missing variables
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  The substituted value with type preservation

### Examples

```pycon
>>> substitute('${count}', {'count': 42})
42
>>> substitute('Count: ${count}', {'count': 42})
'Count: 42'
>>> substitute('${active}', {'active': True})
True
>>> substitute('${items}', {'items': [1, 2, 3]})
[1, 2, 3]
>>> substitute(42, {})
42
```

### embody.substitution.substitute_all_syntaxes(template, params, syntaxes=None, strict=False)

Apply substitution for multiple syntax styles.

Useful when you want to support mixed syntax in templates.

* **Parameters:**
  * **template** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – The template value
  * **params** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Dictionary of parameters
  * **syntaxes** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – List of syntaxes to try (default: [‘dollar_brace’, ‘brace’])
  * **strict** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, raise errors for missing variables
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  The substituted value

### Examples

```pycon
>>> substitute_all_syntaxes('${name} is {age}', {'name': 'Alice', 'age': 30})
'Alice is 30'
```


# _autosummary/embody.templater.html.md

# embody.templater

Base objects for definding templates

Born from a
[stackoverflow Q&A](https://stackoverflow.com/questions/69383734/templated-object-generation-in-python/69384846).

```pycon
>>> from embody.templater import Templater
>>> # the following template has templated dicts, strings, and lists
>>> template = {
...     'hello': '{name}',
...     'how are you': ['{verb}', 2, '{name} and {verb} again']
... }
>>> g = Templater.template_func(template=template)
>>> g(name='NAME', verb="VERB")
{'hello': 'NAME', 'how are you': ['VERB', 2, 'NAME and VERB again']}
>>> str(g.__signature__)
'(*, name, verb)'
```

### Functions

| `get_generator_return`(gen)                                                             |                                               |
|-----------------------------------------------------------------------------------------|-----------------------------------------------|
| `templated_dict_func`(template)                                                         |                                               |
| `templated_list_func`(template)                                                         |                                               |
| [`templated_string_func`](_autosummary/embody.templater.html.md#embody.templater.templated_string_func)(template)        | A function making templated strings.          |
| [`unique_list_conserving_order`](_autosummary/embody.templater.html.md#embody.templater.unique_list_conserving_order)(iterable) | List of unique elements in the original order |

### Classes

| `Templater`()   |    |
|-----------------|----|

### embody.templater.templated_string_func(template)

A function making templated strings. Like template.format, but with a signature

* **Return type:**
  [`Generator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`None`](https://docs.python.org/3/builtins/constants.html#None), [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### embody.templater.unique_list_conserving_order(iterable)

List of unique elements in the original order

```pycon
>>> unique_list_conserving_order([3, 2, 3, 5, 1, 2, 6, 3, 5])
[3, 2, 5, 1, 6]
```

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


# _autosummary/embody.templating.html.md

# embody.templating

Making templates for various objects

### Functions

| `get_specs`(template[, gen_specs])     |    |
|----------------------------------------|----|
| `templated_gen`(template[, gen_specs]) |    |

### Classes

| `Field`(name)   |    |
|-----------------|----|
| `Literal`(obj)  |    |


# _autosummary/embody.util.html.md

# embody.util

Utility functions for embody: flattening, unflattening, and cycle detection.

This module provides helper functions for working with nested data structures,
including path-based operations and cycle detection for safe traversal.

### Functions

| [`count_template_markers`](_autosummary/embody.util.html.md#embody.util.count_template_markers)(obj[, syntax])           | Count the number of template markers in a nested structure.                |
|--------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------|
| [`detect_cycle`](_autosummary/embody.util.html.md#embody.util.detect_cycle)(obj[, visited, path])              | Detect cycles in a nested data structure.                                  |
| [`flatten_dict`](_autosummary/embody.util.html.md#embody.util.flatten_dict)(nested_dict[, separator, ...])     | Flatten a nested dictionary into a single-level dictionary with path keys. |
| [`flatten_to_tuples`](_autosummary/embody.util.html.md#embody.util.flatten_to_tuples)(obj[, parent_path])           | Flatten a nested structure using tuple paths (unambiguous).                |
| [`get_by_path`](_autosummary/embody.util.html.md#embody.util.get_by_path)(obj, path[, separator, default])    | Get a value from a nested structure by path.                               |
| [`max_depth`](_autosummary/embody.util.html.md#embody.util.max_depth)(obj[, current_depth])                 | Calculate the maximum depth of a nested structure.                         |
| [`set_by_path`](_autosummary/embody.util.html.md#embody.util.set_by_path)(obj, path, value[, separator, ...]) | Set a value in a nested structure by path (modifies in place).             |
| [`unflatten_dict`](_autosummary/embody.util.html.md#embody.util.unflatten_dict)(flat_dict[, separator])          | Unflatten a dictionary with path keys into a nested structure.             |
| [`unflatten_from_tuples`](_autosummary/embody.util.html.md#embody.util.unflatten_from_tuples)(flat_dict)                | Unflatten a dictionary with tuple paths into a nested structure.           |

### Exceptions

| [`CycleError`](_autosummary/embody.util.html.md#embody.util.CycleError)        | Raised when a circular reference is detected in a data structure.   |
|--------------------------------------------------------------------|---------------------------------------------------------------------|
| [`PathNotFoundError`](_autosummary/embody.util.html.md#embody.util.PathNotFoundError) | Raised when a path doesn't exist in a data structure.               |

### *exception* embody.util.CycleError

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

Raised when a circular reference is detected in a data structure.

### *exception* embody.util.PathNotFoundError

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

Raised when a path doesn’t exist in a data structure.

### embody.util.count_template_markers(obj, syntax='dollar_brace')

Count the number of template markers in a nested structure.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Object to count markers in
  * **syntax** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Template syntax to look for
* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)
* **Returns:**
  Number of template markers found

### Examples

```pycon
>>> count_template_markers({'a': '${x}', 'b': '${y}'})
2
>>> count_template_markers(['${a}', 'literal', '${b} and ${c}'])
3
```

### embody.util.detect_cycle(obj, visited=None, path=None)

Detect cycles in a nested data structure.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – The object to check for cycles
  * **visited** ([`Set`](https://docs.python.org/3/library/typing.html#typing.Set)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]) – Set of object IDs already visited
  * **path** ([`List`](https://docs.python.org/3/library/typing.html#typing.List)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Current path in the structure (for error reporting)
* **Raises:**
  [**CycleError**](_autosummary/embody.util.html.md#embody.util.CycleError) – If a cycle is detected
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### Examples

```pycon
>>> d = {'a': 1, 'b': [2, 3]}
>>> detect_cycle(d)  # No cycle, returns None
```

```pycon
>>> circular = {'a': 1}
>>> circular['self'] = circular
>>> try:
...     detect_cycle(circular)
... except CycleError as e:
...     print("Cycle detected")
Cycle detected
```

### embody.util.flatten_dict(nested_dict, separator='.', parent_key='')

Flatten a nested dictionary into a single-level dictionary with path keys.

* **Parameters:**
  * **nested_dict** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Nested dictionary to flatten
  * **separator** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – String to use for separating path components
  * **parent_key** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Key of the parent (used in recursion)
* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]
* **Returns:**
  Flattened dictionary with path keys

### Examples

```pycon
>>> d = {'a': {'b': {'c': 1}}, 'd': 2}
>>> flatten_dict(d)
{'a.b.c': 1, 'd': 2}
```

```pycon
>>> d = {'user': {'name': 'Alice', 'age': 30}}
>>> flatten_dict(d)
{'user.name': 'Alice', 'user.age': 30}
```

```pycon
>>> d = {'items': [1, 2, 3]}
>>> flatten_dict(d)
{'items.0': 1, 'items.1': 2, 'items.2': 3}
```

### embody.util.flatten_to_tuples(obj, parent_path=())

Flatten a nested structure using tuple paths (unambiguous).

This avoids the ambiguity of string separators. A tuple path like
(‘a’, ‘b’, 0) is unambiguous, while ‘a.b.0’ could mean multiple things
if keys contain dots.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Object to flatten
  * **parent_path** ([`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple)) – Current path as tuple
* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]
* **Returns:**
  Dictionary mapping tuple paths to values

### Examples

```pycon
>>> d = {'a': {'b': [1, 2]}}
>>> flatten_to_tuples(d)
{('a', 'b', 0): 1, ('a', 'b', 1): 2}
```

### embody.util.get_by_path(obj, path, separator='.', default=None)

Get a value from a nested structure by path.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Nested structure
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple)]) – Path as string or tuple
  * **separator** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Separator for string paths
  * **default** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Default value if path not found
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Value at the path, or default if not found

### Examples

```pycon
>>> d = {'a': {'b': {'c': 42}}}
>>> get_by_path(d, 'a.b.c')
42
>>> get_by_path(d, ('a', 'b', 'c'))
42
>>> get_by_path(d, 'a.b.x', default='not found')
'not found'
```

### embody.util.max_depth(obj, current_depth=0)

Calculate the maximum depth of a nested structure.

* **Parameters:**
  * **obj** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Object to measure
  * **current_depth** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Current depth (used in recursion)
* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)
* **Returns:**
  Maximum depth

### Examples

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

### embody.util.set_by_path(obj, path, value, separator='.', create_intermediate=True)

Set a value in a nested structure by path (modifies in place).

* **Parameters:**
  * **obj** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)) – Nested structure to modify
  * **path** ([`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple)]) – Path as string or tuple
  * **value** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – Value to set
  * **separator** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – Separator for string paths
  * **create_intermediate** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool)) – If True, create intermediate dicts/lists as needed
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### Examples

```pycon
>>> d = {}
>>> set_by_path(d, 'a.b.c', 42)
>>> d
{'a': {'b': {'c': 42}}}
```

### embody.util.unflatten_dict(flat_dict, separator='.')

Unflatten a dictionary with path keys into a nested structure.

* **Parameters:**
  * **flat_dict** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Flattened dictionary with path keys
  * **separator** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – String used for separating path components
* **Return type:**
  [`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]
* **Returns:**
  Nested dictionary structure

### Examples

```pycon
>>> flat = {'a.b.c': 1, 'd': 2}
>>> unflatten_dict(flat)
{'a': {'b': {'c': 1}}, 'd': 2}
```

```pycon
>>> flat = {'items.0': 'a', 'items.1': 'b'}
>>> unflatten_dict(flat)
{'items': ['a', 'b']}
```

### embody.util.unflatten_from_tuples(flat_dict)

Unflatten a dictionary with tuple paths into a nested structure.

* **Parameters:**
  **flat_dict** ([`Dict`](https://docs.python.org/3/library/typing.html#typing.Dict)[[`Tuple`](https://docs.python.org/3/library/typing.html#typing.Tuple), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Dictionary with tuple paths as keys
* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)
* **Returns:**
  Nested structure (dict or list)

### Examples

```pycon
>>> flat = {('a', 'b', 0): 1, ('a', 'b', 1): 2}
>>> unflatten_from_tuples(flat)
{'a': {'b': [1, 2]}}
```


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-11-21 17:39 UTC** from commit <a href="https://github.com/i2mint/embody/commit/4b5c8635db102aa9c74350eaf985b51335e53d54"><code>4b5c863</code></a> on branch <code>master</code>, for **embody 0.1.11** (from <code>pyproject.toml</code>).

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

## Source

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

## Continuous integration

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

## Tools

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

## Configuration as resolved

|               |                                                                  |
|---------------|------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>furo</code>)               |
| accent        | <code>#694191</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/embody/0.1.11/">0.1.11</a>, the same as the documented version.

## Reproduce

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

| [`embody`](_autosummary/embody.html.md#module-embody)   | Generate templated objects with advanced structural embodiment features.   |
|-------------------------------------------------------------------------|----------------------------------------------------------------------------|


