Why exceptions shouldn't be used for flow control [Re: YAS to the "Reading line-by-line" Problem]

Greg Ewing greg.ewing at compaq.com
Sun Jun 27 19:17:01 EDT 1999


William Tanksley wrote:
> 
> while not f.eof():
>   line = f.readline()
>   # ...

I'd love to be able to write reading loops that way.
Unfortunately, it's a fact of life that some of the
things read() has to deal with are unable to detect
eof without trying to read something. I think the
existing definition of read() and friends is the best 
that can be done in those circumstances.

> It's been a while since I've used read, so I
> don't recall what it actually returns

It returns an empty string if it can't read more
than 0 characters, same as readline().

> in a function designed to get n!=0
> more characters, an EOF really is an error.  Unfortunately for me, that's
> not the definition of 'read', and never will be.

Perhaps there should be a 2-parameter version of read:

   read(min, max)

which would raise an exception if it couldn't read at
least min characters. Setting min=0 would give the
current behaviour, and setting min=max would allow
reading a fixed-length record without having to check
for errors. Then everyone would be happy!

Greg




More information about the Python-list mailing list