Docstring Basics
What is a Docstring?
A docstring (documentation string) is a string literal that appears as the first statement in a Python module, function, class, or method. It provides a concise explanation of the purpose, behavior, and usage of the code element.
Basic Syntax
In Python, docstrings are defined using triple quotes (""" or '''). Here's a simple example:
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
float: The calculated area of the rectangle.
"""
return length * width
Types of Docstrings
There are three main types of docstrings:
graph TD
A[Docstring Types] --> B[Function/Method Docstrings]
A --> C[Class Docstrings]
A --> D[Module Docstrings]
1. Function/Method Docstrings
Describe the purpose, parameters, and return value of a function.
2. Class Docstrings
Provide an overview of the class, its purpose, and key behaviors.
3. Module Docstrings
Explain the purpose and contents of an entire Python module.
Docstring Best Practices
| Practice |
Description |
| Be Concise |
Keep docstrings clear and to the point |
| Describe Purpose |
Explain what the code does |
| Document Parameters |
List and explain input arguments |
| Specify Return Values |
Describe what the function returns |
| Use Standard Formats |
Follow conventions like Google or NumPy styles |
Accessing Docstrings
You can access docstrings using the __doc__ attribute or the help() function:
def greet(name):
"""Say hello to the given name."""
print(f"Hello, {name}!")
## Accessing docstring
print(greet.__doc__) ## Prints: Say hello to the given name.
help(greet) ## Displays detailed docstring information
Why Use Docstrings?
- Improve code readability
- Provide quick documentation
- Support automatic documentation generation
- Enhance code maintainability
By following these docstring basics, you'll write more understandable and professional Python code. LabEx recommends consistently documenting your code to make it more accessible to other developers.