28
import sys

try:
    raise Exception('foobar')
except:
    info = sys.exc_info()

print(type(e[2])) # <class 'traceback'>
help(traceback) # NameError: name 'traceback' is not defined

What exactly is the type of the traceback objects that Python uses for exception reporting?

The docs on sys.exc_info mention the Reference Manual, but while I've found plenty of information on how to manipulate traceback instances, I want to be able to access the type (class) itself.

4
  • Just because there is a class wiht the __name__ == 'traceback' doesn't mean that in the global namespace, traceback refers to that class. Commented Jul 26, 2017 at 21:38
  • What are you even planning to do with this type? Having access to the type object doesn't get you much. Commented Jul 26, 2017 at 21:45
  • You're already accessing the type with type(e[2]), by the way. Commented Jul 26, 2017 at 21:46
  • 8
    Type annotations and curiosity. Commented Jul 26, 2017 at 21:46

1 Answer 1

38

traceback object is an instance of TracebackType present under types module.

types.TracebackType

The type of traceback objects such as found in sys.exc_info()[2].

>>> from types import TracebackType    
>>> isinstance(info[2], TracebackType)
True    
>>> TracebackType
<class 'traceback'>

As pointed out by @user2357112 the name TracebackType is basically an alias to the internal traceback type and is set by raising an exception in types module. The actual traceback type can be found in CPython code.

Sign up to request clarification or add additional context in comments.

3 Comments

It should be noted that this isn't the "true" name of the type - there's no "true" name - and it's not the place where the type is defined. types.py just raises an exception to get the traceback and sets TracebackType = type(tb).
@user2357112 Updated.
Available in Python >= 3.10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.