Sub topic 15
Limits of pdb and when to use another tool
This chapter assumes you can start a pdb session with breakpoint() or python -m pdb. It also assumes you can step, inspect variables, and set breakpoints, and that you know what PYTHONBREAKPOINT does. It covers what pdb cannot do well, which tools cover those gaps, and how to choose among them.
What pdb is good at
pdb is part of the standard library. It needs no installation and works over any terminal, including an SSH session on a server. It is a good fit when you have a single process, a terminal you can type into, and a bug you can reproduce.
The same properties set its limits. pdb is a line-oriented debugger with a plain text interface. It assumes one thread of attention, one process, and a live keyboard.
Limits you will hit
The interface is minimal
pdb shows one small window of source at a time. You must type l, ll, or w to see where you are. It has no variable panel, no syntax highlighting, and no tab completion for names by default. There is no persistent view of locals, so you use display expressions instead. Command history works only if your Python build has readline available.
Threads and concurrency
pdb traces the thread that called breakpoint(). Other threads keep running while you sit at the prompt. State can change underneath you, and output from other threads can interleave with your typing. pdb cannot freeze all threads and switch between them.
Async code has a related problem. If you stop inside a coroutine, the event loop is blocked for as long as you stay at the prompt. Timeouts can fire and connections can drop. n steps over an await as a single line, and the code you want to watch may run later inside the loop.
Multiple processes
A child process started with multiprocessing often has no usable standard input, so breakpoint() there fails or hangs. Web servers that fork workers have the same problem. Several workers can also reach a breakpoint at once and compete for the same terminal.
No attach to a running process
pdb cannot attach to a program that is already running and was not started with a breakpoint in it. You must change the code or restart under python -m pdb. Python 3.14 added python -m pdb -p PID to attach to a running process, but it requires a recent version and has platform and permission requirements. Check the documentation for your interpreter before you rely on it.
Heisenbugs and timing
Stopping a program changes its timing. Race conditions, timeouts, and bugs that depend on wall-clock time can vanish while you debug. Interactive stepping is the wrong tool for these. Logging, which has little effect on timing, usually works better.
Production and automation
A breakpoint() left in production code blocks the process and waits for input that will never arrive. Treat that as a defect. Setting PYTHONBREAKPOINT=0 disables every breakpoint() call, but it does not remove them from the source. Use a linter rule or a pre-commit check to catch stray calls.
Other gaps
- No reverse stepping. pdb cannot step backward. If you step past the cause, you restart and reproduce the bug again.
- Expression side effects.
p exprand!stmtrun real code. Calling a method that mutates state, or reading a lazy property, changes the program you are trying to observe. - Compiled code. pdb does not step into C extensions. A call into NumPy or a database driver is one opaque step.
- Large data.
pon a huge structure floods the terminal. Useppwith a bounded view, or inspect slices such asp data[:5].
Alternatives and what each adds
| Tool | What it adds over pdb | Cost |
|---|---|---|
| `ipdb` | IPython features: tab completion, colors, better tracebacks | Third-party install |
| `pdb++` | Sticky mode with a persistent source view, completion | Third-party install, replaces `pdb` |
| `pudb` | Full-screen terminal interface with variable and stack panels | Third-party install, needs a real terminal |
| IDE debugger (VS Code, PyCharm) | Visual breakpoints, watch panels, thread view, remote attach | Editor setup |
| `debugpy` | Debug adapter that lets an editor attach to a remote or running process | Install and open a port |
| `faulthandler` | Dumps the traceback of every thread on a crash or signal | None, standard library |
| `logging` | Records behavior over time without stopping | You must add the statements |
| `tracemalloc`, `cProfile` | Memory allocation and time profiles, which a debugger does not give | None, standard library |
ipdb, pdb++, and pudb are drop-in replacements for the prompt. Because breakpoint() calls whatever PYTHONBREAKPOINT names, you can switch without editing code.
pip install ipdb
PYTHONBREAKPOINT=ipdb.set_trace python script.pyInspecting threads with faulthandler
When a program hangs, a debugger is often unnecessary. faulthandler can print every thread's stack on demand. The script below hangs by design: two threads each wait on a lock the other holds. Send it a signal and read where each thread is stuck.
import faulthandler
import signal
import threading
import time
faulthandler.register(signal.SIGUSR1, all_threads=True)
lock_a = threading.Lock()
lock_b = threading.Lock()
def worker_one():
with lock_a:
time.sleep(0.2)
with lock_b:
print("one done")
def worker_two():
with lock_b:
time.sleep(0.2)
with lock_a:
print("two done")
t1 = threading.Thread(target=worker_one, daemon=True)
t2 = threading.Thread(target=worker_two, daemon=True)
t1.start()
t2.start()
time.sleep(1)
print("Deadlock suspected. Run: kill -USR1", __import__("os").getpid())
time.sleep(30)signal.SIGUSR1 exists only on Unix. While the script runs, send kill -USR1 <pid> from another terminal. The traceback of each thread appears on standard error. Both worker threads show a line waiting to acquire a lock. That identifies a deadlock in seconds, which pdb cannot do because the stuck threads never reach a breakpoint.
You can also dump stacks after a timeout, with no signal handling:
import faulthandler
faulthandler.dump_traceback_later(10, repeat=False, exit=True)This prints all thread stacks after 10 seconds and exits. It is useful in CI jobs that hang.
Replacing a stop with a log line
When timing matters, record instead of stopping. This is the same idea as a breakpoint with commands that prints and continues, but it works in code that pdb cannot reach.
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(threadName)s %(message)s",
)
log = logging.getLogger(__name__)
def transfer(account, amount):
log.debug("transfer start balance=%s amount=%s", account["balance"], amount)
account["balance"] -= amount
log.debug("transfer end balance=%s", account["balance"])
transfer({"balance": 100}, 30)Including the thread name and timestamp lets you reconstruct the order of events across threads after the fact.
Choosing a tool
Use these criteria in order:
- Can you reproduce it in one process with a terminal? Use pdb. It is the fastest option because it needs no setup.
- Are you stepping through a lot of code and losing track of context? Move to an IDE debugger or a drop-in such as
pdb++. The extra display saves typinglandwrepeatedly. - Does the program hang? Dump stacks with
faulthandlerbefore attaching anything. - Does the bug depend on timing or other threads? Add logging. Stopping the program is likely to hide the bug.
- Is the process remote, containerized, or already running? Use
debugpywith an editor, or a remote debugger your platform supports. - Is the question about speed or memory rather than correctness? Use
cProfileortracemalloc. A debugger shows state, not cost.
Common mistakes
- Leaving
breakpoint()in committed code. Add a check in CI that searches for it. - Debugging in a worker process that has no terminal. Reproduce the failing call in the main process, or log from the worker.
- Trusting a stepped run of a race condition. If the bug disappears under the debugger, switch to logging.
- Installing a replacement debugger in the wrong environment.
PYTHONBREAKPOINT=ipdb.set_tracefails silently with a warning ifipdbis missing from the interpreter you ran. - Calling methods with side effects from the prompt. Prefer reading attributes to calling functions when you want to observe, not change, state.
A quick check for stray calls, assuming a source tree under src:
grep -rnE "breakpoint\(\)|pdb\.set_trace\(\)" src/ && exit 1 || exit 0The command exits with status 1 when it finds a match, so it can fail a CI step.
Exercise
A service that uses several threads sometimes returns a wrong total. The error disappears whenever you run it under pdb and step through the suspect function. Which tool do you reach for next, and why?
Show answer
Use logging with timestamps and thread names. Stopping at a breakpoint changes the timing, which hides the race condition. Logging has little effect on timing and records the order in which threads touched the shared value, so you can see the interleaving that produces the wrong total.
Exercise
You run PYTHONBREAKPOINT=ipdb.set_trace python app.py and the program runs without stopping, printing a RuntimeWarning. What is the most likely cause, and how do you confirm it?
Show answer
The ipdb package is not installed in the interpreter that ran app.py, so Python could not import it and breakpoint() became a no-op. Confirm by running python -c "import ipdb" with the same interpreter. If it raises ImportError, install the package into that environment.
Exercise
A batch job hangs in CI and you cannot attach a terminal. Name a standard-library way to see where every thread is stuck without editing the job's logic much.
Show answer
Call faulthandler.dump_traceback_later(timeout, exit=True) near the start of the job. After the timeout it prints the stack of every thread to standard error and exits, so the CI log shows where each thread was waiting.