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
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
Summary
- Docstrings explain code, and help() shows them.
- Type hints document types, and mypy checks them.
Finished reading?
Sources: The Python Tutorial, python.org