"Try:" which only encompasses head of compound statement
Ben Finney
bignose+hates-spam at benfinney.id.au
Mon Aug 27 19:38:37 EDT 2007
Jameson.Quinn at gmail.com writes:
> try:
> for line in open(myFileName):
> count += openAndProcessSubfile(line)
> except IOError:
> print "Can't open myfile"
>
> ... now the 'except' incorrectly catches errors from
> openAndProcessSubfile.
So don't include it. You've discovered a good principle of
exception-based programming: try to only catch exceptions from the
minimum amount of code that does one discrete action.
try:
input_file = open(my_filename)
except IOError, exc:
print "Can't open myfile: %(exc)" % locals()
for line in input_file:
count += open_and_process_subfile(line)
This is easier to read, because it's clearer what's going on. Never be
ashamed to break apart a compound statement into simpler statements if
that will improve readability.
(It's also easier to read because it follows naming conventions in
PEP-8, which I strongly suggest you follow.)
> ...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,
Why do that then? You don't need to assign a different name for the
target.
with input_file:
# ... do stuff
> and there's a moment when the above code doesn't know to close
> myFile.
Closing the file will occur when the object is cleaned up by garbage
collection.
--
\ "I bought a self learning record to learn Spanish. I turned it |
`\ on and went to sleep; the record got stuck. The next day I |
_o__) could only stutter in Spanish." -- Steven Wright |
Ben Finney
More information about the Python-list
mailing list