Decimal, __radd__, and custom numeric types...

From: Blake T. Garretson (blake.garretson_at_gmail.com)
Date: 02/28/05


Date: 28 Feb 2005 12:11:33 -0800

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



Relevant Pages

  • RE: Packed decimal arithmetic in C
    ... you need to run computations in more than 5 decimals places, ... >Incoming mail is certified Virus Free. ... Outgoing mail is certified Virus Free. ...
    (comp.os.vms)
  • Re: Decimal, __radd__, and custom numeric types...
    ... > custom data types. ... > The problem is that they only work with Decimals if the custom type is ... > You can interact Decimal only with int, long or Decimal data types." ... TypeError exception is raised. ...
    (comp.lang.python)
  • Re: Subtraction Giving an incorrect value
    ... better, but if you don't specify, the floating point numbers get treated as ... Currency and Decimal don't ... VBA, so to use Decimal data types, you have to use Variants and the CDec ... round off the result to the number of decimals you need. ...
    (microsoft.public.access.forms)
  • Re: Strange calculation
    ... number data types, and they're all adequate to hold enough ... decimals. ... Dim cat ... Set con = CreateObject ...
    (microsoft.public.access.forms)
  • Re: Simple math is giving me trouble
    ... It's a C# cast. ... > For the sake of learning what the do in Adults)? ... >> integers to other numeric data types. ... In any case, use all somethings (decimals, doubles, whatever ...
    (microsoft.public.dotnet.framework.aspnet)