[issue7633] decimal.py: type conversion in context methods

Mark Dickinson report at bugs.python.org
Tue Jan 5 18:49:24 CET 2010


Mark Dickinson <dickinsm at gmail.com> added the comment:

> What about the idea of changing the implementation from:
>
>        return a.__add__(b, context=self)
>
> to
>
>         return Decimal(a+b,context=self)
> ?

I think it would be better to convert the arguments a and b to Decimal before doing the addition.  In the case of addition, it doesn't make much difference:  for integers a and b, Decimal(a+b) rounded to the current context should be the same as Decimal(a) + Decimal(b).  But for e.g., division, Decimal(a/b) is potentially different from Decimal(a)/Decimal(b).

There's also the issue that the context methods can return 'NotImplemented'.  For example:

Python 2.7a1+ (trunk:77217:77234, Jan  2 2010, 15:45:27) 
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import *
>>> C = getcontext()
>>> C.add(Decimal(3), 'not a number')
NotImplemented

It's possible that a TypeError would make more sense here:  NotImplemented should really only be returned by direct invocation of the double underscore magic methods (__add__, etc.).

Any patch should include tests in Lib/test/test_decimal.py, of course!

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue7633>
_______________________________________


More information about the Python-bugs-list mailing list