Python Docstrings

In this tutorial, we are going to learn about “Python Docstrings” with some easy and cool examples.

Before going in-depth into this topic first let us see what actually a Docstring in Python mean:

Docstrings in Python:

In Python Documentation String usually called Docstring are the String Literals.

These are used for Documentation in Python that may be declared in class, function, methods, etc.

Docstring Declaration:

1. The docstring line must begin with a capital letter and end with a “.”

2. The first line in a Docstring must be a short description.

3. If there are more lines usually, we leave the second line blank, to separate the summary from other lines.

4. The next lines should be one or more paragraphs describing the target to be achieved by a function etc.

NOTE:

We usually use 3 double quotes (“”” ) or 3 single quotes (”’) to declare a Docstring.

Types of Docstrings in Python:

There are 2 types namely:

  • Single line Docstring.
  • Multi-line Docstring.

Single line Docstring:

These are usually completed in a single line i.e the starting and ending of the Docstring is in the same line.

Example:

#Single line Docstrings in Python
def fun(a):
    '''Returns the number entered by the user.'''
    return a

print (fun.__doc__)

Output:

Returns the number entered by the user.

Multi-line Docstrings:

These contain multiple lines i.e the starting and ending of the Docstring is in the different line.

Example:

def fun(a):
    """Describing the function

    Parameters:
    it accepts one parameter from the user.

    Returns:
    it returns an integer passed to the function.

   """

    return a
print(fun.__doc__)

Output:

Describing the function

Parameters: it accepts one parameter from the user.

Returns: it returns an integer passed to the function.

Docstring Formats:

The following are the popular Docstring formats in Python:

  • Sphinx Style.
  • Google Style.
  • Numpy Style.

Finally, I hope that this tutorial helped you in understanding the topic “Python Docstrings”.

You can also read:
Merge two files into one in Python

setdefault() method in Python

Class and Instance Attributes in Python

Leave a Reply

Your email address will not be published. Required fields are marked *