Proposal: flatten multi-nested list/tuple/set and other certain class/type.

I thought that itertools.chain.from_iterable isn't useful. cuz this only allow "single-nested iterable -- this will raise error when arg has non-nested element--" like below::
and this can't unpack over double nest.
So, I wanted to make "True chain.from_iterable". and this is it. def flatten(iterables, unpack=(list, tuple, set), peep=(list, tuple, set)): for element in iterables: try: if isinstance(element, unpack): if isinstance(element, peep): yield from flatten(element, unpack=unpack, peep=peep) else: yield from flatten(element, unpack=(), peep=()) elif isinstance(element, peep): yield type(element)(flatten(element, unpack=unpack, peep=peep)) else: raise TypeError except TypeError: yield element Reason why I didin't use type() is wanted to unpack type-object like "range" and I wanted to unpack user-defined-class/func. this is why I didin't use collections.Iterable to check instance. I know this will be destructed by itertools.count :( Please give me advice. And I wanna know why function like this is not in standard library. thx.
participants (1)
-
delta114514