Skip to main content

How to Use Comments and Docstrings in Python for Better Code

How to Use Comments and Docstrings in Python for Better Code | Rustcode

How to Use Comments and Docstrings in Python for Better Code

Writing clear, well-documented code is essential for maintainability and collaboration in Python projects. Python provides two main tools for documentation: comments and docstrings. In this article, you'll learn how to use both effectively, see their syntax and differences, and follow best practices with code examples, outputs, and explanations.


What are Comments and Docstrings?

  • Comments: Notes in your code that are ignored by Python and meant for human readers. Used to explain logic, mark TODOs, or clarify complex code.
  • Docstrings: Special string literals that serve as documentation for modules, functions, classes, or methods. They can be accessed programmatically and are used by tools like help() and documentation generators.
  • Benefits: Both improve code readability, maintainability, and help others (and your future self) understand your code quickly.

01. Single-Line Comments

Single-line comments start with the # symbol and continue to the end of the line.

# This is a single-line comment
x = 42  # You can also add comments at the end of a line
Explanation:
  • Single-line comments are ideal for short explanations or quick notes.
  • They are completely ignored by the Python interpreter.
  • Use them to clarify non-obvious code or mark sections for review.

02. Multi-Line Comments

Python does not have a dedicated multi-line comment syntax, but you can use consecutive # symbols or unassigned string literals (triple quotes) as multi-line comments.

# This is a multi-line comment
# explaining something important
# over several lines

"""
This is also a multi-line comment
using triple double quotes.
It is not assigned to any variable,
so it is ignored by Python.
"""
Explanation:
  • Multiple # lines are the most common way for multi-line comments.
  • Unassigned triple-quoted strings are ignored by the interpreter and can act as block comments.
  • Triple quotes are also used for docstrings (see below), so use them carefully.

03. What are Docstrings?

Docstrings (documentation strings) are special string literals placed as the first statement inside a module, function, class, or method. They describe what the object does, not how it does it.
They are enclosed in triple quotes (''' or """).

def greet(name):
    """Return a greeting for the given name."""
    return f"Hello, {name}!"
Explanation:
  • Docstrings should summarize the purpose of the function, class, or module.
  • They are accessible via the __doc__ attribute and help() function.
  • Follow PEP 257: Start with a capital letter, end with a period, and keep the first line short.

04. One-Line Docstrings

Use a single line for simple functions, classes, or modules.

def square(x):
    """Return the square of x."""
    return x * x
Explanation:
  • One-line docstrings are concise and placed immediately after the definition line.
  • Keep them brief and descriptive.

05. Multi-Line Docstrings

For more complex objects, use a summary line, a blank line, and a more detailed description.

def divide(a, b):
    """
    Divide a by b and return the result.

    Parameters:
        a (float): Numerator.
        b (float): Denominator.

    Returns:
        float: The result of division.

    Raises:
        ZeroDivisionError: If b is zero.
    """
    return a / b
Explanation:
  • First line is a summary, followed by a blank line and further details.
  • Describe parameters, return values, and exceptions if needed.
  • Multi-line docstrings are recommended for public APIs and complex code.

06. Accessing Docstrings

You can access a docstring using the __doc__ attribute or the help() function.

print(greet.__doc__)
help(divide)

Output (example):

Return a greeting for the given name.

Help on function divide in module __main__:

divide(a, b)
    Divide a by b and return the result.

    Parameters:
        a (float): Numerator.
        b (float): Denominator.

    Returns:
        float: The result of division.

    Raises:
        ZeroDivisionError: If b is zero.
Explanation:
  • __doc__ returns the docstring as a string.
  • help() displays the docstring in a formatted way in the terminal or console.
  • Comments are not accessible this way; only docstrings are.

07. Comments vs Docstrings

  • Comments: For explaining code logic, usage, or marking TODOs. Not accessible at runtime.
  • Docstrings: For documenting the purpose, usage, and details of modules, functions, classes, or methods. Accessible at runtime and used by documentation tools.
  • Use comments for implementation details, and docstrings for documentation and API usage.

08. Comparison Table: Comments vs Docstrings in Python

Feature Comments Docstrings
Syntax # for single-line, triple quotes for multi-line (unassigned) Triple quotes (single or double) as first statement in object
Purpose Explain code logic, mark notes/TODOs Document modules, functions, classes, methods
Access at Runtime No Yes (__doc__, help())
Used by Tools No Yes (documentation generators, IDEs)
Best Practice Explain why, not what; keep concise Summarize purpose, parameters, returns, exceptions

Conclusion

Effective use of comments and docstrings is crucial for writing professional, maintainable Python code. Use comments to clarify logic and mark important notes, and use docstrings to document your modules, classes, and functions for users and tools. Following these best practices will make your code easier to understand, maintain, and use.

Tip: Write comments for developers, and docstrings for users and documentation tools. Keep both clear, concise, and up to date!

Comments