[Python-ideas] Except block for with-statement

Carl M. Johnson cmjohnson.mailinglist at gmail.com
Sun Nov 20 00:43:16 CET 2011


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")

I assume that this has already been proposed and rejected. Does anyone have a good explanation of why? 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.

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. ;-)


More information about the Python-ideas mailing list