我有一个函数
my_function
,它接受两个参数:x
和method
。根据 method
的值,将使用两个助手之一:helper1
和 helper2
。这两个助手将 x
作为参数:helper1
期望它是一个整数,而 helper2
期望它是一个浮点数。这两个助手都可以由用户独立使用,从而检查 x
的类型,如果类型错误则引发错误。下面是我的代码,带有类型提示:
from typing import Literal
def helper1(x: int):
if not isinstance(x, int):
raise ValueError("x should be an integer.")
# Do some stuff.
def helper2(x: float):
if not isinstance(x, float):
raise ValueError("x should be a float.")
# Do some stuff.
def my_function(x: int | float, method: Literal[1, 2]):
match method:
case 1:
return helper1(x)
case 2:
return helper2(x)
case _:
raise ValueError(f"Invalid method: {method}.")
Mypy 将在调用
helper1
时引发错误,因为 int | float
中的 x
类型与 int
中的预期类型 helper1
不兼容。这里推荐的取悦 mypy 的方法是什么?我应该在调用 my_function
之前重复 helper1
中的类型检查吗?
由于
helper1()
中的参数可以采用 int 或 float 类型的 x,因此您也应该使用 def helper1(x: int | float):
。这将满足 mypy 并满足您的代码的期望。 helper2()
也一样。