[Python-Dev] fileobj.read(float): warning or error?
Cameron Simpson
cs at zip.com.au
Wed Jul 23 00:46:29 CEST 2008
On 21Jul2008 23:35, Leif Walsh <leif.walsh at gmail.com> wrote:
| On Tue, 22 Jul 2008, Cameron Simpson wrote:
| > Leaving aside the 0.2 => 0 converstion, shouldn't read() raise an
| > exception if asked for < 1 bytes? Or is there a legitimate use for
| > read(0) with which I was not previously aware?
|
| I think read(0) should be a no-op, just like it is in libc. This lets
| you write 'read(bytes)' without worrying about checking bytes, and
| also lets you silently stop reading when you have no more space, like
| in the following:
|
| buf = f.read(max(bytes_left, page_size))
| while buf:
| process(buf) # updates bytes_left
| buf = f.read(max(bytes_left, page_size))
[ Don't you mean "min()"? Unimportant. ]
I see the convenience here, but doubt I'd ever do that myself.
I'd write the above like this:
while bytes_left > 0:
buf = f.read(max(bytes_left, page_size))
if buf == 0:
break
process(buf) # updates bytes_left
I'm kind of picky about doing things exactly as often as required and no
more. Especially things that call another facility.
read(0) itself must internally have a check for size == 0 anyway, so
it's not like the overall system is less complex. If we're unlucky it
could trickle all the way down to an OS system call to read(2) (UNIX,
substitute as suitable elsewhere) and for a no-op that would be overkill
by far. The only way the read() implementation would avoid that is by
doing the test on size anyway. But since read() is opaque IMO it is
better to avoid it at the upper level if we know it will produce
nothing.
Which leaves me unconvinced of the utility of this mode.
Cheers,
--
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/
More information about the Python-Dev
mailing list