Investigating with pdb Breakpoints
Intuitive Python — by David Muller (11 / 41)
👈 Try Out Different Versions of Python with D ocker | TOC | Detecting Problems Early 👉
Python includes a built-in debugger called pdb.[20] pdb allows you to halt your program’s execution on any given line and use an interactive Python console to inspect your program’s state. Since pdb is a built-in part of Python, you can import and use pdb at anytime without running additional external executables other than your program.
To add a breakpoint to your program, pick a target line and then add import pdb; pdb.set_trace() on that line. Up until now, we’ve been typing and/or pasting code into Python’s interactive console, but for this example try running the following example code by saying python3 pdb_example.py:
1: def get_farm_animals():
2: farm = ["cow", "pig", "goat"]
3: return farm
4:
5: import pdb; pdb.set_trace() # add breakpoint
6: animals = ["otter", "seal"]
7: farm_animals = get_farm_animals()
8: animals = animals + farm_animals
9: print(animals)
pdb_example.py constructs a list of animals and prints it out. For our purposes, the most important part of pdb_example.py is that we set a breakpoint on line 5 using pdb. (The actual code in the file is just something for us to step through.)