Skip to content

Docstrings in Functions

Docstrings in Functions

It is good programming practice to document your code. Reusable chunks of code are particularly relevant to document as other programmers may use the code, and you may use the code again at a different time.

Python has a couple of different ways for programmers to add documentation. One way is to use simple comments. Comments are lines of code that do not get run by the Python interpreter. Comments are meant to be viewed by humans. In Python, comment lines start with the pound symbol #. Any line that starts with a # symbol will not be run by the Python Interpreter.

Another way to document code is to use docstrings. Docstrings are comments which are surrounded with triple quotation marks and usually contain multiple lines of explanation. A function containing a docstring takes the form:

def function_name(arguments):
    """"
    Docstring text



    """
    <code>

    return output

Doc strings are what you see when the help() function is called. As an example, running the help() function on the built-in function sum brings up:

In [1]:
help(sum)

Help on built-in function sum in module builtins:

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

We can produce the same type of output when a user types types help() by adding docstrings to a function. Let's create a new function that converts grams (g) to kilograms (kg). Let's call our function g2kg. The first thing to do is make sure that the name g2kg is not assigned to another function and is not a keyword by Python. We can check quick using Python's built-in type() function. We know that sum() is a Python function, how about g2kg()?

In [2]:
print(type(sum))
print(type(g2kg))
<class 'builtin_function_or_method'>
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-487fcfc6eb43> in <module>()
      1 print(type(sum))
----> 2 print(type(g2kg))

NameError: name 'g2kg' is not defined

Since g2kg is not already defined in Python, we can use g2kg as the name of a new user-defined function. Remember the parenthesis, colon, and return statement.

In [3]:
def g2kg(g):
    kg = g/1000

<span class="k">return</span> <span class="n">kg</span>

Now let's try and use our function. How many kilograms is 1300 grams? We expect the output to be 1.3 kilograms.
In [4]:
g2kg(1300)

Out[4]:
1.3

If we call help() on our g2kg() function, nothing is returned. help(g2kg) does not return any output because our new g2kg() function does not contain a docstring yet.
In [5]:
help(g2kg)

Help on function g2kg in module __main__:

g2kg(g)

If we insert a docstring into the function definition, help(g2kg) will return whatever text we included in the docstring.

The standard components of docstrings included in function definitions include:

  • a summary of the function
  • the function inputs
  • the function outputs
  • an example of the function running including the result

The docstring is included right below the def line and is enclosed in triple quotes """ """. The triple quotes are typically included on their own lines. The syntax to add a docstring in a function definition is below.

 def function_name(arguments):
     """

     <docstring text>

     """

     <code>

     return output

Let's include a docstring with our g2kg() function definition.

In [6]:
def g2kg(g):
    """
    
    Function g2kg converts between g and kg
    
    input: number of grams, int or float
    output: number of kilograms, float
    
    Example:
    
        >>> g2kg(1300)
            
            1.3
        
    """
    kg = g/1000

<span class="k">return</span> <span class="n">kg</span>

Now let's ask for help() on our g2kg() function and see the docstring we wrote in the g2kg() function definition printed back to us.
In [7]:
help(g2kg)

Help on function g2kg in module __main__:

g2kg(g)
    Function g2kg converts between g and kg

    input: number of grams, int or float
    output: number of kilograms, float

    Example:

        >>> g2kg(1300)

            1.3