The current *implementation* guarantees this; it uses reference
counting and is completely deterministic (module bugs :-). There are
some subtle things you need to know, e.g. if you make something a
local variable it may survive longer because the stack frame is saved
for the debugger, but there are ways to handle this.
> Is there some problem with calling leave even if an exception is
> raised in __enter__, or between completion of enter and execution of
> suite? Something like:
>
> try:
> object.__enter__()
> ...execute suite...
> except:
> object.__leave__(exc_type, exc_value, exc_traceback)
> else:
> object.__leave__(None,None,None)
Hmm... What do you do in this case if an interrupt occurs *before*
any code in object.__enter__ has run? I could envisage a two-stage
start, e.g.
object.__setup__()
try:
object.__enter__()
except:
object.__leave__(...)
etc.
But it is beginning to look cumbersome. Maybe we need a way instead
to block asynchronous exceptions? (You could do this with the signal
module but that's UNIX specific.) If there were a way to block
asynchronous exceptions it could be part of the specs for the 'in'
statement that async exceptions are not delivered while the __enter__
is running, this would solve the problem. Of course if through a bug
the __enter__ routine were to hang in an infinite loop it would be
rather hard to kill...
--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>