How to yield results from a nested generator function?

You may have to use the new yield from, available since Python 3.3, known as “delegated generator”.

If I understood the question correctly, I came to the same issue, and found an answer elsewhere.

I wanted to do something like this:

def f():

    def g():

        do_something()
        yield x
        …
        yield y

    do_some_other_thing()
    yield a
    …
    g()  # Was not working.
    yield g()  # Was not what was expected neither; yielded None.
    …
    yield b

I now use this instead:

yield from g()  # Now it works, it yields x and Y.

I got the answer from this page: Python 3: Using "yield from" in Generators - Part 1 (simeonvisser.com).


Can't believe I missed this; The answer is to simply return the generator function with suitable arguments applied:

import time

def GeneratorFunction(max_val):
    for i in range(0,max_val):
        time.sleep(1)
        yield "String %d"%i

def SmallGenerator():
    return GeneratorFunction(3) # <-- note the use of return instead of yield

for s in SmallGenerator():
    print s

Came here looking for a different form of "nested yield" and finally found the hidden answer. Might not be the best but it works.

I was wanting to yield through a registry tree and here is the solution.

        def genKeys(key):
            for value in key.values():
                yield value
            for subkey in key.subkeys():
                print(subkey)
                for x in genKeys(subkey): #this is the trick
                    continue