Getting the raised exception in a sys.setprofile trace function

I’m working on a tool that introspects running python code using a sys.setprofile trace function. When an exception is raised by an introspected function, I would like to obtain the exception object somehow so I can introspect it, but I can’t work out how to do this.

The documentation says:

'return'

A function (or other code block) is about to return. The local trace function is called; arg is the value that will be returned, or None if the event is caused by an exception being raised. The trace function’s return value is ignored.

When handling the return frame, is there a way to distinguish between the case when an exception is raised and the case when the function just returned None?

Do I have to switch to the more complicated sys.settrace to deal with this case? I’m only interested (right now) in exceptions that bubble out of the function I’m introspecting causing an early return, not any caught locally and handled.

I have tried using sys.exception(), but this just returns None.

Afaik sys.exception only makes sense inside an exception handler, not after the fact. I’m not very familiar with the sys.setprofile function, so don’t know if it’s at all possible to use that for your purpose - I kind of think it’s not possible to do so. Seems sys.settrace is a lot easier to use here since it hands you “exception” as a separate event - and if those are the only events you want to trace, you could condition it on that.

Unfortunately sys.settrace is a lot more overhead (it traces every single line of Python code) and as far as I know, it doesn’t trace calls to C functions.