Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> dereferences the pointers to get the integer values

Doesn't it find a method of x that implements addition?



Nope! There's a branch in the interpreter that checks if both operands are Python's built-in int objects. If they are, and the result can fit in a C int without overflow, then the interpreter adds the numbers directly. This is by far the most common case.


How can the interpreter know, at bytecode compilation time, that x is bound to an int? Surely it generates two code paths, one for the "common case" and another for when x is a general object with an __add__ method?


The test is in the interpreter, not the compiler to byte-code. Every time the + is evaluated, the interpreter checks for the common case before resorting to finding the first object's method.


Okay, I think I get it now. The check you refer to is done inside the BINARY_ADD implementation. That's why the bytecode is the same for both cases. Am I right?


Yes, as you say, it's not known at compile-time and is checked at interpretation time, each time. http://hg.python.org/cpython/file/b49971a1e70d/Python/ceval....


Thanks. And wow, the CPython source code seems to be very much readable. I've been meaning to dive further into Python internals for a while, maybe this is the time to do so.


Interesting, thanks.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: