Skip to content

liblaf.grapes.itertools ¤

Functions:

as_iterable ¤

as_iterable(
    obj: Any, base_type: ClassInfo | None = (str, bytes)
) -> Iterable
Source code in src/liblaf/grapes/itertools/_as_iterable.py
 7
 8
 9
10
11
12
13
14
15
def as_iterable(obj: Any, base_type: ClassInfo | None = (str, bytes)) -> Iterable:
    # https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.always_iterable
    if obj is None:
        return ()
    if base_type is not None and isinstance(obj, base_type):
        return (obj,)
    if isinstance(obj, Iterable):
        return obj
    return (obj,)

as_sequence ¤

as_sequence(
    obj: Any, base_type: ClassInfo | None = (str, bytes)
) -> Sequence
Source code in src/liblaf/grapes/itertools/_as_sequence.py
 9
10
def as_sequence(obj: Any, base_type: ClassInfo | None = (str, bytes)) -> Sequence:
    return tuple(as_iterable(obj, base_type))

deep_merge ¤

deep_merge(
    *mappings: Mapping[deep_merge[KT], deep_merge[VT]],
    append_arrays: bool = False,
) -> dict[deep_merge[KT], deep_merge[VT]]
Source code in src/liblaf/grapes/itertools/_deep_merge.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def deep_merge[KT, VT](
    *mappings: Mapping[KT, VT], append_arrays: bool = False
) -> dict[KT, VT]:
    result: dict[KT, VT] = {}
    for mapping in mappings:
        for key, value in mapping.items():
            if key in result:
                if isinstance(result[key], Mapping):
                    result[key] = deep_merge(  # pyright: ignore[reportArgumentType]
                        result[key],  # pyright: ignore[reportArgumentType]
                        value,  # pyright: ignore[reportArgumentType]
                        append_arrays=append_arrays,
                    )
                    continue
                if append_arrays and isinstance(result[key], Sequence):
                    result[key] = [*result[key], *value]  # pyright: ignore[reportArgumentType, reportGeneralTypeIssues]
                    continue
            result[key] = value
    return result

first_not_none ¤

first_not_none(
    *args: first_not_none[T] | None,
) -> first_not_none[T]

.

References
  1. more_itertools.first_true
Source code in src/liblaf/grapes/itertools/_first_not_none.py
1
2
3
4
5
6
7
def first_not_none[T](*args: T | None) -> T:
    """.

    References:
        1. [`more_itertools.first_true`](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.first_true)
    """
    return next(arg for arg in args if arg is not None)