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

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Aug 28 13:35:48 CEST 2013


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.


Oscar


More information about the Python-ideas mailing list