[issue30140] Binary arithmetic does not always call subclasses first

Guido van Rossum report at bugs.python.org
Mon Sep 17 12:53:37 EDT 2018


Guido van Rossum <guido at python.org> added the comment:

If anyone cares, here's what I recall of the history of this feature.

Originally my design was just

1. try left arg's __op__
2. if that returns NotImplemented, try right arg's __rop__

That's simple to explain and usually works. But when thinking through edge cases, we found that if the right class is a subclass of the left class, this gives unexpected results, so we added the exception

0. if the right class subclasses the left class *and it overrides __rop__*, try that first

I honestly believe that I didn't realize that it could ever matter if the right class subclasses the left class *without overriding __rop__*. And nobody else realized it either.

I think we decided on the "right class must override __rop__" condition in part to preserve the original, simpler rules for cases where we thought they would suffice, in part because for most users trying __rop__ before __op__ is unexpected, and in part because we didn't realize that it mattered.

And it only matters if the base class uses something like type(self) or self.__class__, which as a design pattern is sometimes dubious and other times useful.

Also note that the language Stephan quoted is somewhat different: it uses "provides" (__rop__) instead of "overrides". I could imagine that this, again, was a difference too subtle for most folks to notice.

If I had to do it over, I agree that if the right class subclasses the left class, we should always try __rop__ first. But now that this has been an ingrained behavior for so long I worry that it will break existing code, esp. in cases where there is an asymmetry between __op__ and __rop__ and the class author did not expect __rop__ ever to be called first.

Whether that's enough to stop this PR I think this is a question for the next BDFL to decide, alas. (I don't think it requires a PEP, it just requires someone to decide.)

----------
nosy: +gvanrossum
versions: +Python 3.8 -Python 3.7

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


More information about the Python-bugs-list mailing list