Need to inspect a function while it runs? Place a breakpoint at the suspected location. Execution pauses there and activates Python’s interactive debugger, allowing the program state and subsequent steps to be examined. section 13.2.1
Use the simplest practical forms:
- Call the built-in breakpoint() function directly. section 13.2.1
- Use import pdb; pdb.set_trace() when working with the underlying debugger interface or legacy code. section 13.2.1
- At the (Pdb) prompt, press n to execute the current line and stop at the next one; press Enter or Return to repeat n. section 13.2.2
- Use s instead of n when you need to step into a called operation, and l to list nearby source lines. section 13.5 section 13.2.2
Inspecting task creation
Place breakpoint() before the operation you want to inspect: def create_task(inject_bug: bool): breakpoint() task_text = obtain_text_data(inject_bug) title, urgency_text = task_text.split(",") urgency = int(urgency_text) return Task(title, urgency) Running the script opens a (Pdb) prompt and identifies the current function, line number, and next line to execute. Step through the parsing operations with n; when a failure occurs, inspect the nearby source with l. section 13.2.2 section 13.2.1
Listing 13.3 Creating a function containing a breakpoint (task_bebug.py)
from collections import namedtuple
Task = namedtuple("Task", "title urgency") #1
def obtain_text_data(want_bad):
text = "Laundry,3#" if want_bad else "Laundry,3"
return text
def create_task(inject_bug: bool):
breakpoint() #2
task_text = obtain_text_data(inject_bug) #3
title, urgency_text = task_text.split(",")
urgency = int(urgency_text)
task = Task(title, urgency)
return task
if __name__ == "__main__":
create_task(inject_bug=False)
Explore a complete script that creates task data, inserts a breakpoint, and provides an optional path for injecting a parsing bug. section 13.2.2





