[issue30140] Binary arithmetic does not always call subclasses first

Mark Dickinson report at bugs.python.org
Mon Apr 24 03:21:50 EDT 2017


Mark Dickinson added the comment:

> could you point me to where this logic is implemented in CPython's source?

Most of the relevant code is in Objects/abstract.c and Objects/typeobject.c.

A BINARY_ADD opcode (for example) ends up calling PyNumber_Add:

    https://github.com/python/cpython/blob/v3.6.1/Objects/abstract.c#L913

which in turn calls binary_op1, where you see an explicit check for the nb_add slots of the two operands being identical:

    https://github.com/python/cpython/blob/v3.6.1/Objects/abstract.c#L769-L770

For a user-defined class, the slots themselves are defined in typeobject.c. Here's where nb_add is defined:

    https://github.com/python/cpython/blob/v3.6.1/Objects/typeobject.c#L5952

and here's the explicit check for overloading in the SLOT1BIN macro definition:

    https://github.com/python/cpython/blob/v3.6.1/Objects/typeobject.c#L5796

There's also an explicit test for the arithmetic operation behaviour in Lib/test/test_descr.py. In short, I doubt this was ever a bug: everything points to this being a deliberate design decision. I hope someone on python-ideas can elaborate on the rationale behind that design decision (and also on why that rationale doesn't apply to comparisons).

In contrast, it does seem plausible to me that the *comparison* failure to check for an explicit override may have been accidental.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue30140>
_______________________________________


More information about the Python-bugs-list mailing list