What are Python Docstrings?

Home » Python » What are Python Docstrings?

Table of Contents

Python Docstrings

Introduction to Python Docstrings

Python Docstrings are special strings that we use to explain the purpose of a code. It can be a method, a module, a class, a function or code.

By using docstrings, we can explain how the specific code does, how it works and how to use it.

Docstrings are a critical part of Python code, as they help developers understand the purpose and functionality of the code. Especially when working in team on large codebases.

Key Features of Python Docstrings:

  • Definition:
    • Docstrings is a string that will appear at the beginning of a module, a class, a method or a function.
    • We enclose it in multiple quotes(“”” “””, ”’ ”’) which allows it to span to multiple lines.
  • Purpose:
    • Docstrings serve as documentation for your code. They explain the functionality, inputs, outputs, and any other relevant information about the code.
    • They help both the developer and users of the code understand what a particular function, class, or module does without needing to examine the code itself.
  • Accessing Docstrings:
    • We can access the Docstrings with the help of built in function help() or the .__doc__ attribute.

Conventions for writing docstrings (PEP 257)

PEP 257 is the Python Enhancement Proposal that provides conventions for writing docstrings. It suggests the structure and style of docstrings, including:

  • The first line should be a brief description of the object’s purpose.
  • If the docstring is more than one line, the second line should be empty, followed by a more detailed explanation.
  • Parameters and return values should be documented if applicable.

Syntax of Docstring


def function_name(parameters):
    """
    Brief description of the function's purpose.
    
    Detailed description of what the function does.
    
    Arguments:
    param1 -- description of parameter 1
    param2 -- description of parameter 2
    
    Returns:
    Return value description.
    """
    # Function implementation here

Examples:

1. Function Docstring: It is used for simple function.


def add(a, b):
    """
    Adds two numbers and returns the result.
    
    Arguments:
    a -- The first number (int or float)
    b -- The second number (int or float)
    
    Returns:
    The sum of a and b (int or float)
    """
    return a + b

2. Class Docstring: It is used for class.


class Person:
    """
    A class that represents a person.
    
    Attributes:
    name -- Name of the person (string)
    age -- Age of the person (int)
    
    Methods:
    greet() -- Prints a greeting message.
    """
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        """Prints a greeting message."""
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

3. Module Docstring: It is used for a module.


class Person:
    """
    A class that represents a person.
    
    Attributes:
    name -- Name of the person (string)
    age -- Age of the person (int)
    
    Methods:
    greet() -- Prints a greeting message.
    """
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        """Prints a greeting message."""
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

Accessing Docstrings

You can access the docstring of any Python object (function, class, method, etc.) using the .__doc__ attribute or the help() function.


# This will output the docstring for the add() function

print(add.__doc__)

Alternatively, you can use the help() function:


# This will output the docstring for the add() function

help(add)

This will display the docstring in a more user-friendly format, along with other relevant information.

Best Practices for Writing Docstrings:

  1. Be Concise but Descriptive: Provide a clear and concise description of what the function, class, or module does, and include details only as necessary.
  2. Use Consistent Formatting: Follow the conventions defined by PEP 257. Keep the docstring consistent and structured, especially when documenting parameters, return types, and exceptions.
  3. Document Parameters and Return Types: For functions and methods, clearly describe the parameters and the return value. Specify the types of inputs and outputs.
  4. Use Triple Quotes for Multiline Docstrings: Always use triple double-quoted (""") or triple single-quoted (''') strings for docstrings, even if they are a single line.
  5. Explain Complex Logic: If your code involves complex logic, explain it in the docstring to help others understand how it works.

Conclusion of Python Docstrings

Docstrings are an essential part of Python programming, providing clear and structured documentation for functions, classes, methods, and modules.

They improve code readability, help developers understand the purpose of a function or class, and make it easier to use and maintain the code in the future.

Using docstrings consistently in your codebase is a good practice that enhances collaboration and makes your code more user-friendly.


Posted

in

by

Comments

Leave a Reply

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