Skip to content
Visual explainer 2h to learn 4 steps

Debugging & reading tracebacks

Find bugs with tracebacks, breakpoints and pdb instead of random prints.

By Invicly Tech, , in Python Programming from Zero. About 12 minutes to read.

Topic 26 of 34

In short

Debugging is finding out why code does something you did not expect. Read the traceback first, then pause the program at a breakpoint and inspect real values instead of guessing with scattered prints.

Explained simply

Every programmer writes bugs every day. The skill is not avoiding them completely but finding them quickly. Debugging is detective work: the program did something you did not expect, and you collect evidence until you know why.

Python gives you the first clue for free: the traceback. It is the error report printed when the program crashes. It looks scary, but it always has the same shape, and the most useful part is the very last line, which names the error and gives a short message.

The second tool is a debugger. Instead of adding print() everywhere and running again and again, you pause the program at a line you choose, called a breakpoint. While it is paused you can look at every variable, then move forward one line at a time and watch what changes.

Python has a debugger built in, called pdb, which works in any terminal. VS Code has a graphical one with buttons and a variables panel. Both do the same job. Learn a handful of commands and you will solve bugs in minutes that used to take hours.

Press Play on a diagram to walk through it one step at a time.

FlowA calm debugging routine
  1. 1
    Reproduce

    Find the smallest input that triggers the bug

  2. 2
    Read the traceback

    Last line: error type; frames above: where

  3. 3
    Set a breakpoint

    breakpoint() or click the editor gutter

  4. 4
    Step & inspect

    Check variables line by line

  5. 5
    Fix & add a test

    So the bug cannot quietly return

MapCommon errors and their usual cause
Error on the last line
  • NameError
    • Typo in a name
    • Used before it was assigned
  • TypeError
    • Wrong type, like str + int
    • 'NoneType' object is not subscriptable: a function returned None
  • AttributeError
    • Method on the wrong type
    • Often a None you did not expect
  • KeyError / IndexError
    • Missing dict key
    • List shorter than you thought
  • ModuleNotFoundError
    • Package not installed
    • Wrong venv is active

In depth

Anatomy of a traceback

A traceback starts with Traceback (most recent call last):, then lists the chain of calls, oldest at the top. Each entry, called a frame, shows the file, the line number, the function name and the line of code. The last line is the exception type and its message. Since Python 3.11, many tracebacks also mark the exact part of the line that failed with ^ and ~ characters.

Read it from the bottom up. First the error type and message: what went wrong. Then find the lowest frame that is in your own code: that is usually where to look, even if deeper frames are inside a library. If you see During handling of the above exception, another exception occurred, a second error happened inside an except block. The above exception was the direct cause of the following exception means someone used raise ... from err to wrap the original error.

LayersReading a traceback, top to bottom
  1. 1
    Traceback (most recent call last):

    The header

  2. 2
    Outer frames

    Where the call chain started, often main()

  3. 3
    Your lowest frame

    Usually the line to inspect first

  4. 4
    Library frames

    Inside code you did not write

  5. 5
    ErrorType: message

    Read this first: what went wrong

The pdb commands that matter

Put breakpoint() on a line, run the program normally, and you get a (Pdb) prompt there. n runs the next line, s steps into a function call, r runs until the current function returns, and c continues to the next breakpoint. p expr prints any expression and pp pretty-prints big dicts. l shows code around the current line, and ll shows the whole function.

w (where) prints the call stack, and u and d move up and down it, so you can inspect the caller's variables too. b 42 sets another breakpoint at line 42, and b 42, total < 0 makes it conditional. q quits. Setting the environment variable PYTHONBREAKPOINT=0 makes every breakpoint() call do nothing, a safety net if one slips into production.

  • n next, s step into, r return, c continue
  • p x, pp data, ll list the function
  • w where, u up, d down
  • b 42, x > 100 sets a conditional breakpoint

Post-mortem: debugging after the crash

You do not always know where to put a breakpoint. Post-mortem debugging lets you inspect the program at the moment it crashed. Run python -m pdb script.py and type c; when an uncaught exception happens, pdb stops right at the failing line with every variable still available. With pytest, run pytest --pdb and you land in the debugger at the first failing assertion or error.

In an interactive session, run python -i script.py; after the crash you stay in the Python prompt, and import pdb; pdb.pm() opens the debugger on the last error. This is often the fastest route: no code changes, no guessing, just look at what the values really were when it failed.

FlowPost-mortem with python -m pdb
  1. 1
    python -m pdb app.py

    Starts paused on the first line

  2. 2
    c

    Run normally until something breaks

  3. 3
    Uncaught exception

    pdb stops at the failing frame

  4. 4
    p, w, u

    Inspect values and the callers

  5. 5
    Fix, then add a test

    So the bug stays fixed

Debugging in VS Code

With the Python extension installed (it brings the Python Debugger, based on debugpy), click in the gutter left of a line number to set a red breakpoint dot, then press F5 and choose Python File. When execution stops, the Variables panel shows all locals, Watch tracks expressions you type, Call Stack shows the frames from the traceback, and the Debug Console runs any Python expression in the paused program.

The default keys: F5 continue, F10 step over, F11 step into, Shift+F11 step out, Shift+F5 stop. Right-click a breakpoint to make it conditional (stop only when count == 500) or turn it into a logpoint that prints a message without pausing, like a print you never have to delete. By default, the debugger skips library code (justMyCode); turn that off in launch.json when the bug is inside a package.

A method, not luck

Good debugging follows the scientific method. Reproduce the bug reliably, ideally with the smallest input that still fails. Form one guess about the cause. Test it by inspecting values, not by changing code at random. Change one thing at a time and rerun.

When the cause is hard to find, cut the search space in half: check the value halfway through the process; if it is already wrong, the bug is earlier, otherwise later. git bisect applies the same idea to history, finding the commit that introduced a bug. Explaining the code line by line to someone, or even to a rubber duck, often reveals a wrong assumption. Finish by writing a test that fails without your fix, so the same bug cannot return quietly.

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Read tracebacks from bottom to top~30m
  2. 2
    Set breakpoints in VS Code~30m
  3. 3
    Step through code with pdb~30m
  4. 4
    Inspect variables at a failure~30m

Key points

  • Tracebacks list the most recent call last; start reading at the bottom.
  • breakpoint() drops you into pdb at that line.
  • In pdb: n next line, s step into, c continue, p x prints x, q quits.
  • VS Code breakpoints show all local variables without changing your code.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
def average(nums):
    total = sum(nums)
    breakpoint()          # pauses here in pdb
    return total / len(nums)

average([])

# (Pdb) p nums          -> []
# (Pdb) p len(nums)     -> 0
# (Pdb) n               -> ZeroDivisionError: division by zero
# Fix: return 0 or raise ValueError for empty input

Reading a real traceback

Step 1: the last line says ZeroDivisionError: division by zero. Step 2: the lowest frame is report.py line 9, in summary, and the carets point at total / len(items), so len(items) was 0. Step 3: the frame above shows summary was called with load("expenses.json"), so load returned an empty list. Step 4: the real question is now why the file had no expenses, and whether summary should handle an empty list.

text
Traceback (most recent call last):
  File "/home/ana/tracker/cli.py", line 41, in <module>
    main()
  File "/home/ana/tracker/cli.py", line 37, in main
    print(summary(load("expenses.json")))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ana/tracker/report.py", line 9, in summary
    return total / len(items)
           ~~~~~~^~~~~~~~~~~~
ZeroDivisionError: division by zero

Post-mortem on a KeyError from a CSV

A report crashes with KeyError: 'amount' somewhere in thousands of rows. Step 1: run it under pdb and continue until it crashes. Step 2: pdb stops in the generator expression that failed. Step 3: p row shows the bad row: its header says amt, not amount. Step 4: the fix is in the data or in the column name mapping, found without adding a single print.

text
$ python -m pdb report.py
> /home/ana/report.py(1)<module>()
-> import csv
(Pdb) c
Traceback (most recent call last):
  ...
KeyError: 'amount'
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> /home/ana/report.py(7)<genexpr>()
-> return sum(float(row["amount"]) for row in rows)
(Pdb) p row
{'date': '2026-03-02', 'amt': '4.50', 'category': 'food'}
(Pdb) q

Quick reference

  • Read tracebacks bottom up: error line first, then the lowest frame in your own code
  • breakpoint() pauses in pdb; PYTHONBREAKPOINT=0 disables all of them
  • pdb: n next, s step in, r return, c continue, p x print, w where, q quit
  • python -m pdb app.py then c: stops at the crash with all variables
  • pytest --pdb opens the debugger at the first failing test
  • VS Code: F5 run, F10 step over, F11 step in, Shift+F11 step out
  • 'NoneType' object has no attribute ... means something returned None

Common mistakes

  • Reading only the top of the traceback and blaming library code.
  • Changing many things at once, so you never learn what fixed it.
  • Leaving breakpoint() calls in committed code.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Where does a Python traceback show the error type and message?

Question 2

2In pdb, which command runs the current line and stops at the next one without entering called functions?

Question 3

3You get TypeError: 'NoneType' object is not subscriptable on data[0]. What is the likely cause?

Question 4

4What is the quickest way to inspect variables at the moment of a crash without editing code?

Question 5

5During handling of the above exception, another exception occurred. What does this tell you?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    A program stops with TypeError: can only concatenate str (not "int") to str on the line msg = "Total: " + total. Explain the error and fix it two ways.

  2. Exercise 2medium

    largest([-5, -2, -9]) returns 0 instead of -2. Use pdb to find out why, then fix it.

  3. Exercise 3hard

    A loop over 50,000 CSV rows crashes with ValueError: could not convert string to float: '' on one row. Stop exactly on that row, see its line number, and inspect it, without stepping 50,000 times.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is print debugging bad?
No, a quick print is fine for small checks. A debugger is better when you need many values, or need to see how they change step by step, and nothing has to be deleted afterwards.
Why does VS Code not stop at my breakpoint?
Usually the code never reached that line, a different file or interpreter is running, or the line is in library code with justMyCode on. Check the selected interpreter in the status bar.
How do I debug code inside a library?
Step into it with s in pdb, or set justMyCode to false in VS Code's launch.json. Remember the bug is usually in how you call the library.
What does the ^^^^ under a line in a traceback mean?
Since Python 3.11 the traceback points at the exact expression that failed, which helps when one line has several calls or operations.

Go deeper

ShareXLinkedInWhatsApp