Skip to content

Module 9 · Functions — topic 18 of 19

Docstrings

Documenting functions with docstrings: one-line and multi-line formats, describing parameters, return values and exceptions, and how help() and editors use them.

Beginner 8 min read·Lesson 143 of 306 in Python Programming

Learning objectives

  • Write one-line and multi-line docstrings
  • Document parameters, return values and exceptions
  • Read documentation with help() and __doc__

Definition

A docstring is a string literal placed as the first statement of a function, class or module. Python stores it in the object's __doc__ attribute, and tools such as help() and IDEs display it.

Introduction

When you hover over a function in VS Code or call help(len), the explanation you see is a docstring. Writing them for your own functions makes your code usable by others — including you in six months.

Why it matters

Docstrings document what a function does and how to call it, without readers having to study the body. Unlike comments, they are available at run time and in editor tooltips.

Detailed explanation

A docstring is written with triple quotes immediately after the def line. It must be the first statement.

One-line docstrings state what the function does or returns, as a command ending with a period: """Return the area of a circle."""

Multi-line docstrings start with a summary line, a blank line, then details: parameters (Args), return value (Returns) and exceptions raised (Raises). Google and NumPy styles are common conventions.

Docstrings describe behaviour and contract — what callers need to know — not how the code works internally; comments are for that.

help(func) prints the signature and docstring; func.__doc__ gives the raw string; doctest can even run examples written in docstrings.

Syntax

Python
def bmi(weight_kg, height_m):
"""Return the 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.
Raises:
ValueError: If height_m is not positive.
"""
  • Triple quotes, first statement.
  • Summary line, blank line, details.
  • Describe arguments, return value and errors.

Code examples

Reading a docstring

Python
def area(radius):
"""Return the area of a circle with the given radius."""
return 3.14159 * radius ** 2
print(area.__doc__)
print(len.__doc__.splitlines()[0])
Output
Return the area of a circle with the given radius.
Return the number of items in a container.

help() output

Python
def greet(name, punctuation="!"):
"""Return a friendly greeting for name."""
return f"Hello, {name}{punctuation}"
import pydoc
text = pydoc.render_doc(greet, renderer=pydoc.plaintext)
print(text.splitlines()[2])
print(text.splitlines()[3].strip())
Output
greet(name, punctuation='!')
Return a friendly greeting for name.

More examples

A fully documented function with a doctest

Python
def bmi(weight_kg, height_m):
"""Return the body-mass index rounded to one decimal place.
Args:
weight_kg: Weight in kilograms.
height_m: Height in metres; must be positive.
Raises:
ValueError: If height_m is not positive.
>>> bmi(70, 1.75)
22.9
"""
if height_m <= 0:
raise ValueError("height must be positive")
return round(weight_kg / height_m ** 2, 1)
import doctest
print(doctest.run_docstring_examples(bmi, {"bmi": bmi}) is None)
print(bmi.__doc__.splitlines()[0])
print("Raises:" in bmi.__doc__)
Output
True
Return the body-mass index rounded to one decimal place.
True

Step-by-step explanation

  • The docstring has a summary line, an Args section, a Raises section and an example.
  • Lines starting with >>> are doctest examples: doctest runs them and compares the output; it prints nothing when they pass.
  • run_docstring_examples returns None, so the first print shows True.
  • The summary line is what editors show in tooltips.

Expected output

Running “A fully documented function with a doctest” prints exactly:

TextOutput
True
Return the body-mass index rounded to one decimal place.
True

Practical applications

  • IDE tooltips and autocompletion display docstrings.
  • Sphinx and MkDocs generate documentation websites from docstrings.

Best practices

  • Give every public function a docstring.
  • Start with a one-line summary in the imperative mood.
  • Document arguments, return value and exceptions for non-trivial functions.

Common mistakes

Docstring not first

Avoid

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

Prefer

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

Only a string that is the first statement becomes the docstring.

Restating the code

Avoid

"""Adds a and b and returns it.""" # for an obscure tax formula

Prefer

"""Return the payable tax for income under the 2026 slab rules."""

Explain purpose and contract, not line-by-line mechanics.

Important notes

  • PEP 257 describes docstring conventions.

Key takeaways

  • A docstring is the first statement of a function, in triple quotes.
  • It is stored in __doc__ and shown by help().
  • Describe what the function does, its arguments, return value and errors.

Try it yourself

  1. 1
    Add Google-style docstrings to three functions you wrote earlier.
  2. 2
    Write a function with a doctest example and run doctest.testmod().

Finished reading? Mark it complete to update your dashboard.

Suggested practice

15 questions cover the “Functions” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module