mypy:为什么是“int"?“浮动"的子类型? [英] mypy: Why is "int" a subtype of "float"?

查看:52
本文介绍了mypy:为什么是“int"?“浮动"的子类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么mypy"将int"视为float"的子类型?子类型应支持其超类型的所有方法,但float"具有int"不支持的方法:

Why does "mypy" consider "int" as a subtype of "float"? A subtype shall support all methods of its supertype, but "float" has methods, which "int" does not support:

test.py:

def f(x : float) -> bool:
    return x.is_integer()

print(f(123.0))
print(f(123))

静态类型检查器接受为float"参数传递int"参数:

The static type checker accepts passing an "int" argument for a "float" parameter:

(3.8.1) myhost% mypy test.py
Success: no issues found in 1 source file

但这并不能保证运行时没有错误:

But this does not guarantee, that there are no errors at runtime:

(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"没有.

because "float" has additional methods, which "int" does not have.

推荐答案

'为什么mypy"将int"视为float"的子类型?'

'Why does "mypy" consider "int" as a subtype of "float"?'

因为到目前为止,实用性被认为优于纯粹性.这并不是说人们不能建议类型定义一个标量类型,它包括整数和浮点数,但只对算术运算有效.

Because practicality has so far been considered to beat purity here. This is not to say that one could not propose that typing define a Scalar type that would include ints and floats but only be valid for arithmetic operations.

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

Note that int / int was changed in 3.0 so that float(int / int) == float(int) / float(int), to make int and float arithmetic consistent for equal int and float values.

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

Note also that a type-check passing does not mean no runtime errors: division by zero and overflow are still possible, as well as many others.

这篇关于mypy:为什么是“int"?“浮动"的子类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆