Info node 'Emulating numeric types' says:
__radd__(self, other)
__rsub__(self, other)
...
These functions are only called if the left operand
does not support the corresponding operation.
Not so. Info node 'Coercion rules' lists one exception:
if the left operand is an instance of a built-in
type or a new-style class, and the right operand is
an instance of a proper subclass of that type or
class, the right operand's `__rop__()' method is
tried _before_ the left operand's `__op__()' method.
...and one time where above the text is misleading:
When either operand type defines a coercion, this
coercion is called before that type's `__op__()' or
`__rop__()' method is called, but no sooner. If the
coercion returns an object of a different type for
the operand whose coercion is invoked, part of the
process is redone using the new object.
Thus, Python can call __rop__(self, other) even if
self.__op__ exists: If one does `x - y' where
y.__coerce__(x) coerces x to y's class, y.__rsub__(x)
is called instead of (coerced x).__sub__(y). I think
this should be documented in the 'Emulating numeric
types' node. Unless Python is changed to redo the
choice between __op__, __rop__ and __iop__ after
coercion.
I think it would also be good to explain in that Info
node what __op__ and __rop__ can do if they do not
support the operation with the supplied arguments, but
the other argument might support it. It seems obvious
that self.__op__(other) can simply attempt to call
other.__rop__(self) and let that fail if it is not
supported. However, the above rules seem to mean that
self.__rop__(other) might want to call
other.__op__(self) too, which could lead to infinite
recursion. Are there some special times where it can
do that, and other times where it should not?
|