Sub topic 9
Reading tracebacks and keeping your session state
This chapter assumes you can write simple functions and loops, and that you can start the shell with python3. You will learn to read a traceback from the bottom up. You will also learn which parts of your session survive an exception.
Anatomy of a traceback
When a statement raises an exception that nothing catches, the shell prints a traceback. It shows the chain of calls that led to the error. Define two small functions and trigger a failure:
>>> def parse_age(text):
... return int(text)
...
>>> def describe(text):
... return "Age: " + str(parse_age(text))
...
>>> describe("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in describe
File "<stdin>", line 2, in parse_age
ValueError: invalid literal for int() with base 10: 'abc'Read it from the bottom:
- The last line gives the exception type (
ValueError) and its message. Start here. - The line just above it is the innermost frame, where the error was raised. Here that is
parse_age. - Each line above it is the caller of the frame below. The top frame,
<module>, is the statement you typed.
The file label depends on your Python version. Older versions print <stdin>. Python 3.13 and later print labels such as <python-input-3> and may also show the source line. The structure is the same either way.
The line numbers are relative to the block you typed. The shell compiles each statement on its own, so line 2 means the second line of that function definition. It does not refer to a file.
What survives an error
An exception ends only the statement that failed. The session keeps running, and everything bound before the error is still there:
>>> x = 5
>>> int("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> x
5Work done inside the failing statement before the error is also kept. This catches many learners out:
>>> items = []
>>> for n in ["1", "2", "x", "4"]:
... items.append(int(n))
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'x'
>>> items
[1, 2]The loop appended two values before it failed on "x". The list now holds partial results, and "4" was never processed. If you rerun the loop without resetting items, you will get duplicates.
An assignment that fails never completes, so the name is not bound:
>>> age = int("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> age
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'age' is not defined| Situation | State afterwards |
|---|---|
| Error in an expression | Nothing changes. All earlier names remain. |
| Error in `name = expression` | `name` is not bound, or keeps its old value. |
| Error halfway through a loop | Changes made before the error remain. |
| Error inside a function | Local variables are discarded. Global changes remain. |
| `Ctrl+C` during a long statement | `KeyboardInterrupt` is raised. The session continues. |
Common errors at the prompt
- A
NameErrorright after an error often means the failed assignment never ran. - A
SyntaxErrormeans Python could not parse your input, so nothing from that input ran at all. - An
IndentationErrorin a block usually means you forgot the blank line that ends it, or mixed tabs and spaces. - Unexpected values after a retry usually mean partial changes from the failed run are still in place. Reset the variable first, for example
items = [].
Exercise
You run total = 0, then a loop for n in ["10", "20", "oops", "30"]: total += int(n). The loop raises a ValueError. What does total show afterwards, and why?
Show answer
It shows 30. The loop added 10 and 20 before int("oops") raised the exception. The exception ended the loop, so "30" was never processed. The session is still running, and the changes made before the error are kept.
Exercise
Look at the last line of a traceback and then at the frame just above it. What does each one tell you?
Show answer
The last line gives the exception type and message, which says what went wrong. The frame above it is the innermost call, the place where the error was raised.