GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask
  • Introduction1 min read
  • Input & Output2 min read

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — Python Docstrings - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask

Python Docstrings

Last Updated : 19 Sep, 2025

Docstrings (Documentation Strings) are special strings used to document Python code. They provide a description of what a module, class, function or method does.

  • Declared using triple quotes (' ' ' or " " ").
  • Written just below the definition of a function, class, or module.
  • Unlike comments (#), docstrings can be accessed at runtime using __doc__ or help().

Example:

Python
def greet(name):
    """This function greets the user by their name."""
    return f"Hello, {name}!"

Here, the docstring explains what the function does in one simple line.

Declaring and Accessing Docstrings

Docstrings are written just below the function, class or module definition. They can be accessed later using either:

  • object.__doc__: Returns the docstring as a string.
  • help(object): Displays the docstring in a more detailed format.

Example: The following code shows how to declare a docstring for a function and access it using both __doc__ and help().

Python
def my_function():
    """Demonstrates triple quotes docstring and does nothing."""
    return None

print("Using __doc__:")
print(my_function.__doc__)

print("Using help():")
help(my_function)

Output
Using __doc__:
Demonstrates triple quotes docstring and does nothing.
Using help():
Help on function my_function in module __main__:

my_function()
    Demonstrates triple quotes docstring and does no...

Explanation:

  • """Demonstrates triple quotes docstring and does nothing.""": Declares the docstring for my_function.
  • my_function.__doc__: Directly prints the docstring text.
  • help(my_function): Displays docstring in a structured help format.

What should a docstring look like?

  • The doc string line should begin with a capital letter and end with a period.
  • The first line should be a short description.
  • If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
  • The following lines should be one or more paragraphs describing the object’s calling conventions, side effects, etc.

Types of Docstrings

Python supports different docstring styles. Let’s go through them one by one with examples.

1. Triple-Quoted Strings

Most common style in Python. Uses triple single (''') or triple double (""") quotes. Can span multiple lines.

Example 1: This function shows how to use triple single quotes for docstrings.

Python
def my_func():
    '''This is a docstring using triple single quotes.'''
    return None

print("Using __doc__:")
print(my_func.__doc__)

print("Using help():")
help(my_func)

Output
Using __doc__:
This is a docstring using triple single quotes.
Using help():
Help on function my_func in module __main__:

my_func()
    This is a docstring using triple single quotes.

Explanation: docstring is written just below the function definition. __doc__ prints it directly and help() shows it in a structured way.

Example 2: This function shows how to use triple double quotes for docstrings.

Python
def my_func():
    """This is a docstring using triple double quotes."""
    return None

print(my_func.__doc__)

Output
This is a docstring using triple double quotes.

2. Google Style Docstrings

Google style docstrings follow a specific format and are inspired by Google's documentation style guide. They provide a structured way to document Python code, including parameters, return values and descriptions.

Example: This function multiplies two numbers using Google-style docstrings.

Python
def multiply(a, b):
    """
    Multiply two numbers.

    Args:
        a (int): First number.
        b (int): Second number.

    Returns:
        int: Product of a and b.
    """
    return a * b
print(multiply(3, 5))

Output
15

Explanation: Args describes input parameters and Returns describes output.

3. Numpydoc Style Docstrings

Numpydoc-style docstrings are widely used particularly for documenting functions and classes related to numerical computations and data manipulation. It is an extension of Google-style docstrings, with some additional conventions for documenting parameters and return values.

Example: This function divides two numbers using Numpydoc-style docstrings.

Python
def divide(a, b):
    """
    Divide two numbers.

    Parameters
    ----------
    a : float
        Dividend.
    b : float
        Divisor.

    Returns
    -------
    float
        Quotient of division.
    """
    if b == 0:
        raise ValueError("Division by zero not allowed.")
    return a / b
print(divide(6, 2))

Output
3.0

4. One-line Docstrings

As the name suggests, one-line docstrings fit in one line. They are used in obvious cases. The closing quotes are on same line as the opening quotes. This looks better for one-liners.

Example: This function raises a number to a power with a one-line docstring.

Python
def power(a, b):
    """Return a raised to power b."""
    return a ** b
print(power.__doc__)

Output
Return a raised to power b.

5. Multi-line Docstrings

Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line. The summary line may be on same line as opening quotes or on next line.

Example: This function shows a multi-line docstring with parameters and return value.

Python
def add(a, b):
    """
    Add two numbers.

    Parameters:
        a (int): First number.
        b (int): Second number.

    Returns:
        int: Sum of a and b.
    """
    return a + b
print(add(3, 7))

Output
10

6. Docstrings in Classes (with Indentation)

Docstrings in classes describe the class itself, its attributes, and its methods. Proper indentation is important:

  • The class docstring is aligned with the class keyword.
  • Method docstrings are indented inside the method.
  • Tools automatically strip extra spaces but preserve relative indentation.

Example: This example shows class-level and method-level docstrings with proper indentation.

Python
class Employee:
    """
    A class representing an employee.

    Attributes:
        name (str): Employee name.
        age (int): Employee age.
        salary (float): Employee salary.
    """

    def __init__(self, name, age, salary):
        """
        Initialize an Employee object.

        Parameters:
            name (str): Employee name.
            age (int): Employee age.
            salary (float): Employee salary.
        """
        self.name = name
        self.age = age
        self.salary = salary

    def promote(self, amount):
        """
        Increase salary by a given amount.

        Parameters:
            amount (float): Raise amount.

        Returns:
            str: Message with new salary.
        """
        self.salary += amount
        return f"{self.name} promoted! New salary: {self.salary}"

Output (using help):

Help on class Employee in module __main__:

class Employee(builtins.object)
| A class representing an employee.
|
| Attributes:
| name (str): Employee name.
| age (int): Employee age.
| salary (float): Employee salary.
|
| Methods defined here:
|
| __init__(self, name, age, salary)
| Initialize an Employee object.
|
| promote(self, amount)
| Increase salary by a given amount.

Explanation:

  • The class docstring documents attributes.
  • Each method docstring documents parameters and return values.
  • Proper indentation ensures readability and compatibility with tools like help().

Difference between Comments, String and Docstrings

  • Comments (#): Explain code but are ignored by Python at runtime.
  • Strings (" " or ' '): Represent text data and are used in variables/operations.
  • Docstrings (""" """): Special strings placed below definitions to document modules, classes or functions. Unlike comments, they can be accessed using __doc__ or help().

Note: Docstrings are actually strings too, but Python treats them specially when placed right after a function, class or module definition.

Example: This example shows the difference between a comment, a string and a docstring.

Python
# This is a comment (ignored by Python)

name = "Daniel"   # A string assigned to a variable

def greet():
    """This is a docstring. It explains what greet() does."""
    return "Hello!"

Explanation:

  • # This is a comment: just for developers, ignored at runtime.
  • "Daniel": a normal string stored in a variable.
  • """This is a docstring""": documents the function and can be accessed via greet.__doc__ or help(greet).
Comment

Explore

    Python Fundamentals
    • Introduction1 min read
    • Input & Output2 min read
    • Variables4 min read
    • Operators4 min read
    • Keywords2 min read
    • Data Types4 min read
    • Conditional Statements3 min read
    • Loops3 min read
    • Functions4 min read
    Python Data Structures
    • String4 min read
    • List3 min read
    • Tuples3 min read
    • Dictionary3 min read
    • Set2 min read
    • Arrays5 min read
    Advanced Python
    • OOP Concepts3 min read
    • Exception Handling5 min read
    • File Handling4 min read
    • Python Database2 min read
    • MongoDB3 min read
    • MySQL7 min read
    • Packages4 min read
    • Modules3 min read
    • DSA Libraries5 min read
    • Python GUI2 min read
    Data Science with Python
    • Numpy3 min read
    • Pandas4 min read
    • Matplotlib3 min read
    • Seaborn3 min read
    • StatsModel2 min read
    • Model Building6 min read
    • TensorFlow2 min read
    • PyTorch5 min read
    Web Development with Python
    • Flask3 min read
    • Django5 min read
    • Django ORM4 min read
    • Jinja2 Templating5 min read
    • Django Templates5 min read
    • REST API3 min read
    • Build API with DRF4 min read
    Python Practice
    • Quiz1 min read
    • Practice Problems2 min read
    • Interview Q & A15+ min read
    Courses
    • Placement 360 Course2 min read
    • Data Science 360 Course2 min read
    • AI Engg Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.