01 / 20
T

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.

Python

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.

def greet(name): """Return a greeting message for the given name.""" return f"Hello, {name}!"

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+).

def greet(name: str) -> str: """Return a greeting message for the given name.""" return f"Hello, {name}!"

Why Do They Matter?

★ Readability
Future you (or a teammate) can understand a function without reading its entire body.
★ Tooling
IDEs use type hints for autocomplete, and linters like mypy catch bugs before runtime.
★ Documentation
Tools like Sphinx auto-generate docs from docstrings, saving you manual work.

Anatomy of a Docstring

1 2 3 4 5 6 7 8 9 10 def calculate_area (width, height): """Calculate the area of a rectangle. Args: width: The width of the rectangle. height: The height of the rectangle. Returns: The area as a float. """ Summary line Args section Returns section

Anatomy of Type Hints

def add ( a : int , b : int ) -> int : Parameter type Return type Colon syntax Arrow syntax

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

str
Text data: "hello"
int
Whole numbers: 42
float
Decimals: 3.14
bool
True / False
list[int]
A list of integers
dict[str, int]
Keys are str, values are int
None
Function returns nothing

How to Write Great Docstrings

1
Start with a one-line summary. Use an imperative verb: "Calculate...", "Return...", "Check...".
2
Leave a blank line after the summary if you need more detail.
3
Document parameters under an Args: section with name, type, and description.
4
Document the return value under a Returns: section.
5
Mention exceptions under a Raises: section if the function can raise errors.

How to Add Type Hints

1
Annotate every parameter with a colon and type: name: str.
2
Add a return annotation using the arrow: -> str.
3
Use None as the return type when the function has no return value.
4
Use container types for collections: list[int], dict[str, float].
5
Run a type checker like mypy to catch mismatches before running your code.

Example 1: Simple Function

def is_even(number: int) -> bool: """Check whether a number is even. Args: number: The integer to check. Returns: True if the number is divisible by 2, False otherwise. """ return number % 2 == 0

Example 2: List Parameter

def average(scores: list[float]) -> float: """Calculate the arithmetic mean of a list of scores. Args: scores: A non-empty list of numeric scores. Returns: The mean value as a float. Raises: ValueError: If the list is empty. """ if not scores: raise ValueError("List cannot be empty") return sum(scores) / len(scores)

Example 3: Dictionary Return

def word_count(text: str) -> dict[str, int]: """Count occurrences of each word in the given text. Args: text: A string of space-separated words. Returns: A dictionary mapping each lowercase word to its count. """ counts: dict[str, int] = {} for word in text.lower().split(): counts[word] = counts.get(word, 0) + 1 return counts

The Full Picture

Your Function Docstring Describes behavior Type Hints Declares types Human Readers Understand intent Tools & IDEs Autocomplete & lint

Common Mistakes

✕ Using Comments Instead
Writing # calculates area above the function instead of a proper docstring. Comments are not accessible via help().
✕ Restating the Name
Writing """This function adds two numbers.""" when the function is called add. Describe what it returns, not its name.
✕ Wrong Placement
Putting the docstring before the def line or after a regular statement. It must be the first expression in the body.
✕ Thinking Hints Enforce Types
Assuming Python will raise an error if you pass the wrong type. Type hints are advisory only: you need a tool like mypy to check them.
✕ Forgetting the Return Type
Annotating parameters but leaving out -> ReturnType. Always include the return annotation, even if it is -> None.

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?