If I have two objects A
and B
, I can return NotImplemented
for A
's __iadd__
method and have B
modify A
using it's __radd__
method.
>>> class A():
... def __init__(self, val):
... self.val = val
... def __iadd__(self, other):
... return NotImplemented
... def __ipow__(self, other):
... return NotImplemented
...
>>> class B():
... def __init__(self, val):
... self.val = val
... def __radd__(self, other):
... return A(other.val + self.val)
... def __rpow__(self, other):
... return A(other.val ** self.val)
...
>>> a = A(2)
>>> b = B(2)
>>> a += b
>>> a.val
4
This seems to work for all inplace operators with the exception of __ipow__
where a TypeError
is raised.
>>> a **= b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'A' and 'B'
Why is the behavior different here? Is this failing because pow()
requires numeric data? What is the best workaround for this?