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.
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'- The last line is the exception type and message: a dictionary had no
discountkey. - 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 wasorder["discount"], notorder["total"]. - Walk up until you reach the first frame in your code that made a bad decision. Here
net_totalassumed every order has a discount. Whether the fix belongs there (useorder.get("discount", 0)) or inload_ordersis 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:
Press Run (⌘ Enter) to see what happens.AttributeError: 'NoneType' object has no attribute 'email'. Where should you look first?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:
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)
2The commands worth knowing by heart:
| Command | What 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 expr | Print a value; pp pretty-prints big dicts and lists |
l / ll | List 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:line | Set another breakpoint without editing code |
until | Keep 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 each pdb command to the situation it solves.
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 lineWithout -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 rowDebugging 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.
print, logging, or a debugger?
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.
What does this print?
subtotal = 3 * 4
print(f"{subtotal=}")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:
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 8000Then 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.
debugpy runs inside the same process as your app and opens a debug port.
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 -20The 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.
Reproduce it reliably, ideally as a failing test. A bug you cannot trigger on demand cannot be fixed with confidence.
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.pyEach step halves the range, so even hundreds of commits take a handful of runs. Here is the search itself:
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 the bug-hunting method in order.
- Tap the steps below in the right order.
- 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 pdborpytest --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.