different ways to write docstrings in python

In Python, there are two popular ways to write docstrings:

  1. One-line docstrings: These docstrings are short and fit on a single line. They are enclosed within triple quotes and start and end with a single " or '.
main.py
def square(num):
    """Return the square of a number."""
    return num*num
77 chars
4 lines
  1. Multi-line docstrings: These docstrings span multiple lines and are usually used to provide detailed information about the module, class, or function. They start and end with triple quotes on separate lines and can encompass multiple paragraphs of text.
main.py
def greet(name):
    """
    This function greets the person passed in as a parameter.
    It prints a greeting and returns None.
  
    Parameters:
    name (str): The name of the person to greet.
    """
    print("Hello, " + name + ". How are you?")
253 chars
10 lines

Both types of docstrings are used to document Python code so that it is easier for others (or your future self!) to read and understand. As a best practice, it is recommended to include docstrings for every module, class, and function you write in Python.

related categories

gistlibby LogSnag