Docstrings, help, and dir

As part of the Function Design Recipe, we've been writing descriptions of our functions and placing them below the function header inside triple-quoted strings. These descriptions are called docstrings, which stands for documentation strings.

The docstrings are useful to others reading our saved programs and using our code, and these descriptions can be accessed using Python's built-in function help.

Recall our function square, from earlier:

In [1]:
def square(num):
    """(number) -> number
    Return num squared.
    >>> square(5)
    >>> my_abs(-6)
    return num * num

In the Python shell, we can called help(square) to get the docstring description:

In [2]:
Help on function square in module __main__:

    (number) -> number
    Return num squared.
    >>> square(5)
    >>> my_abs(-6)

We can use help and another built-in function named dir to find out more about Python's built-in functions too. Calling dir(__builtins__) produces output that includes a list of Python's built-in functions (for now, focus only on the names that are entirely lowercase):

In [3]:

Once we've found a function using dir, we can find out more about it by calling help:

In [4]:
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.

In [5]:
Help on built-in function round in module builtins:

    round(number[, ndigits]) -> number
    Round a number to a given precision in decimal digits (default 0 digits).
    This returns an int when called with one argument, otherwise the
    same type as the number. ndigits may be negative.

Practice Exercise: learning about functions using help

Consider this description of built-in function ord:

In [6]:
Help on built-in function ord in module builtins:

ord(c, /)
    Return the Unicode code point for a one-character string.

  1. How many parameter(s) does function ord take?
  2. What are the type(s) of ord's parameter(s)?
  3. Give an example of how to call on function ord.