python - mypy:为什么 "int"是 "float"的子类型?

标签 python mypy

为什么“mypy”将“int”视为“float”的子类型?子类型应支持其父类(super class)型的所有方法,但“float”具有“int”不支持的方法:

测试.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”将“int”视为“float”的子类型?

因为到目前为止,实用性被认为在这里击败了纯度。这并不是说人们不能建议打字定义一个标量类型,它包括整数和浮点数,但只对算术运算有效。

请注意,int/int 在 3.0 中已更改,因此 float(int/int) == float(int)/float(int),以使 int 和 float 算术对于相等的 int 和 float 值保持一致。

另请注意,类型检查通过并不意味着没有运行时错误:除以零和溢出仍然可能,以及许多其他错误。

关于python - mypy:为什么 "int"是 "float"的子类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59619778/

相关文章:

python - 什么是好的 Django 工作流程?

python - aiohttp Websocket 客户端和 HTTP 服务器

python - 如何安全地删除 Django 中的模型字段?

python - 上下文管理器处理路径的类型提示

mypy - 为什么 mypy 不从@overload 推断函数注解?

python - 如果一个类有 __len__ 和 __getitem__ 但没有 __iter__,为什么 mypy 不认为它是可迭代的

Python >=3.5 : Checking type annotation at runtime

python - ReviewBoard pip 安装失败

python - pandas 在 grouby 之后按日期时间过滤

python - mypy 找不到模块 'dropbox'