Skip to content

# collections

## `xsdata.utils.collections`

### `is_array(value)`

Return whether the value is a list style type.

Source code in `xsdata/utils/collections.py`

    11
    12
    13
    14
    15
    16

    def is_array(value: Any) -> bool:
        """Return whether the value is a list style type."""
        if isinstance(value, tuple):
            return not hasattr(value, "_fields")

        return isinstance(value, (list, set, frozenset, Generator))

### `unique_sequence(items, key=None)`

Return a new unique list, preserving the original order.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`items` | `Iterable[T]` | The iterable to filter | required
`key` | `str | None` | An optional callable to generate the unique keys | `None`

Returns:

Type | Description
--- | ---
`list[T]` | A new unique list.

Source code in `xsdata/utils/collections.py`

    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41

    def unique_sequence(items: Iterable[T], key: str | None = None) -> list[T]:
        """Return a new unique list, preserving the original order.

        Args:
            items: The iterable to filter
            key: An optional callable to generate the unique keys

        Returns:
            A new unique list.
        """
        seen = set()

        def is_new(val: Any) -> bool:
            if key:
                val = getattr(val, key)

            if val in seen:
                return False

            seen.add(val)
            return True

        return [item for item in items if is_new(item)]

### `remove(items, predicate)`

Return a new list without the items that match the predicate.

Source code in `xsdata/utils/collections.py`

    44
    45
    46

    def remove(items: Iterable[T], predicate: Callable) -> list[T]:
        """Return a new list without the items that match the predicate."""
        return [x for x in items if not predicate(x)]

### `group_by(items, key)`

Group the items of an iterable object by the result of the callable.

Source code in `xsdata/utils/collections.py`

    49
    50
    51
    52
    53
    54

    def group_by(items: Iterable[T], key: Callable) -> dict[Any, list[T]]:
        """Group the items of an iterable object by the result of the callable."""
        result = defaultdict(list)
        for item in items:
            result[key(item)].append(item)
        return result

### `apply(items, func)`

Apply the given function to each item of the iterable object.

Source code in `xsdata/utils/collections.py`

    57
    58
    59
    60

    def apply(items: Iterable, func: Callable) -> None:
        """Apply the given function to each item of the iterable object."""
        for item in items:
            func(item)

### `find(items, value)`

Return the index of the value in the given sequence.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`items` | `Sequence` | The sequence to search in | required
`value` | `Any` | The value to search for | required

Returns:

Type | Description
--- | ---
`int` | The index in the sequence or -1 if the value is not found.

Source code in `xsdata/utils/collections.py`

    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76

    def find(items: Sequence, value: Any) -> int:
        """Return the index of the value in the given sequence.

        Args:
            items: The sequence to search in
            value: The value to search for

        Returns:
            The index in the sequence or -1 if the value is not found.
        """
        try:
            return items.index(value)
        except ValueError:
            return -1

### `first(items)`

Return the first item of the iterator.

Source code in `xsdata/utils/collections.py`

    79
    80
    81

    def first(items: Iterator[T]) -> T | None:
        """Return the first item of the iterator."""
        return next(items, None)

### `prepend(target, *args)`

Prepend items to the target list.

Source code in `xsdata/utils/collections.py`

    84
    85
    86

    def prepend(target: list, *args: Any) -> None:
        """Prepend items to the target list."""
        target[:0] = args

### `connected_components(lists)`

Merge lists of lists that share common elements.

Source code in `xsdata/utils/collections.py`

     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107

    def connected_components(lists: list[list[Any]]) -> Iterator[list[Any]]:
        """Merge lists of lists that share common elements."""
        neighbors = defaultdict(set)
        for each in lists:
            for item in each:
                neighbors[item].update(each)

        def component(node: Any, neigh: dict[Any, set], see: set[Any]) -> Iterator[Any]:
            nodes = {node}
            while nodes:
                next_node = nodes.pop()
                see.add(next_node)
                nodes |= neigh[next_node] - see
                yield next_node

        seen: set[Any] = set()
        for item in neighbors:
            if item not in seen:
                yield sorted(component(item, neighbors, seen))

### `find_connected_component(groups, value)`

Find the list index that contains the given value.

Source code in `xsdata/utils/collections.py`

    110
    111
    112
    113
    114
    115
    116

    def find_connected_component(groups: list[list[Any]], value: Any) -> int:
        """Find the list index that contains the given value."""
        for index, group in enumerate(groups):
            if value in group:
                return index

        return -1