Writing recursive generator functions with the yield from statement
There are a number of algorithms that can be expressed neatly as recursions. In the Designing recursive functions around Python's stack limits recipe, we looked at some recursive functions that could be optimized to reduce the number of function calls.
When we look at some data structures, we see that they involve recursion. In particular, JSON documents (as well as XML and HTML documents) can have a recursive structure. A JSON document might include a complex object that contains other complex objects within it.
In many cases, there are advantages to using generators for processing these kinds of structures. How can we write generators that work with recursion? How does the yield from
statement save us from writing an extra loop?
Getting ready
We'll look at a way to search an ordered collection for all matching values in a complex data structure. When working with complex JSON documents, we'll often model them as dict-of-dict...