contextlib.contextmanager and try/finally

Peter Otten __peter__ at web.de
Tue Jan 31 17:02:22 EST 2012


Prasad, Ramit 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()?
> What happens if 1) sys.exit is called while in the same thread
> 2) sys.exit is called from another thread but while this thread
> is in context manager?

sys.exit() uses the normal exception mechanism to terminate a program:

>>> import sys
>>> try:
...     sys.exit()
... except SystemExit:
...     print "I'd rather not"
...
I'd rather not
>>>

It won't derail a context manager:

>>> from contextlib import contextmanager
>>> @contextmanager
... def f():
...     try:
...             yield
...     finally: print "bye"
...
>>> import sys
>>> with f():
...     sys.exit()
...
bye
$




More information about the Python-list mailing list