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(obj[, syntax])

Count the number of template markers in a nested structure.

detect_cycle(obj[, visited, path])

Detect cycles in a nested data structure.

flatten_dict(nested_dict[, separator, ...])

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

flatten_to_tuples(obj[, parent_path])

Flatten a nested structure using tuple paths (unambiguous).

get_by_path(obj, path[, separator, default])

Get a value from a nested structure by path.

max_depth(obj[, current_depth])

Calculate the maximum depth of a nested structure.

set_by_path(obj, path, value[, separator, ...])

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

unflatten_dict(flat_dict[, separator])

Unflatten a dictionary with path keys into a nested structure.

unflatten_from_tuples(flat_dict)

Unflatten a dictionary with tuple paths into a nested structure.

Exceptions

CycleError

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

PathNotFoundError

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

exception embody.util.CycleError[source]

Bases: Exception

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

exception embody.util.PathNotFoundError[source]

Bases: Exception

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

embody.util.count_template_markers(obj, syntax='dollar_brace')[source]

Count the number of template markers in a nested structure.

Parameters:
  • obj (Any) – Object to count markers in

  • syntax (str) – Template syntax to look for

Return type:

int

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.util.detect_cycle(obj, visited=None, path=None)[source]

Detect cycles in a nested data structure.

Parameters:
  • obj (Any) – The object to check for cycles

  • visited (Set[int]) – Set of object IDs already visited

  • path (List[str]) – Current path in the structure (for error reporting)

Raises:

CycleError – If a cycle is detected

Return type:

None

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.util.flatten_dict(nested_dict, separator='.', parent_key='')[source]

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

Parameters:
  • nested_dict (Dict[str, Any]) – Nested dictionary to flatten

  • separator (str) – String to use for separating path components

  • parent_key (str) – Key of the parent (used in recursion)

Return type:

Dict[str, Any]

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.util.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:
  • obj (Any) – Object to flatten

  • parent_path (Tuple) – Current path as tuple

Return type:

Dict[Tuple, Any]

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.util.get_by_path(obj, path, separator='.', default=None)[source]

Get a value from a nested structure by path.

Parameters:
  • obj (Any) – Nested structure

  • path (Union[str, Tuple]) – Path as string or tuple

  • separator (str) – Separator for string paths

  • default (Any) – Default value if path not found

Return type:

Any

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.util.max_depth(obj, current_depth=0)[source]

Calculate the maximum depth of a nested structure.

Parameters:
  • obj (Any) – Object to measure

  • current_depth (int) – Current depth (used in recursion)

Return type:

int

Returns:

Maximum depth

Examples

>>> 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)[source]

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

Parameters:
  • obj (Dict) – Nested structure to modify

  • path (Union[str, Tuple]) – Path as string or tuple

  • value (Any) – Value to set

  • separator (str) – Separator for string paths

  • create_intermediate (bool) – If True, create intermediate dicts/lists as needed

Return type:

None

Examples

>>> d = {}
>>> set_by_path(d, 'a.b.c', 42)
>>> d
{'a': {'b': {'c': 42}}}
embody.util.unflatten_dict(flat_dict, separator='.')[source]

Unflatten a dictionary with path keys into a nested structure.

Parameters:
  • flat_dict (Dict[str, Any]) – Flattened dictionary with path keys

  • separator (str) – String used for separating path components

Return type:

Dict[str, Any]

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.util.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:

Any

Returns:

Nested structure (dict or list)

Examples

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