Docstrings (Documentation Strings) are special strings used to document Python code. They provide a description of what a module, class, function or method does.
- Declared using triple quotes (' ' ' or " " ").
- Written just below the definition of a function, class, or module.
- Unlike comments (#), docstrings can be accessed at runtime using __doc__ or help().
Example:
Python
def greet(name):
"""This function greets the user by their name."""
return f"Hello, {name}!"
Here, the docstring explains what the function does in one simple line.
Declaring and Accessing Docstrings
Docstrings are written just below the function, class or module definition. They can be accessed later using either:
- object.__doc__: Returns the docstring as a string.
- help(object): Displays the docstring in a more detailed format.
Example: The following code shows how to declare a docstring for a function and access it using both __doc__ and help().
Python
def my_function():
"""Demonstrates triple quotes docstring and does nothing."""
return None
print("Using __doc__:")
print(my_function.__doc__)
print("Using help():")
help(my_function)
OutputUsing __doc__:
Demonstrates triple quotes docstring and does nothing.
Using help():
Help on function my_function in module __main__:
my_function()
Demonstrates triple quotes docstring and does no...
Explanation:
- """Demonstrates triple quotes docstring and does nothing.""": Declares the docstring for my_function.
- my_function.__doc__: Directly prints the docstring text.
- help(my_function): Displays docstring in a structured help format.
What should a docstring look like?
- The doc string line should begin with a capital letter and end with a period.
- The first line should be a short description.
- If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
- The following lines should be one or more paragraphs describing the object’s calling conventions, side effects, etc.
Types of Docstrings
Python supports different docstring styles. Let’s go through them one by one with examples.
1. Triple-Quoted Strings
Most common style in Python. Uses triple single (''') or triple double (""") quotes. Can span multiple lines.
Example 1: This function shows how to use triple single quotes for docstrings.
Python
def my_func():
'''This is a docstring using triple single quotes.'''
return None
print("Using __doc__:")
print(my_func.__doc__)
print("Using help():")
help(my_func)
OutputUsing __doc__:
This is a docstring using triple single quotes.
Using help():
Help on function my_func in module __main__:
my_func()
This is a docstring using triple single quotes.
Explanation: docstring is written just below the function definition. __doc__ prints it directly and help() shows it in a structured way.
Example 2: This function shows how to use triple double quotes for docstrings.
Python
def my_func():
"""This is a docstring using triple double quotes."""
return None
print(my_func.__doc__)
OutputThis is a docstring using triple double quotes.
2. Google Style Docstrings
Google style docstrings follow a specific format and are inspired by Google's documentation style guide. They provide a structured way to document Python code, including parameters, return values and descriptions.
Example: This function multiplies two numbers using Google-style docstrings.
Python
def multiply(a, b):
"""
Multiply two numbers.
Args:
a (int): First number.
b (int): Second number.
Returns:
int: Product of a and b.
"""
return a * b
print(multiply(3, 5))
Explanation: Args describes input parameters and Returns describes output.
3. Numpydoc Style Docstrings
Numpydoc-style docstrings are widely used particularly for documenting functions and classes related to numerical computations and data manipulation. It is an extension of Google-style docstrings, with some additional conventions for documenting parameters and return values.
Example: This function divides two numbers using Numpydoc-style docstrings.
Python
def divide(a, b):
"""
Divide two numbers.
Parameters
----------
a : float
Dividend.
b : float
Divisor.
Returns
-------
float
Quotient of division.
"""
if b == 0:
raise ValueError("Division by zero not allowed.")
return a / b
print(divide(6, 2))
4. One-line Docstrings
As the name suggests, one-line docstrings fit in one line. They are used in obvious cases. The closing quotes are on same line as the opening quotes. This looks better for one-liners.
Example: This function raises a number to a power with a one-line docstring.
Python
def power(a, b):
"""Return a raised to power b."""
return a ** b
print(power.__doc__)
OutputReturn a raised to power b.
5. Multi-line Docstrings
Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line. The summary line may be on same line as opening quotes or on next line.
Example: This function shows a multi-line docstring with parameters and return value.
Python
def add(a, b):
"""
Add two numbers.
Parameters:
a (int): First number.
b (int): Second number.
Returns:
int: Sum of a and b.
"""
return a + b
print(add(3, 7))
6. Docstrings in Classes (with Indentation)
Docstrings in classes describe the class itself, its attributes, and its methods. Proper indentation is important:
- The class docstring is aligned with the class keyword.
- Method docstrings are indented inside the method.
- Tools automatically strip extra spaces but preserve relative indentation.
Example: This example shows class-level and method-level docstrings with proper indentation.
Python
class Employee:
"""
A class representing an employee.
Attributes:
name (str): Employee name.
age (int): Employee age.
salary (float): Employee salary.
"""
def __init__(self, name, age, salary):
"""
Initialize an Employee object.
Parameters:
name (str): Employee name.
age (int): Employee age.
salary (float): Employee salary.
"""
self.name = name
self.age = age
self.salary = salary
def promote(self, amount):
"""
Increase salary by a given amount.
Parameters:
amount (float): Raise amount.
Returns:
str: Message with new salary.
"""
self.salary += amount
return f"{self.name} promoted! New salary: {self.salary}"
Output (using help):
Help on class Employee in module __main__:
class Employee(builtins.object)
| A class representing an employee.
|
| Attributes:
| name (str): Employee name.
| age (int): Employee age.
| salary (float): Employee salary.
|
| Methods defined here:
|
| __init__(self, name, age, salary)
| Initialize an Employee object.
|
| promote(self, amount)
| Increase salary by a given amount.
Explanation:
- The class docstring documents attributes.
- Each method docstring documents parameters and return values.
- Proper indentation ensures readability and compatibility with tools like help().
- Comments (#): Explain code but are ignored by Python at runtime.
- Strings (" " or ' '): Represent text data and are used in variables/operations.
- Docstrings (""" """): Special strings placed below definitions to document modules, classes or functions. Unlike comments, they can be accessed using __doc__ or help().
Note: Docstrings are actually strings too, but Python treats them specially when placed right after a function, class or module definition.
Example: This example shows the difference between a comment, a string and a docstring.
Python
# This is a comment (ignored by Python)
name = "Daniel" # A string assigned to a variable
def greet():
"""This is a docstring. It explains what greet() does."""
return "Hello!"
Explanation:
- # This is a comment: just for developers, ignored at runtime.
- "Daniel": a normal string stored in a variable.
- """This is a docstring""": documents the function and can be accessed via greet.__doc__ or help(greet).
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice