Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KeyurRamoliya/f3d8df8c728f0a786c3fafe19004109d to your computer and use it in GitHub Desktop.
Save KeyurRamoliya/f3d8df8c728f0a786c3fafe19004109d to your computer and use it in GitHub Desktop.
Document Your Code with Docstrings in Python

Document Your Code with Docstrings in Python

Documentation is essential for understanding and maintaining code, and Python provides a straightforward way to add documentation to your functions, classes, and modules using docstrings. A docstring is a string literal that occurs as the first statement in a module, function, class, or method. It serves as documentation for that object.

Docstrings provide several benefits:

  • Documentation: They explain what a function, class, or module does, what arguments it accepts, and what it returns. This helps you and others understand and use your code correctly.
  • Auto-generating documentation: Many documentation tools and systems can extract docstrings to generate documentation in various formats, such as HTML or PDF.
  • IDE support: Integrated development environments (IDEs) can display docstring information when you hover over or inspect functions or classes, making it easier to work with your code.
  • Clarity: Well-documented code is more accessible and maintainable, especially when collaborating with others or revisiting your own code after some time.

When writing docstrings:

  • Use triple double-quotes (""") for docstrings. This allows for multiline descriptions.
  • Follow a consistent format, such as the one shown in the example below, which includes a brief description, parameter descriptions (Args), and a return value description (Returns).
  • Be concise and clear in your descriptions.
def add(a, b):
    """
    This function takes two numbers, 'a' and 'b', and returns their sum.
    
    Args:
        a (int): The first number.
        b (int): The second number.
    
    Returns:
        int: The sum of 'a' and 'b'.
    """
    return a + b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment