Docstrings
tags: #python/documentation/python_functions
What is a docstring?
A docstring, short for "documentation string," is a string literal that occurs as the first statement in a module, function, class, or method definition in Python.
Purpose of a docstring
Its purpose is to provide documentation about the purpose and usage of the code it describes. In the context of function definitions, a docstring is placed immediately after the function signature and is enclosed in triple quotes (single or double).
Comments are short notes that are added to the code to improve readability and clarify specific lines of code or sections, whereas docstrings are to provide documentation about the usage of the function, module, class, and methods.
General Syntax
# example docstring for a user-defined function greet()
def greet(name):
"""
This function takes a name as an argument and
prints a greeting message.
"""
print(f"Hello, {name}!")
Accessing docstrings
We can access the docstring by using the __doc__ attribute of the function:
# Method 1
print(function.__doc__)
# Method 2
function.__doc__
__docs__ Attribute
Whenever string literals are present just after the definition of a function, module, class or method, they are associated with the object as their __doc__ attribute.