Which method is called for a binary operator?

In Python, binary operators are generally syntactic sugar for a call to a corresponding “dunder” (double underscore) method. For instance, ‘x + y’ (usually) desugars into

But there's more to the story, because either type (‘type(x)’ or ‘type(y)’) should have a chance to specify the behavior, and because subclasses should have a chance to override the behavior of a superclass.

To allow the rhs to specify the behavior, there is also a “reflected dunder” method for each operator (‘__add__’ → ‘__radd__’). (If a type wants an operator to be symmetric, it will use the same implementation for both the dunder and the reflected dunder.)

The decision tree is not _that_ complex, but it is specified piecemeal in the language reference. Piecing it together, you get:

§3.3.8 Emulating numeric types [Python language reference]

» Languages » Python