[Tutor] importance of Docstring

wesley chun wescpy at gmail.com
Thu Apr 16 23:51:29 CEST 2009


>>>> def f(x):
>
> '''f(x) -> x+5'''
> return x+5
>
>>>> help(f)
>
> Help on function f in module __main__:
>
> f(x)
>   f(x) -> x+5

another thing that has not been mentioned is that if you put
docstrings everywhere, you can use tools like Epydoc, doxygen, or
sphinx to generate full documentation of an entire codebase, all
because developers made it easy by dropping in useful documentation in
their docstrings instead of just 1-line comments.

on top of this, you can add extra comments to DEMONSTRATE how the
function works, i.e.,

def f(x):
   """
   f(x) -> x+5

   >>> f(123)
   128
   """
   return x+5


this save your users critical time it takes to understand the code and
how it works. on top of THAT, you can use the doctest module to *run*
that code to confirm it works (or doesn't). try adding that code plus
the 5 lines below to a file called f.py:

def _test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    _test()

now run it:

$ f.py
$

you get no output which means everything worked! if you want to see it
in action, use "-v":

$ f.py -v
Trying:
    f(123)
Expecting:
    128
ok
2 items had no tests:
    __main__
    __main__._test
1 items passed all tests:
   1 tests in __main__.f
1 tests in 3 items.
1 passed and 0 failed.
Test passed.

it tells you how many possible places you can add doctests, how many
were found, and what the results were.

if you had an error, then you would definitely get output, with or
without the "-v". let's change our docstring output to the wrong
answer and rerun:

$ f.py
**********************************************************************
File "f.py", line 7, in __main__.f
Failed example:
    f(124)
Expected:
    128
Got:
    129
**********************************************************************
1 items had failures:
   1 of   1 in __main__.f
***Test Failed*** 1 failures.

of course, you can also implement doctesting along with your normal
unit tests too and not necessarily have to add those 5 lines to all of
your modules.

hope you can now see the usefulness and importance of docstrings.
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list