Docstrings and Type Hints

Docstrings

A docstring is a string that provides documentation for a function or module. It helps other developers (and your future self) understand how to use the code. Docstrings are enclosed in triple quotes and placed immediately after the function definition.

Example. Add a docstring to our previous greet function.

def greet(name):
    """
    This function greets a person.

    Parameters
    ----------
    name : str
        The name of the person to greet.

    Returns
    -------
    str
        A greeting message.
    """
    return f"Hello, {name}!"

print(greet("Alice"))
Hello, Alice!

The docstring does not change the function’s behavior — it simply documents what the function does, what it expects, and what it returns.


Type Hints

Type hints are a way to specify the types of function arguments and return values. Python does not enforce them at runtime, but they serve as valuable documentation for understanding code.

To add a type hint for a parameter, place a colon : after the parameter name followed by the type. To hint the return type, use a right arrow ->.

Example. Implement an addition function with type hints.

def add(a: int, b: int) -> int:
    return a + b

print(add(3, 4))
7

Combining Docstrings and Type Hints

In practice, you should use docstrings and type hints together. This gives the reader complete information about a function at a glance.

Example. Implement a function that takes a student’s name and their grade, then returns a message saying whether they passed or not. Include a docstring and type hints.

def check_pass(name: str, grade: int) -> str:
    """
    This function returns a message saying if the student
    has passed or not.

    Parameters
    ----------
    name : str
        The student's name.
    grade : int
        The student's score, between 0 and 10.

    Returns
    -------
    str
        Message saying whether the student passed or not.
    """
    if grade >= 5:
        return f"{name} has passed!"
    else:
        return f"{name} has failed"

print(check_pass("Daniel", 8))
Daniel has passed!
print(check_pass("Alex", 3))
Alex has failed

Why Use Them?

Both docstrings and type hints can be seen in Google Colaboratory when you hover your cursor over a function name. Try it now!

From now on, I expect you to add docstrings and type hints to all the functions you write.