Explain docstring in Python?

The Python docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. It provides a convenient way to associate the documentation.

String literals occurring immediately after a simple assignment at the top are called “attribute docstrings”.

String literals occurring immediately after another docstring are called “additional docstrings”.

Python uses triple quotes to create docstrings even though the string fits on one line.

Docstring phrase ends with a period (.) and can be multiple lines. It may consist of spaces and other special chars.

Example:

  1. # One-line docstrings  
  2. def hello():  
  3.     “””A function to greet.”””  
  4.     return “hello”