Open In App

Python Docstrings

Last Updated : 02 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When it comes to writing clean, well-documented code, Python developers have a secret weapon at their disposal – docstrings. Docstrings, short for documentation strings, are vital in conveying the purpose and functionality of Python functions, modules, and classes.

What are the docstrings in Python?

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. It’s specified in source code that is used, like a comment, to document a specific segment of code. Unlike conventional source code comments, the docstring should describe what the function does, not how.

  • Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “”” triple double quotes “”” just below the class, method, or function declaration. All functions should have a docstring.
  • Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function. The below examples demonstrate how to declare and access a docstring.

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.

Docstrings in Python

Below are the topics that we will cover in this article:

  • Triple-Quoted Strings
  • Google Style Docstrings
  • Numpydoc Style Docstrings
  • One-line Docstrings
  • Multi-line Docstrings
  • Indentation in Docstrings
  • Docstrings in Classes
  • Difference between Python comments and docstrings

Triple-Quoted Strings

This is the most common docstring format in Python. It involves using triple quotes (either single or double) to enclose the documentation text. Triple-quoted strings can span multiple lines and are often placed immediately below the function, class, or module definition

Example 1: Using triple single quotes

Python
def my_function():
    '''Demonstrates triple double quotes
    docstrings and does nothing really.'''
 
    return None

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

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

Output:

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

Example 2: Using triple-double quotes

Python
def my_function():
    ' ' 'Demonstrates triple double quotes docstrings and does nothing really' ' '
 
    return None

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

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

Output:

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

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.

Python
def multiply_numbers(a, b):
    """
    Multiplies two numbers and returns the result.

    Args:
        a (int): The first number.
        b (int): The second number.

    Returns:
        int: The product of a and b.
    """
    return a * b
print(multiply_numbers(3,5))

Output
15

Numpydoc Style Docstrings

Numpydoc-style docstrings are widely used in the scientific and data analysis community, 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.

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

    Parameters
    ----------
    a : float
        The dividend.
    b : float
        The divisor.

    Returns
    -------
    float
        The quotient of the division.
    """
    if b == 0:
        raise ValueError("Division by zero is not allowed.")
    return a / b
print(divide_numbers(3,6))

Output
0.5

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 the same line as the opening quotes. This looks better for one-liners. For example:

Python
def power(a, b):
    ' ' 'Returns arg1 raised to power arg2.' ' '
 
    return a**b

print(power.__doc__)

Output:

Returns arg1 raised to power arg2.

Multi-line Docstrings

Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. The summary line may be on the same line as the opening quotes or on the next line. The example below shows a multi-line docstring.

Python
def add_numbers(a, b):
    """
    This function takes two numbers as input and returns their sum.

    Parameters:
    a (int): The first number.
    b (int): The second number.

    Returns:
    int: The sum of a and b.
    """
    return a + b
print(add_numbers(3, 5))

Output:

8

Indentation in Docstrings

The entire docstring is indented the same as the quotes in its first line. Docstring processing tools will strip a uniform amount of indentation from the second and further lines of the docstring, equal to the minimum indentation of all non-blank lines after the first line. Any indentation in the first line of the docstring (i.e., up to the first new line) is insignificant and removed. Relative indentation of later lines in the docstring is retained.

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

    Attributes:
        name (str): The name of the employee.
        age (int): The age of the employee.
        department (str): The department the employee works in.
        salary (float): The salary of the employee.
    """

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

        Parameters:
            name (str): The name of the employee.
            age (int): The age of the employee.
            department (str): The department the employee works in.
            salary (float): The salary of the employee.
        """
        self.name = name
        self.age = age
        self.department = department
        self.salary = salary

    def promote(self, raise_amount):
        """
        Promotes the employee and increases their salary.

        Parameters:
            raise_amount (float): The raise amount to increase the salary.

        Returns:
            str: A message indicating the promotion and new salary.
        """
        self.salary += raise_amount
        return f"{self.name} has been promoted! New salary: ${self.salary:.2f}"

    def retire(self):
        """
        Marks the employee as retired.

        Returns:
            str: A message indicating the retirement status.
        """
        # Some implementation for retiring an employee
        return f"{self.name} has retired. Thank you for your service!"

# Access the Class docstring using help()
help(Employee)

Output:

class Employee
| A class representing an employee.
|
| Attributes:
| name (str): The name of the employee.
| age (int): The age of the employee.
| department (str): The department the employee works in.
| salary (float): The salary of the employee.
|
| Methods defined here:
|
| __init__(self, name, age, department, salary)
| Initializes an Employee object.
|
| Parameters:
| name (str): The name of the employee.
| age (int): The age of the employee.
| department (str): The department the employee works in.
| salary (float): The salary of the employee.
|
| promote(self, raise_amount)
| Promotes the employee and increases their salary.
|
| Parameters:
| raise_amount (float): The raise amount to increase the salary.
|
| Returns:
| str: A message indicating the promotion and new salary.
|
| retire(self)
| Marks the employee as retired.
|
| Returns:
| str: A message indicating the retirement status.

Docstrings in Classes

Let us take an example to show how to write docstrings for a class and the method ‘help’ is used to access the docstring.

Python
class ComplexNumber:
    """
    This is a class for mathematical operations on complex numbers.

    Attributes:
        real (int): The real part of the complex number.
        imag (int): The imaginary part of the complex number.
    """

    def __init__(self, real, imag):
        """
        The constructor for ComplexNumber class.

        Parameters:
            real (int): The real part of the complex number.
            imag (int): The imaginary part of the complex number.
        """
        self.real = real
        self.imag = imag

    def add(self, num):
        """
        The function to add two Complex Numbers.

        Parameters:
            num (ComplexNumber): 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)

# Access the Class docstring using help()
help(ComplexNumber)

# Access the method docstring using help()
help(ComplexNumber.add)

Output:

Help on class ComplexNumber in module __main__:
class ComplexNumber(builtins.objects)
| This is a class for mathematical operations on complex numbers.
|
| Attributes:
| real (int): The real part of complex number.
| imag (int): The imaginary part of complex number.
|
| Methods defined here:
|
| __init__(self, real, imag)
| The constructor for ComplexNumber class.
|
| Parameters:
| real (int): The real part of complex number.
| imag (int): The imaginary part of complex number.
|
| add(self, num)
| The function to add two Complex Numbers.
|
| Parameters:
| num (ComplexNumber): The complex number to be added.
|
| Returns:
| ComplexNumber: A complex number which contains the sum.
Help on method add in module __main__:
add(self, num) unbound __main__.ComplexNumber method
The function to add two Complex Numbers.

Parameters:
num (ComplexNumber): The complex number to be added.

Returns:
ComplexNumber: A complex number which contains the sum.

Difference between Python comments, String, and Docstrings

String: In Python, a string is a sequence of characters enclosed within single quotes (‘ ‘) or double quotes (” “). Strings are used to represent text data and can contain letters, numbers, symbols, and whitespace. They are one of the fundamental data types in Python and can be manipulated using various string methods.

You all must have got an idea about Python docstrings but have you ever wondered what is the difference between Python comments and docstrings? Let’s have a look at them.

They are useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. It is written using

#

symbols.

Example:

Python
# Python program to demonstrate comments
print("GFG")

name = "Abhishek Shakya" #demostrate String

Output:

GFG


Whereas Python Docstrings as mentioned above provides a convenient way of associating documentation with Python modules, functions, classes, and methods.

Python Docstrings – FAQs

What are docstrings in Python?

Docstrings in Python are string literals that appear right after the definition of a function, method, class, or module. They are used to document what the object does. Enclosed in triple quotes, docstrings can be one line or multiline and are accessible via the .__doc__ attribute of the object.

def add(a, b):
"""Add two numbers and return the result."""
return a + b

print(add.__doc__) # Output: Add two numbers and return the result.

What is the difference between comments and docstrings in Python?

  • Comments: Comments in Python start with a hash mark (#) and are intended to explain the code to developers. They are ignored by the Python interpreter.
  • Docstrings: Docstrings provide a description of the function, method, class, or module. Unlike comments, they are not ignored by the interpreter and can be accessed at runtime using the .__doc__ attribute.

What is the best format for docstrings in Python?

The best format for docstrings depends on the project and any related style guidelines. However, commonly accepted formats are outlined by PEP 257, which recommends a concise summary line followed by a more detailed description. The Google and NumPy/SciPy formats are also widely used, particularly in projects involving scientific computing.

def add(a, b):
"""
Add two numbers and return the result.

Args:
a (int): The first number.
b (int): The second number.

Returns:
int: The sum of the two numbers.
"""
return a + b

What is the difference between docstring and multiline string?

  • Docstring: A docstring is a string literal that describes a module, function, class, or method. It is accessible via the .__doc__ attribute.
  • Multiline String: A multiline string can be used for any purpose where a string spanning multiple lines is needed, including as data, in file I/O operations, or just within the code for complex string constructions. It is not used for documentation accessible via the .__doc__ attribute.

Should Python classes have docstrings?

Yes, Python classes should have docstrings. Including a docstring in a Python class improves code readability and provides a convenient place to document the class’s purpose, constructor, attributes, and methods. This is especially helpful for larger projects or for API documentation generation tools such as Sphinx.

Docstrings like these are crucial for maintaining clear and comprehensible code, especially as projects grow and evolve.



Previous Article
Next Article

Similar Reads

Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
Context Managers are the tools for wrapping around arbitrary (free-form) blocks of code. One of the primary reasons to use a context manager is resource cleanliness. Context Manager ensures that the process performs steadily upon entering and on exit, it releases the resource. Even when the wrapped code raises an exception, the context manager guar
7 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Debugger – Python pdb
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to the Python standard library. It is actually defined as the class Pdb which internally makes use of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters) modules. The major advantage of pdb is it runs purely in the command line
5 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and going for walks in Python packages. While there are ma
3 min read
GeeksforGeeks Python Foundation Course - Learn Python in Hindi!
Python - it is not just an ordinary programming language but the doorway or basic prerequisite for getting into numerous tech domains including web development, machine learning, data science, and several others. Though there's no doubt that the alternatives of Python in each of these respective areas are available - but the dominance and popularit
5 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
What is Python Used For? | 7 Practical Python Applications
Python is an interpreted and object-oriented programming language commonly used for web development, data analysis, artificial intelligence, and more. It features a clean, beginner-friendly, and readable syntax. Due to its ecosystem of libraries, frameworks, and large community support, it has become a top preferred choice for developers in the ind
9 min read
How to Install python-dotenv in Python
Python-dotenv is a Python package that is used to manage & store environment variables. It reads key-value pairs from the “.env” file. How to install python-dotenv?To install python-dotenv using PIP, open your command prompt or terminal and type in this command. pip install python-dotenvVerifying the installationTo verify if you have successful
3 min read
Future of Python : Exploring Python 4.0
The future of Python 4.0 is a topic of great anticipation and speculation within the tech community. Guido van Rossum, the creator of Python, offers exclusive insights into what might lie ahead for this popular programming language. With Python 3.9 approaching its release, many are curious about t the potential for Python 4.0. This article explores
8 min read
Top 10 Python Built-In Decorators That Optimize Python Code Significantly
Python is a widely used high-level, general-purpose programming language. The language offers many benefits to developers, making it a popular choice for a wide range of applications including web development, backend development, machine learning applications, and all cutting-edge software technology, and is preferred for both beginners as well as
12 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python , two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but no
5 min read
Sort Python Dictionary by Key or Value - Python
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Sorting Dictionary By Key Using sort()In this example, we will sort the dictionary by keys and the result type will be a dictionary. [
6 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
str() vs repr() in Python
In Python, the str() and repr() functions are used to obtain string representations of objects. While they may seem similar at first glance, there are some differences in how they behave. Both of the functions can be helpful in debugging or printing useful information about the object. Python str() In the given example, we are using the str() funct
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg