为什么在需要str和float时bool和int不被视为类型错误?

2024-06-01 11:09:23 发布

您现在位置:Python中文网/ 问答频道 /正文

使用mypypyre-check检查以下代码的类型错误时,两者都不会产生错误:

from typing import List, Union

tlist: List[Union[str, float]] = [False, int(12)]

只是好奇为什么会这样


Tags: 代码fromimportfalsetyping类型check错误
1条回答
网友
1楼 · 发布于 2024-06-01 11:09:23

boolint的一个子类,这意味着它们都是自然数。自然数是实数的一个子集,所以当浮点数可以接受时,自然数是可以接受的

在指定了float的地方int是可接受的,在PEP 484 Type Hints中显式调用:

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类型的注释使得12False可以接受

  • int()调用是完全冗余的,12文本语法已经生成了一个int对象

相关问题 更多 >