As you start writing more functions to organize your code into reusable blocks, you'll quickly realize that just having the code isn't always enough. How do you remember what a specific function does a few weeks or months after writing it? How can others understand how to use your functions without needing to read every line of code? The answer lies in documentation, specifically, documentation embedded directly within your code using docstrings.
A docstring is a string literal that appears as the very first statement within a module, function, class, or method definition. Its purpose is to explain what the object does. Python automatically attaches these strings to the object's __doc__
attribute, making them accessible at runtime.
The standard convention is to use triple quotes ("""Docstring content"""
or '''Docstring content'''
) even for single-line docstrings. This makes it easy to expand them later if needed.
def greet(name):
"""Prints a simple greeting."""
print(f"Hello, {name}!")
def calculate_rectangle_area(length, width):
"""
Calculates the area of a rectangle.
This function takes the length and width of a rectangle
and returns its calculated area.
Args:
length (float): The length of the rectangle.
width (float): The width of the rectangle.
Returns:
float: The calculated area of the rectangle.
"""
if length < 0 or width < 0:
# We'll learn about raising errors later, for now just return None
print("Error: Length and width cannot be negative.")
return None
return length * width
Writing good docstrings is a fundamental aspect of writing clean, maintainable Python code. Here's why:
help()
function uses docstrings. If you run help(calculate_rectangle_area)
in a Python interpreter after defining the function above, you'll see the formatted docstring.While you can put any string there, following conventions makes your docstrings much more useful. PEP 257 provides guidelines for writing good docstrings. Here are the highlights:
def function_name(...):
line.""" """
."""
should be on the same line.
def square(x):
"""Returns the square of the input number."""
return x * x
Args:
or Parameters:
): List each parameter on a separate line, including its name, type (optional but helpful), and a description.Returns:
): Describe the value(s) returned by the function, including the type. If the function doesn't explicitly return anything (returns None
), you can state that or omit this section.Raises:
): If the function is designed to raise specific exceptions under certain conditions, list them here. (We'll cover exceptions in detail later).Look back at the calculate_rectangle_area
function example earlier; it demonstrates a standard multi line docstring format.
Python makes it easy to access the docstring associated with a function.
Using the __doc__
attribute: Every function object has a special attribute __doc__
that holds its docstring.
print(calculate_rectangle_area.__doc__)
This will print the raw docstring string.
Using the help()
function: The more user friendly way is to use the built-in help()
function in an interactive Python session.
# In a Python console or REPL
help(calculate_rectangle_area)
This command nicely formats and prints the docstring, making it easy to read.
Writing docstrings might seem like extra work initially, but it's an investment that pays off significantly in the long run. It makes your code more professional, understandable, and easier to maintain and share. Get into the habit of writing docstrings for every function you create.
© 2025 ApX Machine Learning