Exceptions are not just for errors
Gregory Ewing
greg.ewing at canterbury.ac.nz
Thu Oct 14 18:48:43 EDT 2010
Ben Finney wrote:
> Another way of thinking about it is that there's no sensible sequence of
> bytes to return at EOF, so the Pythonic thing to do is to raise an
> exception for this exceptional circumstance.
But this is *not* what Python does, so it's obviously
not Pythonic. :-)
If f.read(n) is to mean "read n bytes, or however many are
left", and there are no bytes left, then the consistent
thing to do is to return a zero-length sequence of bytes.
I came across a situation recently where Microsoft got this
badly wrong. I was using a language that didn't have very
good file-access capabilities, and I wanted to compare the
contents of two files. So I used Scripting.FileSystemObject
via COM, and wrote something like the equivalent of
f = open(...)
g = open(...)
if f.read() == g.read():
...
This worked fine... except when one of the files was empty,
in which case the read() call *raised an exception*!
I am very glad that Python didn't go down that route.
--
Greg
More information about the Python-list
mailing list