the full guide

Docstrings and type hints

A docstring is a string placed first inside a function, class or module, which explains what it does. Type hints are optional notes that say what types a function expects and returns. Python doesn't enforce them, but tools such as mypy can check them.

8 min Intermediate

What you need: The earlier topics of this module.

Definition

A docstring is a string placed first inside a function, class or module, which explains what it does. Type hints are optional notes that say what types a function expects and returns. Python doesn't enforce them, but tools such as mypy can check them.

In simple words

A docstring is the instruction leaflet in the box. A type hint is the label saying "takes AA batteries". The device still works if you ignore the label, until you put in the wrong battery.

Why it matters

Code is read far more often than it's written. Editors use hints for autocomplete and to catch bugs before you run anything. LLM tool schemas are often generated from them too.

How it works

In code

hints.py
def average(marks: list[float], round_to: int = 1) -> float:
    """Return the mean of marks, rounded.

    Raises ValueError if marks is empty.
    """
    if not marks:
        raise ValueError("marks is empty")
    return round(sum(marks) / len(marks), round_to)

print(average([90, 85.5, 70]))
print(average.__doc__.splitlines()[0])
print(average.__annotations__["return"])

Output

81.8
Return the mean of marks, rounded.
<class 'float'>

Common mistakes

  • Writing a docstring that just repeats the name. Explain what it returns and what can go wrong.
  • Believing hints protect you at run time.

Check yourself

Question 1

1. What happens if you break a type hint when running the code?

Question 2

2. Where does a docstring go?

Summary

  • Docstrings explain code, and help() shows them.
  • Type hints document types, and mypy checks them.

Finished reading?

Sources: The Python Tutorial, python.org