Search code examples
pythontraceback

AttributeError: 'traceback' object has no attribute 'format_exception'


Here is my code, simplified to illustrate the problem:

import sys
def my_excepthook(exc_type, exc_value, exc_traceback):
    print(exc_traceback.format_exception())
sys.excepthook = my_excepthook
x = 5/0

Python hits another exception while handling the ZeroDivisionError, hence the title of this post.

Looking at my debugger, it's certainly a traceback object. It has four attributes:

  • tb_frame: frame
  • tb_lasti: int
  • tb_lineno: int
  • tb_next: traceback

but no methods. Why?

edit:

Reading the traceback module python docs, I had the misconception that I was reading the traceback object python docs.

how to format traceback objects


Solution

  • I think you are getting a traceback object confused with the traceback package, which contains a format_exception function.

    import sys
    import traceback
    def my_excepthook(exc_type, exc_value, exc_traceback):
        print(traceback.format_exception(exc_type, exc_value, exc_traceback))
    sys.excepthook = my_excepthook
    x = 5/0