qnet.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

qnet.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:
  • iterable (Iterable) – Iterable returning a finite number of elements to sort.
  • kwargs – Keyword arguments are passed on to sorted.
Returns:

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

Return type:

list

qnet.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

tuple of key-value pair tuple`s. The order is preserved in the case of an `OrderedDict, otherwise the key-value pairs are sorted if orderable and otherwise kept in the order of iteration.
Sequence
tuple containing the same elements in unchanged order.
Container and Iterable and Sized (equivalent to Collection in python >= 3.6)
tuple containing the same elements in sorted order if orderable and otherwise kept 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.
Return type:tuple