[Python-ideas] Except block for with-statement

Guido van Rossum guido at python.org
Sun Nov 20 05:09:12 CET 2011


On Sat, Nov 19, 2011 at 3:43 PM, Carl M. Johnson
<cmjohnson.mailinglist at gmail.com> wrote:
> I was looking through the "What's New for Python 3.3" file and I saw this example code:
>
> try:
>    with open("document.txt") as f:
>        content = f.read()
> except FileNotFoundError:
>    print("document.txt file is missing")
> except PermissionError:
>    print("You are not allowed to read document.txt")
>
> and I thought it would be more elegant if you could drop the try.
>
> with open("document.txt") as f:
>    content = f.read()
> except FileNotFoundError:
>    print("document.txt file is missing")
> except PermissionError:
>    print("You are not allowed to read document.txt")

Eew. No please. There seems to be a trend in proposing more random
variants of the existing compound statements. Please don't do this.
The existing complement of compound statements is quite sufficient and
the new proposals do nothing but complicate the parser, the
documentation, and the learning process for occasional users.

> I assume that this has already been proposed and rejected. Does anyone have a good explanation of why?

I suppose "because I say so" is not a good explanation? :-)

> ISTM that the with-statement is mostly just a way of abstracting out try-except blocks, so it might be nice to have a way of handling errors that pop up during the initialization phase instead of just the code-block phase.

Wrong. The with-statement abstracts out a try-*finally* block. A
try-except cannot be replaced by a with-statement (or it would have to
be a very crooked context manager).

> I guess one obvious counter argument is that naive programmers might think that the "except" applies to things in the block instead of just things in the initializer. But naive programmers think lots of wrong things. ;-)

That's actually a deal killer right there. (If it wasn't born dead,
that is. :-) Your proposal above, through it "this could be equivalent
to that" example, makes it seem like the except block applies to the
entire with-statement. But here you appear to say that an error in the
body of the with-block would not be covered? And your example use of
exceptions that are only raised by open() strengthens this.

If a proposal manages to confuse even its proposer, perhaps that is
enough to reject it?

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list