Sub topic 9
Reading tracebacks and keeping your session state
This chapter assumes you can start the shell, type expressions and multi-line blocks, and use print(). It covers two skills. The first is reading the report Python prints when a statement fails. The second is knowing what is still true in your session afterward.
What a traceback is
When a statement raises an exception that nothing catches, Python stops that statement and prints a traceback. The traceback is a report of the chain of function calls that was active when the error happened. The shell then shows a fresh >>> prompt. It does not exit.
Here is a small example with two functions, so the chain has more than one link:
>>> def parse_age(text):
... return int(text)
...
>>> def load(record):
... return parse_age(record["age"])
...
>>> load({"age": "abc"})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in load
File "<stdin>", line 2, in parse_age
ValueError: invalid literal for int() with base 10: 'abc'The report has three parts:
- The header,
Traceback (most recent call last):. It tells you the order of the frames below it. - The frames. Each
File ..., line N, in NAMEentry is one active call. The oldest call comes first and the newest comes last. Here<module>is the shell statement you typed,loadis the function it called, andparse_ageis the function thatloadcalled. - The final line, which is the exception type, a colon, and a message. This is the summary of what went wrong.
Read a traceback from the bottom up. The last line tells you what failed. The last frame above it tells you where Python was when it failed. The frames above that show how the program got there.
In the example, the failing code is int(text) inside parse_age. The real cause is further up: load passed it the string 'abc'. The bottom frame is where the error surfaced, and the mistake may belong to an earlier frame.
The file label
In the classic shell, code typed at the prompt has no file on disk, so frames are labelled File "<stdin>" and no source line is shown. Python 3.13 and later ship a newer interactive shell. It labels frames like <python-input-0> and shows the source line under each frame. The structure is the same, so only the labels differ.
Common exception types
Most errors you meet while experimenting come from a short list. The type name is the quickest clue.
| Exception | Typical cause at the prompt |
|---|---|
| `NameError` | You used a name that is not defined, often a typo or a missing `import`. |
| `TypeError` | An operation got the wrong kind of value, such as `"a" + 1`. |
| `ValueError` | The type is right but the value is not, such as `int("abc")`. |
| `KeyError` | A dictionary lookup used a key that is not present. |
| `IndexError` | A sequence index is outside the sequence. |
| `AttributeError` | The object has no attribute with that name. |
| `SyntaxError` | The text is not valid Python. Nothing in the statement runs. |
| `KeyboardInterrupt` | You pressed Ctrl+C while a statement was running. |
TypeError and ValueError are easy to confuse. int([]) is a TypeError because a list is the wrong kind of thing to convert. int("abc") is a ValueError because a string is an acceptable type with an unacceptable value.
Chained exceptions
Sometimes a traceback contains two reports separated by a sentence. This happens when a second exception is raised while the first is being handled:
>>> try:
... {}["k"]
... except KeyError:
... int("x")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyError: 'k'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: invalid literal for int() with base 10: 'x'The report is in time order, so the original error is at the top and the final error is at the bottom. Usually the bottom one is the one you see in your own code, but the top one often explains why you were in the handler at all.
If code uses raise NewError(...) from original, the connecting sentence is instead The above exception was the direct cause of the following exception:. The reading order is the same.
What survives an error
The key rule is that an exception aborts only the statement that raised it. The interpreter keeps its state: every name you bound earlier is still bound, and every module you imported is still imported.
This is why the shell is good for experiments. A mistake costs you one line and nothing else. The details deserve care, though.
Partial effects remain
An exception stops the statement partway through, and anything it did before the failure stays done:
>>> data = {"a": 1, "b": 2}
>>> seen = []
>>> for key in ["a", "b", "c", "d"]:
... seen.append(data[key])
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyError: 'c'
>>> seen
[1, 2]
>>> key
'c'The loop ran twice, the third pass failed, and the fourth never started. seen holds the two results, and the loop variable key still holds 'c'. If you re-run the loop without resetting seen, you will append 1 and 2 again.
A failed assignment changes nothing
An assignment binds the name only after the right-hand side has been computed. If computing it raises an exception, the old binding stays:
>>> x = 5
>>> x = int("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> x
5A failed `def` keeps the old function
A function definition is a statement that binds a name. If you retype a function and the new text has a syntax error, the definition never happens, so the previous version is still in place. You may then call the old code and wonder why your fix had no effect. When a fix seems to do nothing, check that the redefinition printed no error.
The `except ... as` name disappears
Python deletes the name in except ... as e when the handler finishes. Values you copy out of it survive:
>>> try:
... int("abc")
... except ValueError as e:
... msg = str(e)
...
>>> msg
"invalid literal for int() with base 10: 'abc'"
>>> e
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'e' is not definedIf you want to examine an exception object after the block, assign it to another name inside the handler.
Syntax errors
A SyntaxError is raised while Python is still parsing, before any part of the statement runs. This means a syntax error cannot leave partial effects behind. The report points at the line and marks the position where parsing gave up. The actual mistake is sometimes just before that mark, such as a missing closing bracket on the previous line.
In a multi-line block, a syntax error in any line discards the whole block. You must retype it, and the history keys from the editing chapter help here.
Looking at the last error after the fact
After an uncaught exception, the interactive shell stores it in the sys module. You can examine it without reproducing the error:
>>> import sys
>>> int("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> sys.last_value
ValueError("invalid literal for int() with base 10: 'abc'")
>>> type(sys.last_value)
<class 'ValueError'>sys.last_value, sys.last_type, and sys.last_traceback are set only by the interactive shell, after an uncaught exception. Python 3.12 added sys.last_exc, which holds the same exception object as one value.
To step into the failing frames with the debugger, call the post-mortem function:
>>> import pdb
>>> pdb.pm()This opens the pdb prompt at the point where the last exception was raised. There you can print local variables and move up and down the call chain. Type q to leave the debugger. Your session state is still intact afterward.
To see a traceback without ending a statement, catch the exception and ask the traceback module to print it:
>>> import traceback
>>> try:
... [][0]
... except IndexError:
... traceback.print_exc()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list index out of rangeInterrupts and exits
Ctrl+C raises KeyboardInterrupt in the running statement. It prints a traceback and returns you to the prompt, which makes it the way to stop an accidental infinite loop. Whatever the loop had already done remains, as with any other exception.
exit() and quit() work differently. They raise SystemExit, which the shell treats as a request to end the session rather than an error to report. Your state is lost at that point. Nothing on disk is saved unless your own code saved it.
Habits that follow from this
- Read the last line first, then the last frame, then work upward.
- After any error in a block that mutates data, print the data before continuing.
- Rebuild suspect objects from scratch instead of trying to repair them by hand.
- Keep results you care about in named variables. Do not rely on
_, which is rebound by the next echoed value. - If the session has drifted into a confusing state, restart it. A clean session costs a few seconds and removes doubt.
Exercise
You run for n in [3, 2, 1, 0]: results.append(12 // n) in a session where results = [] was set earlier, and the loop raises ZeroDivisionError on the last pass. What does results contain afterward, and what should you do before running the loop again?
Show answer
results is [4, 6, 12]. The three successful passes appended their values before the error, and the exception does not undo them. Reset it with results = [] before running the loop again, or the old values will be duplicated.
Exercise
A traceback shows frames for <module>, load, and parse_age, in that order, ending in ValueError. Which function was running when the exception was raised, and which function called it?
Show answer
parse_age was running, because the most recent call is listed last. It was called by load, which was called from the shell statement (<module>).
Exercise
You type y = 1, then retype a longer function f that contains a syntax error, then call f(). Does the call use the new f, an old f, or fail? Is y still defined?
Show answer
If an earlier f was defined, the call runs that old f, because the failed definition never bound the name. If no earlier f existed, the call raises NameError. y is still defined, because a syntax error affects only the statement that contains it.