How to Read a Traceback
A traceback is Python’s report of where execution was when the program failed. It can look noisy, but the first useful pass is simple:
- start near the bottom;
- find the error type;
- read the message;
- read the line of your code mentioned just above it.
Here is a small program:
It fails because one value is a string:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The error type is TypeError. The message says Python tried to add an integer
and a string. The failing line is inside the loop:
total = total + value
That line assumed value was a number.
Read the bottom first
Ready to run.
The extra print is not the final fix. It is a temporary inspection. It shows
which value was being handled when the failure occurred.
Tracebacks are stacked calls
If one function calls another function, the traceback may show several frames. A frame is one active function call. The bottom frame is often closest to the actual error.
The traceback tells a story:
mean called total
total failed while adding a value
Read it as a path, not as a wall of text.
What not to do
Do not copy the whole traceback into your head. You usually need only four pieces:
| Part | Question |
|---|---|
| error type | What kind of failure is this? |
| message | What did Python try to do? |
| file and line | Where in my code did it happen? |
| failing expression | What assumption did this expression make? |
This code fails:
What is the error type?
Answer it first, then check.
HintEliminate what succeeded
The name numbers exists and index 2 exists. Inspect the types being added.
SolutionThe failure is a TypeError
numbers[0] is the integer 2, while numbers[2] is the string "6".
Adding an integer and a string raises TypeError.