Docstrings &
Type Hints
Learn to write clear docstrings and use type hints so your Python code communicates its purpose to every reader: human and machine alike.
What Are Docstrings?
A docstring is a special string literal placed as the very first statement inside a function, class, or module. Python stores it in the __doc__ attribute so tools like help() can display it at runtime.
What Are Type Hints?
Type hints (also called annotations) let you declare the expected types of a function's parameters and its return value. They were introduced in PEP 484 (Python 3.5+).
Why Do They Matter?
Anatomy of a Docstring
Anatomy of Type Hints
Docstrings vs Comments
| Docstrings | Comments | |
|---|---|---|
| Syntax | """Triple quotes""" | # Hash symbol |
| Stored at runtime? | Yes (__doc__) | No (stripped) |
| Accessed by help()? | Yes | No |
| Purpose | What code does | Why or how |
| Placement | First statement in block | Anywhere |
Common Built-in Types
How to Write Great Docstrings
How to Add Type Hints
Example 1: Simple Function
Example 2: List Parameter
Example 3: Dictionary Return
The Full Picture
Common Mistakes
Summary Cheat Sheet
| Feature | Docstrings | Type Hints |
|---|---|---|
| Syntax | """...text...""" | param: Type, -> Type |
| PEP standard | PEP 257 | PEP 484 |
| Runtime effect | Stored in __doc__ | Stored in __annotations__ |
| Enforced? | No | No (needs mypy, etc.) |
| Main audience | Humans reading docs | IDEs, linters, humans |
| Best practice | Every public function | Every function signature |
Question 1 of 5
Where must a docstring be placed for Python to recognize it?
Question 2 of 5
What does the -> str annotation in def greet(name: str) -> str: indicate?
Question 3 of 5
Which of the following is a well-written one-line docstring for a function called reverse_list?
Question 4 of 5
Given the signature def fetch(url: str, timeout: int = 30) -> dict[str, str]:, what type does timeout expect?
Question 5 of 5
What happens if you pass a float to a parameter annotated as int in Python 3?