Introduction
Welcome to this lesson on using Python Debugger, commonly known as pdb. As we progress beyond foundational debugging techniques, this lesson will help you master pdb, enabling effective tracking and resolution of errors in Python scripts. We will explore how to set breakpoints, inspect variables, and utilize stack traces, along with step-by-step guides on executing code with specific pdb commands.
Understanding Python Debugger (pdb)
Python's built-in debugger, pdb, is a powerful tool for developers who need to step through their code to track down hard-to-find bugs. It provides the capability to pause the program and inspect the current state or change it on the fly.
Setting Breakpoints
Breakpoints in pdb are used to halt program execution at a specified state, allowing you to inspect the environment and debug issues interactively. You can set breakpoints in your Python script using the following methods:
- Inline Breakpoints:
Insert
import pdb; pdb.set_trace()directly into your code where you suspect an issue might occur.def my_function(x): import pdb; pdb.set_trace() return x * 2 result = my_function(3) print(result) - Breakpoint() Function:
Use the built-in
breakpoint()function for an easier way to invoke the debugger, available since Python 3.7:def calculate_total(a, b): breakpoint() return a + b total = calculate_total(5, 10) print(total)
Inspecting Variables During Execution
Once your program is paused at a breakpoint, you can inspect variables to see their current state:
- Use the
pcommand to print a variable's value.(Pdb) p my_variable - Evaluate expressions directly.
(Pdb) p my_list[0]
Utilizing Stack Traces for Error Identification
Stack traces provide a detailed report of the execution path taken to reach the current point in your program. You can view the stack trace using the following commands:
whereorw: Displays the current position in the call stack.(Pdb) wupanddown: Navigate up and down the stack trace to explore parent and child frames.(Pdb) up (Pdb) down
Step-by-Step Code Execution with pdb Commands
pdb offers a variety of commands to control the execution of your program:
n(next): Execute the next line of code. Moreover, it steps over function calls.(Pdb) ns(step): Step into the function call, allowing you to debug inside the function.(Pdb) sc(continue): Continue execution until the next breakpoint or the end of the script.(Pdb) c
Practical Example
Let's examine a practical example using the above techniques:
import pdb
def division(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b
def main():
numbers = [(10, 5), (20, 0), (30, 15)]
results = []
for num, denom in numbers:
try:
pdb.set_trace() # Start debugging here
result = division(num, denom)
results.append(result)
except ValueError as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
By setting a breakpoint using pdb.set_trace(), you can inspect the variables num and denom, navigate the stack trace for exception contexts, and make use of stepping commands (n, s) to identify issues.
Summary / Key Takeaways
In this lesson on using Python Debugger (pdb), you have learned:
- How to set breakpoints using inline
pdb.set_trace()and thebreakpoint()function. - Methods for inspecting variables during execution using the
pcommand. - The utility of stack traces with commands like
where,up, anddown. - Techniques for step-by-step code execution using
n,s, andccommands. - Practical application of these techniques to debug a Python script effectively.
