[Python-ideas] Catching the return value of a generator at the end of a for loop

Terry Reedy tjreedy at udel.edu
Tue Apr 16 23:47:43 EDT 2019


On 4/16/2019 4:54 PM, Stefano Borini wrote:
> given the following code
> 
> def g():
>      yield 2
>      yield 3
>      return 6
> 
> for x in g():
>      print(x)
> 
> The output is obviously
> 2
> 3
> 
> As far as I know, there is currently no way to capture the
> StopIteration value when the generator is used in a for loop. Is it
> true?
> If not, would a syntax like:
> 
> for x in g() return v:
>      print(x)
> 
> print(v) # prints 6
> 
> be useful? It would be syntactic sugar for (corner cases omitted)

Syntactic sugar should be reserved for fairly common cases, not for 
extremely rare cases.

> def g():
>      yield 2
>      yield 3
>      return 6

If a for loop user needs to see 6, it should be yielded.

Adding non-None return values to StopIteration is fairly new, and was/is 
intended for cases where a generator is not being used as a simple 
forward iterator.  For such special cases, special code like the 
following should be used.

> it = iter(g())
> while True:
>      try:
>          x = next(it)
>      except StopIteration as exc:
>          v = exc.value
>          break
>      else:
>          print(x)
> print(v)





-- 
Terry Jan Reedy



More information about the Python-ideas mailing list