[Python-ideas] isinstance(Decimal(), Real) -> False?

Draic Kin drekin at gmail.com
Wed Aug 28 14:32:10 CEST 2013


On Wed, Aug 28, 2013 at 1:35 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com>wrote:

> On 28 August 2013 12:14, Draic Kin <drekin at gmail.com> wrote:
> >> Why shouldn't there be implicit conversion in Decimal arithmetic?
> >> There already is for all the other numeric types. Also explicit
> >> conversion seems to blocked in some cases. This one in particular
> >> bothers me (since it's often desirable to get a decimal representation
> >> of a fraction):
> >>
> >> $ python3.3
> >> Python 3.3.0 (default, Sep 29 2012, 17:14:58)
> >> [GCC 4.7.2] on linux
> >> Type "help", "copyright", "credits" or "license" for more information.
> >> >>> from decimal import Decimal as D
> >> >>> from fractions import Fraction as F
> >> >>> D(F(1, 2))
> >> Traceback (most recent call last):
> >>   File "<stdin>", line 1, in <module>
> >> TypeError: conversion from Fraction to Decimal is not supported
> >>
> > I would think that it's because you can express a fraction as finite
> decimal
> > expansion iff the prime decomposition of denominator contains only 2s and
> > 5s, since conceptualy decimal is just a fraction with power of 10 in
> > denominator. So Decimal is less expressible than Fraction.
>
> The same is true of float but float(Fraction) happily works and so
> does float(int), complex(int), float(Decimal) and Decimal(float)
> (depending on the context Decimal can be either a subset or a superset
> of float). A recent example where I wanted to do this was:
>
> def sum_exact(nums):
>     T = type(nums[0])
>     return T(sum(map(Fraction, nums)))
>
> The above sum function can happily sum anything that is convertible to
> Fraction (which includes Decimals in Python 3.3). However
> Decimal(Fraction) fails so you need something like:
>
> def sum_exact(nums):
>     T = type(nums[0])
>     if issubclass(T, Decimal):
>         return T.from_decimal(...)
>     else:
>        ...
>
> This just seems unnecessary to me.
>
> Maybe it's because float and complex don't care for exactness. On the
other hand Decimal always represent exactly the value of int and float but
it cannot represent exactly the value of Fraction(1, 3). But if would be
nice if one could make a decimal of given precision from fraction or make
exact decimal representaion of a fraction if it is possible and raise
exception otherwise.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130828/ce3e3795/attachment-0001.html>


More information about the Python-ideas mailing list