Setting a breakpoint in Python

Chris
poweruser.blog
Published in
1 min readSep 10, 2017

--

It’s easy to set a breakpoint in Python code to i.e. inspect the contents of variables at a given line.

illustration: iStock/Getty Images (modified)

Add import pdb; pdb.set_trace() at the corresponding line in the Python code and execute it. The execution will stop at the breakpoint. An interactive shell (the pdb shell) will appear and allows you to run regular Python code, i.e. to print the current contents of variables and data structures.

There are several commands to continue or abort the further execution, here are some:

  • c continue execution
  • n step to the next line within the same function
  • s step to the next line in this function or a called function
  • q quit the debugger/execution

This is just the tip of the iceberg, the builtin Python Debugger (pdb) has many more powerful commands and usecases. Check the h help command or the docs for Python2 and Python3.

Update December 2019: Since Python 3.7 things have become even easier: There’s now a built-in breakpoint() function that calls pdb. Just place breakpoint() anywhere in the code to get into the pdb shell.

Additionally, if you want to run a python script and ignore all breakpoint() calls in the code it’s possible to do so by setting the environment variable PYTHONBREAKPOINT=0.

--

--