contextlib.contextmanager and try/finally

Steven D'Aprano steve+comp.lang.python at
Tue Jan 31 21:15:20 EST 2012

On Tue, 31 Jan 2012 15:09:34 -0700, Ian Kelly wrote:

> On Tue, Jan 31, 2012 at 2:07 PM, Prasad, Ramit
> <ramit.prasad at> wrote:
>>>Like Neil mentioned, a contextmanager generator is wrapped with an
>>>__exit__ method that is guaranteed to be called and that explicitly
>>>resumes or closes the generator.  So as long as your contextmanager
>>>generator is properly written (i.e. it yields exactly once), the
>>>finally block will execute in a timely fashion.
>> Is that true even in the face of something like sys.exit()?
> Yes.
> You can certainly come up with scenarios in which the finally clause
> does not execute, e.g. killing the interpreter with "kill -9" or yanking
> out the power cord.  Within the confines of the Python interpreter,
> though, it is guaranteed that the finally block will execute.

Almost, but not quite.

The finally block is not guaranteed to execute if the try block never 
exits -- infinite loops are still infinite loops.

Also, unlike sys.exit, os._exit doesn't work through the exception 
mechanism, can't be caught, and simply exits immediately.

>>> import os
>>> try:
...     os._exit(1)
... finally:
...     print "exiting"
steve at runes:~$ 


More information about the Python-list mailing list