How to create a traceback object

python, traceback

Solution

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.

Problem

I want to create a traceback like the one returned by sys.exc_info()[2]. I don't want a list of lines, I want an actual traceback object: ``` <traceback object at 0x7f6575c37e48> ``` How can I do this? My goal is to have it include the current stack minus one frame, so it looks the the caller is the most recent call.

Original source