Let generator.close() return StopIteration.value #104770
Labels
type-feature
A feature request or enhancement
Content-Length: 221330 | pFad | https://github.com/python/cpython/issues/104770
2BFetched URL: https://github.com/python/cpython/issues/104770
Alternative Proxies:
Feature or enhancement
Change the
close()
method of generators to return the value ofStopIteration
.Pitch
If a generator handles the
GeneratorExit
thrown byclose()
, it can exit gracefully, raisingStopIteration
with its return value.The
StopIteration
is handled byclose()
, but the return value is currently discarded, andclose()
always returnsNone
.The proposed change is to let
close()
return the value of aStopIteration
it encounters after a graceful generator exit.Every other case, including errors thrown between
except GeneratorExit
andreturn
, is already handled byclose()
and would remain unchanged. This includes repeated calls toclose()
: Only the first such call might cause a generator to exit gracefully, after which it cannot raiseStopIteration
any longer.The change enables more natural use of generators as "pipelines" that process input data until ended. As a trivial example of the functionality, consider this computer of averages:
The generator processes data in an infinite loop. Once the controlling process terminates processing, the generator performs post-processing, and returns a final result. Without the return value of
close()
, there is no intrinsic way of obtaining such a post-processed result.Previous discussion
Discourse thread: Let generator.close() return StopIteration.value
Linked PRs
The text was updated successfully, but these errors were encountered: