[Python-ideas] Enhanced context managers with ContextManagerExit and None

Ronald Oussoren ronaldoussoren at mac.com
Thu Aug 8 13:31:50 CEST 2013


On 7 Aug, 2013, at 16:23, Kristján Valur Jónsson <kristjan at ccpgames.com> wrote:

> I just added a patch to the tracker: http://bugs.python.org/issue18677
>  
> Here is its' text:
>  
> A proposed patch adds two features to context managers:
> 
> 1)It has always irked me that it was impossible to assemble nested context managers in the python language. See issue 
> #5251
> .
> The main problem, that exceptions in __enter__ cannot be properly handled, is fixed by introducing a new core exception, ContextManagerExit.  When raised by __enter__(), the body that the context manager protects is skipped.  This exception is in the spirit of other semi-internal exceptions such as GeneratorExit and StopIteration.  Using this exception, contextlib.nested can properly handle the case where the body isn't run because of an internal __enter__ exception which is handled by an outer __exit__.

This appears to be simular to the mechanism in PEP 377 <http://www.python.org/dev/peps/pep-0377/> which was rejected.  

> 
> 2) The mechanism used in implementing ContextManagerExit above is easily extended to allowing a special context manager: None.  This is useful for having _optional_ context managers.  E.g. code like this:
>     with performance_timer():
>         do_work()
> 
>     def performance_timer():
>         if profiling:
>             return accumulator
>         return None
> 
> None becomes the trivial context manager and its __enter__ and __exit__ calls are skipped, along with their overhead.

How bad is the overhead of a trivial contextmanager (that is, one with empty bodies for both __enter__ and __exit__)? 

Ronald


More information about the Python-ideas mailing list