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

Steven D'Aprano steve at pearwood.info
Tue Apr 16 19:44:37 EDT 2019

On Tue, Apr 16, 2019 at 09:54:31PM +0100, Stefano Borini wrote:

> 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?

I think you are correct. See 


> If not, would a syntax like:
> for x in g() return v:
>     print(x)
> print(v) # prints 6
> be useful?

I don't know. You tell us -- why do you care about the StopIteration 
value in a for-loop?

I think your question here is backwards. You should not start with 
syntax to capture the exception value, then ask if it would be 
useful. You should start by finding a reason why we would want to 
capture the exception value, and only then worry about whether we need 
syntax for it, or some other method.


More information about the Python-ideas mailing list