【发布时间】:2021-11-28 23:00:18
【问题描述】:
为什么“mypy”将“int”视为“float”的子类型?子类型应支持其父类型的所有方法,但“float”具有“int”不支持的方法:
test.py:
def f(x : float) -> bool:
return x.is_integer()
print(f(123.0))
print(f(123))
静态类型检查器接受为“float”参数传递“int”参数:
(3.8.1) myhost% mypy test.py
Success: no issues found in 1 source file
但这并不能保证运行时没有错误:
(3.8.1) myhost% python test.py
True
Traceback (most recent call last):
File "test.py", line 5, in <module>
print(f(123))
File "test.py", line 2, in f
return x.is_integer()
AttributeError: 'int' object has no attribute 'is_integer'
因为“float”有额外的方法,而“int”没有。
【问题讨论】:
-
哦,哇,这对我来说似乎很糟糕,这是解释:mypy.readthedocs.io/en/latest/duck_type_compatibility.html
-
@BlackFrog 不,它不能。
-
@BlackFrog An
int不能放入浮点数。 Pythonints 不是机器ints。 (无论如何,我不确定这与类型检查有什么关系,这并不真正关心类型的运行时表示。) -
@StefanPochmann 是的,但如图所示,从类型系统 POV 来看,它不是
-
@StefanPochmann 感谢您发现这一点,我在 github 中寻找一些相关问题。但请注意,Guido 甚至在使用
.hex方法引用类似问题时说(可能是一个错误?)。虽然,我认为在这种情况下,这意味着应该实现int.hex,实际上,int.is_integer也可以实现。老实说,这对我来说是最好的解决方案。