[Python-ideas] Possible PEP 380 tweak
greg.ewing at canterbury.ac.nz
Sat Oct 30 08:13:29 CEST 2010
Nick Coghlan wrote:
> 1. Send in a sentinel value (often None, but you could easily reuse
> the exception types as sentinel values as well)
> 2. Throw in GeneratorExit explicitly
> 3. Throw in StopIteration explicitly
> 4. Throw in a different specific exception
> 5. Call g.close()
> Yield from also
> isn't innately set up to unwind correctly in any of these cases,
On the contrary, I think it works perfectly well with 1, and
also with 4 as long as the inner generator catches it in the
Note that you *don't* want to unwind in this situation, you
want to continue with normal processing, in the same way that
a function reading from a file continues with normal processing
when it reaches the end of the file.
> without some form of framework based signalling from the inner
> generator to indicate whether or not the outer generator should
> continue or bail out.
No such signalling is necessary -- all it needs to do is
return in the normal way.
Or to put it another way, from the yield-from statement's
point of view, the signal is that it raised StopIteration
and not GeneratorExit.
> To avoid giving false impressions as to which level of the stack
> return values are from, gtally2() would need to be implemented a bit
> differently in order to *also* convert GeneratorExit to StopIteration:
> def gtally2():
> # The PEP 380 equivalent of a "tail call" if g.close() returns a value
> yield from gtally()
> except GeneratorExit as ex:
> return ex.value
Exactly, which I think is a horrible thing to have to do,
and I'm loathe to make any modification to PEP 380 to
support this kind of pattern.
> With these modifications, a framework could then quite easily provide
> a context manager to make the idiom a little more readable
Which would be papering over an awful mess that has no
need to exist in the first place, as long as you don't
insist on using technique no. 5.
More information about the Python-ideas