Say I have built a library containing a Foo class, with support for some magic methods, say __add__() and __radd__():
>>> class Foo(object):
... def __add__(self, rhs):
... print("Foo.__add__", rhs)
... def __radd__(self, lhs):
... print("Foo.__radd__", lhs)
...
>>> foo = Foo()
>>> foo + 3
Foo.__add__ 3
>>> 3 + foo
Foo.__radd__ 3
When computing 3 + foo, python first calls type(3).__add__(3, foo), but as this returns NotImplemented, it falls back to type(foo).__radd__(foo, 3):
>>> type(3).__add__(3, foo)
NotImplemented
I would like developers to be able to build libraries on top of my library, say a library containing a class Bar, and I want them to have full control. In particular, I want to implement some mechanism that lets the other library decide whether foo + bar should call foo.__add__(bar) or bar.__radd__(foo).
I see that NumPy solved this using the __array_priority__ scheme. But this seems to cause some headaches (considering the number of questions and issues opened about this). Are there other best practices?