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:
>>> from embody import embody
>>> template = {'name': '${name}', 'age': '${age}'}
>>> result = embody(template, {'name': 'Alice', 'age': 30})
>>> result
{'name': 'Alice', 'age': 30}
Advanced usage:
>>> 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
|
Convenience function for template embodiment. |
|
Get an embodiment engine by name. |
|
Perform type-preserving substitution on a template value. |
|
Extract all template variable names from a string. |
|
Check if template is exactly one variable placeholder (no other text). |
|
Flatten a nested dictionary into a single-level dictionary with path keys. |
|
Unflatten a dictionary with path keys into a nested structure. |
|
Flatten a nested structure using tuple paths (unambiguous). |
|
Unflatten a dictionary with tuple paths into a nested structure. |
|
Detect cycles in a nested data structure. |
|
Get a value from a nested structure by path. |
|
Set a value in a nested structure by path (modifies in place). |
|
Calculate the maximum depth of a nested structure. |
|
Count the number of template markers in a nested structure. |
|
Convert data to a Mapping with the specified style. |
|
Parse a path in various formats. |
|
Resolve a path against data. |
|
Set a value at a path. |
Classes
|
Main class for embodying templates with parameters. |
|
Parameter store for template embodiment with support for resolvers. |
|
Wrapper for template data with introspection capabilities. |
|
|
|
Dynamic traversal strategy using the Visitor pattern. |
|
Pre-compiled path-based traversal strategy. |
|
Iterative stack-based traversal strategy. |
Defines the syntax patterns for template variable substitution. |
|
|
Read-only Mapping wrapper for embodied objects with lazy evaluation. |
|
Lazy Mapping that embodies values on access. |
|
Mapping with flattened nested structure for path-based access. |
|
Mapping that allows attribute access (Box pattern). |
|
Immutable Mapping wrapper. |
|
Mutable Mapping wrapper for embodied objects. |
|
Mapping supporting multiple path access styles. |
|
JSON Pointer implementation (RFC 6901). |
|
Dot notation path handler (e.g., 'user.address.city'). |
|
Tuple-based path (unambiguous, e.g., ('user', 'address', 'city')). |
Exceptions
Raised when a required template parameter is missing. |
|
Raised when dynamic keys resolve to the same value. |
|
Raised when a circular reference is detected in a data structure. |
|
Raised when a path doesn't exist in a data structure. |
|
Raised when a path is malformed or invalid. |
- class embody.AttributeMapping(data)[source]¶
Bases:
MappingMapping that allows attribute access (Box pattern).
Allows accessing dictionary keys as attributes for more fluid syntax.
Examples
>>> 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'
- class embody.CompiledPathEngine(*args, **kwargs)[source]¶
Bases:
BaseEmbodimentEnginePre-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
>>> 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)[source]¶
Compile a template into a flat path map.
Examples
>>> engine = CompiledPathEngine() >>> template = {'a': {'b': '${x}'}} >>> compiled = engine.compile(template) >>> compiled['flat'] {('a', 'b'): '${x}'}
- class embody.Context(params=None, parent=None, resolvers=None, auto_call=True)[source]¶
Bases:
MappingParameter 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
>>> ctx = Context({'name': 'Alice', 'age': 30}) >>> ctx['name'] 'Alice'
>>> import datetime >>> ctx = Context({'now': lambda: datetime.datetime.now()}) >>> ctx['now'] datetime.datetime(...)
>>> ctx = Context({'base': 10}, parent={'base': 5, 'other': 20}) >>> ctx['base'] # Local overrides parent 10 >>> ctx['other'] # Falls back to parent 20
- register_resolver(name, func)[source]¶
Register a named resolver function.
- Parameters:
Examples
>>> import os >>> ctx = Context() >>> ctx.register_resolver('env', lambda: os.environ.get('USER', 'unknown'))
- exception embody.CycleError[source]¶
Bases:
ExceptionRaised when a circular reference is detected in a data structure.
- class embody.DotPath(path, separator='.')[source]¶
Bases:
objectDot notation path handler (e.g., ‘user.address.city’).
Examples
>>> data = {'user': {'address': {'city': 'NYC'}}} >>> path = DotPath('user.address.city') >>> path.resolve(data) 'NYC'
- class embody.EmbodiedMapping(data)[source]¶
Bases:
MappingRead-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
>>> 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')[source]¶
Bases:
objectMain 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
>>> template = {'greeting': 'Hello ${name}', 'age': '${age}'} >>> embodier = Embodier(template) >>> embodier({'name': 'Alice', 'age': 30}) {'greeting': 'Hello Alice', 'age': 30}
>>> template = {'count': '${num}'} >>> embodier = Embodier(template) >>> embodier({'num': 42}) # Type preserved {'count': 42}
- class embody.FlatMapping(data, separator='.')[source]¶
Bases:
MappingMapping with flattened nested structure for path-based access.
Allows accessing nested values using dot notation as single keys.
Examples
>>> nested = {'user': {'name': 'Alice', 'age': 30}} >>> flat = FlatMapping(nested) >>> flat['user.name'] 'Alice' >>> flat['user.age'] 30 >>> list(flat.keys()) ['user.name', 'user.age']
- class embody.FrozenMapping(data)[source]¶
Bases:
MappingImmutable Mapping wrapper.
Provides a frozen (immutable) view of a dictionary.
Examples
>>> 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[source]¶
Bases:
ExceptionRaised when a path is malformed or invalid.
- class embody.IterativeStackEngine(syntax='dollar_brace', strict=False, key_collision='error')[source]¶
Bases:
BaseEmbodimentEngineIterative 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
- class embody.JSONPointer(pointer)[source]¶
Bases:
objectJSON 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
>>> data = {'foo': {'bar': [1, 2, 3]}} >>> ptr = JSONPointer('/foo/bar/0') >>> ptr.resolve(data) 1
>>> data = {'user': {'name': 'Alice', 'age': 30}} >>> JSONPointer('/user/name').resolve(data) 'Alice'
- classmethod from_parts(parts)[source]¶
Create a JSON Pointer from path components.
- Parameters:
- Return type:
- Returns:
JSONPointer instance
Examples
>>> ptr = JSONPointer.from_parts(['foo', 'bar', '0']) >>> ptr.pointer '/foo/bar/0'
- resolve(data, default=None)[source]¶
Resolve the pointer against data.
- Parameters:
- Return type:
- Returns:
Resolved value or default
Examples
>>> 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)[source]¶
Set a value at the pointer location.
- Parameters:
- Raises:
InvalidPathError – If path cannot be set
Examples
>>> data = {'a': {'b': {}}} >>> JSONPointer('/a/b/c').set(data, 42) >>> data {'a': {'b': {'c': 42}}}
- exception embody.KeyCollisionError[source]¶
Bases:
ExceptionRaised when dynamic keys resolve to the same value.
- class embody.LazyEmbodiedMapping(template, params, embodier)[source]¶
Bases:
MappingLazy 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
>>> 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[source]¶
Bases:
ExceptionRaised when a required template parameter is missing.
- class embody.MutableEmbodiedMapping(data)[source]¶
Bases:
MutableMappingMutable Mapping wrapper for embodied objects.
Provides full MutableMapping interface for modifying embodied results.
Examples
>>> data = {'a': 1, 'b': 2} >>> mutable = MutableEmbodiedMapping(data) >>> mutable['c'] = 3 >>> mutable['a'] = 10 >>> del mutable['b'] >>> dict(mutable) {'a': 10, 'c': 3}
- class embody.PathMapping(data, separator='.')[source]¶
Bases:
MappingMapping 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
>>> 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[source]¶
Bases:
ExceptionRaised when a path doesn’t exist in a data structure.
- class embody.RecursiveVisitorEngine(syntax='dollar_brace', strict=False, key_collision='error')[source]¶
Bases:
BaseEmbodimentEngineDynamic 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
>>> engine = RecursiveVisitorEngine() >>> template = {'greeting': 'Hello ${name}', 'count': '${num}'} >>> engine.embody(template, {'name': 'Alice', 'num': 42}) {'greeting': 'Hello Alice', 'count': 42}
- class embody.SubstitutionSyntax[source]¶
Bases:
objectDefines the syntax patterns for template variable substitution.
- classmethod get_pattern(syntax='dollar_brace')[source]¶
Get the regex pattern for the specified syntax.
- Parameters:
syntax (
str) – One of ‘dollar_brace’, ‘brace’, ‘double_bracket’- Return type:
- Returns:
Compiled regex pattern
Examples
>>> pattern = SubstitutionSyntax.get_pattern('dollar_brace') >>> pattern.findall('${name} is ${age}') ['name', 'age']
- class embody.TemplateWrapper(template, syntax='dollar_brace', check_cycles=True)[source]¶
Bases:
objectWrapper 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
>>> template = TemplateWrapper({'name': '${user}', 'age': '${years}'}) >>> sorted(template.get_dependencies()) ['user', 'years']
- class embody.TuplePath(parts)[source]¶
Bases:
objectTuple-based path (unambiguous, e.g., (‘user’, ‘address’, ‘city’)).
Examples
>>> data = {'user': {'address': {'city': 'NYC'}}} >>> path = TuplePath(('user', 'address', 'city')) >>> path.resolve(data) 'NYC'
- embody.as_mapping(data, style='basic')[source]¶
Convert data to a Mapping with the specified style.
- Parameters:
- Return type:
- Returns:
Mapping instance
Examples
>>> data = {'user': {'name': 'Alice'}} >>> m = as_mapping(data, 'attribute') >>> m.user.name 'Alice'
>>> m = as_mapping(data, 'flat') >>> m['user.name'] 'Alice'
- embody.count_template_markers(obj, syntax='dollar_brace')[source]¶
Count the number of template markers in a nested structure.
- Parameters:
- Return type:
- Returns:
Number of template markers found
Examples
>>> 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)[source]¶
Detect cycles in a nested data structure.
- Parameters:
- Raises:
CycleError – If a cycle is detected
- Return type:
Examples
>>> d = {'a': 1, 'b': [2, 3]} >>> detect_cycle(d) # No cycle, returns None
>>> 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)[source]¶
Convenience function for template embodiment.
This is the main entry point for simple embodiment use cases.
- Parameters:
- Return type:
- Returns:
Embodied object
Examples
>>> embody({'name': '${name}'}, {'name': 'Alice'}) {'name': 'Alice'}
>>> embody({'count': '${n}'}, {'n': 42}) {'count': 42}
>>> embody(['${a}', '${b}'], {'a': 1, 'b': 2}) [1, 2]
- embody.extract_template_vars(template, syntax='dollar_brace')[source]¶
Extract all template variable names from a string.
- Parameters:
- Return type:
- Returns:
List of variable names found in the template
Examples
>>> 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='')[source]¶
Flatten a nested dictionary into a single-level dictionary with path keys.
- Parameters:
- Return type:
- Returns:
Flattened dictionary with path keys
Examples
>>> d = {'a': {'b': {'c': 1}}, 'd': 2} >>> flatten_dict(d) {'a.b.c': 1, 'd': 2}
>>> d = {'user': {'name': 'Alice', 'age': 30}} >>> flatten_dict(d) {'user.name': 'Alice', 'user.age': 30}
>>> d = {'items': [1, 2, 3]} >>> flatten_dict(d) {'items.0': 1, 'items.1': 2, 'items.2': 3}
- embody.flatten_to_tuples(obj, parent_path=())[source]¶
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:
- Return type:
- Returns:
Dictionary mapping tuple paths to values
Examples
>>> 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)[source]¶
Get a value from a nested structure by path.
- Parameters:
- Return type:
- Returns:
Value at the path, or default if not found
Examples
>>> 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)[source]¶
Get an embodiment engine by name.
- Parameters:
strategy (
str) – Name of strategy (‘recursive’, ‘compiled’, ‘iterative’)**kwargs – Arguments to pass to engine constructor
- Return type:
- Returns:
Embodiment engine instance
Examples
>>> engine = get_engine('recursive', syntax='brace') >>> isinstance(engine, RecursiveVisitorEngine) True
- embody.is_exact_match(template, syntax='dollar_brace')[source]¶
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:
- Return type:
- Returns:
Variable name if exact match, None otherwise
Examples
>>> is_exact_match('${name}') 'name' >>> is_exact_match('Hello ${name}')
>>> is_exact_match('${count}') 'count'
- embody.max_depth(obj, current_depth=0)[source]¶
Calculate the maximum depth of a nested structure.
- Parameters:
- Return type:
- Returns:
Maximum depth
Examples
>>> 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')[source]¶
Parse a path in various formats.
- Parameters:
- Return type:
- Returns:
Path object
Examples
>>> parse_path('/user/name') <embody.paths.JSONPointer object at ...>
>>> parse_path('user.name') <embody.paths.DotPath object at ...>
>>> parse_path(('user', 'name')) <embody.paths.TuplePath object at ...>
- embody.resolve_path(data, path, default=None, format='auto')[source]¶
Resolve a path against data.
- Parameters:
- Return type:
- Returns:
Resolved value or default
Examples
>>> 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)[source]¶
Set a value in a nested structure by path (modifies in place).
- Parameters:
- Return type:
Examples
>>> 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)[source]¶
Set a value at a path.
- Parameters:
Examples
>>> data = {} >>> set_path(data, '/user/name', 'Alice') >>> data {'user': {'name': 'Alice'}}
- embody.substitute(template, params, syntax='dollar_brace', strict=False)[source]¶
Perform type-preserving substitution on a template value.
This is the core substitution function. It handles:
Exact match: ${var} -> returns params[‘var’] with type preserved
Partial match: “Count is ${var}” -> string interpolation
Non-string templates: returned unchanged
- Parameters:
- Return type:
- Returns:
The substituted value with type preservation
Examples
>>> 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='.')[source]¶
Unflatten a dictionary with path keys into a nested structure.
- Parameters:
- Return type:
- Returns:
Nested dictionary structure
Examples
>>> flat = {'a.b.c': 1, 'd': 2} >>> unflatten_dict(flat) {'a': {'b': {'c': 1}}, 'd': 2}
>>> flat = {'items.0': 'a', 'items.1': 'b'} >>> unflatten_dict(flat) {'items': ['a', 'b']}
- embody.unflatten_from_tuples(flat_dict)[source]¶
Unflatten a dictionary with tuple paths into a nested structure.
- Parameters:
flat_dict (
Dict[Tuple,Any]) – Dictionary with tuple paths as keys- Return type:
- Returns:
Nested structure (dict or list)
Examples
>>> flat = {('a', 'b', 0): 1, ('a', 'b', 1): 2} >>> unflatten_from_tuples(flat) {'a': {'b': [1, 2]}}
Modules
Core classes for embody: Context, Template, and Embodier. |
|
Graphviz templates |
|
Mapping interface wrappers for embodied objects. |
|
This module is about generating, validating, and operating on (parametrized) fields (i.e. stings, e.g. paths). |
|
Path addressing for nested data structures. |
|
Traversal strategies for template embodiment. |
|
Pattern matching and type-preserving substitution logic for templates. |
|
Base objects for definding templates |
|
Making templates for various objects |
|
Utility functions for embody: flattening, unflattening, and cycle detection. |