Decimal, __radd__, and custom numeric types...

Kanenas kanenas_ at t_comcast_d.t_net
Tue Mar 1 02:42:09 EST 2005


On 28 Feb 2005 12:11:33 -0800, "Blake T. Garretson"
<blake.garretson at gmail.com> wrote:

[...]
>From the Python docs (specifically sections 3.3.7 and 3.3.8), I thought
>that the left object should try its own __add__, and if it doesn't know
>what to do, THEN try the right object's __radd__ method.  

To me it reads more like the interpreter is responsible for picking
which method to call.  Specifically, section 3.3.8 of the reference
manual states that y.__rop__() will be called if x.__op__() is not
implemented or returns NotImplemented.  The decision to call
y.__rop__() is made outside the x.__op__() method, implying that
x.__op__() doesn't handle a call to y.__rop__() in this case.  The
other rules dealing with whether x.__op__() or y.__rop__() is called
don't apply to your situation (but they could, keep reading).

>I guess
>Decimal objects don't do this?  Is there a way to change this behavior?
> If Decimal objects prematurely throw a TypeError before trying the
>__rop__, is Decimal broken, or was it designed this way?  I think I'm
>missing something...
>
You could change the behavior of Decimal.__add__ by patching it or you
could use subclassing.  If your classes are subclasses of Decimal,
their __rop__ methods will be called before Decimal.__op__ is tried.
I'm guessing your matrix and rational classes don't use decimal
representation, which makes this an OOP style-breaking kludge.




More information about the Python-list mailing list