Status of side-effecting functions in python

Dan Sommers dan at tombstonezero.net
Sun Oct 26 14:41:23 CET 2014


On Sun, 26 Oct 2014 00:45:49 -0700, wxjmfauth wrote:

> Ditto for <fileobj>.write(). Why should it return "something" ?
> 
>>>> with open('z.txt', 'w') as f:
> ...     f.write('abc')
> ...     
> 3

OTOH, why shouldn't it return something?  In this case, it returns the
length of the string written.  This value is analogous to the value
returned by the underlying OS function (at least on a POSIX-like system,
where write(2) returns the number of bytes written).  This value can be
useful for detecting when things have gone wrong; e.g., disk full,
network down, pipe broken, etc.  Practicality definitely beats purity.

At one time, on a huge project, millions of lines of C and assembly
code, we had a local guideline *not* to write void functions.  The idea
was to return something that might be useful later, even if it seemed
unlikely now.  A simple success flag was sufficient; as functions grew,
often did their failure modes.

Dan



More information about the Python-list mailing list