Status of side-effecting functions in python

Roy Smith roy at panix.com
Mon Oct 27 09:28:37 EDT 2014


In article <544e2cf2$0$13009$c3e8da3$5496439d at news.astraweb.com>,
 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?

It's not throwing away data.  The write() call returns a count of how 
many bytes is consumed, so you can present the rest of them again in a 
later write() call (assuming that makes sense to do for your 
application).

In some cases, the underlying hardware (or network protocol) may be 
unable to handle the number of bytes you requested, or may fail in 
mid-transmission.  Imagine a serial link.  You tell it to write 100 
bytes.  It starts sending them down the line and after 20 bytes, the 
connection fails.  What should write() do in that case?  It hasn't 
written all the data, so it needs to let you know that.  It also has 
written *some* of the data, so it needs to let you know that too.  What 
you do with that information is up to you, but it clearly needs to 
return a richer status indication than just success/failure.



More information about the Python-list mailing list