mypy 确实很方便并且捕获了很多错误,但是当我编写“科学”应用程序时,我经常最终会这样做:
def my_func(number: Union[float, int]):
# Do something
number
是 float 或 int,具体取决于用户的输入。有官方的方法可以做到这一点吗?
Use float
only, as int
隐含在该类型中:
def my_func(number: float):
PEP 484 类型提示 https://www.python.org/dev/peps/pep-0484/#the-numeric-tower特别指出:
而不是要求用户写入导入编号然后使用numbers.Float
等等,这个 PEP 提出了一个几乎同样有效的简单捷径:当参数被注释为具有类型时float
,类型参数int
是可以接受的;类似地,对于注释为复杂类型的参数,float 或 int 类型的参数是可接受的。
(粗体强调我的)。
理想情况下你仍然会使用numbers.Real https://docs.python.org/3/library/numbers.html#numbers.Real:
from numbers import Real
def my_func(number: Real):
因为那样会接受fractions.Fraction()
and decimal.Decimal()
也有物体;数字金字塔比整数和浮点值更广泛。
然而,这些目前在使用时不起作用mypy
要进行类型检查,请参阅我的py #3186 https://github.com/python/mypy/issues/3186.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)