I’ve been reading about magic methods in python, and I’ve found a lot of info about overriding them and what purpose they serve, but I haven’t been able to find where in the language specific operators and actions are mapped to those methods (+ looks for __add__, += looks for __iadd__, creating a new object from a class might call __new__ and __init__, etc.) Is there somewhere I can see what happens when the python interpreter (or whatever lower level mechanism) encounters a plus sign?
I’ve been reading about magic methods in python, and I’ve found a lot of
Share
Your question is a bit generic. There is a comprehensive list of “special methods”, even though it misses some stdlib specific methods(e.g.
__setstate__and__getstate__used bypickleetc. But it’s a protocol of the modulepicklenot a language protocol).If you want to know exactly what the interpreter does you can use the
dismodule to disassemble the bytecode:You can see that the intereper executes a
BINARY_ADDbyte code when doing addition.If you want to see exactly the operations that
BINARY_ADDdoes you can download Python’s source code and check theceval.cfile:So here we can see that python special cases int and string additions, and eventually falls back to
PyNumber_Add, which checks if the first operand implements__add__and calls it, eventually it tries__radd__of the right hand side and if nothing works raises aTypeError.Note that the byte codes are version-specific, so
diswill show different results on different versions:Also the same byte code may be optimized in future versions, so even if the byte code is the same different versions of python will actually perform different instructions.
If you’re interested in learning how python works behind the scenes I’d advise you to write some C extensions, following the tutorials and documentation that you can find on the official python’s website.