Type hints and docstrings

Topic 5 of 5 in Functions6 min readBeginnerFree course

Overview

When you come back to a function after a month — or someone else reads it — two questions come first: what does it do, and what does it take and give back? Docstrings answer the first; type hints answer the second. Both are free to write and pay off quickly.

Docstrings

A docstring is a string literal written as the first statement of a function (or module, or class). By convention it uses triple double quotes:

Python
def average(numbers):
    """Return the arithmetic mean of a non-empty list of numbers."""
    return sum(numbers) / len(numbers)

Unlike a # comment, Python keeps the docstring and makes it available:

Python
help(average)
Text
Help on function average in module __main__:

average(numbers)
    Return the arithmetic mean of a non-empty list of numbers.

Editors show it when you hover over a call, too.

Writing good docstrings

  • First line: one sentence in the imperative mood saying what the function does — “Return…”, “Calculate…”, “Send…” — ending with a full stop.
  • For more complex functions, add a blank line, then details: arguments, return value, errors raised, and an example.
Python
def shipping_cost(total, country):
    """Return the shipping cost for an order.

    Orders of 100 or more ship free. Domestic (IN) orders cost 5,
    everything else 15.

    Raises ValueError if total is negative.
    """

Describe what and why, not how — the code shows how.

Type hints

Type hints (or annotations) state the types a function expects and returns:

Type hints document what goes in and out: def total(prices: list[float], tax: float = 0.2) -> float:. list[float] is a parameter type; float = 0.2 is a type plus a default; -> float is the return type. Python does NOT check hints when the code runs. Editors and tools such as mypy or pyright use them to catch mistakes before you run anything — and they document your code for readers.

Python
def total(prices: list[float], tax: float = 0.2) -> float:
    return sum(prices) * (1 + tax)
  • name: type after each parameter;
  • = default after the type, if there is one;
  • -> type before the colon for the return value (-> None for functions that don’t return anything).

Common types

Hint Meaning
int, float, str, bool the basic types
list[str] a list of strings
dict[str, float] a dict with string keys and float values
tuple[int, int] a tuple of exactly two ints
set[str] a set of strings
str | None a string or None (an “optional” value)
int | float either type

Variables can be annotated too, though you rarely need to: scores: list[int] = [] helps when you start with an empty collection.

Hints are not checked at run time

This surprises many people:

Python
def double(n: int) -> int:
    return n * 2

print(double("ha"))    # 'haha' — no error!

Python ignores hints when running the code. They’re information for people and tools:

  • Editors (VS Code with Pylance, PyCharm) use them to offer completions and underline mistakes as you type — double("ha") gets a squiggle.
  • Type checkers such as mypy and pyright check a whole project without running it:
Terminal
pip install mypy
mypy shop.py
Text
shop.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int"  [arg-type]

Catching that kind of mistake before the code ever runs is the big win, and it grows with the size of your project.

When to add hints

  • Always on functions other people (or future you) will call.
  • Not necessary on every local variable — type checkers work out most of them.
  • Start simple; hints are optional and you can add them gradually.

Seeing hints and docstrings in code

Both are stored on the function object:

Python
average.__doc__              # the docstring
average.__annotations__      # {'numbers': list[float], 'return': <class 'float'>}

Tools like documentation generators and frameworks (FastAPI, for example, uses hints to validate web requests) read these attributes.

Habit to build: every function that’s more than a quick helper gets a one-line docstring and type hints. It takes ten seconds and saves minutes every time someone reads it.

Exercise

Document a small library

The starter has three working but undocumented functions. Add a docstring and complete type hints to each: average takes a list of floats and returns a float; find_price takes a dict of str → float and a str, and returns a float or None; format_name takes a first name, an optional middle name (str or None, default None) and a last name passed by keyword, returning a str. Then print the first line of each function’s docstring using __doc__, and print average.__annotations__.

Python
def average(numbers):
    return sum(numbers) / len(numbers)


def find_price(prices, item):
    return prices.get(item)


def format_name(first, middle=None, *, last):
    if middle:
        return f"{first} {middle[0]}. {last}"
    return f"{first} {last}"


print(average([2.0, 4.0]))
print(find_price({"tea": 3.5}, "tea"), find_price({"tea": 3.5}, "pie"))
print(format_name("Ada", last="Lovelace"), format_name("John", "Fitzgerald", last="Kennedy"))

Summary

  • A docstring is a string literal on the first line of a function; it explains what the function does and shows in help() and editors.
  • Type hints annotate parameters (price: float) and return values (-> float).
  • Use built-in generics like list[str] and dict[str, int], and X | None for optional values.
  • Python doesn’t enforce hints at run time; editors and checkers such as mypy and pyright use them to find bugs early.
  • Hints and docstrings are documentation for people as much as for tools — add them to every function others will use.