0
0
PythonHow-ToBeginner · 3 min read

How to Use pdb Debugger in Python: Simple Guide

Use the pdb module in Python by importing it and calling pdb.set_trace() where you want to pause execution. This opens an interactive debugger allowing you to inspect variables and step through code line-by-line.
📐

Syntax

To use the pdb debugger, first import the pdb module. Then insert pdb.set_trace() at the point in your code where you want to start debugging. When the program runs and reaches this line, it pauses and opens an interactive prompt.

  • import pdb: Loads the debugger module.
  • pdb.set_trace(): Starts the debugger at this line.
python
import pdb

# Your code here
pdb.set_trace()  # Pause and open debugger
# More code
💻

Example

This example shows how to use pdb.set_trace() to pause execution and inspect variables. When running, the program stops at the debugger prompt where you can type commands like n to go to the next line or p variable to print a variable's value.

python
import pdb

def add_numbers(a, b):
    pdb.set_trace()  # Start debugger here
    result = a + b
    return result

sum_value = add_numbers(3, 5)
print(f"Sum is {sum_value}")
Output
(Pdb) p a 3 (Pdb) p b 5 (Pdb) n > <stdin>(6)add_numbers() -> result = a + b (Pdb) n > <stdin>(7)add_numbers() -> return result (Pdb) n Sum is 8
⚠️

Common Pitfalls

Common mistakes when using pdb include:

  • Forgetting to import pdb before calling set_trace().
  • Leaving pdb.set_trace() in production code, which pauses the program unexpectedly.
  • Not knowing debugger commands, which can make navigation confusing.

Always remove or comment out pdb.set_trace() after debugging.

python
import pdb

# Wrong: missing import
# pdb.set_trace()  # This will cause an error

# Right:
import pdb
pdb.set_trace()  # Correct usage
📊

Quick Reference

CommandDescription
nGo to the next line of code
cContinue execution until next breakpoint or program end
p variablePrint the value of a variable
lList source code around the current line
qQuit the debugger and stop the program

Key Takeaways

Import pdb and use pdb.set_trace() to start debugging at any code line.
Use debugger commands like n, p, c, l, and q to navigate and inspect your code.
Remove pdb.set_trace() calls before deploying your code to avoid unwanted pauses.
The pdb debugger helps find bugs by letting you pause and check variables step-by-step.