I wrote this function to flatten nested iterables (with arbitrary depth) but refrain from flattening excepted types (for instance, string or tuple):
from typing import Iterable, Tuple, Type
def flatten(item: Iterable, except_types: Type | Tuple[Type] | None = None):
if except_types is not None and isinstance(item, except_types):
yield item
for element in item:
if except_types is not None and isinstance(element, except_types):
yield element
continue
try:
yield from flatten(element, except_types)
except TypeError:
yield element
Therefore it works this way:
>>> list(flatten([(1, 2), [(3, 4), [(5, 6), (7, 8)]]], tuple))
[(1, 2), (3, 4), (5, 6), (7, 8)]
Could this code be made more concise and elegant, and yet easily readable?