为什么在需要 str 和 float 时 bool 和 int 不被视为类型错误?
Why bool and int are not considered as a type error when str and float is required?
使用mypy and pyre-check检查以下代码的类型错误时,均未产生错误:
from typing import List, Union
tlist: List[Union[str, float]] = [False, int(12)]
只是好奇这是为什么?
bool
是int
的子类,也就是说它们都是自然数。自然数是实数的子集,因此在可接受浮点数的情况下它们也是可接受的。
中明确指出 int
在指定 float
的地方是可以接受的
Rather than requiring that users write import numbers
and then use numbers.Float
etc., this PEP proposes a straightforward shortcut that is almost as effective: when an argument is annotated as having type float
, an argument of type int
is acceptable[.]
Union[]
中的 str
组件在这里没有任何作用;您可以将其删除,但仍会接受分配。纯粹是 float
类型注释使 12
和 False
成为可接受的值。
int()
调用完全是多余的,12
文字语法已经生成了一个 int
对象。
使用mypy and pyre-check检查以下代码的类型错误时,均未产生错误:
from typing import List, Union
tlist: List[Union[str, float]] = [False, int(12)]
只是好奇这是为什么?
bool
是int
的子类,也就是说它们都是自然数。自然数是实数的子集,因此在可接受浮点数的情况下它们也是可接受的。
int
在指定 float
的地方是可以接受的
Rather than requiring that users write
import numbers
and then usenumbers.Float
etc., this PEP proposes a straightforward shortcut that is almost as effective: when an argument is annotated as having typefloat
, an argument of typeint
is acceptable[.]
Union[]
中的str
组件在这里没有任何作用;您可以将其删除,但仍会接受分配。纯粹是float
类型注释使12
和False
成为可接受的值。int()
调用完全是多余的,12
文字语法已经生成了一个int
对象。