What is a Python docstring?

"Programs must be written for people to read, and only incidentally for machines to execute." —Harold Abelson, American mathematician and computer scientist

A Python docstring is a text written inside triple quotes to describe a module, class, function, or method. It serves as inline documentation, explaining the purpose, parameters, and usage of the code to improve readability and help other developers understand it.

When writing code, it’s essential to not only focus on functionality but also clarity and readability. This is where docstrings come into play in Python. A docstring is a string literal used to document modules, functions, classes, or methods. Unlike traditional comments, docstrings serve as an official guide to how your code should be used. This feature is crucial for understanding code behavior, especially in collaborative environments or for future reference.

What is a docstring?

A docstring in Python is a special kind of comment used to document a specific segment of code. Docstrings are declared using triple quotes (""" """) and can span across multiple lines or be as short as one line. Unlike regular comments, which are ignored by the interpreter, docstrings are stored as an attribute of the function or class and can be accessed during runtime.

Python docstring
Python docstring

Docstrings provide a high-level overview of what a piece of code does. For instance, they describe the purpose of a function, its parameters, and its return values.

  • Declaring docstrings: In Python, docstrings are declared directly under the function, class, or module definition. They use either single-line or multi-line triple-quoted strings (""" """).

  • Accessing docstrings: You can access docstrings using two main methods:

    • The __doc__ attribute.

    • The help() function.

The __doc__ attribute retrieves the docstring of any object, while the help() function provides more comprehensive documentation.

Why is docstring important?

Docstrings are essential for several reasons:

  • Clarity: They make your code easier to understand for other developers (or for yourself when revisiting the code).

  • Maintenance: Well-documented code is easier to maintain and debug.

  • Automated documentation: Tools like Sphinx can automatically generate documentation from docstrings.

  • Interactive help: The help() function leverages docstrings to provide quick insights into your code during runtime.

Rules of Python docstring

Docstring implementation

Let's see how docstrings are used in Python:

Triple-quoted strings

Docstrings use triple-quoted strings (""" """), which can span multiple lines or remain on a single line. They must be placed at the very start of a module, class, or function.

def multiply(a, b):
'''In this function, we will multiply two numbers and return the result.'''
return a * b
print(multiply.__doc__)

Single-line docstring

A single-line docstring is used for simple functions or classes. Here’s an example:

def hello_world():
"""Demonstrating docstring."""
return None
# printing using __doc__ method
print "Using __doc__ method:"
print hello_world.__doc__
# printing using help function
print "Using help function:"
help(hello_world)

Multi-line docstring

For more complex functions or classes, a multi-line docstring is more appropriate:

def hello_world(argument):
"""
Summary line.
Here comes description of a function.
Parameters:
argument (int): Description of argument
Returns:
int: Description of return value
"""
return argument
# printing using __doc__ method
print "Using __doc__ method:"
print hello_world.__doc__
# printing using help function
print "Using help function:"
help(hello_world)

Indentation in docstring

Proper indentation is crucial for readability in docstrings, especially for multi-line ones. The first line should start right after the triple quotes, and subsequent lines should be indented accordingly.

def add(a, b):
"""Add two numbers and return the result.
This function takes two arguments, `a` and `b`, and returns their sum.
The result will be either an integer or a float, depending on the input types.
Parameters:
a (int or float): The first number
b (int or float): The second number
Returns:
int or float: The sum of a and b
"""
return a + b
# Accessing the docstring
print(add.__doc__)
  • The first line of the docstring starts immediately after the opening triple quotes.

  • Subsequent lines are indented for better readability, especially when describing parameters and return values.

  • Proper indentation is not enforced by Python, but it’s important for consistency and readability when working in teams or sharing your code.

Docstring in classes

Docstrings are also applicable in classes. You can define a docstring for the class itself and each method within the class.

class complex_number:
"""
This is a class for mathematical operations on complex numbers.
Parameters:
real (int): The real part of complex number.
imag (int): The imaginary part of complex number.
"""
def add(self, number):
"""
The function adds two complex numbers.
Parameters:
number (complex_number): The complex number to be added.
Returns:
ComplexNumber: A complex number which contains the sum.
"""
re = self.real + num.real
im = self.imag + num.imag
return ComplexNumber(re, im)
help(complex_number) # to access Class docstring
help(complex_number.add) # to access method's docstring

Difference between Python comments and docstring

Comments and docstrings serve different purposes in Python. While both are non-executable and meant to clarify the code, comments are for internal explanations and are ignored by Python during execution. In contrast, docstrings are stored as attributes of the functions or classes and can be accessed at runtime. Here's a comparison:

# Comments in Python
def add_with_comments(a, b):
return a + b
# Docstring in Python
def add_with_docstring(a, b):
"""Add two numbers and return the result."""
return a + b

Comments are for the developer's reference and are ignored by Python whereas docstrings provide structured documentation accessible via code and tools such as help().

Key takeaways

  • Python docstrings are used to document modules, functions, and classes.

  • They can be accessed using __doc__ or the help() function.

  • Docstrings are written using triple-quoted strings and can be single-line or multi-line.

  • Proper documentation improves code readability, maintainability, and collaboration.

  • Python comments differ from docstrings as they are not accessible at runtime.

Challenge: Fix the docstring

Consider the following function, which is supposed to add and subtract two numbers. The docstring, however, has several issues:

  • It only mentions addition, not subtraction.

  • The parameters are incorrectly documented.

  • The docstring format is inconsistent with typical conventions.

Your task is to do the following:

  1. Identify and correct the errors in the docstring.

  2. Update the code to accurately describe both addition and subtraction.

  3. Use the help() function after your modifications to see how the corrected docstring appears.

def add_subtract(a, b):
""'
This function adds two numbers.
Parameters:
x (int): The first number to add
y (int): The second number to add
Returns:
tuple: containing the sum and the difference of a and b
'""
sum_result = a + b
diff_result = a - b
return sum_result, diff_result
# Check the function docstring
print("Using help() to view the docstring:")
help(add_subtract)

If you are stuck, click the "Solution" button after clicking the "Run" button.

Become a Python developer with our comprehensive learning path!

Ready to kickstart your career as a Python Developer? Our Become a Python Developer path is designed to take you from your first line of code to landing your first job.

This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How can I access a Python docstring?

You can access a Python docstring in two ways:

  1. Using the __doc__ attribute:
  • print(example.__doc__)

  1. Using the help() function:
  • help(example)

What tools use Python docstrings for documentation?

Several documentation generators use Python docstrings, such as:

  • Sphinx: Converts docstrings into structured documents like HTML or PDFs.
  • pydoc: A built-in Python tool that generates documentation from docstrings.
  • Doxygen: Works across various languages, including Python, and uses docstrings for generating code documentation.

What are some best practices for writing Python docstrings?

Write docstrings for all public modules, functions, classes, and methods.

  • Use triple quotes, even for one-line docstrings.
  • Keep one-liners concise.
  • For multi-line docstrings, include a summary, followed by more detail, and descriptions of parameters and return values.
  • Follow PEP 257 for docstring conventions in Python.

Do all functions need docstrings?

No, not all functions in Python require docstrings, but it’s a best practice to include them for public functions, methods, and classes. If a function is complex or intended for use by others, a docstring helps explain its purpose and usage. For simple or private functions, docstrings are optional, but they enhance readability and maintainability.


What is the difference between string and docstring in Python?

  • A string in Python is a data type used to represent a sequence of characters, enclosed in quotes (" " or ' '). It’s primarily used to store and manipulate text data.

  • A docstring, on the other hand, is a specific type of string used to document code. It is enclosed in triple quotes (""" """ or ''' ''') and placed at the beginning of a module, function, class, or method to describe its purpose. Docstrings are accessible at runtime using __doc__ or help(), whereas regular strings are not.


Which is the correct location to place a docstring for a function?

The correct location for a docstring in a function is immediately after the function definition, before any code or logic inside the function. It should be placed inside triple quotes. Here’s an example:

def example_function():
    """
    This is the function's docstring. 
    It should explain what the function does.
    """
    # Function code goes here
    pass

This ensures that the docstring can be accessed by tools like help() or __doc__.


What are common mistakes made when writing Python docstrings, and how can they be avoided?

Common mistakes in writing Python docstrings include:

  • Inaccurate or outdated descriptions: When functions are modified, docstrings may not get updated, leading to mismatched descriptions.
    Solution: Always review and update docstrings after making changes to a function’s parameters or purpose.

  • Inconsistent format: Skipping standard conventions (like those in PEP 257) can make docstrings unclear.
    Solution: Follow a consistent format (e.g., summarize the function in the first line, list parameters, and explain the return value) to improve readability.

  • Vague descriptions: Using unclear or minimal descriptions that don’t convey the function’s purpose.
    Solution: Be specific; briefly explain what the function does, parameters, and the result it returns.

  • Incorrect parameter names or types: Using incorrect or missing parameter names and types can lead to confusion.
    Solution: Double-check that parameter names, types, and return types in docstrings match the code.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved