Python Basics

Debugging with PDB

Debug Python code using the built-in PDB debugger

Debugging Python Code with PDB

PDB (Python Debugger) is the built-in command-line debugger for Python. It lets you pause your program, inspect variables, and step through code line by line.

Starting PDB

The easiest way to start debugging is to insert breakpoint() (Python 3.7+):

def divide(a, b):
    result = a / b
    return result

num = 10
den = 0

breakpoint()  # execution will pause here
answer = divide(num, den)
print(answer)

When Python hits breakpoint(), it drops you into the PDB prompt: (Pdb).

Common PDB Commands

  • l (list): show source code around the current line
  • n (next): execute the current line and move to the next in the same function
  • s (step): step into a function call
  • c (continue): continue execution until the next breakpoint
  • p expr: print the value of an expression (p num, p den)
  • q (quit): exit the debugger and stop the program
(Pdb) l
(Pdb) p num
(Pdb) p den
(Pdb) n
(Pdb) s
(Pdb) c

Using PDB from the Command Line

You can also run a script under the debugger directly:

python -m pdb your_script.py

Execution will stop at the first line of your script and you can start stepping through.

Setting Breakpoints by Line Number

Inside PDB you can set breakpoints at specific lines:

(Pdb) b 10      # set breakpoint at line 10
(Pdb) b myfile.py:25  # set breakpoint at line 25 in myfile.py
(Pdb) b         # list all breakpoints
(Pdb) cl 10     # clear breakpoint at line 10

Inspecting State

You can inspect variables and expressions at any time:

(Pdb) p my_list
(Pdb) p len(my_list)
(Pdb) p user.__dict__

Tip: Learning a few PDB commands (n, s, c, l, p) can dramatically speed up how you debug Python code compared to using only print() statements.