Skip to content

Module 2 · Python Syntax and Fundamentals — topic 6 of 14

Documentation strings

Docstrings are string literals that document modules, functions and classes. Learn where to put them, what to write, and how help() and editors display them.

Beginner 12 min read·Lesson 20 of 306 in Python Programming

Learning objectives

  • Write a docstring for a function and a module
  • Read docstrings with help() and __doc__
  • Describe parameters and return values clearly

Definition

Docstrings are string literals that document modules, functions and classes. Learn where to put them, what to write, and how help() and editors display them.

Introduction

A docstring is a string placed as the very first statement inside a module, function or class. Unlike a # comment, Python keeps it and attaches it to the object, so tools can show it later.

Why it matters

Docstrings are how Python code documents itself. When you hover over a function in VS Code or call help() in the shell, the docstring is what you see. Well-documented functions are easier to use correctly without reading their code.

Detailed explanation

Docstrings use triple quotes ("""...""") so they can span several lines.

A one-line docstring describes what the function does in a short sentence, ending with a full stop: """Return the average of a list of numbers."""

A longer docstring adds a blank line and then details: parameters, the return value, and any errors raised.

Python stores the docstring in the object’s __doc__ attribute. help(function) formats and displays it.

A string placed anywhere else, such as after other statements, is not a docstring and is simply ignored.

Docstrings and comments serve different readers. A docstring is for people who call your function and only need to know what it does, what to pass in and what comes back. A # comment is for people reading the inside of the function and explains how or why a particular line works.

Syntax

Python
def function_name(parameter):
"""One-line summary.
Longer explanation, parameters and return value.
"""
...
  • The docstring is the first statement in the body.
  • Start with a one-line summary written as a command: “Return…”, “Calculate…”.
  • Add details after a blank line when needed.

Code examples

Reading a docstring

Python
def square(n):
"""Return n multiplied by itself."""
return n * n
print(square(9))
print(square.__doc__)
Output
81
Return n multiplied by itself.

Built-in functions have docstrings too

Python
print(len.__doc__)
Output
Return the number of items in a container.

More examples

A fully documented function

Python
def bmi(weight_kg, height_m):
"""Calculate body-mass index.
Args:
weight_kg: weight in kilograms.
height_m: height in metres (must be positive).
Returns:
The BMI rounded to one decimal place.
"""
return round(weight_kg / height_m ** 2, 1)
print(bmi(68, 1.72))
print(bmi.__doc__.splitlines()[0])
Output
23.0
Calculate body-mass index.

Step-by-step explanation

  • The triple-quoted block directly under def is the docstring.
  • The Args and Returns sections are a common, readable convention.
  • height_m ** 2 is calculated before the division because ** binds tighter.
  • splitlines()[0] picks the first line of the docstring, the summary.

Expected output

Running “A fully documented function” prints exactly:

TextOutput
23.0
Calculate body-mass index.

Practical applications

  • Documentation websites for libraries such as requests are generated from docstrings by tools like Sphinx.
  • IDE tooltips show docstrings while you type function calls.
  • Code reviews often require every public function to have a docstring.

Best practices

  • Give every function you share a docstring.
  • Start with a one-line summary in the imperative mood.
  • Document units, valid ranges and errors raised.

Common mistakes

Docstring not first in the body

Avoid

def f():
x = 1
"""Explain f."""

Prefer

def f():
"""Explain f."""
x = 1

Only the first statement counts as the docstring; otherwise f.__doc__ is None.

Describing how instead of what

Avoid

"""Loop over the list and add numbers to total."""

Prefer

"""Return the sum of the numbers."""

Users need to know what a function does and returns, not its internal steps.

Key takeaways

  • A docstring is the first string in a module, function or class.
  • It is stored in __doc__ and shown by help() and editors.
  • Use triple quotes and start with a one-line summary.

Try it yourself

  1. 1
    Write a function that converts minutes to hours and minutes, with a docstring describing its parameter and return value.
  2. 2
    Run help(print) in the shell and read which parameters print accepts.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhere must a function's docstring be written?
Practise this topic