I know about inlining, and from what I checked it is not done by the Python’s compiler.
My question is : is there any optimizations with the python’s compiler which transforms :
print myList.__len__()
for i in range(0, myList.__len__()):
print i + myList.__len__()
to
l = myList.__len__()
print l
for i in range(0, l):
print i + l
So is it done by the compiler ?
If it is not : is it worth it to do it by myself ?
Bonus question (not so related) : I like to have a lot of functions (better for readability IMHO)… like there is no inlining in Python is this something to avoid (lots of functions) ?
No, there isn’t. You can check what Python does by compiling the code to byte-code using the
dismodule:As you can see, the
__len__attribute is looked up and called each time.Python cannot know what a given method will return between calls, the
__len__method is no exception. If python were to try to optimize that by assuming the value returned would be the same between calls, you’d run into countless different problems, and we haven’t even tried to use multi-threading yet.Note that you would be much better off using
len(myList), and not call the__len__()hook directly: