mypy,输入提示:Union[float, int] ->有数字类型吗? [英] mypy, type hint: Union[float, int] -> is there a Number type?

查看:192
本文介绍了mypy,输入提示:Union[float, int] ->有数字类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mypy 真的很方便,可以捕获很多错误,但是当我编写科学"应用程序时,我经常会这样做:

mypy is really handy and catches a lot of bugs, but when I write "scientific" applications, I often end up doing:

def my_func(number: Union[float, int]):
    # Do something

number 是浮点数或整数,取决于用户的输入.有官方的方法吗?

number is either a float or int, depending on the user's input. Is there an official way to do that?

推荐答案

使用 float only,因为 int 隐含在该类型中:

Use float only, as int is implied in that type:

def my_func(number: float):

PEP 484 类型提示 特别声明:

这个 PEP 不是要求用户编写导入数字然后使用 numbers.Float 等,而是提出了一个几乎同样有效的简单快捷方式:当参数被注释为具有类型时floatint 类型的参数是可以接受的;类似的,对于注释为 complex 类型的参数,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; similar, for an argument annotated as having type complex, arguments of type float or int are acceptable.

(粗体强调我的).

理想情况下,您仍会使用 numbers.Real:

Ideally you would still use numbers.Real:

from numbers import Real

def my_func(number: Real):

因为它也接受 fractions.Fraction()decimal.Decimal() 对象;数字金字塔不仅仅是整数和浮点值.

as that would accept fractions.Fraction() and decimal.Decimal() objects as well; the number pyramid is broader than just integers and floating point values.

但是,当使用 mypy 进行类型检查时,这些当前不起作用,请参阅 Mypy #3186.

However, these are not currently working when using mypy to do your type checking, see Mypy #3186.

这篇关于mypy,输入提示:Union[float, int] ->有数字类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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