mypy, type hint: Union[float, int] -> is there a Number type?

一个人想着一个人 提交于 2020-07-17 03:07:11

问题


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 is either a float or int, depending on the user's input. Is there an official way to do that?


回答1:


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

def my_func(number: float):

PEP 484 Type Hints specifically states that:

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.

(Bold emphasis mine).

Ideally you would still use numbers.Real:

from numbers import Real

def my_func(number: Real):

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

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



来源:https://stackoverflow.com/questions/50928592/mypy-type-hint-unionfloat-int-is-there-a-number-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!