Python __doc__
The __doc__
is a special attribute in Python that allows you to access the documentation string (docstring) of a function, module, class, or method.
The docstring is a string that provides information about the object it belongs to. It typically contains a brief description of what the object does, explains its parameters and return values, and provides any additional information that is important for understanding and using the object.
For example, consider the following function with a docstring:
def square(x):
"""
This function returns the square of a given number.
Parameters:
x (int or float): The number to be squared.
Returns:
int or float: The square of the given number.
"""
return x ** 2
To access the docstring of the square
function, you can use the __doc__
attribute like this:
print(square.__doc__)
This will output:
This function returns the square of a given number.
Parameters:
x (int or float): The number to be squared.
Returns:
int or float: The square of the given number.
You can use the __doc__
attribute to retrieve the docstring of any Python object, not just functions. It is a useful feature for providing self-documentation within your code and for generating automatic documentation using tools like Sphinx.