[Python-ideas] Except block for with-statement

Terry Reedy tjreedy at udel.edu
Sun Nov 20 09:05:24 CET 2011


On 11/19/2011 6:43 PM, Carl M. Johnson 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")

This saves one short line. That is insufficient reason for a puzzling 
construct.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list