Python has a nifty feature called documentation strings which are usually referred to by their shorter name docstrings. DocStrings are an important tool that you should make use of since it helps to document the program better. We can even get back the docstring from a function at runtime i.e. when the program is running.
Example 7.8. Using DocStrings
#!/usr/bin/python # Filename : func_doc.py def printMax(x, y): '''Prints the maximum of the two numbers. The two values must be integers. If they are floating point numbers, then they are converted to 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__
$ python func_doc.py 5 is maximum Prints the maximum of the two numbers. The two values must be integers. If they are floating point numbers, then they are converted to integers.
A string on the first logical line of a function is a docstring for that function. 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 such a convention for all your docstrings for all your functions.
We access the docstring of the printMax function using the __doc__ attribute of that function. Just remember that Python treats everything as an object including functions. Objects will be explored in detail in the chapter on object-oriented programming.
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 the function and prints it for you. You can try it out on the function above. Just include the help(printMax) statement. Remember to press q to exit the help().
Automated tools can retrieve documentation from your program in this manner. Therefore, I strongly recommend that you use docstrings for any nontrivial function that you write. The pydoc command that comes with your Python distribution works similarly to help() using docstrings.