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 the number of template markers in a nested structure. |
|
Detect cycles in a nested data structure. |
|
Flatten a nested dictionary into a single-level dictionary with path keys. |
|
Flatten a nested structure using tuple paths (unambiguous). |
|
Get a value from a nested structure by path. |
|
Calculate the maximum depth of a nested structure. |
|
Set a value in a nested structure by path (modifies in place). |
|
Unflatten a dictionary with path keys into a nested structure. |
|
Unflatten a dictionary with tuple paths into a nested structure. |
Exceptions
Raised when a circular reference is detected in a data structure. |
|
Raised when a path doesn't exist in a data structure. |
- exception embody.util.CycleError[source]¶
Bases:
ExceptionRaised when a circular reference is detected in a data structure.
- exception embody.util.PathNotFoundError[source]¶
Bases:
ExceptionRaised 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:
- 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.util.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.util.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.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:
- 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.util.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.util.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.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:
- Return type:
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:
- 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.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:
- Returns:
Nested structure (dict or list)
Examples
>>> flat = {('a', 'b', 0): 1, ('a', 'b', 1): 2} >>> unflatten_from_tuples(flat) {'a': {'b': [1, 2]}}