Reputation: 17203
I would like to be able to inject a piece of code in the beginning of a given function.
Research mostly mentions using decorators, but for my specific use case I wouldn't want to wrap the modified function with an additional function call.
I am also unable to add a parameter to the function - I have an already compiled function at runtime and that's it.
The reason I wouldn't want to use a wrapper, is because I'd like to write a utility library which allows the programmer to "paste" a piece of code at the beginning of an already written function, without adding another level to the call stack at all. Mainly for performance reasons.
How can this be done? And would it work across Python versions without breaking?
Upvotes: 2
Views: 1180
Reputation: 7459
Premature optimization is the root of all evil. You should not "simply assume" a wrapper function will have a major performance impact. There is no safe, simple, portable, way to do what you're asking. The most applicable solution is a custom metaclass as it allows you to control the creation of new objects based on it.
Upvotes: 1