Let's say I built a library containing the Foo
class with support for some magic methods, for example __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 evaluating 3 + foo
, python first calls type(3).__add__(3, foo)
, but since this returns NotImplemented
, it returns to type(foo).__radd__(foo, 3)
:
>>> type(3).__add__(3, foo) NotImplemented
I would like for developers to be able to build libraries on top of my library, say, a library containing the Bar
class, and I want them to have full control. In particular, I want to implement some mechanism that allows another library to decide whether foo + bar
call foo.__add__(bar)
or bar.__radd__(foo)
.
I see that NumPy solved this with the __array_priority__
schema. But this, apparently, causes some headaches (given the number of questions and problems open about this). Are there any other recommendations?
source share