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

Ronald Oussoren ronaldoussoren at mac.com
Thu Aug 8 14:34:21 CEST 2013


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

> 
> 
> ________________________________________
> Frá: Ronald Oussoren [ronaldoussoren at mac.com]
>> This appears to be simular to the mechanism in PEP 377 http://www.python.org/dev/peps/pep-0377/
>> which was rejected.
> Indeed, it is similar, but simpler.  (I was unaware of Nick's PEP).  The PEP contains the fallacy that in case of __enter__ raising the SkipStatement (or in my case, ContextManagerExit) exception, that something needs to be assigned to the "as" body.   The proposal I'm making is to make it possible to do in a single context manager, what it is possible to do with two context managers currently:
> @contextmanager errordude:
>    1 // 0
>    yield
> @contextmanager handler:
>    try:
>        yield
>    except ZeroDivisionError:
>        pass
> with handler as a, errordude as b:
>    do_stuff(a, b)
> 
> do_stuff will be silently skipped, and b won't be assigned to.
> I'm proposing a mechanism where the same could be done with a single context manager:
> with combined as a, b:
>    do_stuff(a, b)
> 
> Currently, you have programmatic capabilities (silent skipping of the statement) with two context managers that you don't have with a single one.  That's just plain odd.
> 
> I don't think the original objectsions to PEP 377 are valid.  My approach introduces very little added complexity.  The use case is "correctly being able to combine context managers".  It is a "completeness" argument too, that you can do with a single context manager what you can do with two nested ones.

Skipping the body makes it possible to introduce flow control in a context manager, which could make it harder to read code. That is, currently the body is either executed unless an exception is raised that raises an exception, while with your proposal the body might be skipped entirely.  I haven't formed an opinion yet on whether or not that is a problem, but PEP 343 (introduction of the with statement) references <http://blogs.msdn.com/b/oldnewthing/archive/2005/01/06/347666.aspx> which claims that hiding flow control in macros can be bad.

Ronald


More information about the Python-ideas mailing list