Python tutorials > Best Practices > Documentation > How to write docstrings?
How to write docstrings?
What is a Docstring?
__doc__
attribute of the object. Docstrings explain what the code does and how to use it. They are used by documentation generators (like Sphinx) and interactive help systems.
Basic Docstring Example
__doc__
attribute allows you to access the docstring programmatically.
def add(x, y):
"""Return the sum of x and y."""
return x + y
print(add.__doc__)
Multi-line Docstring Example
def calculate_area(length, width):
"""Calculate the area of a rectangle.
Args:
length (int): The length of the rectangle.
width (int): The width of the rectangle.
Returns:
int: The calculated area of the rectangle.
"""
return length * width
print(calculate_area.__doc__)
Docstring Components: Summary Line
Docstring Components: Argument Description
Docstring Components: Return Value Description
Docstring Components: Raising Exceptions
def divide(x, y):
"""Divide x by y.
Args:
x (int): The numerator.
y (int): The denominator.
Returns:
float: The result of the division.
Raises:
ZeroDivisionError: If y is zero.
"""
if y == 0:
raise ZeroDivisionError("Cannot divide by zero.")
return x / y
Google Style Docstrings
def example_function(arg1, arg2):
"""Does something.
Args:
arg1 (str): The first argument.
arg2 (int): The second argument.
Returns:
bool: True if successful, False otherwise.
Raises:
ValueError: If something goes wrong.
"""
# Function implementation here
return True
NumPy/SciPy Style Docstrings
def another_example(param1, param2):
"""Do something else.
Parameters
----------
param1 : str
The first parameter.
param2 : int
The second parameter.
Returns
-------
bool
True if successful, False otherwise.
Raises
------
TypeError
If the parameters have the wrong type.
"""
return True
Real-Life Use Case Section: Documenting a Class
class Dog:
"""Represents a dog.
Attributes:
name (str): The name of the dog.
breed (str): The breed of the dog.
Methods:
bark(): Prints the dog's bark.
"""
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
"""Prints the dog's bark."""
print("Woof!")
Best Practices: Consistency
Best Practices: Clarity
Best Practices: Completeness
Interview Tip: Docstring Knowledge
When to Use Them: Always!
Alternatives: Comments
Pros: Improved Readability
Pros: Automatic Documentation Generation
Pros: Interactive Help
help()
function and IDEs to provide interactive help to users.
Cons: Time Investment
Example: Using Sphinx to generate documentation
pip install sphinx
. Then, install a theme like ReadTheDocs: pip install sphinx_rtd_theme
. After that configure Sphinx to generate documentation by typing in the terminal: sphinx-quickstart
in your project's folder. Follow the prompts to configure your project. Then edit the `conf.py` to include the needed extension: extensions = ['sphinx.ext.autodoc', 'sphinx_rtd_theme']
. Finally generate the html files by typing make html
in the terminal. Sphinx will automatically parse your docstrings and generate a beautiful and easy to navigate website.
FAQ
-
What is PEP 257?
PEP 257 is a Python Enhancement Proposal that provides conventions for docstrings. It covers topics such as the format of docstrings, how to write summary lines, and how to document arguments and return values. -
How do I access a docstring programmatically?
You can access a docstring using the__doc__
attribute of the object (e.g.,function.__doc__
,class.__doc__
,module.__doc__
). -
What's the difference between a comment and a docstring?
Comments are used to explain specific lines of code or complex logic within a function, while docstrings are used to document the purpose of modules, classes, functions, and methods. Docstrings are used by documentation generators and interactive help systems, while comments are typically ignored by these tools.