Status of side-effecting functions in python
rosuav at gmail.com
Mon Oct 27 12:44:12 CET 2014
On Mon, Oct 27, 2014 at 10:30 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Roy Smith wrote:
>>> Yes and no. If something goes wrong in a .write() method,
>>> is not Python supposed to raise an error? (!)
>> Define "wrong". It is not an error for a write() call to consume fewer
>> bytes than were requested.
> It's not? I'm asking a genuine question here, not a rhetorical one. I would
> expect that if I ask to write 2 bytes, and only 1 byte is written, that
> absolutely is an error. Under what circumstances is it okay for write() to
> throw data away?
>> How would you expect this to be handled in Python? Raise
> I would expect it to raise an IOError, most likely with one of the following
> error codes:
> * errno.EIO (physical input/output error)
> * errno.EFBIG (file is too large)
> * errno.ENOSPC (no space left on device, disk is full)
You're assuming the condition, whatever it is, is permanent. The most
common reason for write() to be temporarily unable to write everything
is a non-blocking socket, pipe, or somesuch. It writes as much as it
can, tells you how much that is, and lets you buffer the rest or deal
with it in whatever other way you choose.
If it is permanent, though, then yes, it should tell you. But what if
you ask it to write a megabyte, it writes half of it, and then finds
that there's no space on the disk? Should it:
1) Back out the write and raise an exception?
2) Write part of the data and raise an exception?
3) Write part of the data and NOT raise an exception?
All three make sense. The third one is an option only if it's
documented as being able to tell you about partial writes. The second
has a problem in that you can't necessarily communicate "this is how
much I wrote" properly while also signalling the exception (imagine if
one function calls write() more than once, and it doesn't catch any
exceptions, just lets them bubble up). And backing out a write isn't
always possible. So what's to do?
More information about the Python-list