Code Comments and Inline DocumentationLesson 5.3
Documenting Python functions with docstrings
Python docstring formats, Google style docstrings, NumPy style, Sphinx format, Args section, Returns section, Raises section, Examples section, pydoc generation
Python Docstrings
Python docstrings are first-class documentation. They're accessible at runtime via help(), used by IDEs for tooltips, and consumed by tools like Sphinx to generate HTML docs. Every public function, class, and module should have one.
Google Style Docstring
def create_user(email: str, name: str, role: str = "viewer") -> dict:
"""Creates a new user and sends a verification email.
Args:
email: Valid email address for the new user.
name: Display name between 2 and 100 characters.
role: User permission level. One of 'admin', 'editor',
or 'viewer'. Defaults to 'viewer'.
Returns:
A dict containing the created user with fields:
id (str), email (str), name (str), created_at (str).
Raises:
ValueError: If email format is invalid or name length
is outside the allowed range.
DuplicateUserError: If a user with this email exists.
Example:
>>> user = create_user("alice@example.com", "Alice Chen")
>>> print(user["id"])
'usr_01HQ...'
"""
...Choosing a Format
Pick one docstring format and use it consistently across your entire codebase. Google style is the most readable inline. NumPy style is preferred for scientific Python. Sphinx RST is most common in legacy codebases. The format matters less than the consistency.
