[Python-ideas] Protecting finally clauses of interruptions

Yury Selivanov yselivanov.ml at gmail.com
Mon Apr 2 22:37:35 CEST 2012


On 2012-04-02, at 3:43 PM, Paul Colomiets wrote:

> Hi,
> 
> I'd like to propose a way to protect `finally` clauses from
> interruptions (either by KeyboardInterrupt or by timeout, or any other
> way).
> 
> I think frame may be extended to have `f_in_finally` attribute (or
> pick a better name). Internally it should probably be implemented as a
> counter of nested finally clauses, but interface should probably
> expose only boolean attribute. For `__exit__` method some flag in
> `co_flags` should be introduced, which says that for whole function
> `f_in_finally` should be true.

Paul,

First of all sorry for not replying to your previous email in the thread.  

I've been thinking about the mechanism that will be both useful for thread
interruption + for the new emerging coroutine libraries.  And I think that
we need to draft a PEP.  Your current approach with only 'f_in_finally'
flag is a half measure, as you will have to somehow monitor frame 
execution.

I think a better solution would be to:

1. Implement a mechanism to throw exceptions in running threads.  It should
be possible to wake up thread if it waits on a lock, or any other syscall.

2. Add 'f_in_finally' counter, as you proposed.

3. Either add a special base exception, that can be thrown in a currently
executing frame to interrupt it, or add a special method to frame object 
'f_interrupt()'. Once a frame is attempted to be interrupted, it checks 
its 'f_in_finally' counter.  If it is 0, then throw exception, if not -
wait till it sets back to 0 and throw exception immediately.

This approach would give you enough flexibility to cover the following 
cases:

1. Thread interruption
2. Greenlet-based coroutines (throw exception in your event hub)
3. Generator-based coroutines

Plus, proper 'finally' statements execution will be guaranteed by the
interpreter.

-
Yury



More information about the Python-ideas mailing list