Skip to content

topmark.utils.merge

topmark / utils / merge

Field merge helpers.

none_if_empty

none_if_empty(items)

Return None if an iterable materializes to an empty list.

Source code in src/topmark/utils/merge.py
def none_if_empty(items: Iterable[T]) -> list[T] | None:
    """Return `None` if an iterable materializes to an empty list."""
    materialized: list[T] = list(items)
    return materialized or None

merge_unique_iterables

merge_unique_iterables(current, incoming)

Returns a new list with unique items from current and incoming.

Preserves order. Always returns a list (empty if both are None).

Source code in src/topmark/utils/merge.py
def merge_unique_iterables(
    current: Iterable[T] | None,
    incoming: Iterable[T] | None,
) -> list[T]:
    """Returns a new list with unique items from current and incoming.

    Preserves order. Always returns a list (empty if both are None).
    """
    # Use a set for O(1) lookups to avoid O(N^2) performance hits
    result: list[T] = []
    seen: set[T] = set()

    for item in current or []:
        if item not in seen:
            result.append(item)
            seen.add(item)

    if incoming:
        for item in incoming:
            if item not in seen:
                result.append(item)
                seen.add(item)

    return result

merge_unique_iterables_or_none

merge_unique_iterables_or_none(current, incoming)

Returns None if both inputs are None, otherwise merges uniquely.

Source code in src/topmark/utils/merge.py
def merge_unique_iterables_or_none(
    current: Iterable[T] | None,
    incoming: Iterable[T] | None,
) -> list[T] | None:
    """Returns None if both inputs are None, otherwise merges uniquely."""
    if current is None and incoming is None:
        return None
    return merge_unique_iterables(current, incoming)

merge_mappings_last_wins

merge_mappings_last_wins(current, incoming)

Merges two dicts (incoming overrides current).

Always returns a dict (empty if both are None).

Source code in src/topmark/utils/merge.py
def merge_mappings_last_wins(
    current: dict[str, T] | None,
    incoming: dict[str, T] | None,
) -> dict[str, T]:
    """Merges two dicts (incoming overrides current).

    Always returns a dict (empty if both are None).
    """
    # Python 3.9+ merge operator (|) handles the copy and update logic cleanly
    return (current or {}) | (incoming or {})

merge_mappings_last_wins_or_none

merge_mappings_last_wins_or_none(current, incoming)

Returns None if both inputs are None, otherwise merges dicts.

Source code in src/topmark/utils/merge.py
def merge_mappings_last_wins_or_none(
    current: dict[str, T] | None,
    incoming: dict[str, T] | None,
) -> dict[str, T] | None:
    """Returns None if both inputs are None, otherwise merges dicts."""
    if current is None and incoming is None:
        return None
    return merge_mappings_last_wins(current, incoming)