当需要 str 和 float 时,为什么 bool 和 int 不被视为类型错误? [英] Why bool and int are not considered as a type error when str and float is required?

查看:27
本文介绍了当需要 str 和 float 时,为什么 bool 和 int 不被视为类型错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 mypypyre-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)]

只是好奇这是为什么?

推荐答案

boolint 的子类,这意味着它们都是自然数.自然数是实数的子集,因此在可以接受浮点数的情况下,它们也是可以接受的.

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 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 成为可接受的值.

    • The str component in your Union[] doesn't play any role here; you could remove it and still the assignment would be accepted. It's purely the float type annotation that makes 12 and False acceptable values.

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

      The int() call is entirely redundant, the 12 literal syntax already produces an int object.

      这篇关于当需要 str 和 float 时,为什么 bool 和 int 不被视为类型错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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