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?
Python – Where Operators are Mapped to Magic Methods
python
Best Answer
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 bypickle
etc. But it's a protocol of the modulepickle
not a language protocol).If you want to know exactly what the interpreter does you can use the
dis
module to disassemble the bytecode:You can see that the intereper executes a
BINARY_ADD
byte code when doing addition. If you want to see exactly the operations thatBINARY_ADD
does you can download Python's source code and check theceval.c
file: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
dis
will 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.