python – mypy,type提示:Union [float,int] – >是否有Number类型?
作者:互联网
mypy非常方便并且捕获了很多错误,但是当我编写“科学”应用程序时,我经常最终会这样做:
def my_func(number: Union[float, int]):
# Do something
number是float或int,具体取决于用户的输入.有官方的方法吗?
解决方法:
仅使用float,因为int隐含在该类型中:
def my_func(number: float):
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 typefloat
, an argument of typeint
is acceptable; similar, for an argument annotated as having type complex, arguments of type float or int are acceptable.
(大胆强调我的).
理想情况下,你仍然会使用numbers.Real
:
from numbers import Real
def my_func(number: Real):
因为它会接受fractions.Fraction()和decimal.Decimal()对象;数字金字塔不仅仅是整数和浮点值.
但是,当使用mypy进行类型检查时,这些当前不起作用,请参阅Mypy #3186.
标签:type-hinting,python,mypy 来源: https://codeday.me/bug/20190910/1800777.html