[Python-ideas] with statement vs. try...except...finally
Steven D'Aprano
steve at pearwood.info
Sat May 30 02:52:23 CEST 2009
On Sat, 30 May 2009 08:02:31 am Carl Johnson wrote:
> This example is too simplified to understand if it's worth adding an
> except clause or not. If all you're doing is pulling the text out of
> the file, why can't you just make a function for this?
>
> lines = fancyread("myfile.txt") #Returns "couldn't open", "couldn't
> close", etc. in case of errors
Python has exceptions for exception handling. Unless you have a *really
good reason*, you shouldn't go backwards to error codes, especially not
such course-grained error codes that throw away useful information, and
even more especially not error codes which can easily be mistaken for
legitimate output:
lines = fancyread(filename)
if lines == "couldn't open":
pass
else:
# oops, forgot to check for "couldn't read"
for line in lines:
process(line)
will accidentally process each of 'c' 'o' 'u' ... 'r' 'e' 'a' 'd' if the
file could be opened but there was an error reading from it.
On the very rare case that I don't want to raise an exception on error,
I return a tuple of (success_flag, result). If the function is
successful, it returns (True, whatever) and if it fails, it returns
(False, error-description).
Sometimes I'll use the same idiom as string.find() and re.match():
return a sentinel (usually None) to stand in for "not found" or
similar. I only do this if it represents something which is not an
error condition, but an expected result.
--
Steven D'Aprano
More information about the Python-ideas
mailing list