What Is A Docstring In Python?

What Is A Docstring In Python?

Published on October 07 2023

In this tutorial, we will learn what docstring in Python is and how to use it. This tutorial is part of Python's top 25 most commonly asked interview questions.

Definition

  • Documentation string or docstring is a multiline string used to document a specific code segment.
  • Python lets users include a description for their methods using docstrings that occur as the first statement in a module, function, class, or method definition.
  • These docstrings are within triple quotes.
  • The docstring should describe what the function or method does.
  • __doc__ or help() can be used to access document strings.
  • They are not assigned to any variable and therefore, at times, serve the purpose of comments as well (Docstrings are not actually comments).

Example

  • One line docstrings
def hello():
 """ A function to print message. """
 return "hello"

print(hello.__doc__)

Output

A function to print message.
  • Multi-line docstrings
""" 
    Using docstring as a comment.
"""

To know about it, please refer to the official documentation website - official website.