0
0
PythonHow-ToBeginner · 3 min read

How to Write Docstring in Python: Syntax and Examples

In Python, a docstring is a string literal placed right after the definition of a function, class, or module to describe its purpose. You write it using triple quotes """Your description""" immediately below the definition line.
📐

Syntax

A Python docstring is written as a string literal enclosed in triple quotes """...""" placed immediately after the function, class, or module header. It can span multiple lines and describes what the code does.

  • Triple quotes: Allow multi-line text.
  • Placement: Directly below the definition line.
  • Purpose: Explain the behavior, parameters, and return values.
python
def function_name(parameters):
    """Describe what the function does, its parameters, and return value."""
    # function body
💻

Example

This example shows a function with a docstring explaining its purpose, parameters, and return value. It helps others understand the function without reading the code.

python
def greet(name):
    """Return a greeting message for the given name.

    Args:
        name (str): The name of the person to greet.

    Returns:
        str: A greeting message.
    """
    return f"Hello, {name}!"

print(greet("Alice"))
Output
Hello, Alice!
⚠️

Common Pitfalls

Common mistakes when writing docstrings include:

  • Not placing the docstring immediately after the definition line.
  • Using single or double quotes instead of triple quotes, which limits multi-line descriptions.
  • Leaving docstrings empty or too vague, which reduces their usefulness.
  • Not following a consistent style for parameters and return descriptions.
python
def add(a, b):
    # Wrong: no docstring or misplaced string
    pass

def add_correct(a, b):
    """Add two numbers and return the result."""
    return a + b
📊

Quick Reference

Tips for writing good Python docstrings:

  • Use triple double quotes """ even for one-liners.
  • Start with a short summary line.
  • Optionally add details, parameters, and return info.
  • Keep it clear and concise.
  • Follow PEP 257 style for consistency.

Key Takeaways

Write docstrings immediately after the function, class, or module definition line using triple quotes.
Include a clear description of what the code does, its parameters, and return values.
Use multi-line docstrings for detailed explanations and follow consistent style.
Avoid missing or vague docstrings to keep your code understandable.
Follow PEP 257 guidelines for standard docstring formatting.