Learning Resources

DocStrings and annotations


Python has a nifty feature called documentation strings, usually referred to by its shorter name docstrings. DocStrings are an important tool that you should make use of since it helps to document the program better and makes it easier to understand. Amazingly, we can even get the docstring back from, say a function, when the program is actually running!


# 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')
        print(y, 'is maximum')
printMax(3, 5)


   $ 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 non-trivial 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. 

If you have used 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 include help(printMax) in your program. Remember to press the q key to exit help.

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 to help() using docstrings.


Functions have another advanced feature called annotations which are a nifty way of attaching additional information for each of the parameters as well as the return value. Since the Python language itself does not interpret these annotations in any way (that functionality is left to third-party libraries to interpret in any way they want), we will skip this feature in our discussion.