Combining iterators with chain()

We can use the chain() function to combine a collection of iterators into a single, overall iterator. This can be helpful to combine data that was decomposed via the groupby() function. We can use this to process a number of collections as if they were a single collection.

In particular, we can combine the chain() function with the contextlib.ExitStack() method to process a collection of files as a single iterable sequence of values. We can do something such as this:

from contextlib import ExitStackimport csvdef row_iter_csv_tab(*filenames: str) -> Iterator[List[str]]:    with ExitStack() as stack:        files = [            stack.enter_context(cast(TextIO, open(name, 'r')))            for name in filenames        ]  # type: List[TextIO] readers ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.