traceback

term

programming

Kept in this browser · My desk

The report Python prints when an exception is not handled: the calls that led to it, outermost first, then the exception's type and message on the last line.

Read it from the bottom. The last line names the exception; the frames above it run from the first call down to the innermost, each with its file, line, function and source line, and since Python 3.11 markers under each line point at the expression that failed (Python Enhancement Proposal 657, PEP 657). Chained exceptions print one after another, separated by The above exception was the direct cause of the following exception for raise from, or During handling of the above exception, another exception occurred when a handler fails. Exception groups print as nested, numbered boxes.

What it is, and what it is not. A traceback is two things in Python: an object, the chain of frames attached to every exception as its __traceback__ attribute, and the report the interpreter prints from it when the exception reaches the top without being handled. The printing is done by sys.excepthook, which the interpreter calls for any uncaught exception other than SystemExit, writing to standard error. The report opens with the line Traceback (most recent call last), lists one entry per frame, each with the file, the line number, the function and the line of source, and ends with the exception's type and message, which the tutorial calls the line that indicates what happened. The phrase most recent call last is the key to reading it: the first frame is the outermost call, usually the module itself, and the last frame is where the exception was raised. Other languages print the opposite way. Java's Throwable.printStackTrace puts the exception first and then the frames with the innermost method at the top and main at the bottom, so engineers moving between the two learn to look at opposite ends. A traceback is not a log, although it is often logged, and it is not a core dump: it describes Python frames, not machine state.

Reading one, line by line. Start at the last line: the type (ValueError, KeyError, ConnectionRefusedError) says what kind of failure, the message says what exactly. Then read upwards to the last frame that belongs to your own code, because frames below it are inside libraries you called and frames above it are the path that got there. Since Python 3.11, Python Enhancement Proposal (PEP) 657 adds carets and tildes under the source line pointing at the exact expression that failed, so that in a line such as a['x']['y']['z'] the marker shows which subscript was None. The PEP, Final since its creation in May 2021, made this possible by storing, for every bytecode instruction, the end line and the start and end column offsets, two one-byte offsets per instruction, readable through a code object's co_positions method. The extra tables can be dropped, with smaller code objects and .pyc files and no markers, by running with -X no_debug_ranges or setting PYTHONNODEBUGRANGES. Python 3.13 added colour in the terminal by default, controlled by PYTHON_COLORS, which takes precedence over NO_COLOR, which in turn takes precedence over FORCE_COLOR, and a hint when the cause is a script named like a standard module, such as a file called random.py importing itself. Python 3.15 keeps refining the last line: an AttributeError can now suggest a nested attribute ('.inner.area') or the Python name of a method from another language, and a lazily imported module that fails to load raises at first use with a traceback that shows both the use and the original import.

Chains, notes and groups. An exception raised while another is being handled carries the first one in its __context__ attribute, and the default display prints both, joined by the banner During handling of the above exception, another exception occurred. Writing raise new from original sets __cause__ instead, printed with the banner The above exception was the direct cause of the following exception; raise new from None sets __suppress_context__, which hides the original from the display while keeping it in __context__ for anyone debugging. An explicit cause is always shown, an implicit context only when there is no cause and it is not suppressed, and in every case the last line of the traceback is the last exception raised. Since Python 3.11 an exception can also carry notes: add_note appends a string, stored in __notes__, that the standard traceback prints after the exception message, which is the right way to say which device or which line of input was being processed without replacing the exception. Exception groups (PEP 654, also 3.11) bundle several exceptions, for example from polling many devices at once, and print as nested, numbered boxes; the traceback module's TracebackException limits the display to 15 exceptions per group and 10 levels of nesting by default.

Working with tracebacks in code. The traceback module is the standard interface to extract, format and print them. traceback.print_exc() prints the exception being handled; traceback.format_exc() returns the same text as a string, for a log or a ticket; a limit argument keeps only the last entries, or the first ones when negative. TracebackException captures an exception for rendering later, without keeping the frames alive, and can optionally capture local variables. In logging, Logger.exception logs at level ERROR and adds the exception information, and belongs only inside an exception handler. sys.tracebacklimit sets the maximum number of levels printed, 1000 by default; at 0 or less only the type and value are printed. After an uncaught exception in an interactive session, sys.last_exc holds it so that pdb.pm() can open a post-mortem debugger without re-running anything. When the process itself crashes, in a C extension or on a stack overflow, there is no Python exception to print; faulthandler, enabled with PYTHONFAULTHANDLER or -X faulthandler, installs handlers for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL and dumps the Python traceback of each thread, using an alternative stack so that it works even when the stack has overflowed.

In network automation. Scripts that drive devices over Secure Shell (SSH) fail in a small set of ways, and the traceback names them. A ConnectionRefusedError, a timeout or an authentication error from a library such as Paramiko or Netmiko says the device or the path refused; a KeyError or ValueError deep in a parser says the device answered with something the code did not expect, often a different software version or a paging prompt left in the output. The useful habit is the one the chaining rules allow: catch the low-level error where it happens, raise a clearer one from it, or add a note naming the device, and let the traceback carry both. A traceback pasted into a ticket is only useful whole, from the first line to the last, with the exact message; the last line alone loses the path, and a screenshot loses the text.

What goes wrong: tracebacks as information disclosure. A traceback shows file paths, function names, lines of source and, in some frameworks, local variables, which is exactly what an attacker probing an application wants. MITRE classifies the weakness as CWE-209, Generation of Error Message Containing Sensitive Information, with the canonical example of an exception printed straight to a web user. Web frameworks are explicit about it. Django's documentation says never to deploy a site into production with DEBUG on, because its debug pages display a detailed traceback with metadata about the environment and the current settings, filtering only names that contain words such as KEY or PASS. Flask's built-in Werkzeug development server shows an interactive traceback in the browser on an unhandled error, and both projects warn that this debugger allows the execution of arbitrary Python code and must never run in production, which is why it is guarded by a code printed on the server's command line; an exposed debugger is remote code execution, not just a leak. The safe pattern is to log the full traceback on the server, with Logger.exception or format_exc, and return a generic error with a correlation identifier to the client. Numbers worth keeping: 1000 levels by default, PEP 657 in 3.11, colour by default from 3.13, and groups shown 15 wide and 10 deep.

Also known as: Python traceback, stack trace, Traceback (most recent call last)

Sources

← Back to T Back to the glossary