How to Use 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""", and it can be accessed via the .__doc__ attribute.Syntax
A docstring is a string literal that appears right after the def line of a function, class, or module. It is enclosed in triple quotes """...""" or '''...'''. This string explains what the function/class/module does.
- Placement: Immediately after the definition line.
- Quotes: Use triple double or single quotes.
- Access: Use
.__doc__to read it.
python
def function_name(parameters): """This is the docstring describing the function.""" # function body pass
Example
This example shows a function with a docstring and how to access it using the .__doc__ attribute.
python
def greet(name): """Return a greeting message for the given name.""" return f"Hello, {name}!" print(greet("Alice")) print(greet.__doc__)
Output
Hello, Alice!
Return a greeting message for the given name.
Common Pitfalls
Common mistakes when using docstrings include:
- Not placing the docstring immediately after the function or class definition line.
- Using single or double quotes instead of triple quotes, which limits the docstring to one line.
- Forgetting to write a docstring at all, which makes code harder to understand.
- Writing docstrings that are too vague or missing important details.
python
def add(a, b): # Wrong: no docstring return a + b def multiply(a, b): 'Multiply two numbers.' # Wrong: missing triple quotes return a * b def divide(a, b): """Divide a by b and return the result.""" return a / b
Quick Reference
Use this quick guide to remember how to write and use docstrings:
| Tip | Description |
|---|---|
| Placement | Right after the function, class, or module definition line |
| Quotes | Use triple quotes: """ or ''' |
| Access | Use .__doc__ to read the docstring |
| Purpose | Explain what the code does and how to use it |
| Style | Keep it clear, concise, and informative |
Key Takeaways
Write docstrings immediately after the function, class, or module definition line using triple quotes.
Access docstrings with the
.__doc__ attribute to help understand code purpose.Avoid missing or vague docstrings to keep your code clear and maintainable.
Use docstrings to explain what the code does, its parameters, and return values if needed.
Triple quotes allow multi-line descriptions, making docstrings more readable.