format_exc() is really just

etype, value, tb = sys.exc_info()
return ''.join(format_exception(etype, value, tb, limit))

So if you have the exception type, value, and traceback ready, it should be easy. If you have just the exception, notice that format_exception() is essentially:

a_list = ['Traceback (most recent call last):\n']
a_list = a_list + format_tb(tb, limit)

where limit defaults to None.


Example:

To further aid in clarifying a (simple) application of format_exc():

import traceback

try:
    # Some code
except Exception:
    print('\nThe following error occurred:\n',
          traceback.format_exc(),
          'Processing aborted.\n',
          sep='\n')
    # sys.exit(1)
Answer from Martin v. Löwis on Stack Overflow
🌐
Python
docs.python.org › 3 › library › traceback.html
traceback — Print or retrieve a stack traceback
February 22, 2026 - The module uses traceback objects — these are objects of type types.TracebackType, which are assigned to the __traceback__ field of BaseException instances. ... Used to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal.
🌐
Real Python
realpython.com › python-traceback
Understanding the Python Traceback – Real Python
July 31, 2023 - The Python documentation defines when this exception is raised: Raised when an operation or function is applied to an object of inappropriate type. (Source) Following are several examples of the TypeError being raised: ... >>> 1 + '1' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> '1' + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be str, not int >>> len(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'int' has no len()
🌐
GeeksforGeeks
geeksforgeeks.org › python › traceback-in-python
Traceback in Python - GeeksforGeeks
August 1, 2020 - Traceback is a python module that provides a standard interface to extract, format and print stack traces of a python program. When it prints the stack trace it exactly mimics the behaviour of a python interpreter.
Top answer
1 of 7
136

The answer to this question depends on the version of Python you're using.

In Python 3

It's simple: exceptions come equipped with a __traceback__ attribute that contains the traceback. This attribute is also writable, and can be conveniently set using the with_traceback method of exceptions:

raise Exception("foo occurred").with_traceback(tracebackobj)

These features are minimally described as part of the raise documentation.

All credit for this part of the answer should go to Vyctor, who first posted this information. I'm including it here only because this answer is stuck at the top, and Python 3 is becoming more common.

In Python 2

It's annoyingly complex. The trouble with tracebacks is that they have references to stack frames, and stack frames have references to the tracebacks that have references to stack frames that have references to... you get the idea. This causes problems for the garbage collector. (Thanks to ecatmur for first pointing this out.)

The nice way of solving this would be to surgically break the cycle after leaving the except clause, which is what Python 3 does. The Python 2 solution is much uglier: you are provided with an ad-hoc function,sys.exc_info(), which only works inside the except clause. It returns a tuple containing the exception, the exception type, and the traceback for whatever exception is currently being handled.

So if you are inside the except clause, you can use the output of sys.exc_info() along with the traceback module to do various useful things:

>>> import sys, traceback
>>> def raise_exception():
...     try:
...         raise Exception
...     except Exception:
...         ex_type, ex, tb = sys.exc_info()
...         traceback.print_tb(tb)
...     finally:
...         del tb
... 
>>> raise_exception()
  File "<stdin>", line 3, in raise_exception

But as your edit indicates, you're trying to get the traceback that would have been printed if your exception had not been handled, after it has already been handled. That's a much harder question. Unfortunately, sys.exc_info returns (None, None, None) when no exception is being handled. Other related sys attributes don't help either. sys.exc_traceback is deprecated and undefined when no exception is being handled; sys.last_traceback seems perfect, but it appears only to be defined during interactive sessions.

If you can control how the exception is raised, you might be able to use inspect and a custom exception to store some of the information. But I'm not entirely sure how that would work.

To tell the truth, catching and returning an exception is kind of an unusual thing to do. This might be a sign that you need to refactor anyway.

2 of 7
116

Since Python 3.0[PEP 3109] the built in class Exception has a __traceback__ attribute which contains a traceback object (with Python 3.2.3):

>>> try:
...     raise Exception()
... except Exception as e:
...     tb = e.__traceback__
...
>>> tb
<traceback object at 0x00000000022A9208>

The problem is that after Googling __traceback__ for a while I found only few articles but none of them describes whether or why you should (not) use __traceback__.

However, the Python 3 documentation for raise says that:

A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute, which is writable.

So I assume it's meant to be used.

🌐
Unterwaditzer
unterwaditzer.net › 2018 › python-custom-tracebacks.html
How to create a traceback object in Python - Markus Unterwaditzer
Using this technique you can already construct arbitrary tracebacks: Create one codeobject (or function) that raises the exception. For each frame, create a new codeobject (or function) that calls the previous one. ... location must be a valid Python identifier.
🌐
Python Module of the Week
pymotw.com › 2 › traceback
traceback – Extract, format, and print exceptions and stack traces. - Python Module of the Week
Now available for Python 3! Buy the book! ... The traceback module works with the call stack to produce error messages. A traceback is a stack trace from the point of an exception handler down the call chain to the point where the exception was raised.
Top answer
1 of 6
25

Since Python 3.7 you can create traceback objects dynamically from Python.
To create traceback identical to one created by raise:

raise Exception()

use this:

import sys
import types

def exception_with_traceback(message):
    tb = None
    depth = 0
    while True:
        try:
            frame = sys._getframe(depth)
            depth += 1
        except ValueError as exc:
            break

        tb = types.TracebackType(tb, frame, frame.f_lasti, frame.f_lineno)

    return Exception(message).with_traceback(tb)

Relevant documentation is here:

  • https://docs.python.org/3/library/types.html#types.TracebackType
  • https://docs.python.org/3/reference/datamodel.html#traceback-objects
  • https://docs.python.org/3/library/sys.html#sys._getframe
2 of 6
16

There's no documented way to create traceback objects.

None of the functions in the traceback module create them. You can of course access the type as types.TracebackType, but if you call its constructor you just get a TypeError: cannot create 'traceback' instances.

The reason for this is that tracebacks contain references to internals that you can't actually access or generate from within Python.


However, you can access stack frames, and everything else you'd need to simulate a traceback is trivial. You can even write a class that has tb_frame, tb_lasti, tb_lineno, and tb_next attributes (using the info you can get from traceback.extract_stack and one of the inspect functions), which will look exactly like a traceback to any pure-Python code.

So there's a good chance that whatever you really want to do is doable, even though what you're asking for is not.

Find elsewhere
🌐
Coursera
coursera.org › tutorials › python-traceback
How to Print, Read, and Format a Python Traceback | Coursera
The traceback module provides a standard interface for extracting, printing, and formatting stack traces. If you need to extract a traceback, you have two options in the traceback module: extract_tb(): This function will return a StackSummary object.
🌐
Sentry
sentry.io › sentry answers › python › print stack traces in python
Print stack traces in Python | Sentry
April 15, 2024 - We can use traceback.print_exception to print the traceback of an exception object we pass to it, along with the usual exception information. This function has three required arguments: the exception’s class, the exception object, and the exception’s traceback.
🌐
Python
docs.python.org › 3.4 › library › traceback.html
29.9. traceback — Print or retrieve a stack traceback — Python 3.4.10 documentation
June 16, 2019 - The module uses traceback objects — this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info().
🌐
Real Python
realpython.com › ref › stdlib › traceback
traceback | Python Standard Library – Real Python
Python · >>> import traceback >>> try: ... {"a": 1}["b"] ... except KeyError: ... traceback.print_exc() Traceback (most recent call last): ... KeyError: 'b' Extracts stack traces from traceback objects · Formats stack traces for display · Prints exceptions and their stack traces to standard error ·
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch14s05.html
Getting More Information from Tracebacks - Python Cookbook [Book]
July 19, 2002 - A traceback object is basically a linked list of nodes, in which each node refers to a frame object. Frame objects, in turn, form their own linked list opposite the linked list of traceback nodes, so we can walk back and forth if needed.
Authors   Alex MartelliDavid Ascher
Published   2002
Pages   608
🌐
W3Schools
w3schools.com › python › ref_module_traceback.asp
Python traceback Module
The traceback module extracts, formats, and prints stack traces of Python exceptions.
🌐
Python.org
discuss.python.org › python help
How to get a full stack summary from a traceback.TracebackException - Python Help - Discussions on Python.org
January 29, 2024 - Hi, The docs say that a TracebackException’s stack attribute is a stack summary but it seems to be only a frame. How can I get the stack from the tbe? I would like to save a TracebackException object in one process and log a stack trace later in another. The snippet below prints tbe.stack=[ ] Similarly, traceback.TracebackException.from_exception(e).format() does not include function a; however traceback.format_stack() has both a an...
🌐
PyPI
pypi.org › project › tblib
tblib · PyPI
Create traceback objects from strings (the from_string method). No pickling is used. Serialize tracebacks to/from plain dicts (the from_dict and to_dict methods). No pickling is used. Raise the tracebacks created from the aforementioned sources. Pickle an Exception together with its traceback and exception chain (raise ... from ...) (Python 3 only)
      » pip install tblib
    
Published   Nov 12, 2025
Version   3.2.2
🌐
Python
docs.python.org › 3.10 › library › traceback.html
traceback — Print or retrieve a stack traceback — Python 3.10.19 documentation
The module uses traceback objects — this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info().
🌐
Readthedocs
boltons.readthedocs.io › en › latest › tbutils.html
tbutils - Tracebacks and call stacks — boltons 25.0.0 documentation
Create an ExceptionInfo object from the exception’s type, value, and traceback, as returned by sys.exc_info(). See also from_current(). ... Returns a string formatted in the traditional Python built-in style observable when an exception is not caught.