Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python Docstrings Tutorial – Write Better Documentation for Functions and Classes

Python Docstrings 

When writing Python programs, code readability is very important. One of the best ways to improve readability is by using docstrings.

Docstrings are used to describe:

  • Functions
  • Classes
  • Modules
  • Methods

They help developers understand what the code does without reading every line.


What is a Docstring?

A docstring is a special string used to document Python code.

It is written using triple quotes:

"""This is a docstring"""

It is placed immediately after:

  • Function definition
  • Class definition
  • Module header

Why Use Docstrings?

Docstrings help to:

  • Explain code functionality
  • Improve readability
  • Support team collaboration
  • Generate documentation automatically
  • Make code easier to maintain

1. Function Docstrings

Example

def add(a, b):
    """Return the sum of two numbers."""
    return a + b

Accessing Docstring

print(add.__doc__)

Output

Return the sum of two numbers.

2. Multi-line Docstrings

def multiply(a, b):
    """
    Multiply two numbers.

    Parameters:
    a (int): First number
    b (int): Second number

    Returns:
    int: Product of a and b
    """
    return a * b

3. Class Docstrings

class Person:
    """
    Represents a person with name and age.
    """

    def __init__(self, name, age):
        self.name = name
        self.age = age

Access Class Docstring

print(Person.__doc__)

4. Module Docstrings

At the top of a Python file:

"""
This module provides basic arithmetic operations.
"""

5. Method Docstrings

class Calculator:
    def add(self, a, b):
        """Return sum of two numbers."""
        return a + b

6. Difference Between Comments and Docstrings

FeatureCommentsDocstrings
Purpose   Explain code logic     Document code
Syntax   # comment     """docstring"""
Accessible   No     Yes
Used by tools   No    Yes

7. Built-in help() Function

Python can display docstrings using help().

def greet():
    """Print greeting message."""
    print("Hello")

help(greet)

Output

Help on function greet:

greet()
    Print greeting message.

8. Google Style Docstrings

def divide(a, b):
    """
    Divide two numbers.

    Args:
        a (int): numerator
        b (int): denominator

    Returns:
        float: result of division
    """
    return a / b

9. NumPy Style Docstrings

def square(x):
    """
    Square a number.

    Parameters
    ----------
    x : int
        Input number

    Returns
    -------
    int
        Squared result
    """
    return x * x

10. Best Practices

  • Always document public functions
  • Keep docstrings concise
  • Use triple double quotes
  • Follow a consistent style
  • Update docstrings when code changes

11. Common Mistakes

Missing Docstrings

def test():
    return 1

Fix:

Add documentation.


Writing unclear docstrings

Bad:

"""do stuff"""

Good:

"""Return user age from database."""

12. Real-World Applications

Docstrings are used in:

  • API development
  • Open-source projects
  • Team collaboration
  • Automated documentation tools (Sphinx)
  • Code maintenance

Summary

Python docstrings are an essential part of writing clean and maintainable code. They help document functions, classes, and modules in a structured way that can be accessed programmatically.


Conclusion

Docstrings improve code quality by making Python programs easier to understand and maintain. By following good documentation practices, developers can build professional and scalable applications.




Post a Comment

0 Comments