51. Python's pdb Debugger
Here are 10 Python code snippets demonstrating how to use Python's built-in debugger, pdb, for step-by-step code analysis:
1. Basic Usage of pdb.set_trace()
Inserting a breakpoint in the code to start the debugger.
import pdb
def calculate_sum(a, b):
result = a + b
pdb.set_trace() # Start debugger here
return result
print(calculate_sum(3, 4))When pdb.set_trace() is hit, the debugger will pause execution, and you can inspect variables and step through the code.
2. Navigating Code with Commands in pdb
Using n (next), s (step), and c (continue) to control the execution flow.
import pdb
def calculate_sum(a, b):
result = a + b
pdb.set_trace() # Start debugger
print(f"Result: {result}")
return result
calculate_sum(3, 4)When the debugger is triggered, use:
n: Move to the next line.s: Step into functions.c: Continue execution.
3. Inspecting Variable Values in Debugger
Inspecting variables using pdb commands.
When the debugger stops, use p name to inspect the value of the variable name.
4. Setting Breakpoints with pdb.set_trace()
Setting multiple breakpoints in a function.
You can add multiple breakpoints, and at each one, you can examine the execution flow and variable values.
5. Using pdb for Conditional Breakpoints
Setting a breakpoint that only activates under a condition.
The debugger will only be triggered if result equals 10.
6. Listing the Source Code with l (list)
Using the l command to list the current source code around the breakpoint.
When the debugger stops, you can use l to list the current source code around the breakpoint.
7. Exiting the Debugger with q (quit)
Exiting the debugger session using the q command.
In the debugger, type q to quit the debugger and stop the execution.
8. Using pdb with Exception Handling
Debugging inside a try-except block.
The debugger will trigger before the exception handling takes place, allowing you to inspect the exception context.
9. Running the Python Script with Debugger from Command Line
Using the -m pdb command to run the script in debugging mode.
This will start the Python script inside the pdb debugger. You can set breakpoints, step through, and inspect variables interactively.
10. Tracing Function Calls with pdb
Using pdb to trace the function calls.
Here, you can trace the execution, going through both the add and multiply function calls, inspecting variables as needed.
These snippets demonstrate different ways to use the pdb debugger for step-by-step code analysis, inspecting variables, and controlling the execution flow. You can use these techniques to troubleshoot, understand the code better, and refine your program.
Last updated