Previous Post
Python Comments: Frequently Asked Questions (Ultimate FAQ Guide)
Introduction
Welcome back to PyCoder blog! Today, we’re examining one of Python’s most essential—yet frequently underestimated—features: Docstrings.
If you’ve ever returned to a project and struggled to recall the purpose of a function or found yourself analyzing unfamiliar source code just to understand a class’s behavior, you know how quickly productivity can decline without proper documentation.
Docstrings provide the clarity that teams and individuals rely on. They serve as built-in, structured documentation that enhances readability, simplifies maintenance, and supports automated tooling across modern development environments.
In this comprehensive guide, we’ll walk through the fundamentals of docstrings, explore widely used documentation formats, and highlight best practices aligned with PEP 257.
Let’s begin.
What Are Docstrings?
A docstring (documentation string) is a literal string that appears as the first statement in a module, function, class, or method definition. The primary purpose of a docstring is to explain what the piece of code does, its parameters, and what it returns.
Unlike normal comments, Python doesn’t ignore docstrings during compilation. It stores them inside the function, class, or module, so they can be accessed while the program is running.
Remember: Docstrings have a fixed position. We must place a docstring exactly where Python expects it—otherwise, it becomes useless. The docstring for any Python code object (a module, class, or function) must be the very first statement inside that object, immediately after its def or class line.
The golden rule: A docstring should describe what the code does, not how it does it. The code itself should make the “how” clear.
The Syntax:
Docstrings are enclosed in triple quotes ("""...""" or '''...'''). This allows them to span multiple lines, which is perfect for more detailed explanations.
Example of a Docstring
def greet(name):
"""Return a greeting message for the given user."""
return f"Hello, {name}!"Key Characteristics
- Defined using triple quotes (
""" """or''' '''). - Always appear as the first statement inside a function/class/module.
- Meant to describe purpose, behavior, parameters, return values, and examples.
- Used by tools like help(), pydoc, Sphinx, IDEs, and documentation generators.
How to Create and Access Docstrings
Creating Docstrings
Docstrings are created using triple-quoted string literals, most commonly triple double quotes. Triple quotes allow you to write multi-line strings, and when such a string appears as the very first statement inside a module, class, or function, Python automatically treats it as that object’s docstring.
You can technically use either triple double quotes (""" """) or triple single quotes (''' ''') to write a docstring, but according to PEP 257, the preferred and standardized convention is to use triple double quotes for consistency across the Python ecosystem.
Rules for Valid Docstrings
Must be a literal string constant.
Python recognizes a docstring only when the first statement in the code block is a string literal, not an expression or a variable reference.
Must appear immediately after the def, class, or module header.
The docstring must be the very first executable statement inside the function, class, method, or module body; otherwise, Python will not associate it with the object.
Should use triple double quotes (""").
Although both triple single and triple double quotes are valid, PEP 257 establishes triple double quotes as the standard, even for single-line docstrings, to ensure consistency and compatibility with documentation tools.
Must not be assigned to a variable or used as an expression.
Assigning the string to a variable or placing it anywhere other than the first statement prevents Python from treating it as the object’s __doc__ attribute.
Must not be assigned to a variable or used as an expression.
Assigning the string to a variable or placing it anywhere other than the first statement prevents Python from treating it as the object’s __doc__ attribute.
Examples of Docstrings
Below are various examples showing how docstrings are written for different kinds of Python code objects. Each example follows the PEP 257 convention of using triple double quotes.
1. Function Docstring
def add(a, b):
"""Add two numbers and return the result."""
return a + b2. Class Docstring
class Person:
"""A class representing a person with name and age."""
def __init__(self, name, age):
"""Initialize person object."""
self.name = name
self.age = age3. Module Docstring (top of file)
"""
This module provides utility functions for string processing.
Includes uppercase conversion and trimming functions.
"""4. Method Docstring Example
class Calculator:
"""A basic calculator class."""
def subtract(self, x, y):
"""Return the result of subtracting y from x."""
return x - yAccessing Docstrings
Once a docstring is correctly placed inside a module, class, function, or method, Python stores it in the object’s __doc__ attribute. This allows you to access documentation at runtime—something regular comments cannot do. There are two built-in ways to retrieve docstrings: the help() function and the __doc__ attribute.
A) Accessing Docstrings Using help()
The help() function is the most user-friendly and interactive way to view docstrings. It formats the docstring, adds additional metadata, and displays it in a clean, readable way. This is especially useful in the Python REPL or while exploring unfamiliar code.
Example
def greet(name):
"""Return a greeting message for the given name."""
return f"Hello, {name}!"Now call help():
def greet(name):
"""Return a greeting message for the given name."""
return f"Hello, {name}!"
help(greet)Output
Help on function greet in module __main__:
greet(name)
Return a greeting message for the given name.How it works
help()retrievesgreet.__doc__internally.- It then formats the information (signature, location, docstring).
- Great for quick inspection and exploration.
B) Accessing Docstrings Using the __doc__ Attribute
Every Python module, class, function, method, and even built-in objects have a special attribute named __doc__. This attribute stores the docstring as a plain string, exactly as written inside the code.
Example
def square(n):
"""Return the square of a number n."""
return n * nAccessing it via the attribute:
def square(n):
"""Return the square of a number n."""
return n * n
print(square.__doc__)Output
Return the square of a number n.How it works
__doc__is simply a string attribute.- It gives you the raw docstring without formatting.
- Ideal when processing docstrings programmatically (e.g., documentation generators, introspection tools).
Important Differences Between help() and __doc__
| Feature | help() | __doc__ |
|---|---|---|
| Returns | Formatted, readable output | Raw docstring string |
| Good for | Interactive inspection | Code automation and introspection |
| Adds metadata | Yes (signature, module info) | No |
Uses __doc__ internally | Yes | N/A |
Example Showing Both Methods Together
def divide(a, b):
"""
Divide a by b and return the result.
Raises:
ZeroDivisionError: If b is zero.
"""
return a / b
print(divide.__doc__) # Raw docstring
help(divide) # Formatted docstringWhere to Place Docstrings (Docstring Must Be the First Statement)
In Python, a docstring only works when it appears as the very first statement inside a module, class, function, or method. This rule exists because Python identifies a docstring in a very simple way: it checks whether the first statement in the code block is a string literal. If it is, Python stores that string in the object’s __doc__ attribute. If it isn’t, Python assumes there is no docstring.
Important: This means that placing a string literal anywhere else—below a variable, after a print statement, or at the end of a function—will not count as a docstring. Python simply treats such strings as regular, unused string literals and discards them during compilation.
Correct placement:
def greet():
"""This function prints a greeting."""
print("Hello!") # Output: This function prints a greeting.Incorrect placement (not a docstring):
def greet():
print("Hello!")
"""This will NOT be recognized as a docstring."""
print(greet.__doc__) # Output: NoneIn the correct example, the docstring becomes part of the function’s metadata and is accessible at runtime via greet.__doc__. In the incorrect example, the string is ignored, and the function ends up with no docstring.
Docstring Structures vs. Docstring Styles
Docstrings in Python can be understood from two perspectives:
(1) their structure (how they are physically written), and
(2) their style (the formatting conventions used inside them).
Both aspects play an important role in writing clean, consistent, and tool-friendly documentation.
Docstring Structure Types
Docstring structure refers to how the docstring is laid out, not its formatting rules.
There are two basic structural forms:
A) Single-Line Docstring
A single-line docstring fits entirely on one line. It is used for simple functions, methods, or classes where the purpose is clear and easy to explain in one sentence.
Single-line docstring should fit on one line within triple quotes and end with a period. It is also called one-line docstring.
Characteristics
- Placed on a single line with closing quotes on the same line.
- Should be concise and direct.
- Ends with a period (recommended by PEP 257).
Example
def is_even(n):
"""Return True if n is an even number."""
return n % 2 == 0When to use
- For small, self-explanatory functions.
- When no parameter/return details or examples are required.
B) Multi-Line Docstring
A multi-line docstring is used for more complex code that requires additional explanation.
It typically includes sections like arguments, return values, exceptions, examples, notes, and more (depending on the style used).
Characteristics
- Opening quotes on their own line.
- Summary line followed by a blank line.
- Additional description or sections below.
Example:
def calculate_area(radius):
"""
Calculate the area of a circle.
Parameters:
radius (float): Radius of the circle.
Returns:
float: The computed area.
"""
return 3.14159 * radius * radiusWhen to use
- Functions/classes with multiple parameters.
- When documenting behavior, edge cases, or exceptions.
- When using structured documentation styles (Google, NumPy, reST).
Docstring Style Types
While structure describes how a docstring is written, style describes the formatting conventions inside the docstring. These formats help humans and documentation tools understand the content.
Below are the major docstring styles used in the Python ecosystem.
A) Google Style Docstrings
Google-style docstrings focus on readability and clean section-based formatting.
Sections include Args, Returns, Raises, and Examples.
Example
def greet(name):
"""
Generate a greeting message.
Args:
name (str): The name of the person.
Returns:
str: A formatted greeting message.
"""
return f"Hello, {name}!"
Best for:
- Beginners and teams wanting clarity.
- Projects emphasizing readability.
- Tools such as Sphinx (with napoleon extension).
B) NumPy / SciPy (NumPyDoc) Style Docstrings
NumPy-style docstrings are more detailed and standardized for scientific and data-science libraries.
Features
- Clear section headers (Parameters, Returns, Notes, Examples).
- Type annotations appear aligned and structured.
- Widely used in data science libraries (NumPy, SciPy, Pandas, Matplotlib).
Example
def normalize(x):
"""
Normalize a list of numbers.
Parameters
----------
x : list of float
Input values.
Returns
-------
list of float
Normalized values.
"""
total = sum(x)
return [i / total for i in x]Best for:
- Scientific computing.
- Data processing libraries.
- Large codebases that require strict documentation structure.
C) reStructuredText (reST) / Sphinx Style Docstrings
This style uses reStructuredText markup language and integrates deeply with Sphinx, the most popular Python documentation generator.
Example
def divide(a, b):
"""
Divide two numbers.
:param a: Numerator.
:type a: float
:param b: Denominator.
:type b: float
:returns: The result of the division.
:rtype: float
:raises ZeroDivisionError: If b is zero.
"""
return a / bBest for:
- Large projects with extensive documentation.
- Auto-generated HTML, PDF, or API docs.
- Professional or enterprise-level Python systems.
Docstring vs Comments in Python
In Python, both comments and docstrings help developers understand the code—but they serve very different purposes. Comments are meant for developers, explaining the “why” behind the code or clarifying complex logic. Docstrings, on the other hand, are written for both users and developers, documenting what functions, classes, and modules do. Unlike comments, docstrings become part of the program at runtime and can be accessed programmatically.
Understanding the difference between docstrings and comments is essential for writing clean, maintainable, and well-documented Python code.
| Feature | Comments | Docstrings |
|---|---|---|
| Purpose | Explain code logic for developers | Document functions/classes/modules |
| Syntax | # for single-line comments | """ triple-quoted string """ |
| Placement | Anywhere in code | Immediately after function/class/module header |
| Execution | Ignored by interpreter | Stored as part of the object |
| Runtime Access | Not accessible | Accessible via __doc__ or help() |
| Documentation Tools | Not included | Included in Sphinx, pydoc, help() |
| Best For | Explaining why / complex logic | Explaining what / API documentation |
| Visibility | Only for developers reading code | Visible to users calling help() |
| PEP Guidance | PEP 8 covers comments | PEP 257 covers docstrings |
Example Showing the Difference
def greet(name):
"""Return a personalized greeting message.""" # Docstring stored
# This is an inline comment for developers
return f"Hello, {name}!"If you access:
print(greet.__doc__)Output:
Return a personalized greeting message.Comment after the code is not accessible.
PEP 257 Recommendations for Docstrings
PEP 257 is the official Python Enhancement Proposal that defines the conventions for writing clean, consistent, and useful docstrings. Following these guidelines helps maintain readability, improves auto-generated documentation, and ensures that your codebase looks professional and standardized across functions, classes, and modules.
Below are the most important recommendations from PEP 257:
1. Always Use Triple Double Quotes (""")
PEP 257 recommends using triple double quotes for all docstrings, even for single-line ones.
def greet():
"""Return a simple greeting."""
return "Hello!"This makes your documentation consistent across your entire project.
2. The Docstring Should Start With a One-Line Summary
The first line should be a short, clear summary of what the function/class/module does.
- Should be written as a single sentence ending with a period.
- Must start immediately after the opening triple quotes.
def add(a, b):
"""Add two numbers and return the result."""
return a + b3. Add a Blank Line After the Summary (For Multi-line Docstrings)
If your docstring extends beyond a single line, add a blank line after the summary before writing more details.
def factorial(n):
"""
Compute the factorial of a number.
This function uses a recursive approach to compute the factorial.
"""This improves readability and makes documentation tools parse it correctly.
4. Describe Parameters, Return Values, and Exceptions (If Applicable)
Even though PEP 257 does not mandate a specific format (like NumPy-style or Google-style), it encourages documenting:
- Function arguments
- Return values
- Exceptions raised
Example:
def divide(a, b):
"""
Divide one number by another.
Parameters:
a (float): Numerator.
b (float): Denominator (must not be zero).
Returns:
float: Result of division.
Raises:
ZeroDivisionError: If b is zero.
"""5. Write Docstrings Using Imperative Mood
Use the imperative form as if giving a command.
✔ “Return the sum.”
❌ “Returns the sum.”
Although both are common, imperative mood is preferred in PEP 257.
Example:
def square(n):
"""Return the square of a number."""6. Docstrings Belong Directly Under the Definition Line
A docstring must appear immediately after the def, class, or module header.
class Person:
"""Represent a person with a name and age."""If anything (even a comment) appears before the docstring, Python won’t treat it as the official docstring.
7. Use a Closing Triple Quote on Its Own Line for Multi-line Docstrings
For multi-line docstrings, the closing """ should be placed on its own line.
def process():
"""
Perform a processing task.
This function does something important.
"""8. Keep the Docstring Focused and Useful
PEP 257 emphasizes brevity, clarity, and relevance:
- Do not describe obvious behavior (e.g., “Add one to x” when the code is
return x + 1). - Avoid unnecessary line breaks.
- Avoid including too much implementation detail—focus on what the function does, not exactly how.
9. Use Docstrings for Public Modules, Classes, and Functions
Private/internal functions may skip docstrings, but all public APIs should include them.
This makes your library or project fully self-documented when others use tools like:
help()pydoc- Sphinx
- IDE tooltips (PyCharm, VSCode, etc.)
Summary of Key PEP 257 Rules
- Use triple double quotes →
"""docstring""" - Start with a one-line summary
- Use imperative mood
- Add a blank line before detailed description
- Place docstring immediately inside the definition
- Keep content clear, concise, and helpful
Common Mistakes to Avoid When Writing Docstrings
Even experienced developers make mistakes when writing docstrings. Many of these mistakes come from misunderstanding what docstrings are for, or mixing them with comments. Below are the most common pitfalls—and how to avoid them.
1. Writing Docstrings That Describe How Instead of What
Docstrings should focus on what the function does, not the low-level implementation details.
Bad:
def process(data):
"""
Loop through the list, check each item, and append matches to result.
"""Good:
def process(data):
"""
Filter the input list and return only items that match the criteria.
"""Implementation details belong in comments, not docstrings.
2. Ignoring the One-Line Summary Rule
Some developers jump straight into long explanations, making documentation harder to read.
❌ Summary missing or buried.
✔️ Always start with a short, clear, single-sentence summary.
3. No Blank Line After the Summary (for Multi-line Docstrings)
PEP 257 requires a blank line after the summary in multi-line docstrings.
Bad:
def example():
"""Do something.
More explanation…
"""Good:
def example():
"""
Do something.
More explanation…
"""4. Using Comments Instead of Docstrings for Public APIs
Public modules, classes, and functions should always include docstrings.
❌ Using only comments in a public function
✔️ Use comments for logic, docstrings for documentation
5. Writing Docstrings That Are Too Vague or Too Obvious
❌ Too vague:
"""Handle stuff."""❌ Too obvious:
"""Return x + 1.""" # The code already tells this.✔️ Ideal:
"""Return the incremented value of x by applying business logic."""6. Writing Docstrings That Are Too Long or Irrelevant
Docstrings should be helpful—not novels.
Avoid:
- Over-explaining logic
- Historical notes
- Stories about why the code exists
- Debugging logs or TODOs
Those belong in comments or commit messages.
7. Incorrect Placement of Docstrings
A docstring must come right after the function, class, or module header.
Wrong:
def add(a, b):
# comment here
"""Add two numbers."""Correct:
def add(a, b):
"""Add two numbers."""If anything comes before the string literal, Python will not treat it as a docstring.
8. Not Documenting Parameters, Return Values, or Exceptions
Even though PEP 257 doesn’t force a strict format, it strongly encourages documenting:
- Parameters
- Return values
- Side effects
- Exceptions raised
Failure to specify these leads to confusion, especially when others use your API.
9. Using the Wrong Quotation Style
PEP 257 prefers triple double quotes (""") even for short docstrings.
❌ Bad: '''docstring'''
✔️ Good: """docstring"""
Consistency matters in large projects.
10. Mixing Docstrings with Comment-Style Notes
Docstrings should not contain:
- TODOs
- FIXMEs
- Implementation plans
- Explanations for tricky logic
These belong in comments or project trackers, not in documentation exposed to users via help().
11. Not Using Imperative Mood
Docstrings should sound like commands.
❌ “Returns the value…”
✔️ “Return the value…”
This is a subtle but important PEP 257 guideline.
12. Forgetting That Docstrings Are User-Facing
Docstrings appear in:
Docstrings appear in:
help()- IDE auto-suggestions
- API documentation
- Generated HTML docs
So avoid:
- Jokes
- Rude comments
- Internal complaints
- Unprofessional language
Keep them clean and helpful.
Conclusion
Docstrings are one of the most powerful features in Python. They help you build readable, maintainable, and well-documented code that is easy for users to understand and easy for tools to use.
By mastering docstrings—formats, best practices, PEP standards—you elevate your Python code from functioning scripts to professional, self-explanatory software.
Next Post
Python Docstrings: The Ultimate FAQ Guide (With Examples & Best Practices)
Suggested Posts
1. Python Docstrings: The Ultimate FAQ Guide (With Examples & Best Practices)

This is a fantastic resource! I’ve been struggling to properly use docstrings, and this really clarifies everything.