Skip to content

toolkit._iter

Functions:

flatten

flatten(iterable: _T | Iterable[_T] | Iterable[Iterable[_T]] | Iterable, base_type: tuple[type, ...] = (str, bytes)) -> Iterable[_T]
Source code in src/toolkit/_iter/_sequence.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
def flatten(
    iterable: _T | Iterable[_T] | Iterable[Iterable[_T]] | Iterable,
    base_type: tuple[type, ...] = (str, bytes),
) -> Iterable[_T]:
    if not tp.is_iterable(iterable, base_type):
        yield iterable  # pyright: ignore [reportReturnType]
        return

    for item in iterable:
        if tp.is_iterable(item, base_type):
            yield from flatten(item)
        else:
            yield item

is_subsequence

is_subsequence(a: Sequence[Any], b: Sequence[Any]) -> bool
Source code in src/toolkit/_iter/_sequence.py
24
25
26
27
28
29
30
31
def is_subsequence(a: Sequence[Any], b: Sequence[Any]) -> bool:
    i: int = 0
    j: int = 0
    while i < len(a) and j < len(b):
        if a[i] == b[j]:
            i += 1
        j += 1
    return i == len(a)

merge_mapping

merge_mapping(origin: Mapping, update: Mapping) -> dict

Updates the original dict with the new data. Similar to dict.update(), but works with nested dicts.

References
  1. [ConfZ/confz/loaders/loader.py:L10-L28)(https://github.com/Zuehlke/ConfZ/blob/6c99cc2a2938e231590dceeef66749ccf2eb6b4c/confz/loaders/loader.py#L10-L28)
Source code in src/toolkit/_iter/_mapping.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def merge_mapping(origin: Mapping, update: Mapping) -> dict:
    """Updates the original dict with the new data. Similar to `dict.update()`, but works with nested dicts.

    References:
        1. [ConfZ/confz/loaders/loader.py:L10-L28)(https://github.com/Zuehlke/ConfZ/blob/6c99cc2a2938e231590dceeef66749ccf2eb6b4c/confz/loaders/loader.py#L10-L28)
    """
    original: dict = dict(origin)
    for key, value in update.items():
        if isinstance(value, Mapping) and key in original:
            if not isinstance(original[key], Mapping):
                msg: str = (
                    "Config variables contradict each other: "
                    f"Key {key:!r} is both a value and a nested dict."
                )
                raise ValueError(msg)
            original[key] = merge_mapping(original[key], value)
        else:
            original[key] = value
    return original