optimization – Python equivalence to inline functions or macros
optimization – Python equivalence to inline functions or macros
Is it possible to inline such a function, as I would do in C using macro or using inline keyword?
No. Before reaching this specific instruction, Python interpreters dont even know if theres such a function, much less what it does.
As noted in comments, PyPy will inline automatically (the above still holds – it simply generates an optimized version at runtime, benefits from it, but breaks out of it when its invalidated), although in this specific case that doesnt help as implementing NumPy on PyPy started only shortly ago and isnt even beta level to this day. But the bottom line is: Dont worry about optimizations on this level in Python. Either the implementations optimize it themselves or they dont, its not your responsibility.
Not exactly what the OP has asked for, but close:
Inliner inlines Python function calls. Proof of concept for this
blog
postfrom inliner import inline @inline def add_stuff(x, y): return x + y def add_lots_of_numbers(): results = [] for i in xrange(10): results.append(add_stuff(i, i+1))
In the above code the add_lots_of_numbers function is converted into
this:def add_lots_of_numbers(): results = [] for i in xrange(10): results.append(i + i + 1)
Also anyone interested in this question and the complications involved in implementing such optimizer in CPython, might also want to have a look at:
- Issue 10399: AST Optimization: inlining of function calls
- PEP 511 — API for code transformers (Rejected)
optimization – Python equivalence to inline functions or macros
Ill agree with everyone else that such optimizations will just cause you pain on CPython, that if you care about performance you should consider PyPy (though our NumPy may be too incomplete to be useful). However Ill disagree and say you can care about such optimizations on PyPy, not this one specifically as has been said PyPy does that automatically, but if you know PyPy well you really can tune your code to make PyPy emit the assembly you want, not that you need to almost ever.