By using sys.setprofile(profilefunc) I can trace not only regular Python functions, but also builtin ones via the events "c_call" and "c_return", but I cannot find a way to get the return value of a builtin function.
For a regular function, the parameter arg, which is passed to profilefunc, refers to the return value if event equals "return".
However, if event equals "c_return", arg is the C function object.
Is there another way to retrieve the return value of a builtin function? Maybe by extracting from the frame the last value what was returned?
Here is a minimal example:
import sys
import numpy as np
from types import FrameType
def tracefunc(frame: FrameType, event: str, arg):
if event == 'call':
func_name = frame.f_code.co_name
print(f'Call_to {func_name}')
elif event == 'return':
func_name = frame.f_code.co_name
print(f'Return_from {func_name}, returning {arg}')
elif event == 'c_call':
func_name = arg.__name__
print(f'Call_to_builtin {func_name}')
elif event == 'c_return':
func_name = arg.__name__
print(f'Return_from_builtin {func_name}, returning ???')
return tracefunc
if __name__ == '__main__':
sys.setprofile(tracefunc)
# non-builtin function
foo = [x + 1 for x in [1, 2]]
# builtin function
bar = np.random.uniform()
sys.setprofile(None)
With the output
Call_to <listcomp>
Return_from <listcomp>, returning [2, 3]
Call_to_builtin uniform
Return_from_builtin uniform, returning ???
Call_to_builtin setprofile