traceback
termKept 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
- The Python Tutorial, 8. Errors and Exceptions (read 2026-10-27)
- Python documentation, Built-in Exceptions: exception context and the chaining banners (read 2026-10-27)
- PEP 657, Include Fine Grained Error Locations in Tracebacks (read 2026-10-27)
- Python documentation (3.15), Built-in Exceptions, Exception context, re-read (read 2026-11-12): __context__ set automatically, __cause__ set by raise from, raise from None setting __suppress_context__; an explicit cause always shown, an implicit context only without a cause and when not suppressed; the last line always the last exception raised; add_note and __notes__, added in 3.11; __traceback__
- The Python Tutorial, 8. Errors and Exceptions, re-read (read 2026-11-12): the last line of the error message says what happened, with the exception type and detail; examples with carets under the failing expression
- PEP 657, Include Fine Grained Error Locations in Tracebacks, re-read (read 2026-11-12): Final, Standards Track, created 8 May 2021, Python 3.11; per-instruction end line and start and end column offsets, two uint8_t offsets per instruction; co_positions
- Python documentation (3.15), traceback, Print or retrieve a stack traceback (read 2026-11-12): a standard interface to extract, format and print stack traces; print_exc, format_exc, the limit argument; TracebackException captures an exception for later rendering, with capture_locals, max_group_width 15 and max_group_depth 10
- Python documentation (3.15), sys (read 2026-11-12): sys.excepthook prints the traceback of an uncaught exception other than SystemExit; sys.tracebacklimit defaults to 1000 levels and at 0 or less prints only type and value; sys.last_exc for post-mortem debugging with pdb.pm()
- Python documentation (3.15), Command line and environment (read 2026-11-12): -X no_debug_ranges and PYTHONNODEBUGRANGES, added in 3.11, drop the per-instruction location tables and the extra visual indicators; PYTHON_COLORS takes precedence over NO_COLOR, which takes precedence over FORCE_COLOR
- Python documentation, What's New in Python 3.11 (read 2026-11-12): fine-grained error locations in tracebacks (PEP 657), exception groups and except* (PEP 654), exception notes (PEP 678)
- Python documentation, What's New in Python 3.13 (read 2026-11-12): tracebacks highlighted in colour by default in the terminal, controlled by PYTHON_COLORS, NO_COLOR and FORCE_COLOR; a hint when a script shadows a standard library module
- Python documentation, What's New in Python 3.15 (read 2026-11-12): a failed lazy import raises at first use with a traceback showing both the access and the import statement; AttributeError suggestions such as '.inner.area' and Python equivalents of methods from other languages
- Python documentation, faulthandler (read 2026-11-12): dumps Python tracebacks on a fault, after a timeout or on a user signal; handlers for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL; enabled with PYTHONFAULTHANDLER or -X faulthandler; an alternative stack lets it dump even on stack overflow
- Python documentation, logging, Logger.exception (read 2026-11-12): logs at level ERROR with the exception information added; to be called only from an exception handler
- MITRE, CWE-209, Generation of Error Message Containing Sensitive Information (read 2026-11-12): the product generates an error message that includes sensitive information about its environment, users or associated data; the example of an exception printed to a web user
- Django documentation, Settings, DEBUG (read 2026-11-12): never deploy a site into production with DEBUG turned on; debug mode displays a detailed traceback with metadata about the environment and the current settings, excluding names that contain API, KEY, PASS and similar
- Werkzeug documentation, Debugging Applications (read 2026-11-12): the interactive debugger allows the execution of arbitrary code and must never be used on production machines; the debug console is protected by a PIN
- Flask documentation, Debugging Application Errors (read 2026-11-12): do not run the development server or enable the built-in debugger in production; the built-in Werkzeug development server's debugger shows an interactive traceback in the browser and allows executing arbitrary Python code; it is protected by a pin
- Oracle, Java SE 21 API, Throwable.printStackTrace (read 2026-11-12): the first line is the exception's toString, followed by the recorded frames, the innermost method first and main last in the typical example