In this lesson, you will learn how to pause your program’s execution mid-run to inspect its state and logic using the Python Debugger (pdb).
While pytest assertions are excellent for verifying final outcomes, they don't show you why a specific line of code misbehaved. When a complex test fails, the pdb module allows you to "step inside" the execution flow to see exactly what your variables contain at the moment of failure.
Starting the Debugger
You can trigger the debugger manually by inserting breakpoint() into your code. When Python hits this line, it halts execution and opens an interactive shell right in your terminal.
def calculate_discount(price, rate):
discount = price * rate
# Imagine we suspect 'discount' is calculating incorrectly
breakpoint()
return price - discount
Navigating the Execution
Once the program halts at your breakpoint(), you gain control over the flow:
n(next): Executes the current line and moves to the next line in the current function.s(step): Steps into a function call to see how it processes data internally.c(continue): Resumes the program until the next breakpoint or the end of the script.p(print): Use this followed by a variable name (e.g.,p discount) to see the current value of that object.q(quit): Exits the debugger and stops the program immediately.
Inspecting State Dynamically
The most powerful aspect of pdb is that it is a live Python environment. You aren't just reading values; you are executing code. If you are inside a function, you can type type(price) to check its data type or even perform manual calculations to verify your logic, like typing price * 0.1 to see if your code’s internal math matches your expectation. By isolating the logic in this interactive space, you can identify hidden bugs that static code analysis simply cannot catch.
Key Takeaway: pdb transforms debugging from a guessing game into an active investigation by allowing you to pause execution, inspect variable states, and test logic hypotheses in real-time.