Decimal, __radd__, and custom numeric types...

Blake T. Garretson blake.garretson at gmail.com
Mon Feb 28 15:11:33 EST 2005


I'm having some issues with decimal.Decimal objects playing nice with
custom data types.  I have my own matrix and rational classes which
implement __add__ and __radd__.  They know what to do with Decimal
objects and react appropriately.

The problem is that they only work with Decimals if the custom type is
on the left (and therefore __add__ gets called), but NOT if the Decimal
is on the left.  The Decimal immediately throws the usual "TypeError:
You can interact Decimal only with int, long or Decimal data types."
without even trying my __radd__ method to see if my custom type can
handle Decimals.

>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.  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...

Thanks,
Blake




More information about the Python-list mailing list