"Try:" which only encompasses head of compound statement

Jameson.Quinn at gmail.com Jameson.Quinn at gmail.com
Mon Aug 27 17:35:35 EDT 2007


I have:

try:
    for line in open(myFileName):
        count += 1
except IOError:
    print "Can't open myfile"

(I know, this is bad, I never close the file, but its just for
illustration). But then I change it to:

try:
    for line in open(myFileName):
        count += openAndProcessSubfile(line)
except IOError:
    print "Can't open myfile"

... now the 'except' incorrectly catches errors from
openAndProcessSubfile.
Of course, I can always do:

try:
    myFile = open(myFileName)
except IOError:
    print "Can't open myfile"
for line in myFile:
    count += openAndProcessSubfile(line)

...But if my compound statement is "with" instead of "for" that seems
to defeat the purpose:

try:
    myFile = open(myFileName)
except IOError:
    print "Can't open myfile"
with myFile as anotherNameForMyFile:
    ....

This is not a very readable "with" statement, I end up giving the same
thing two names, and there's a moment when the above code doesn't know
to close myFile.

It's hard to imagine a good idiom to fix this. The best I can do is:

for line in open(myFileName)
    exceptHead IOError:
        print "Can't open myfile"
    count += openAndProcessSubfile(line)

exceptHead would be usable as the first indented line in any compound
statement, and would catch any errors raised by the preceding line
only. The bad thing about this (besides the silly name exceptHead) is
that after the except block, control flow would skip the entire
compound statement including else blocks.




More information about the Python-list mailing list