You can access a Python docstring in two ways:
- Using the
__doc__
attribute:
print(example.__doc__)
- Using the
help()
function:
help(example)
"Programs must be written for people to read, and only incidentally for machines to execute." —Harold Abelson, American mathematician and computer scientist
A Python docstring is a text written inside triple quotes to describe a module, class, function, or method. It serves as inline documentation, explaining the purpose, parameters, and usage of the code to improve readability and help other developers understand it.
When writing code, it’s essential to not only focus on functionality but also clarity and readability. This is where docstrings come into play in Python. A docstring is a string literal used to document modules, functions, classes, or methods. Unlike traditional comments, docstrings serve as an official guide to how your code should be used. This feature is crucial for understanding code behavior, especially in collaborative environments or for future reference.
A docstring in Python is a special kind of comment used to document a specific segment of code. Docstrings are declared using triple quotes (""" """
) and can span across multiple lines or be as short as one line. Unlike regular comments, which are ignored by the interpreter, docstrings are stored as an attribute of the function or class and can be accessed during runtime.
Docstrings provide a high-level overview of what a piece of code does. For instance, they describe the purpose of a function, its parameters, and its return values.
Declaring docstrings: In Python, docstrings are declared directly under the function, class, or module definition. They use either single-line or multi-line triple-quoted strings (""" """
).
Accessing docstrings: You can access docstrings using two main methods:
The __doc__
attribute.
The help()
function.
The __doc__
attribute retrieves the docstring of any object, while the help()
function provides more comprehensive documentation.
Docstrings are essential for several reasons:
Clarity: They make your code easier to understand for other developers (or for yourself when revisiting the code).
Maintenance: Well-documented code is easier to maintain and debug.
Automated documentation: Tools like Sphinx can automatically generate documentation from docstrings.
Interactive help: The help()
function leverages docstrings to provide quick insights into your code during runtime.
Let's see how docstrings are used in Python:
Docstrings use triple-quoted strings (""" """
), which can span multiple lines or remain on a single line. They must be placed at the very start of a module, class, or function.
def multiply(a, b):'''In this function, we will multiply two numbers and return the result.'''return a * bprint(multiply.__doc__)
A single-line docstring is used for simple functions or classes. Here’s an example:
def hello_world():"""Demonstrating docstring."""return None# printing using __doc__ methodprint "Using __doc__ method:"print hello_world.__doc__# printing using help functionprint "Using help function:"help(hello_world)
For more complex functions or classes, a multi-line docstring is more appropriate:
def hello_world(argument):"""Summary line.Here comes description of a function.Parameters:argument (int): Description of argumentReturns:int: Description of return value"""return argument# printing using __doc__ methodprint "Using __doc__ method:"print hello_world.__doc__# printing using help functionprint "Using help function:"help(hello_world)
Proper indentation is crucial for readability in docstrings, especially for multi-line ones. The first line should start right after the triple quotes, and subsequent lines should be indented accordingly.
def add(a, b):"""Add two numbers and return the result.This function takes two arguments, `a` and `b`, and returns their sum.The result will be either an integer or a float, depending on the input types.Parameters:a (int or float): The first numberb (int or float): The second numberReturns:int or float: The sum of a and b"""return a + b# Accessing the docstringprint(add.__doc__)
The first line of the docstring starts immediately after the opening triple quotes.
Subsequent lines are indented for better readability, especially when describing parameters and return values.
Proper indentation is not enforced by Python, but it’s important for consistency and readability when working in teams or sharing your code.
Docstrings are also applicable in classes. You can define a docstring for the class itself and each method within the class.
class complex_number:"""This is a class for mathematical operations on complex numbers.Parameters:real (int): The real part of complex number.imag (int): The imaginary part of complex number."""def add(self, number):"""The function adds two complex numbers.Parameters:number (complex_number): The complex number to be added.Returns:ComplexNumber: A complex number which contains the sum."""re = self.real + num.realim = self.imag + num.imagreturn ComplexNumber(re, im)help(complex_number) # to access Class docstringhelp(complex_number.add) # to access method's docstring
Comments and docstrings serve different purposes in Python. While both are non-executable and meant to clarify the code, comments are for internal explanations and are ignored by Python during execution. In contrast, docstrings are stored as attributes of the functions or classes and can be accessed at runtime. Here's a comparison:
# Comments in Pythondef add_with_comments(a, b):return a + b# Docstring in Pythondef add_with_docstring(a, b):"""Add two numbers and return the result."""return a + b
Comments are for the developer's reference and are ignored by Python whereas docstrings provide structured documentation accessible via code and tools such as help()
.
Key takeaways
Python docstrings are used to document modules, functions, and classes.
They can be accessed using
__doc__
or thehelp()
function.Docstrings are written using triple-quoted strings and can be single-line or multi-line.
Proper documentation improves code readability, maintainability, and collaboration.
Python comments differ from docstrings as they are not accessible at runtime.
Consider the following function, which is supposed to add and subtract two numbers. The docstring, however, has several issues:
It only mentions addition, not subtraction.
The parameters are incorrectly documented.
The docstring format is inconsistent with typical conventions.
Your task is to do the following:
Identify and correct the errors in the docstring.
Update the code to accurately describe both addition and subtraction.
Use the help()
function after your modifications to see how the corrected docstring appears.
def add_subtract(a, b):""'This function adds two numbers.Parameters:x (int): The first number to addy (int): The second number to addReturns:tuple: containing the sum and the difference of a and b'""sum_result = a + bdiff_result = a - breturn sum_result, diff_result# Check the function docstringprint("Using help() to view the docstring:")help(add_subtract)
If you are stuck, click the "Solution" button after clicking the "Run" button.
Become a Python developer with our comprehensive learning path!
Ready to kickstart your career as a Python Developer? Our Become a Python Developer path is designed to take you from your first line of code to landing your first job.
This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.
Haven’t found what you were looking for? Contact Us
Free Resources