Docstrings and Documentation
Overview
Learn how to document your functions using docstrings. You'll understand how to write clear descriptions that explain what your function does, what parameters it takes, and what it returns, making your code easier to understand and use for yourself and others.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What docstrings are: Understand how to document your functions.
- Writing docstrings: Learn the proper format for function documentation.
- Accessing docstrings: Discover how to view function documentation.
- Best practices: Learn what makes good documentation.
Why This Matters
Documentation helps you and others understand what your code does. When you write a docstring, you're explaining the purpose of your function, what it expects, and what it returns. This makes your code much easier to use and maintain - you can read the docstring instead of reading through all the code to understand what a function does.
Step 1: What Is a Docstring?
A docstring is a special string that documents what a function does. It's placed right after the function definition, inside triple quotes. Python stores this string and makes it available through the help() function and other tools.
def add_numbers(a, b):
"""Add two numbers together and return the result."""
return a + b
Place After Function Definition
The docstring goes immediately after the def line, before any code in the function body. It's the first statement inside the function.
Use Triple Quotes
Docstrings use triple quotes (""" or ''') to allow multi-line strings. This lets you write longer descriptions that span multiple lines.
Write a Clear Description
The docstring should explain what the function does in simple terms. It should be clear enough that someone reading it understands the function's purpose without reading the code.
Key Concept: Docstrings are different from comments. Comments (using #) are for explaining code logic, while docstrings (using """) are for documenting what the function does. Docstrings are accessible through Python's help system, while comments are just for reading the source code.
Mini Practice #1: Writing Your First Docstring
Try It YourselfTry writing a function with a docstring and then accessing it:
What happened? The docstring is stored as part of the function object. You can access it using function_name.__doc__ or by calling help(function_name). The help() function displays the docstring in a formatted way, making it easy to read. This is how Python's built-in documentation system works - when you use help() on any function, it shows you the docstring!
Step 2: Multi-Line Docstrings
For more complex functions, you can write multi-line docstrings that include more details:
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
This function multiplies the length and width to find
the total area of a rectangular shape.
Parameters:
length (float): The length of the rectangle
width (float): The width of the rectangle
Returns:
float: The area of the rectangle
"""
return length * width
How It Works
Multi-line docstrings can include a summary line, followed by a blank line, then more detailed information. You can describe parameters, return values, and any important notes. This format makes it easy for others (and future you) to understand how to use the function.
Step 3: What to Include in Docstrings
A good docstring should include:
Summary
A one-line description of what the function does.
"""Calculate the total price."""
Parameters
What each parameter is and what it's used for.
Parameters:
price (float): The base price
Best Practice: Keep docstrings clear and concise. Focus on what the function does, not how it does it (that's what comments are for). Write docstrings as if explaining to someone who has never seen your code before.
Mini Practice #2: Writing a Detailed Docstring
Try It YourselfTry writing a function with a detailed multi-line docstring:
What happened? The multi-line docstring provides detailed information about the function. It includes a summary, explains what the function does, describes each parameter (what type it is and what it's for), and explains what the function returns. When you call help(greet_person), Python displays all this information in a nicely formatted way. This makes it easy for anyone using your function to understand how to use it correctly!
Step 4: Comments vs Docstrings
It's important to understand the difference between comments and docstrings:
Comments (#)
Explain how code works, for reading the source code.
# Check if number is positive
if x > 0:
return x
For code logic explanation
Docstrings (""")
Document what the function does, accessible via help().
def add(a, b):
"""Add two numbers."""
return a + b
For function documentation
Remember: Use comments to explain complex logic or tricky parts of your code. Use docstrings to document what your function does, what it expects, and what it returns. Both are important, but they serve different purposes!
End-of-Lesson Exercises
Exercise 1: Write a Function with a Docstring
Create a function named square_number that takes one parameter number and returns the square of that number. Add a docstring that explains what the function does. Then call help(square_number) to display the documentation.
Use triple quotes for the docstring right after the function definition.
Exercise 2: Write a Multi-Line Docstring
Create a function named calculate_total that takes two parameters: price and tax_rate (default 0.08). It should return the total price including tax. Write a multi-line docstring that includes a summary, describes the parameters, and explains what it returns.
Use triple quotes for a multi-line docstring with Parameters and Returns sections.