Source code for tet.util.collections

"""
Collection utilities for Tet applications.

This module provides utility functions for working with collections.

Example
-------

Flattening nested iterables::

    from tet.util.collections import flatten

    nested = [1, [2, 3, [4, 5]], 6]
    flat = list(flatten(nested))
    # flat == [1, 2, 3, 4, 5, 6]

    # Strings are not exploded
    with_strings = ["hello", ["world", ["!"]]]
    flat = list(flatten(with_strings))
    # flat == ["hello", "world", "!"]
"""

from collections.abc import Iterable


[docs] def flatten(iterable): """ Flattens a deeply nested iterable, but does not explode str, bytes. From http://stackoverflow.com/a/2158532/ :param iterable: the iterable to flatten :return: a generator of flattened items """ for el in iterable: if isinstance(el, Iterable) and not isinstance(el, (str, bytes)): yield from flatten(el) else: yield el