Style for docstring

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Fri Apr 22 18:22:33 EDT 2022


On 2022-04-22 at 15:35:15 -0500,
"Michael F. Stemper" <michael.stemper at gmail.com> wrote:

> On 22/04/2022 14.59, Chris Angelico wrote:
> > On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper
> > <michael.stemper at gmail.com> wrote:
> > > 
> > > I'm writing a function that is nearly self-documenting by its name,
> > > but still want to give it a docstring. Which of these would be
> > > best from a stylistic point of view:
> > > 
> > > 
> > >     Tells caller whether or not a permutation is even.
> > > 
> > >     Determines if a permutation is even. (Alternative is that it's odd.)
> > > 
> > >     Returns True if permutation is even, False if it is odd.
> 
> 
> > 
> > I'd go with the third one, but "Return" rather than "Returns". Or
> > possibly "Test whether a permutation is even".
> 
> "So let it be written. So let it be done."

"Test whether a permutation is even," while technically factual, leaves
the reader to wonder what form the result takes, and what happens to
that result.  Yes, we'd all like to think that programmers are smart
enough to *assume* that the function returns the result of the test.
I've also seen functions that perform tests and then print the results
out, or write them to a database, or simply execute the tests for their
side effects (or leave it up to the individual tests to do something
with the result).

Do you want callers of the function also to assume that True means that
the permutation is even?  There are other reasonable strategies, such as
an enumerated type (whose items are Even, Odd, and FileNotFound), or
throwing an exception if the permutation is odd.

I prefer the "return" (rather than "returns") version of the third
option.  Assuming that the programmers are familiar with the domain, the
other two leave out important information.


More information about the Python-list mailing list