sys.settrace is inefficient, to say the least. It adds a lot of overhead to every function call in Python.
Instead, I'm looking for a way to trace the "call" event for only a couple hundred functions in Python, without incurring additional overhead. I'm thinking of modifying the code object for each function so that they all call a tracing function.
import sys
def trace():
frame = sys._getframe(1)
...
def func():
trace() # TODO: Add programmatically
...
Does anyone know how to do this? So far, I've found these resources...
- https://hardenedapple.github.io/stories/computers/python_function_override/
- Hooking every function call in Python
- Modifying Code of Function at Runtime
I can't be the only person interested in low overhead localized tracing? Thank you for any help you can provide me!
Okay, so following the approach outlined in Modifying Code of Function at Runtime, I took a stab at it...
And I tested this on classes, closures, decorators, line numbers, traceback, globals...
Let me know if I'm missing anything, please! I don't have much experience with code editing.
Here is my fully working library implementation (tested in a production code base!): https://github.com/PetrochukM/HParams/blob/master/config/trace.py