Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Using DocStrings

Example 7.8. Using DocStrings

#!/usr/bin/python
# Filename: func_doc.py def printMax(x, y):
'''Prints the maximum of two numbers.

The two values must be integers.''' x = int(x) # convert to integers, if possible y = int(y)

if x > y:
print x, 'is maximum'
else: print y, 'is maximum'
printMax(3, 5)
print printMax.__doc__

Output

$ python func_doc.py
5 is maximum
Prints the maximum of two numbers.

The two values must be integers.

How It Works

A string on the first logical line of a function is the docstring for that function. Note that DocStrings also apply to modules and classes which we will learn about in the respective chapters.

The convention followed for a docstring is a multi-line string where the first line starts with a capital letter and ends with a dot. Then the second line is blank followed by any detailed explanation starting from the third line. You are strongly advised to follow this convention for all your docstrings for all your nontrivial functions.

We can access the docstring of the printMax function using the__doc__ (notice the double underscores) attribute (name belonging to) of the function. Just remember that Python treats everything as an object and this includes functions. We'll learn more about objects in the chapter on classes.

If you have used the help() in Python, then you have already seen the usage of docstrings! What it does is just fetch the__doc__ attribute of that function and displays it in a neat manner for you. You can try it out on the function above - just includehelp(printMax) in your program. Remember to press q to exit thehelp.

Automated tools can retrieve the documentation from your program in this manner. Therefore, I strongly recommend that you use docstrings for any non-trivial function that you write. The pydoc command that comes with your Python distribution works similarly tohelp() using docstrings.