pythonyieldyield-from

What happens if I do not yield anything to `yield from`?


What happens if I do not yield anything to yield from?

This is an example:

def inner(x):
    if x > 0:
        yield "Greater than zero"
    elif x==0:
        yield "Zero"

def outer():
    yield from inner(x)

In this case inner(x) yields something to outer() if and only if x is >= 0.

What happens if x is negative?


Solution

  • The same thing that happens if you use inner(-1) directly as an iterator; yield from simply passes along whatever was yielded. If it doesn't yield anything, the StopIteration exception is thrown, and this exception passes through. Operators or functions that loop over the iterator interpret this as the end of the sequence and stop iterating; if you don't call outer() from such a construct, you'll see the exception itself.