Eli Rose
Eli Rose

Reputation: 6998

Why is the traceback not stored in the exception object in Python 2?

From what I understand, in Python 2, if I handle an exception, capture it as an object, and want to do something with the traceback as a string:

try:
    ...
except Exception as e:
    tb = get_traceback(e)
    store_in_database(tb)

there is no get_traceback function that takes e as an argument. There is import traceback; traceback.format_exc(), but this doesn't take e as an argument. That seems to imply that this information isn't stored in e at all.

But in Python > 3.2, the exception object will have a __traceback__ attribute which stores the traceback.

I'm interested in knowing:

Upvotes: 0

Views: 54

Answers (1)

user2357112
user2357112

Reputation: 281141

At a lower level, where is this information stored? (I know this may be an implementation detail).

It's sys.exc_info()[2]. This is not an implementation detail.

If you want the implementation details, sys.exc_info() is implemented in Python/sysmodule.c, and it retrieves the traceback from the exc_traceback member of the thread's PyThreadState.

Why was it not stored in e up until Python 3?

Historical reasons. Python used to not have exception objects at all; the old way used string objects as exceptions. That was a pretty bad system. When they introduced exception objects, they didn't move all the info from sys.exc_info to the exception object immediately.

Upvotes: 1

Related Questions