Skip to content

Lesson 4 of 59Your Python toolbox

Debugging Python

Read tracebacks bottom-up, drive pdb from the terminal, debug failing tests and live servers, and hunt bugs with a method instead of guesses.

17 min read0/5 questions

Every developer writes bugs. What separates a junior from a senior is not the number of bugs but how long each one survives. A senior reads the traceback, forms one guess, checks it in a debugger, and moves on in ten minutes. A junior adds print statements at random for an afternoon. This lesson gives you the senior toolkit: reading tracebacks properly, pdb in the terminal, post-mortem debugging, debugging tests and running servers, and a repeatable method for the bugs that do not explain themselves.

Read the traceback from the bottom up

A traceback is printed most recent call last. The top is where your program started; the bottom is where it died. So read it upwards:

Traceback (most recent call last):
  File "app/reports.py", line 19, in <module>
    report(load_orders())
  File "app/reports.py", line 15, in report
    total += net_total(order)
             ~~~~~~~~~^^^^^^^
  File "app/reports.py", line 10, in net_total
    return order["total"] * (1 - order["discount"])
                                 ~~~~~^^^^^^^^^^^^
KeyError: 'discount'
  1. The last line is the exception type and message: a dictionary had no discount key.
  2. The frame just above it is the exact line that failed. Recent Python versions underline the failing expression with ~ and ^, so you can see it was order["discount"], not order["total"].
  3. Walk up until you reach the first frame in your code that made a bad decision. Here net_total assumed every order has a discount. Whether the fix belongs there (use order.get("discount", 0)) or in load_orders is a design question, but now you are asking the right one.

In a FastAPI app, tracebacks are long because your route sits under Starlette, middleware and AnyIO frames. Skip frames whose paths contain site-packages and look for the lowest frame inside your project. The bug is almost always there, not in the framework.

Two more patterns to recognise. "During handling of the above exception, another exception occurred" means a second error happened inside an except block, often in your error handling itself. "The above exception was the direct cause of the following exception" comes from raise NewError(...) from err; the first traceback is the root cause, so read that one first.

Here is the same walk done in code with the traceback module, which is how error trackers group crashes:

Pythonread_traceback.py
import traceback def load_orders(): return [ {"id": 1, "total": 1200, "discount": 0.1}, {"id": 2, "total": 800}, ] def net_total(order): return order["total"] * (1 - order["discount"]) def report(orders): total = 0 for order in orders: total += net_total(order) return total try: report(load_orders())except KeyError as exc: frames = traceback.extract_tb(exc.__traceback__) print("Bottom up, most recent call first:") for frame in reversed(frames): print(f" line {frame.lineno} in {frame.name}") print(f"The error: {type(exc).__name__}: {exc}")
Output
Press Run (⌘ Enter) to see what happens.
Quick check
A FastAPI traceback is 60 lines long. The last line is AttributeError: 'NoneType' object has no attribute 'email'. Where should you look first?
Need a nudge? A hint rules out a wrong answer.

breakpoint() and pdb

The editor lesson showed breakpoint() and the five basic pdb commands. In practice you will use a few more, especially on servers and in containers where no editor is attached. Put breakpoint() on the line before the suspicious code and run the program normally:

app/services/pricing.py
def net_total(order: dict) -> float:
    breakpoint()                     # execution pauses here
    return order["total"] * (1 - order["discount"])
> app/services/pricing.py(3)net_total()
-> return order["total"] * (1 - order["discount"])
(Pdb) pp order
{'id': 2, 'total': 800}
(Pdb) w
  app/reports.py(19)<module>()
-> report(load_orders())
  app/reports.py(15)report()
-> total += net_total(order)
> app/services/pricing.py(3)net_total()
(Pdb) u
> app/reports.py(15)report()
-> total += net_total(order)
(Pdb) p len(orders)
2

The commands worth knowing by heart:

CommandWhat it does
n (next)Run the current line, stepping over calls
s (step)Step into the function called on this line
c (continue)Run until the next breakpoint
p expr / pp exprPrint a value; pp pretty-prints big dicts and lists
l / llList source around the current line / the whole function
w (where)Show the call stack, current frame marked with >
u / d (up / down)Move to the caller's frame and back, to inspect its variables
b file:lineSet another breakpoint without editing code
untilKeep running until a line greater than the current one, handy to finish a loop
q (quit)Stop the program

Any line pdb does not recognise as a command runs as Python, so you can call functions and even change variables mid-run. If a variable shares a name with a command (a variable called n or c), prefix it with ! or use p n.

Two habits keep breakpoint() safe. First, never commit one: a request handler that stops for input will hang a worker. Ruff's T100 rule flags leftover debugger calls, and pre-commit can run it for you. Second, know the escape hatch: PYTHONBREAKPOINT=0 makes every breakpoint() call do nothing, which is useful when a stray one reaches CI.

Match the pairs0/5 matched

Match each pdb command to the situation it solves.

Choose an item, then its match on the other side.

Post-mortem: debug after the crash

You do not always know where to put a breakpoint. Post-mortem debugging opens pdb at the moment of the crash, with every frame still alive:

python -m pdb -c continue scripts/import_orders.py# runs normally; on an uncaught exception you land in pdb at the failing line

Without -c continue, pdb stops before the first line and waits for you to type c. Either way, once it crashes you can use p, w, u and d exactly as above to inspect the state that caused the error.

In an interactive session, call pdb.pm() right after an exception to jump into the frame that raised it. Combined with python -i, which drops you into the REPL when a script ends or crashes, this is a quick way to poke at a failing script:

python -i scripts/import_orders.py# ... traceback ...>>> import pdb; pdb.pm()(Pdb) p row

Debugging failing tests

Tests are the best place to debug, because a failing test reproduces the bug on demand. pytest has flags that make it a debugger launcher:

uv run pytest -x                      # stop at the first failureuv run pytest -k "refund and not slow"  # run only tests whose names matchuv run pytest -l                      # show local variables in each failing frameuv run pytest -x --pdb                # open pdb at the first failure, post-mortemuv run pytest --trace -k test_refund  # open pdb at the start of each selected testuv run pytest --lf -x --pdb           # rerun last failures, debug the first

--pdb is post-mortem for tests: when an assertion fails or an exception escapes, you are dropped into the failing frame. pytest turns off output capturing while pdb is open, so you can type normally. A plain breakpoint() inside a test or the code under test also works.

Quick check
Forty tests fail after a refactor. You want to inspect the live variables of the first failure only. Which command fits best?
Need a nudge? A hint rules out a wrong answer.

print debugging is fine for a two-minute question. Use the = specifier in f-strings so you never print an unlabelled value, and delete the prints before you commit.

Predict the outputPython

What does this print?

subtotal = 3 * 4
print(f"{subtotal=}")
Need a nudge? Hints walk you through it.

When the question is "what happened in production last night", prints are useless: they are gone, unlabelled, and have no level. Logging is debugging output you keep. Add log.debug(...) calls at decision points, leave them in, and turn the level up for one module when you need detail:

Pythonlogging_for_debugging.py
import loggingimport sys logging.basicConfig( stream=sys.stdout, level=logging.INFO, format="%(levelname)-7s %(name)s: %(message)s",)log = logging.getLogger("orders") def apply_coupon(total, code): log.debug("apply_coupon total=%s code=%r", total, code) rate = {"SAVE10": 0.10, "SAVE20": 0.20}.get(code.strip().upper(), 0) if rate == 0: log.warning("unknown coupon %r, no discount", code) return round(total * (1 - rate), 2) print(apply_coupon(50.0, "save10"))print(apply_coupon(50.0, "SAVE 20")) log.setLevel(logging.DEBUG) # turn on detail for one module onlyprint(apply_coupon(50.0, " save20 ")) code = "SAVE 20"print(f"{code=}") # the quick print-debugging trick
Output
Press Run (⌘ Enter) to see what happens.

The rule of thumb: print for a quick look, logging for anything you may need again, and a debugger when you need to see many values at once or step through decisions. The logging lesson in the Production unit covers configuration and structured logs.

The editor debugger, briefly

Everything above also works with buttons. The Python Editors lesson set up breakpoints, launch.json for Uvicorn, conditional breakpoints and the test explorer; use them whenever you have a local editor. pdb earns its place where the editor cannot reach: SSH sessions, containers and CI runners.

Debugging a running server

Sometimes the bug only appears in the running app: inside Docker, with real config, after a specific sequence of requests. You can attach your editor's debugger to that process with debugpy, the debugger VS Code's Python extension uses. Start the server under debugpy, listening on a port:

uv add --dev debugpyuv run python -m debugpy --listen 0.0.0.0:5678 -m uvicorn app.main:app --port 8000

Then add an attach configuration in VS Code ("request": "attach" with "connect": {"host": "localhost", "port": 5678}) and start it. Add --wait-for-client if you need to debug startup code, so the app waits until the editor connects. If the app runs in a container, publish port 5678 and add pathMappings so the editor knows that /app in the container is your project folder.

Attaching to a running API
YouVS CodedebugpyAPI processstart uvicorn, listen :5678attach to localhost:5678GET /orders/42paused at breakpoint

debugpy runs inside the same process as your app and opens a debug port.

1/4

Python 3.14 added a second option: python -m pdb -p <pid> attaches pdb to an already running Python process, no restart needed. It needs permission to inspect the target process, so check the docs for your platform.

Finding slow code

A slowness bug is still a bug, and guessing is just as bad here. Run the code under the built-in profiler and sort by cumulative time:

uv run python -m cProfile -s cumulative scripts/import_orders.py | head -20

The top rows show which functions the time went into, including the ones they call. Usually one surprise stands out: a function called 10,000 times, or a database query inside a loop. Profiling and Making Python Fast in the Python course covers profilers properly, and the Performance and Scaling lesson at the end of this course applies them to a live server with py-spy.

A method for bugs that do not explain themselves

When the traceback and a breakpoint do not make the cause obvious, stop poking and follow a method. It feels slower and is much faster.

The bug-hunting loop
Reproduce: a failing testReproducea failing testIsolate: shrink the inputIsolateshrink the inputHypothesis: one testable guessHypothesisone testable guessCheck: debugger, log, bisectCheckdebugger, log, bisectFix: test turns greenFixtest turns greenreliablesmallerpredictwrongconfirmed

Reproduce it reliably, ideally as a failing test. A bug you cannot trigger on demand cannot be fixed with confidence.

1/5

Bisect is the most underrated move. If something worked last week and fails now, the cause is in a specific commit, and git bisect finds it by binary search:

git bisect startgit bisect bad                    # the current commit is brokengit bisect good v1.4.0            # this tag was fine# git checks out a commit halfway between; test it, then mark it:git bisect good                   # or: git bisect bad# ...repeat until git names the first bad commit, then:git bisect reset# or let a test decide automatically (exit code 0 = good, non-zero = bad):git bisect run uv run pytest -x tests/test_refunds.py

Each step halves the range, so even hundreds of commits take a handful of runs. Here is the search itself:

Pythonbisect_search.py
commits = [f"c{n:02d}" for n in range(1, 41)] # oldest to newestFIRST_BAD = "c27" # unknown to the search def test_passes(commit): """Stands in for checking out the commit and running the failing test.""" return commits.index(commit) < commits.index(FIRST_BAD) good, bad = 0, len(commits) - 1 # c01 is known good, c40 is known badsteps = 0while bad - good > 1: mid = (good + bad) // 2 steps += 1 ok = test_passes(commits[mid]) print(f"step {steps}: test {commits[mid]} -> {'good' if ok else 'bad'}") if ok: good = mid else: bad = mid print(f"first bad commit: {commits[bad]} after {steps} test runs (of {len(commits)} commits)")
Output
Press Run (⌘ Enter) to see what happens.

The same halving works without git: comment out half a function, feed half the input file, disable half the middleware. Bisect anything that can be split.

Put it in order5 steps

Put the bug-hunting method in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
traceback
The report of the call chain behind an exception, printed most recent call last, so you read it bottom-up.
pdb
Python's built-in command-line debugger, entered with breakpoint(), python -m pdb or pytest --pdb.
post-mortem debugging
Opening a debugger at the point of a crash, with the failing frames still available to inspect.
debugpy
The debug server behind VS Code's Python debugger; it can run inside an app so an editor can attach to it.
regression test
A test that reproduces a fixed bug, kept in the suite so the bug cannot quietly return.
git bisect
A git command that binary-searches history to find the first commit where a check starts failing.