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

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