Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
79: Docstrings and Function Documentation
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)
There are no comments for now.