Preferred syntax for the docstrings

Scott David Daniels Scott.Daniels at Acm.Org
Thu Mar 19 11:40:01 EDT 2009


Luis Zarrabeitia wrote:
> What's the preferred style to document code in python? ...
> def somefunction(arg1, arg2, out = sys.stdout):
>     """ This function does blahblablha with the string arg1, using 
>     the tuple of ints arg2 as the control sequence, and prints the 
>     result to out (defaults to sys.stdout) """
> ... [or] ...
> def somefunction(arg1, ar2, out = sys.stdout):
>     """ brief description, possibly involving <some symbol>arg1, <some symbol> 
>         arg2 and <some symbol> arg3>
>         <some symbol> arg1: string, some description
>         ...
>     """
> I guess there are several languages for writing the docstring. The question is,
> which is the preferred one in python, and where can I learn the syntax? (the one
> that python documentation viewers understand better? the one used by the
> stdlib?) How should/in what order should I write the docs? (brief description,
> argument types, return type, followed perhaps by some doctests).

A fairly common style is to have the first line of the docstring
summarize the function (without repeating the arglist), a blank line,
and then more elaborating text.  Some systems (notably Idle) will
provide the arglist and that first line as a "floating hint" when
using functions/methods interactively.  Note how much of Python's
own library provide help this way.  Exploratory programming becomes
much easier when you follow that rule.

Try it, it is fun.  go into Idle and type:
     >>> def f(a, bc, defg):
         '''A trap: never use 'def' as an arg name.

         In which Doris gets her oats.
         '''
         return 3

     >>> f(
And at this point pause a second, the hint  will appear.  I use
both this and "print(a.b.__doc__)" regularly for reminders of what
I have once read.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list