Docstrings in Python
In Python, docstrings can be used to document modules, functions, classes, & methods.
Here are some examples:
Module docstring
"""
This is a module-level docstring.
It provides an overview of the module's purpose and contents.
"""
def my_function(param1, param2):
"""
This is a function-level docstring.
It describes what the function does, its parameters, and return value.
Parameters
param1 (int): The first parameter.
param2 (str): The second parameter.
Returns
bool: True if successful, False otherwise.
"""
# Function body goes here
class MyClass:
"""
This is a class-level docstring.
It describes the purpose and behavior of the class.
"""
def my_method(self, param):
"""
This is a method-level docstring.
It describes what the method does, its parameters, and return value.
Parameters
param (int): The parameter.
Returns
str: A string value.
"""
# Method body goes here
As you can see, docstrings are placed immediately after the definition of the module, function, class, or method they document. They provide a clear & structured way to describe the purpose & functionality of each component of your Python code.
Triple-Quoted Strings
In Python, docstrings are defined using triple-quoted strings. You can use either triple single quotes (''') or triple double quotes (""").
For example :
def greet(name):
'''
This function greets the person passed in as a parameter.
Parameters
name (str): The name of the person to greet.
Returns
str: The greeting message.
'''
return f"Hello, {name}! Welcome!"
def calculate_average(numbers):
"""
This function calculates the average of a list of numbers.
Parameters
numbers (list): A list of numeric values.
Returns
float: The average of the numbers.
"""
total = sum(numbers)
count = len(numbers)
return total / count
Using triple-quoted strings allows you to write docstrings that span multiple lines. This is particularly useful when you need to provide detailed explanations or include code examples within your docstrings. The Python interpreter ignores the leading & trailing whitespace in the docstring, so you can indent your docstrings to match the indentation level of your code for better readability.
Google Style Docstrings
Google has its own style guide for writing docstrings in Python. The Google style is characterized by a concise one-line summary, followed by a more detailed description, and then sections for parameters, returns, and other details.
For example :
def calculate_discount(price, discount_percentage):
"""Calculates the discounted price of a product.
Args
price (float): The original price of the product.
discount_percentage (float): The discount percentage (0 to 100).
Returns
float: The discounted price of the product.
"""
discounted_price = price * (1 - discount_percentage / 100)
return discounted_price
In the Google style:
- The docstring starts with a one-line summary that does not exceed 80 characters.
- The summary is followed by a blank line and a more detailed description (if necessary).
- The Args section lists the parameters, their types, and descriptions.
- The Returns section specifies the return type and description.
- Other sections like Raises (for exceptions) or Examples can be added as needed.
The Google style is widely used and provides a clear and structured format for documenting your Python code.
Numpydoc Style Docstrings
Numpydoc is a Numpy-specific style guide for writing docstrings. It is similar to the Google style but with a few additional conventions.
For example :
def calculate_mean(numbers):
"""
Calculate the mean of a list of numbers.
Parameters
numbers : list
A list of numeric values.
Returns
float
The mean of the numbers.
Examples
--------
>>> calculate_mean([1, 2, 3, 4, 5])
3.0
"""
total = sum(numbers)
count = len(numbers)
return total / count
In the Numpydoc style:
- The docstring starts with a one-line summary.
- The summary is followed by a blank line and a more detailed description (if necessary).
- The Parameters section lists the parameters, their types, and descriptions, with each parameter on a separate line.
- The Returns section specifies the return type and description.
- The Examples section provides examples of how to use the function or method.
- Other sections like Raises, Notes, or References can be added as needed.
The Numpydoc style is commonly used in scientific Python projects and provides a detailed and structured format for documenting your code.
One-line Docstrings
For simple functions or methods that don't require a lot of explanation, you can use one-line docstrings. One-line docstrings are concise and fit on a single line. Here are a few examples:
def square(x):
"""Return the square of x."""
return x ** 2
def is_even(num):
"""Check if a number is even."""
return num % 2 == 0
def greet(name):
"""Greet the person with the given name."""
print(f"Hello, {name}!")
One-line docstrings are useful when the purpose of the function or method is clear from its name and the parameters it takes. They provide a quick summary without going into much detail.
Keep in mind that one-line docstrings should still follow the conventions of the docstring style you are using (e.g., starting with a capital letter and ending with a period).
Note: While one-line docstrings can be helpful for simple cases, it's generally recommended to use multi-line docstrings for more complex functions or methods that require additional explanation or have multiple parameters or return values.
Multi-line Docstrings
When a function or method is more complex and requires a detailed explanation, you should use multi-line docstrings. Multi-line docstrings allow you to provide more information about the purpose, parameters, return values, and usage of the code.
For example :
def calculate_discount(price, discount_percentage):
"""
Calculate the discounted price of a product.
- This function takes the original price and the discount percentage
- as input and returns the discounted price. The discount percentage
- should be provided as a number between 0 and 100.
Parameters
price (float): The original price of the product.
discount_percentage (float): The discount percentage (0 to 100).
Returns
float: The discounted price of the product.
Example
>>> calculate_discount(100, 20)
80.0
"""
discounted_price = price * (1 - discount_percentage / 100)
return discounted_price
In this example:
- The docstring starts with a one-line summary of what the function does.
- The summary is followed by a blank line and a more detailed description that explains the purpose and behavior of the function.
- The Parameters section lists each parameter, along with its type and a brief description.
- The Returns section specifies the type and description of the return value.
- The Example section provides an example of how to use the function.
Multi-line docstrings are useful when you need to provide more context and explanation about the code. They help other developers (including yourself) understand the purpose, inputs, outputs, and usage of the function or method.
Remember to follow the docstring style guidelines you are using (e.g., Google style or Numpydoc style) to maintain consistency and readability in your codebase.
Indentation in Docstrings
When writing docstrings, it's important to pay attention to indentation to maintain readability and consistency. Here are some guidelines for indenting docstrings:
- The docstring should be indented at the same level as the code it describes.
- The opening and closing triple quotes should be on their own lines.
- The content of the docstring should be indented consistently (usually 4 spaces).
Here's an example:
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Parameters
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns
float: The area of the rectangle.
"""
area = length * width
return area
In this example, the docstring is indented at the same level as the function definition. The opening and closing triple quotes are on their own lines, and the content of the docstring is indented with 4 spaces.
Proper indentation makes the docstring more readable and visually separates it from the code. It also adheres to the Python style guide (PEP 8), which recommends using 4 spaces for indentation.
When using multi-line docstrings, you can also use hanging indents to improve readability. Hanging indents are used when the content of a section (e.g., parameters or returns) spans multiple lines. Here's an example:
def complex_function(param1, param2, param3):
"""
Perform a complex operation.
Parameters
param1 (int): The first parameter. This is a long description
that spans multiple lines.
param2 (str): The second parameter.
param3 (list): The third parameter. Another long description
that spans multiple lines.
Returns
dict: The result of the complex operation.
"""
# Function body goes here
In this case, the descriptions of param1 and param3 span multiple lines. The hanging indent helps visually separate the parameter names from their descriptions and makes the docstring more readable.
Docstrings in Classes
Docstrings can also be used to document classes in Python. Class docstrings should provide a high-level overview of the class, including its purpose, attributes, and methods. Here's an example:
class Rectangle:
"""
A class representing a rectangle.
Attributes
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Methods
area(): Calculate the area of the rectangle.
perimeter(): Calculate the perimeter of the rectangle.
"""
def __init__(self, length, width):
"""
Initialize a Rectangle object.
Parameters
length (float): The length of the rectangle.
width (float): The width of the rectangle.
"""
self.length = length
self.width = width
def area(self):
"""
Calculate the area of the rectangle.
Returns
float: The area of the rectangle.
"""
return self.length * self.width
def perimeter(self):
"""
Calculate the perimeter of the rectangle.
Returns
float: The perimeter of the rectangle.
"""
return 2 * (self.length + self.width)
In this example:
- The class docstring provides an overview of the Rectangle class, including its attributes (length and width) and methods (area() and perimeter()).
- The __init__ method has its own docstring describing the initialization of the Rectangle object and the parameters it takes.
- Each method (area() and perimeter()) has its own docstring describing what the method does and what it returns.
Class docstrings help users understand the purpose and structure of the class, while method docstrings provide more detailed information about each method's functionality.
It's important to keep class and method docstrings concise yet informative, following the same guidelines and styles mentioned earlier (e.g., Google style or Numpydoc style) for consistency and readability.
Difference between Python comments, String, & Docstrings
While comments, strings, & docstrings all involve adding explanatory text to your Python code, they serve different purposes. Let’s look at the basic difference between all these :
Comments
- Comments are used to add explanatory notes or annotations within the code.
- They are intended for developers reading the source code & are ignored by the Python interpreter.
- Comments start with a hash symbol (#) & can be placed anywhere in the code.
Example
# This is a comment explaining the purpose of the code below
x = 10 # This is an inline comment
Strings
- Strings are used to represent textual data within the code.
- They are part of the executable code & can be assigned to variables, concatenated, or manipulated.
- Strings are enclosed in single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' or """...""") for multi-line strings.
Example
- message = "Hello, world!" # Assigning a string to a variable
- print(message) # Using a string as a function argument
Docstrings
- Docstrings are used to provide documentation for modules, functions, classes, & methods.
- They are string literals that appear as the first statement in a module, function, class, or method definition.
- Docstrings are enclosed in triple quotes ('''...''' or """...""") & can span multiple lines.
- They are accessible through the __doc__ attribute of the corresponding object.
Example
def greet(name):
"""
A function that greets the person with the given name.
Parameters
name (str): The name of the person to greet.
Returns
str: The greeting message.
return f"Hello, {name}!"
In summary:
- Comments are used for in-code annotations & are ignored by the interpreter.
- Strings are used to represent textual data within the code & are part of the executable code.
- Docstrings are used for documentation purposes & provide information about modules, functions, classes, & methods.
Note: It's important to use comments, strings, & docstrings appropriately in your Python code to enhance readability, maintainability, & understanding for yourself & other developers who may work with your code.
Frequently Asked Questions
Can docstrings be accessed programmatically in Python?
Yes, docstrings can be accessed using the .__doc__ attribute of the object (functions, classes, modules, etc.) they document.
Are docstrings mandatory for all Python functions?
No, while docstrings are not mandatory, they are highly recommended for better code documentation and maintainability.
What's the difference between a one-line docstring and a multi-line docstring?
A one-line docstring provides a brief description of what the function does in a single sentence. A multi-line docstring includes a more detailed description, parameters, return type, and other relevant information.
Conclusion
In this article, we discussed the concept & importance of docstrings in Python. We learned how to write effective docstrings using different styles, such as the Google style & Numpydoc style, and discussed the benefits of including them in your Python code. By utilizing docstrings, you can enhance the readability, maintainability, & usability of your code, which makes it easier for everybody to understand & work with your Python projects.