Skip to content

Collections

rn_forge.commons.lang.collections

Nested collection access, deep merge, comparison, filtering, and grouping.

DictUtils

Utilities for nested dict traversal, mutation, merging, and comparison.

Dot-delimited key paths (e.g. "a.b.c") are supported; escape a literal dot with a backslash ("a\.b").

as_mapping(value) staticmethod

Return a shallow, string-keyed copy of value if it is a mapping.

Parameters:

Name Type Description Default
value object

Any value, such as the root of a parsed document.

required

Returns:

Type Description
dict[str, object]

The mapping with its keys converted to str, or an empty dict for

dict[str, object]

any other value.

Example::

DictUtils.get_mapping(DictUtils.as_mapping(YamlUtils.load(text)), "jobs")

compare(dict_a, dict_b) staticmethod

Return a structural diff between two dicts.

The result dict may contain the following top-level keys:

  • "only_in_a": mapping of keys present in dict_a but not dict_b.
  • "only_in_b": mapping of keys present in dict_b but not dict_a.
  • "conflicts": mapping of keys present in both with differing values. For nested dicts the value is a recursive diff result; for leaf values it is [value_a, value_b].

Parameters:

Name Type Description Default
dict_a Mapping[str, Any]

The first dictionary.

required
dict_b Mapping[str, Any]

The second dictionary.

required

Returns:

Type Description
dict[str, Any]

A diff dict, or an empty dict when the two inputs are structurally

dict[str, Any]

equal.

Example::

DictUtils.compare({"a": 1, "b": 2}, {"b": 3, "c": 4})
# {
#   "only_in_a": {"a": 1},
#   "only_in_b": {"c": 4},
#   "conflicts": {"b": [2, 3]},
# }

flatten(value, prefix='') staticmethod

Flatten nested mappings into a single level of dotted-path keys.

The inverse of the dotted-path traversal :meth:get/:meth:set already perform — {"a": {"b": 1}} becomes {"a.b": 1}. A dict key containing a literal . is escaped as \. in the flattened key, matching :meth:get/:meth:set's own escaping convention.

Parameters:

Name Type Description Default
value Mapping[str, Any]

The (possibly nested) mapping to flatten.

required
prefix str

Internal recursion accumulator — leave at the default.

''

Returns:

Type Description
dict[str, Any]

A single-level dict whose keys are dotted paths.

Example::

DictUtils.flatten({"a": {"b": 1, "c": 2}, "d": 3})
# {"a.b": 1, "a.c": 2, "d": 3}

get(data, key_path, *, default=None) staticmethod

Retrieve a value from a nested dict using a dot-delimited key path.

Supports both dict and list traversal; list indices are expressed as numeric path segments (e.g. "items.0.name"). Escape a literal dot in a key with a backslash ("a\.b").

Parameters:

Name Type Description Default
data Mapping[str, Any]

The dictionary to search.

required
key_path str

Dot-delimited path, e.g. "a.b.0.c".

required
default Any

Value returned when the path cannot be resolved. Defaults to None.

None

Returns:

Type Description
Any

The resolved value, or default if any segment is missing,

Any

out of bounds, or data/key_path is empty.

Example::

data = {"users": [{"name": "Alice"}, {"name": "Bob"}]}
DictUtils.get(data, "users.1.name")  # "Bob"
DictUtils.get(data, "users.5.name", default="N/A")  # "N/A"

get_bool(data, key_path, *, default=False) staticmethod

Return the boolean at key_path, or default if it is not a bool.

No truthiness coercion: "false", 0 and 1 read as absent.

Parameters:

Name Type Description Default
data Mapping[str, Any]

The dictionary to search.

required
key_path str

Dot-delimited path, as for :meth:get.

required
default bool

Returned when the path is missing or holds a non-boolean.

False

Returns:

Type Description
bool

The boolean value, or default.

get_list(data, key_path) staticmethod

Return the list at key_path; a lone scalar reads as one element.

Only a list is spread — a mapping or string is a single element.

Parameters:

Name Type Description Default
data Mapping[str, Any]

The dictionary to search.

required
key_path str

Dot-delimited path, as for :meth:get.

required

Returns:

Type Description
list[object]

A shallow copy of the list, [value] for any other non-None

list[object]

value, or an empty list if the path is missing or holds None.

Example::

DictUtils.get_list({"cmds": "echo hi"}, "cmds")  # ["echo hi"]
DictUtils.get_list({"cmds": None}, "cmds")       # []

get_mapping(data, key_path) staticmethod

Return the mapping at key_path as a string-keyed dict.

Parameters:

Name Type Description Default
data Mapping[str, Any]

The dictionary to search.

required
key_path str

Dot-delimited path, as for :meth:get.

required

Returns:

Type Description
dict[str, object]

A shallow copy of the mapping with its keys converted to str,

dict[str, object]

or an empty dict if the path is missing or holds a non-mapping.

Example::

doc = {"repository": {"name": "demo"}, "docs": "mkdocs"}
DictUtils.get_mapping(doc, "repository")  # {"name": "demo"}
DictUtils.get_mapping(doc, "docs")        # {}

get_str(data, key_path, *, default='') staticmethod

Return the string at key_path, or default if it is not a str.

Parameters:

Name Type Description Default
data Mapping[str, Any]

The dictionary to search.

required
key_path str

Dot-delimited path, as for :meth:get.

required
default str

Returned when the path is missing or holds a non-string.

''

Returns:

Type Description
str

The string value, or default.

get_strings(data, key_path) staticmethod

Return the string elements at key_path, ignoring anything else.

Reads through :meth:get_list, so a lone string is a one-element list.

Parameters:

Name Type Description Default
data Mapping[str, Any]

The dictionary to search.

required
key_path str

Dot-delimited path, as for :meth:get.

required

Returns:

Type Description
list[str]

The str elements, in order; non-strings are dropped.

Example::

doc = {"dev": ["pytest", {"include-group": "lint"}]}
DictUtils.get_strings(doc, "dev")  # ["pytest"]

merge(target, *overrides) staticmethod

Deep-merge one or more overrides dicts into target, mutating target.

Merging rules:

  • dict values are merged recursively.
  • Non-dict values in overrides replace the corresponding value in target.
  • Override values are deep-copied to prevent shared references between target and overrides.
  • Empty or None override dicts are silently skipped.

Parameters:

Name Type Description Default
target dict[str, Any]

The dictionary to merge into (mutated in-place).

required
*overrides dict[str, Any]

One or more dicts whose values are merged into target in order.

()

Returns:

Type Description
dict[str, Any]

target after merging, enabling chained calls.

Example::

base = {"a": {"x": 1}, "b": 2}
DictUtils.merge(base, {"a": {"y": 3}, "b": 99})
# {"a": {"x": 1, "y": 3}, "b": 99}

merge_layers(*layers, layer_names=None, append_paths=()) staticmethod

Deep-merge layers in increasing precedence order, tracking provenance.

Unlike :meth:merge, every dotted key path in the result is tracked back to the name of the highest-precedence layer that supplied it — this is what drives a diff/doctor-style command that explains where each config value came from. This does not replace :meth:merge, whose signature and semantics are unchanged and remain load-bearing elsewhere; this is additive.

Parameters:

Name Type Description Default
*layers Mapping[str, Any] | tuple[str, Mapping[str, Any]]

Each layer is either a plain mapping or an explicit (name, mapping) pair. Unnamed layers are assigned conventional names in order: "defaults", "global", "local", "overrides", then "layer-N".

()
layer_names Sequence[str] | None

Explicit names for the unnamed layers, by position. Overridden by an explicit (name, mapping) tuple at that position.

None
append_paths Collection[str]

Dotted paths (DictUtils.get-style, e.g. "servers.hosts") whose list values concatenate across layers instead of the default replace-wholesale behaviour.

()

Returns:

Name Type Description
A MergeResult

class:MergeResult with the merged config and a

MergeResult

provenance map of dotted path -> layer name. A subtree

MergeResult

introduced wholesale by one layer gets a provenance entry on

MergeResult

every leaf, not just the subtree root.

Example::

result = DictUtils.merge_layers(
    {"a": 1}, ("overrides", {"a": 2}),
)
result.config       # {"a": 2}
result.provenance   # {"a": "overrides"}

set(data, key_path, value) staticmethod

Set a value in a nested dict using a dot-delimited key path.

Intermediate dicts are created automatically when a segment is absent. List segments must reference existing indices — the list is never auto-extended. Does nothing when key_path is empty or whitespace.

Parameters:

Name Type Description Default
data dict[str, Any]

The dictionary to mutate in-place.

required
key_path str

Dot-delimited path to the target key, e.g. "database.host".

required
value Any

The value to assign at the resolved path.

required

Raises:

Type Description
KeyError

If a non-numeric index is used for a list segment.

IndexError

If a list index is out of bounds.

TypeError

When traversal encounters an existing value that is neither a dict nor a list.

Example::

cfg: dict[str, Any] = {}
DictUtils.set(cfg, "database.host", "localhost")
assert cfg == {"database": {"host": "localhost"}}

ListUtils

Utilities for list access, sorting, filtering, and grouping.

as_list(value) staticmethod

Return value as a list; a lone scalar reads as one element.

Only a list is spread; a mapping or string is a single element.

Parameters:

Name Type Description Default
value object

Any value.

required

Returns:

Type Description
list[object]

A copy of a list, [] for None, else [value].

Example::

ListUtils.as_list("echo hi")  # ["echo hi"]
ListUtils.as_list(None)       # []

as_strings(value) staticmethod

Return the string elements of as_list(value).

Parameters:

Name Type Description Default
value object

Any value.

required

Returns:

Type Description
list[str]

The str elements, in order; non-strings are dropped.

Example::

ListUtils.as_strings(["pytest", {"include-group": "lint"}])  # ["pytest"]

filter(items, predicate) staticmethod

Return items matching predicate or equal to predicate.

get(items, index=0, *, default=None) staticmethod

Return the item at index, or default when missing.

group_by(items, key_fn, value_fn=None, group_fn=None) staticmethod

Group items by key_fn without mutating the input list.

sort(items, key=None, reverse=False) staticmethod

Sort items in-place and return it.

MergeResult(config, provenance) dataclass

Configuration and provenance returned by :meth:DictUtils.merge_layers.