Style for docstring

Chris Angelico rosuav at gmail.com
Fri Apr 22 18:33:37 EDT 2022


On Sat, 23 Apr 2022 at 08:24, <2QdxY4RzWzUUiLuE at potatochowder.com> wrote:
>
> 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.

While it's definitely possible to have other results and other ways to
deliver them, the return of a boolean would be the most obvious
default.

> 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'm assuming that the function is called something like "is_even()"
and that it either is a method on a permutation object, or its
parameters make it very clear what the permutation is.

If it returns an enumeration, I would say that in the docstring. If
the docstring doesn't say, I would assume it returns True or False.

> 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.

Core Python methods and functions seem to prefer either "Return ..."
or "Verb the thing" where the result is implicit (eg str.zfill.__doc__
which says "Pad a numeric string..."). Both are used extensively.
Neither form leaves out anything that wouldn't be the obvious default.

We don't need to say "Figures out algorithmically whether the
permutation is even. If it is, will return True; if it isn't, will
return False; if something goes wrong, will raise an exception". This
is Python; we know that if something goes wrong, an exception is
raised. (Though it can help to say WHICH exception will be raised
under WHAT circumstances). Some things are obvious.

ChrisA


More information about the Python-list mailing list