mypy,类型提示:Union [float,int]->是否存在数字类型?

时间:2018-06-19 12:33:56

标签: python type-hinting mypy

mypy确实很方便,并且捕获了许多错误,但是当我编写“科学的”应用程序时,我常常最终会这样做:

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

number是float或int,取决于用户的输入。有官方的方法吗?

4 个答案:

答案 0 :(得分:18)

仅使用float ,因为该类型隐含了int

def my_func(number: float):

PEP 484 Type Hints特别声明:

  

此PEP提出了一种简单而有效的快捷方式,而不是要求用户编写导入号然后使用numbers.Float等:当参数被注释为具有类型float时,可接受类型int的参数;类似,对于注释为复杂类型的参数,可以接受float或int类型的参数。

(加粗强调)。

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

from numbers import Real

def my_func(number: Real):

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

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

答案 1 :(得分:1)

您可以定义自己的类型来解决这个问题并保持代码简洁。

FloatInt = Union[float, int]

def my_func(number: FloatInt):
    # Do something

答案 2 :(得分:0)

对于那些针对更普遍的Union键入提示问题的人(例如validate,这些实体没有共同的超类型的实体),解决方案是导入Option Explicit Sub EnterRemainingValues() ' Define workbook. Dim wb As Workbook ' You might need to use '.xlsm' Set wb = Workbooks("Workbook 1") ' name of workbook ' Define worksheet. Dim ws As Worksheet Set ws = wb.Worksheets("Sheet1") ' Calculate last row. Dim lastrow As Long lastrow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row ' Write values. ws.Range("D14:D" & lastrow).Value = "427" End Sub 来自Union[int, numpy.ndarray]

示例1:

Union

示例2:

typing

答案 3 :(得分:0)

Python > 3.10 允许您执行以下操作。

def my_func(number: int | float) -> int | float: