[Python-ideas] Potential PEP: with/except

David Shawley daveshawley at gmail.com
Thu Jan 24 08:08:29 EST 2019

On Jan 22, 2019, at 8:28 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> I've been thinking more about this proposal, and realised why I've been 
> feeling a slight sense of disquiet about it. I think it encourages an 
> anti-pattern of catching too much. (Or at least a code smell.)
> Although we're all guilty of violating this principle from time to time, 
> in general we ought to surround the minimum amount of code with a 
> try...except that we need. Ideally (but rarely possible in practice) we 
> want to surround a single operation which might raise at a time.

I ended up at a similar conclusion this morning.  I'm wary of enclosing too
much code in the try block since it makes handling exceptions very difficult
unless you have a rich hierarchy of exceptions -- something that I also warn
against.  I view the problem of enclosing too much in the try block as an
extension of an overly broad except block.  It makes it nearly impossible to
know where the exception came from so you cannot handle it safely unless you
have an exception hierarchy where each exception is raised from a single
place in the code.

A similar anti-pattern that I see regularly is to *catch too often* where
there is a try-catch block every time that a method from another module or
library is called and the catch portion translates the exception instead of
handling it.  It's interesting that the "exception translator" pattern leads
to an overly rich exception hierarchy.

It is interesting that you mention whether the try-catch would wrap __enter__
or not.  The main reason that I am -1 on this proposal is that it introduces
more ambiguity in what is happening.  I was about to write pretty much what
you have written with regards to the syntax muddying the waters about the
scope of exception handling especially with regards to the meaning of the
return value of `context_manager.__exit__`

> But the alternative is to enshrine in syntax something which *by design* 
> guards too much and is a code smell.

Very well put ;)

- dave
Safe wiring is not something to be learned after the fire trucks have left.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190124/3598fb28/attachment-0001.html>

More information about the Python-ideas mailing list