Skip to Content
Functional Python Programming - Second Edition
book

Functional Python Programming - Second Edition

by Steven F. Lott
April 2018
Intermediate to advanced content levelIntermediate to advanced
408 pages
10h 42m
English
Packt Publishing
Content preview from Functional Python Programming - Second Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Functional Python Programming - Third Edition

Functional Python Programming - Third Edition

Steven F. Lott

Publisher Resources

ISBN: 9781788627061Supplemental Content