qalgebra.utils.containers module

Tools for working with data structures built from native containers.

Summary

Functions:

nested_tuple

Recursively transform a container structure to a nested tuple.

sorted_if_possible

Create a sorted list of elements of an iterable if they are orderable.

Reference

qalgebra.utils.containers.sorted_if_possible(iterable, **kwargs)[source]

Create a sorted list of elements of an iterable if they are orderable.

See sorted for details on optional arguments to customize the sorting.

Parameters

of a finite number of elements to sort. (Iterable) –

kwargs:

Keyword arguments are passed on to sorted.

Returns

List of elements in iterable, sorted if orderable, otherwise kept in the order of iteration.

qalgebra.utils.containers.nested_tuple(container)[source]

Recursively transform a container structure to a nested tuple.

The function understands container types inheriting from the selected abstract base classes in collections.abc, and performs the following replacements:

  • Mapping to tuple of key-value pair tuples.

  • Sequence to tuple containing the same elements in unchanged order.

  • Collection to tuple containing the same elements in sorted order if

    orderable and otherwise in the order of iteration.

The function recurses into these container types to perform the same replacement, and leaves objects of other types untouched.

The returned container is hashable if and only if all the values contained in the original data structure are hashable.

Parameters

container – Data structure to transform into a nested tuple.

Returns

Nested tuple containing the same data as container.