[Python-ideas] Except block for with-statement

Nick Coghlan ncoghlan at gmail.com
Sun Nov 20 13:22:00 CET 2011


On Sun, Nov 20, 2011 at 9:43 AM, 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")

Hmm, this code is dubious, as the scope of the try block is too broad.
It should really be written so it only covers the creation of the file
object:

try:
   f = open("document.txt")
except FileNotFoundError:
   print("document.txt file is missing")
except PermissionError:
   print("You are not allowed to read document.txt")
else:
   with f:
       content = f.read()

At that point, it's hopefully clearer why this proposal doesn't make
sense. (A tracker issue suggesting that the What's New example be
updated wouldn't hurt, though).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list