1

I have a generator and want to yield none after which I want the iteration of the generator to stop, i.e. StopIteration but I am not sure which way to accomplish this.

I think of the following to options:

yield None
return

and

return

in my generator. Are they equivalent? Or which one should I use?

2 Answers2

2

Are they equivalent?

No. The second one isn't even a generator (no yield expression)

Which one should I use?

The first one is fine. The return statement and also the value None explicitly yielded are redundant and can be removed (but they're not harming anything either).

def myfunc():
    print("doing stuff before yielding the first (and only) value")
    yield
    print("doing more stuff before raising StopIteration")

Should you use an explicit return statement, then the value returned will appear on the StopIteration exception instance (literally a value attribute).

Syntactically, you can put code after the return statement, but it will be unreachable. So, there's no point to do that.

wim
  • 338,267
  • 99
  • 616
  • 750
  • Yea.. My connection went away while editing.. –  Apr 17 '19 at 22:59
  • No, I know what `yield` does and the fact that a `yield` statement makes a function a generator. So in the second case, the code after the `return` would contain a `yield`. Then, what are the difference between `yield None; return` and `return None` or `return` in the case that the function is a generator in BOTH cases –  Apr 17 '19 at 23:05
  • The difference is whether you yield a value or not. `list(gen1)` would be `[None]` and `list(gen2)` would be `[]`. – wim Apr 17 '19 at 23:07
  • Even though there were `yield` statements in BOTH cases and thus both are generators? –  Apr 17 '19 at 23:08
  • 1
    Yeah. Generators can yield no values and still be generators. I suppose that's kind of a weird maybe use-case for putting a yield statement behind the return, although I don't know why you would want a generator instance which yields no vals as opposed to just passing around a function object directly. – wim Apr 17 '19 at 23:10
0

Returning using return from a generator doesn't return the value 'None' like a function would. It instead merely stops the generator.

>>> def f():
...     yield 1
...     yield 2
...     yield None
...     return
... 
>>> def f2():
...     yield 1
...     yield 2
...     return
... 
>>> for i in f():
...     print(i)
... 
1
2
None
>>> for i in f2():
...     print(i)
... 
1
2
>>>
Anuj Kumar
  • 130
  • 1
  • 9