Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is no value returned from my generator?

I've come across some surprising behavior with Python generators:

>>> def f(n):
...     if n < 2:
...         return [n]
...     for i in range(n):
...         yield i * 2
... 
>>> list(f(0))
[]
>>> list(f(1))
[]
>>> list(f(2))
[0, 2]

Why is no value returned from the generator in the first two cases?

like image 441
planetp Avatar asked Aug 31 '25 22:08

planetp


1 Answers

Because generator return statements don't return anything, they end the execution (python knows this is a generator because it contains at least one yield statement). Instead of return [n] do

 yield n
 return

EDIT

after raising this with the python core devs, they pointed me to the python docs where it says

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

So you can do

def f(n):
    if n < 2:
         return [n]
    for i in range(n):
         yield i * 2

g = f(1)
res = []
while True:
    try:
         res.append(next(g))
    except StopIteration as e:
         if e.value is not None:
              res = e.value
         break

if you really, really wanted.

like image 146
FHTMitchell Avatar answered Sep 03 '25 23:09

FHTMitchell