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

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


On 28 August 2013 08:02, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 28 August 2013 11:47, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
>>
>> That seems plainly absurd to me. Decimals are quite clearly real
>> numbers. I then found the following in PEP-3141 [1]:
>> """
>> The Decimal Type
>>
>> After consultation with its authors it has been decided that the
>> Decimal type should not at this time be made part of the numeric
>> tower.
>> """
>>
>> What was the rationale for this decision and does it still apply?
>
> If I recall correctly, it was the fact that isinstance(d, Real)
> implies isinstance(d, Complex), yet there's no way to do complex
> arithmetic with Decimal real and imaginary components.

There's also no way to arithmetic with int/Fraction real and imaginary
components (e.g. gaussian integers etc.) but these are still instances
of Complex.

>From the PEP
'''
Complex defines the operations that work on the builtin complex type.

    In short, those are: conversion to complex, bool(), .real, .imag,
    +, -, *, /, **, abs(), .conjugate(), ==, and !=.
'''

Complex(decimal) works, Decimal defines all the above operations and
has .real and .imag attributes:

$ 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
>>> d = Decimal('4')
>>> complex(d)
(4+0j)
>>> bool(d)
True
>>> d.real
Decimal('4')
>>> d.imag
Decimal('0')
>>> d + d
Decimal('8')
>>> d - d
Decimal('0')
>>> d * d
Decimal('16')
>>> d / d
Decimal('1')
>>> d ** d
Decimal('256')
>>> abs(d)
Decimal('4')
>>> d.conjugate()
Decimal('4')
>>> d == d
True
>>> d != d
False


Oscar


More information about the Python-ideas mailing list