Explain it simply
Explain it simply
Debugging is detective work. The program printing a wrong answer or crashing is the "crime". A good detective does not arrest the first suspect; they collect evidence about what happened, when, and where. In code, that evidence is the values of variables, their types, and the order in which functions were called.
Python hands you the tools for gathering that evidence. A traceback shows where a crash happened, print() and logging show values, and breakpoint() pauses the program so you can look around inside it. More important than any single tool is having a calm, step-by-step method.
Problem → Why → Solution
The problem: a "fix" that only hides the symptom
Imagine a sales report that crashes with ZeroDivisionError. The quickest "fix" is a try/except inside average() that returns 0. The crash disappears, but now the report claims the average is 0 even though two orders were paid. The real bug is not in average() at all: the data says "Paid" and "PAID", the filter only looks for lowercase "paid", and so it hands back an empty list.
def paid_amounts(orders):
return [o["amount"] for o in orders if o["status"] == "paid"]
def average(values):
try:
return sum(values) / len(values)
except ZeroDivisionError:
return 0 # "fixed": the crash is gone, the bug is not
orders = [{"status": "Paid", "amount": 40}, {"status": "PAID", "amount": 60}]
print(average(paid_amounts(orders))) # prints 0, the right answer is 50.0Why does this happen?
The line where an error appears and the line where the bug starts are often different. ZeroDivisionError is only the symptom; the bad state, an empty list, entered earlier in the filter. You find the root cause by asking "where did this wrong value come from?" and tracing backwards, not by stopping at "where did it crash?".
Core concept: a method, not guesswork
Treat debugging as a six-step process you can repeat on any bug. Each step narrows the area you have to search. Skip one and you can easily spend an hour staring at the wrong file.
1. Reproduce
Find the exact input and command that make the bug happen every time. If you cannot reproduce it, you cannot prove you fixed it either.
2. Minimize
Cut the data and code down until you have the smallest input that still fails. Two rows are far easier to reason about than a thousand.
3. Hypothesize
Write down one testable guess, such as "the filter returns an empty list".
4. Gather evidence
Check the guess with print(f"{x=}"), logging or breakpoint(). Look at types, callers and where the data came from, not only the final value.
5–6. Fix and add a regression test
Fix the cause where it starts, then add a test using the input that used to fail. That test warns you immediately if the bug ever comes back.
Each evidence tool has its own job. print(f"{numbers=}") (Python 3.8+) shows a variable's name and value together, which makes it the fastest throwaway check. assert condition, "message" writes an assumption into the code, "this must be true here", and stops with AssertionError the moment it is false. logging has levels (DEBUG, INFO, WARNING, ERROR), so you can switch detailed messages on and off without deleting code.
assert is not input validation
Running Python with the -O flag strips out every assert statement. Use assert only for a developer's own assumptions. To check user input or file data, use an if test and raise an exception such as ValueError.
- Find the line showing the symptom
- Ask where that value came from
- Walk back one caller at a time
- Fix where the value first went wrong
The crashing line is where the search starts, not where it ends.
General pattern
import logging
logging.basicConfig(level=logging.DEBUG) # show DEBUG and above
log = logging.getLogger(__name__)
print(f"{variable=}") # name=value, quick check
assert condition, "assumption that must hold"
log.debug("state: %s", value) # switchable detail
breakpoint() # pause here in pdbbasicConfig() decides the lowest level that gets shown. f"{variable=}" prints a name with its value, and assert checks an assumption. log.debug() prints nothing when its level is switched off, and breakpoint() opens the debugger at that line.
Example: why can't this average be computed?
This example calls calculate_average() with two inputs. The first list holds numbers and works. The second holds strings, just like values read from a file, and raises TypeError. The debug print and log messages tell you why.
By default, logging writes to stderr. Here stream=sys.stdout sends log lines to the same place as print(), so they appear in order with it.
import logging
import sys
# Send log records to stdout so they appear in order with print()
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout,
format="%(levelname)s:%(name)s:%(message)s")
log = logging.getLogger("stats")
def calculate_average(numbers):
print(f"{numbers=}") # debug print: name and value together
assert numbers, "numbers must not be empty"
total = sum(numbers)
log.debug("total=%s count=%s", total, len(numbers))
return total / len(numbers)
print(f"Average: {calculate_average([10, 20, 30, 40])}")
raw = ["10", "20", "30"] # values read from a file are strings
try:
calculate_average(raw)
except TypeError as err:
log.error("bad input %r: %s", raw, err)
print(f"{type(raw[0])=}")Code breakdown
- Lines 5-6
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout,level=logging.DEBUG lets debug messages through. Change it to logging.INFO and the DEBUG lines vanish without deleting a single line of code.
- Line 11
print(f"{numbers=}") # debug print: name and value togetherThe f-string with = prints the name and the value, such as numbers=['10', '20', '30']. The quotes around each item are the first clue that these are strings, not numbers.
- Line 12
assert numbers, "numbers must not be empty"An empty list stops here with a clear message instead of reaching a ZeroDivisionError later. This checks the developer's own assumption.
- Line 14
log.debug("total=%s count=%s", total, len(numbers))Passing %s placeholders and separate arguments means logging skips building the string entirely when the DEBUG level is off.
- Lines 23-25
except TypeError as err:The exception is recorded with log.error() together with the input (%r shows its repr), then type(raw[0]) is printed. <class 'str'> is the root cause: the values need int() where the data enters the program.
numbers=[10, 20, 30, 40]
DEBUG:stats:total=100 count=4
Average: 25.0
numbers=['10', '20', '30']
ERROR:stats:bad input ['10', '20', '30']: unsupported operand type(s) for +: 'int' and 'str'
type(raw[0])=<class 'str'>Read a traceback from the bottom up
When nobody catches an exception, Python prints a traceback. The bottom line is the exception type and message: what went wrong. The frames above it are the chain of calls from where the program started down to where it failed; as "most recent call last" says, the newest frame sits at the bottom.
Reading a traceback
-------------------
Traceback (most recent call last):
File "report.py", line 14, in <module> <- 3. who started the chain
print(calculate_average(raw))
File "report.py", line 5, in calculate_average
total = sum(numbers) <- 2. the line that failed
TypeError: unsupported operand type(s) for +: 'int' and 'str'
^-- 1. read this first: exception type + messageStepping with breakpoint() and pdb
Instead of adding ten print statements, put one breakpoint() just before the suspicious line (Python 3.7+). The program pauses there and shows a (Pdb) prompt where you can inspect any variable, evaluate expressions and continue one line at a time. Running with the environment variable PYTHONBREAKPOINT=0 makes every breakpoint() call do nothing.
| Command | What it does |
|---|---|
| n (next) | Run the current line and stop at the next one, without entering calls |
| s (step) | Step into the function being called |
| p expr | Print the value of an expression |
| w (where) | Show the current call stack |
| c (continue) | Run until the next breakpoint |
| q (quit) | Stop the debugger and the program |
In real projects
Where this shows up in real projects
On a production server you cannot pause at a breakpoint() while users are waiting, so logging becomes the main source of evidence. Teams log each request's id, user and duration at INFO level, then search those logs when something goes wrong. Calling log.exception() inside an except block records the full traceback along with the message.
When a bug report arrives, experienced developers do not edit the code straight away. They first write a test that reproduces the bug and watch it fail, then fix the code and watch the test pass. That test stays in the suite forever, so if a refactor reintroduces the old bug, CI catches it. The debuggers in VS Code and PyCharm work on the same idea as pdb: set a breakpoint, step, inspect variables.
Common mistakes
Common mistakes
1. Swallowing errors with except: pass
try: ... except: pass keeps the program running but destroys every clue about what went wrong. Catch only the exception type you expect, by name, and at least record it with log.exception().
2. Patching the line where the error appeared
Guarding the crashing line, as average() did in the problem section, lets the bad data keep flowing. Trace the wrong value backwards and fix it where it enters, which here is the filter that never calls .lower() on the status.
3. Leaving debug prints behind
Committing print(f"{x=}") lines mixes them into the real output users see. Delete temporary prints once you are done, and turn any message worth keeping into log.debug().
Best practices
Best practices
- Write a test that reproduces the bug and see it fail before you touch the code.
- Change one thing at a time and re-check; change two at once and you will not know which one fixed it.
- Use logging.getLogger(__name__) in each module so every log line shows which module produced it.
Mini challenge
Mini challenge: hunt down the cart total bug
cart_total() should return 16 for three pens at 2 each plus one book at 10, but it returns 10. Gather evidence with logging, find and fix the bug, then add regression checks.
- Configure logging at DEBUG level, writing to stdout
- Log each item's name, price, qty and line total with logging.debug
- Fix the bug so the program prints Total: 16
- Add two assert checks: one for this cart, one for an empty cart
# TODO: import logging and sys, then configure DEBUG logging to stdout
def cart_total(items):
total = 0
for item in items:
total = item["price"] * item["qty"] # the bug hides in this loop
# TODO: log the item's name, price, qty and line total
return total
cart = [
{"name": "pen", "price": 2, "qty": 3},
{"name": "book", "price": 10, "qty": 1},
]
print(f"Total: {cart_total(cart)}") # prints 10, expected 16
# TODO: once fixed, assert the result for this cart and for an empty cartExpected: The program prints: DEBUG: pen: 2 x 3 = 6 DEBUG: book: 10 x 1 = 10 Total: 16 All regression checks passed
Show hint
Logging the line totals shows that 6 and 10 are both correct. So look at how each one goes into total: = or +=?
Show solution
import logging
import sys
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout,
format="%(levelname)s: %(message)s")
def cart_total(items):
total = 0
for item in items:
line = item["price"] * item["qty"]
logging.debug("%s: %s x %s = %s", item["name"], item["price"], item["qty"], line)
total += line # the fix: add, do not overwrite
return total
cart = [
{"name": "pen", "price": 2, "qty": 3},
{"name": "book", "price": 10, "qty": 1},
]
result = cart_total(cart)
print(f"Total: {result}")
# Regression checks: the first one failed before the fix
assert result == 16, result
assert cart_total([]) == 0
print("All regression checks passed")Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Debug in order: reproduce, minimize, hypothesize, gather evidence, fix, add a regression test.
- Read tracebacks from the bottom line, then trace the bad value back from the crash to where it began.
- print(f"{x=}") is for quick checks, logging is for evidence you keep, breakpoint() is for stepping.
- assert is for your own assumptions and vanishes under -O; validate input with if and an exception.
The Python Tutorial — Python Software Foundation