-1

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?

albertopasqualetto
  • 87
  • 1
  • 1
  • 11
  • 1
    Did you mean for `outer` to have an argument `x`? Why not try it yourself and see what happens? – Pranav Hosangadi Aug 09 '23 at 22:19
  • 3
    Nothing happens with generators until you use them by calling `next`. In this case `next(inner(-1))` raises a `StopIteration` exception, which is what we expect when a generator has nothing more to say. You will get a `StopIteration` from `outer` as well. If you do something like `list(outer())` you will get an empty list as expected. – Mark Aug 09 '23 at 22:20
  • @PranavHosangadi it is not important where `x` comes from, anyway I asked while trying since I am new to `yield` keyword, so I am not sure what I am expecting – albertopasqualetto Aug 09 '23 at 22:21
  • Related: [What Happens when a Generator Runs out of Values to Yield?](https://stackoverflow.com/q/39110210/2745495) – Gino Mempin Aug 09 '23 at 22:37

1 Answers1

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612