当需要 str 和 float 时,为什么 bool 和 int 不被视为类型错误? [英] Why bool and int are not considered as a type error when str and float is required?
问题描述
使用 mypy 和 pyre-check 来检查以下代码的类型错误,都不会产生错误:
When using mypy and pyre-check to check type errors of the following code, neither produces an error:
from typing import List, Union
tlist: List[Union[str, float]] = [False, int(12)]
只是好奇这是为什么?
推荐答案
bool
是 int
的子类,这意味着它们都是自然数.自然数是实数的子集,因此在可以接受浮点数的情况下,它们也是可以接受的.
bool
is a subclass of int
, which means they are both natural numbers. Natural numbers are a subset of real numbers, so they are acceptable where a float is acceptable.
int
是可以接受的,其中 float
是在 PEP 484 -- 输入提示:
That int
is acceptable where float
is specified is explicitly called out in PEP 484 -- Type Hints:
与其要求用户编写import numbers
然后使用numbers.Float
等,本PEP提出了一个几乎同样有效的简单快捷方式:当一个参数是注释为具有 float
类型,int
类型的参数是可以接受的[.]
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
成为可接受的值.The
str
component in yourUnion[]
doesn't play any role here; you could remove it and still the assignment would be accepted. It's purely thefloat
type annotation that makes12
andFalse
acceptable values.int()
调用完全是多余的,12
文字语法已经生成了一个int
对象.The
int()
call is entirely redundant, the12
literal syntax already produces anint
object.这篇关于当需要 str 和 float 时,为什么 bool 和 int 不被视为类型错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!