基本上,我在 PyCharm 中的语句 math.isclose(a_val, b_val)
预期类型为“SupportsFloat”,得到的是“Number”
最小的、可重现的例子如下。
from numbers import Number
import math
a_val = '123'
b_val = 123.4
if isinstance(a_val, Number) and isinstance(b_val, Number):
is_close = math.isclose(a_val, b_val, abs_tol=0.5)
实际上,a_val
和 b_val
来自其他地方,可以返回 float 、整数或字符串。如果 a_val
和 b_val
都是数字,我想检查它们是否几乎相等。否则,如果其中任何一个是字符串,就忽略它。
问题 - 在将 a_val
和 b_val
传递给 math.isclose()
之前进行类型检查的最佳方法是什么?清除 PyCharm wanring 应该做哪些更改?
最佳答案
math.isclose
不支持任意Number
实例。与大多数 math
函数一样,math.isclose
需要可以转换为 float
的参数。 Number
可能类似于 1+2j
,它不能转换为 float
。 (此外,str
不算数 - 它必须是带有 __float__
方法的东西。)
我本来打算建议使用 typing.SupportsFloat
,但看起来我误读了代码,typing.SupportsFloat
不支持 isinstance
检查。如果您的唯一选项是 str
、float
和 int
,那么最简单的方法可能是只检查 float
和 int
,或者换一种方式拒绝 str
:
if isinstance(a_val, (float, int)) and isinstance(b_val, (float, int)):
...
或
if not isinstance(a_val, str) and not isinstance(b_val, str):
...
关于python - math.isclose() 的类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58298650/