Yield Items From Another Iterable
Learn how we can fetch data from another iterable with the help of an example.
We'll cover the following
Overview
Often, when we build a generator function, we end up in a situation where we want to yield data from another iterable object, possibly a list comprehension or generator expression we constructed inside the generator, or perhaps some external items
that were passed into the function. We’ll look at how to do this with the yield from
statement.
Example
Let’s adapt the generator example a bit so that instead of accepting an input file, it accepts the name of a directory. The idea is to keep our existing warnings filter generator in place, but tweak the structure of the functions that use it. We’ll operate on iterators as both input and result; this way the same function could be used regardless of whether the log lines came from a file, memory, the web, or another iterator.
This version of the code illustrates a new file_extract()
generator. This does some basic setup before yielding information from the warnings_filter()
generator:
Get hands-on with 1400+ tech skills courses.