What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python Docstring: How to Write Docstrings? (with Examples)

  • Jun 06, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Kusum Jain
Python Docstring: How to Write Docstrings? (with Examples)

Python is called a powerful programming language known for its simplicity. While writing clean code makes good software, documenting it is equally important for maintenance. One such indispensable tool is docstring in Python. So, let's learn how to use docstrings!

What is a Docstring in Python?

Docstrings are used to explain a module, function, class, or method's objectives in Python. Additionally, they can be used to include details like the author's name, the time the code was written, and any other pertinent data.

Basically, it is a string literal that appears as the first statement in a module, function, class, or method definition. It serves as a form of documentation and provides information about the purpose, usage, and behavior of the code.

Docstrings are enclosed in triple quotes (""" or ''') and can span multiple lines. They can be accessed at runtime using the __doc__ attribute of the object they are attached to. 

Here is an illustration of a Python docstring:

def add(a, b):

"""

This function adds two numbers.

Args:

a (int): The first number.

b (int): The second number.

Returns:

int: The sum of the two numbers.

"""

return a + b

 

In the aforementioned illustration, the docstring gives a succinct explanation of the function's purpose, the parameters it accepts, and the results it produces. Docstrings are frequently used to offer more thorough documentation, such as instructions on how to use a method or a list of potential exceptions.

Docstring Python Example

Here are a few instances of how to use Python's docstrings:

Example 1: Docstring function

def multiply(a, b):

"""

This function multiplies two numbers.

Args:

a (int): The first number.

b (int): The second number.

Returns:

int: The product of the two numbers.

"""

return a * b

 

Example 2: Class Docstring

class Person:

"""

This class represents a person.

Attributes:

name (str): The person's name.

age (int): The person's age.

"""

def __init__(self, name, age):

self.name = name

self.age = age

 

How to Write Docstrings in Python?

Triple quotes are used for writing docstrings in Python. A concise explanation of what the code does should be on the first line, followed by a blank line. More thorough documentation should be provided in the remaining docstring.

Python supports both single-line and multi-line docstrings. Simple functions and methods are documented using single-line docstrings, whereas more sophisticated functions and classes are documented using multi-line docstrings.

Single-line Docstrings: For straightforward functions and procedures, single-line docstrings are employed. When the docstring can fit on a single line, it should be utilized.

An example of a single-line docstring is shown below:

def add(a, b):

"""This function adds two numbers."""

return a + b

 

Multi-line docstrings: These are used for more intricate classes and functions. When the docstring is too long to fit on a single line, it ought to be utilized. A one-line overview is followed by several additional lines of more in-depth description in multi-line docstrings. A blank line should be placed between the summary and the comprehensive description.

An example of a multi-line docstring is shown here:

class Rectangle:

"""

This class represents a rectangle.

Attributes:

width (int): The width of the rectangle.

height (int): The height of the rectangle.

"""

def __init__(self, width, height):

self.width = width

self.height = height

 

In the aforementioned illustration, the docstring gives a succinct explanation of what the class does before going into great depth on its characteristics.

Formatting Docstring

Python has a number of formatting conventions for docstrings. The Google-style docstring convention is the most often used one. A one-line overview is followed by a longer description in Google-style docstrings. Utilizing reStructuredText (reST), the comprehensive description has been formatted.

Here is an example of a docstring in the Google style:

def add(a, b):

"""

This function adds two numbers.

Args:

a (int): The first number.

b (int): The second number.

Returns:

int: The sum of the two numbers.

"""

return a + b

 

In the aforementioned illustration, the docstring starts with a one-line overview before going into greater detail about the function's arguments and return value. The Args: and Returns: keywords are used to describe the arguments and return value, respectively.

What is the Format of Docstring?

A docstring has a straightforward format: it is a string surrounded by triple quotes that appear as the first statement of a function, method, or module. Here is an illustration of a Python function's documentation string:

def calculate_sum(a, b):

"""

This function calculates the sum of two numbers.

Parameters:

a (int): The first number.

b (int): The second number.

Returns:

int: The sum of a and b.

"""

return a + b

 

The function's purpose is briefly described in the first line of the docstring. The parameters are listed after a blank line following the first line. A brief description and the data type for each parameter are provided. Another blank line follows the parameters, and then the return value is explained.

It's crucial to remember that Python does not impose rules on the format of docstrings. To make their code consistent and simple to read, developers must adhere to certain rules.

An alternative is Documented Comments

Python now provides documented comments in addition to docstrings. Regular comments and documented comments are similar, but documented comments have special formatting that makes them simpler to read and understand. Use the pound sign (#), a space, and then a colon (:) to create a documented comment. Here's an illustration:

# TODO: Add error handling

Other developers are informed by this comment that a job needs to be finished in the future. Regular comments are distinguished from recorded remarks by the colon at the end of each one.

In the aforementioned illustration, the docstring describes the function's purpose as well as the input and output parameters. Additionally, it formats the docstring using the preferred syntax for Python docstrings, reStructuredText.

Features of Docstring

The following characteristics of Python's docstrings make them an effective tool for code documentation:

  1. The creation of documentation automatically: The ability to automatically generate documentation is one of the most important benefits of using docstrings. You can save a lot of time that would otherwise be spent on writing documentation by using docstrings.
  2. Reliable and understandable documentation: Your code will be consistent and simple to read if you adhere to the docstring rules. Collaboration is facilitated through consistent documentation, which makes it simpler for other developers to comprehend your code.
  3. Higher-Quality Code: You are compelled to consider your code's functionality and workings more carefully when you use docstrings to document it. This can assist you in spotting potential bugs or problems before they arise.

Conclusion

Whether you are a beginner or an experienced coder, using docstrings in Python will undoubtedly enhance your programming skills. This way, you can produce good code with future-proofing to make it more better. Even while making Python Projects, you much try them to test them out.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.