[Python-ideas] with ... except

Nick Coghlan ncoghlan at gmail.com
Sat Mar 9 15:34:13 CET 2013

On Sat, Mar 9, 2013 at 8:53 PM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Antoine Pitrou, 09.03.2013 11:45:
> On Fri, 8 Mar 2013 11:01:27 -0800
>> Of course, you are right in some way. But it's a bit of a shame to have
>> to resort to a helper function because the syntax isn't powerful
>> enough :-)
> OTOH, why add syntax for something that is easily done with a helper function?

It's not just with statements that don't play nice with supplementary
exception handling - for loops actually have the same problem. In both
cases, you can fairly easily put an exception handler around just the
expression, or around the entire statement, but you can't quite so
easily define custom exception handling for the protocol methods
invoked implicitly in the statement header (__enter__ in with
statements, __iter__ and __next__ in for loops). While loops
technically suffer from it as well, but it's rather rare for a bool()
invocation to risk triggering an exception.

contextlib.ExitStack at least brings context managers close to on par
with iterables - you can use either stack.enter_context(cm) and
iter(iterable) to lift just the __enter__ or __iter__ call out into a
separate try block. Wrapping an exception handler around next() pretty
much requires reverting to a while loop, though.

Ultimately, though, this may be an inevitable price we pay for the
abstraction - you *do* lose flexibility when you design for the
typical case, and so you do eventually have to say "sorry, to handle
that more complex case you need to drop back down to the lower level
syntax" (try/except/else/finally for with statements, while loops for
for loops). An important part of minimising language complexity is
actually recognising when that limit has been reached and saying, no,
sorry, we want to keep the higher level API simple, so that use case
won't be supported, since it can already be handled with the lower
level API in those cases where it is needed.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list