[Python-ideas] with-except-finally blocks
Steven D'Aprano
steve at pearwood.info
Thu Apr 16 18:38:57 CEST 2015
On Thu, Apr 16, 2015 at 08:35:14AM -0700, Ethan Furman wrote:
> > No more than any other block of code. There is nothing special about
> > with blocks that go with exception handling [...]
>
> I have to disagree: 'with' blocks are exactly a condensed try/finally, with the
> added capability of being able to suppress exceptions -- this makes them very
> special with respect to exception handling.
Yes, yes, that's a given that with statements encapsulate a finally
clause. But that is missing the point. The proposal is not to add a
finally clause to context managers, because they already have one.
The proposal is to allow special syntax for the situation where you want
a separate and independent finally.
with spam():
try:
blockA
except Error:
blockB
finally:
blockC
The finally: blockC has nothing to do with the context manager's
__exit__ method. We might as well be talking about this:
while spam():
try:
blockA
except Error:
blockB
finally:
blockC
giving us syntactic sugar:
# not a serious proposal
while spam():
blockA
except Error:
blockB
finally:
blockC
In fact, if I were a betting man, I'd venture a small wager that there
are more while- or for-loops with try blocks inside them than with
blocks. After all, the whole purpose of with statements is to avoid
needing to write a try...finally!
--
Steve
More information about the Python-ideas
mailing list