4

The python Decimal object is not currently specified a subclass of the Real abstract base class:

from numbers import Real
from decimal import Decimal

isinstance(Decimal("1.0"), numbers.Real) #  False

This is easily changed by registering Decimal as a subclass:

Real.register(Decimal)

But it makes me ask the question: why is Decimal not registered this way to begin with? Is there some practical reason, or design reason, that it would be a bad idea to make this assumption about decimal instances?

Rick
  • 43,029
  • 15
  • 76
  • 119
  • I think you can just take this as a sign of how low adoption of those ABCs is. – user2357112 Apr 12 '19 at 17:00
  • @user2357112 fair point. i'm the only person on the planet i've even seen try to make use of them. – Rick Apr 12 '19 at 17:01
  • i swear i searched for this question and did not find anything. how did i miss that duplicate? ah well. – Rick Apr 12 '19 at 17:03

1 Answers1

4

Answer is in numbers module source:

## Notes on Decimal
## ----------------
## Decimal has all of the methods specified by the Real abc, but it should
## not be registered as a Real because decimals do not interoperate with
## binary floats (i.e.  Decimal('3.14') + 2.71828 is undefined).  But,
## abstract reals are expected to interoperate (i.e. R1 + R2 should be
## expected to work if R1 and R2 are both Reals).

they probably can add this to docs, I think.

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
  • The source code line `503` says basically the same thing as well: [_pydecimal.py](https://github.com/python/cpython/blob/master/Lib/_pydecimal.py). But it references `numbers` which you pasted above. – Error - Syntactical Remorse Apr 12 '19 at 17:04