Using Docstrings
Python has a fascinating feature called a document string, which is often referred to as docstrings. Docstrings is an important tool that you should try to use as it helps your program document to be easier to understand. You can even recover a document string from a function while the program is running. using Docstrings
Example 7.8 using docstrings
#!/usr/bin/python
# Filename:func_doc.py
def printmax (x, y): ' Prints ' 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:
pri NT 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
The string in the first logical line of the function is the document string for this function. Note that Docstrings also applies to modules and classes, and we will study them later in the corresponding chapters.
The Convention for a document string is a multiline string whose first line begins with a capital letter and ends with a period. The second line is a blank line, starting with a detailed description of the third line. It is strongly recommended that you follow this practice when using document strings in your functions.
You can use __DOC__ (note double underlines) to call the Printmax function's document string property (which is the name of the function). Remember that Python takes everything as an object, including this function. We'll learn more about objects in the later class chapter.
If you've already used help in Python, you've seen the use of docstings. All it does is grab the __doc__ property of the function and show it neatly to you. You can try this on the above function-just include help (Printmax) in your program. Remember to press Q to exit help.
Automated tools can also extract documents from your program in the same way. Therefore, I strongly recommend that you write a document string for any formal functions you write. Use docstrings similar to help () with the Pydoc command that comes with your Python release.