yield in try/finally case

Steven D'Aprano steve at pearwood.info
Thu Mar 3 10:57:08 EST 2016


On Fri, 4 Mar 2016 02:00 am, Random832 wrote:

> On Thu, Mar 3, 2016, at 06:52, 刘琦帆 wrote:
>> I have just saw PEP 255, and it says that
>> 
>> "A yield statement is not allowed in the try clause of a try/finally
>> construct.  The difficulty is that there's no guarantee the generator
>> will ever be resumed, hence no guarantee that the finally block will ever
>> get executed; that's too much a violation of finally's purpose to bear."
>> from https://www.python.org/dev/peps/pep-0255/
> 
> I'm not sure I understand this reasoning. Why not simply execute it in
> __del__ if it hasn't been reached until then? AIUI that is what C# does.

I believe that under certain circumstances, __del__ may never be executed at
all; it may be executed under rather perilous circumstances where the
interpreter is already shutting down; and even if it is executed, it is not
guaranteed to be executed at any particular time or in any particular
order. In other words, cleaning up in __del__ may be non-deterministic,
while the whole point of try...finally is that the finally block is
executed in a deterministic fashion.

In any case, PEP 255 is obsolete: that is no longer a limitation of yield.


# Python 2.7

py> def gen():
...     try:
...             yield 1
...     finally:
...             yield 2
...
py> it = gen()
py> next(it)
1
py> next(it)
2





-- 
Steven




More information about the Python-list mailing list