Skip to Content
Course content

79: Docstrings and Function Documentation

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I was digging through an old project last week—a pricing engine I wrote about a year ago—and I ran into a function called calculate_adjusted_total. I stared at it for a good three minutes just trying to remember if the discount parameter was supposed to be a percentage (like 0.15) or a flat dollar amount (like 15.00). I had written the code, but I'd forgotten the "contract" of the function.

Where did I put that info?

Usually, when we're first learning, we just throw a comment above the function. Let's try that with a simplified version of my pricing function and see if it actually helps me when I'm using the function in a different part of the app.

def calculate_adjusted_total(price, discount, tax_rate):
    # This function takes a price, applies a percentage discount, 
    # and then adds sales tax.
    discounted = price * (1 - discount)
    return discounted * (1 + tax_rate)

# Now, let's pretend I'm a different developer using this function.
# I'll try to get help from Python's built-in help system.
help(calculate_adjusted_total)

If you run that, you'll see that Python tells you the function signature, but the help text is empty. The comment is there in the source code, but it's completely invisible to the Python runtime. If I'm working in an IDE or a REPL, I have to actually open the file and find the line where the function is defined to see that comment. That's a friction point I don't want.

Making it visible to the system

Python has a specific way of handling this called "docstrings." The trick is to move the explanation inside the function body, as the very first statement, and wrap it in triple quotes. Let's move my comment and see what happens.

def calculate_adjusted_total(price, discount, tax_rate):
    """Calculates the final price after a percentage discount and tax."""
    discounted = price * (1 - discount)
    return discounted * (1 + tax_rate)

help(calculate_adjusted_total)

Now, when I call help(), Python actually prints that string. It's not just a comment anymore; it's an attribute of the function object itself. In fact, you can access it directly via calculate_adjusted_total.__doc__. This is how modern IDEs show you those little tooltips when you hover over a function name.

Organizing the chaos

A single line is great for simple functions, but for anything professional, it's not enough. I still don't know for sure if discount should be 0.15 or 15. I need to document the arguments and the return value. While Python doesn't enforce a strict format, most of us follow a pattern (like Google or NumPy style) to keep things consistent.

Let's refine this into a proper multi-line docstring:

def calculate_adjusted_total(price, discount, tax_rate):
    """
    Calculate the final cost of an item.

    Args:
        price (float): The base price of the item.
        discount (float): The discount as a decimal (e.g., 0.1 for 10%).
        tax_rate (float): The tax rate as a decimal (e.g., 0.05 for 5%).

    Returns:
        float: The total price after discount and tax.
    """
    discounted = price * (1 - discount)
    return discounted * (1 + tax_rate)

I personally love this approach because it serves as a manual and a contract. If a teammate passes a whole number like 10 for the discount instead of 0.1, I can point to the docstring and say, "The contract says decimals." It saves a lot of arguing in code reviews.

One last thing to note: the triple quotes """ are essential. They allow the string to span multiple lines without needing \n characters everywhere, keeping the documentation readable for the humans who actually have to maintain the code.




📋 Practical Task

Documenting a Trapezoid Area Calculator

You have been handed a piece of legacy code that calculates the area of a trapezoid. The code works perfectly, but it has zero documentation, and the next developer has no idea what the parameters represent or what units are expected.

Your Task: Update the following function by adding a professional, multi-line docstring. Your docstring should clearly explain:

  • What the function does.
  • The purpose and expected type of each parameter (base1, base2, height).
  • What the function returns and its type.
def calculate_trapezoid_area(base1, base2, height):
    return 0.5 * (base1 + base2) * height

# Test your documentation using help()
help(calculate_trapezoid_area)
Rating
0 0

There are no comments for now.

to be the first to leave a comment.