为什么'decimal.Decimal(1)'不是'numbers.Real'的一个实例?

2022-01-17 00:00:00 python decimal numbers isinstance

问题描述

我尝试检查一个变量是否是任何类型(intfloatFraction十进制等).

I try to check if a variable is an instance of a number of any type (int, float, Fraction, Decimal, etc.).

我遇到了这个问题及其答案:如何正确使用 python 的 isinstance() 检查变量是否为数字?

I cam accross this question and its answer: How to properly use python's isinstance() to check if a variable is a number?

但是,我想排除复数,例如 1j.

However, I would like to exclude complex numbers such as 1j.

numbers.Real 看起来很完美,但它为 <返回 Falsecode>十进制 数字...

The class numbers.Real looked perfect but it returns False for Decimal numbers...

from numbers Real
from decimal import Decimal

print(isinstance(Decimal(1), Real))
# False

相反,它适用于 Fraction(1) 例如.

In contradiction, it works fine with Fraction(1) for example.

文档描述了一些应该与数字,我在十进制实例上测试它们没有任何错误.此外,十进制对象不能包含复数.

The documentation describes some operations which should work with the number, I tested them without any error on a decimal instance. Decimal objects cannot contains complex numbers moreover.

那么,为什么 isinstance(Decimal(1), Real) 会返回 False?

So, why isinstance(Decimal(1), Real) would return False?


解决方案

所以,我直接在cpython/numbers.py:

So, I found the answer directly in the source code of cpython/numbers.py:

## 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).

确实,将 Decimal 添加到 float 会引发 TypeError.

Indeed, adding Decimal to float would raise a TypeError.

在我看来,它违反了最小惊讶的原则,但没关系.

In my point of view, it violates the principle of least astonishment, but it does not matter much.

作为一种解决方法,我使用:

As a workaround, I use:

import numbers
import decimal

Real = (numbers.Real, decimal.Decimal)

print(isinstance(decimal.Decimal(1), Real))
# True

相关文章