python 中更好的打字提示?
Better typing hints in python?
当我使用联合类型时,我该如何具体说明,假设我编写了一个函数,它接受 str
或 list
并输出传入的任何类型,请考虑以下内容例子
from typing import Union
def concat(x1: Union[str, list], x2: Union[str, list]) -> Union[str, list]:
return x1 + x2
我希望上面的示例更具体,例如 x1
、x2
并且函数的返回值所有三个都必须匹配相同的类型,但这些类型必须是 str
或 list
.
from typing import TypeVar
T = TypeVar("T")
def concat(x1: T, x2: T) -> T:
return x1 + x2
打字库有一个 @overload
注释,可以执行您想要的操作。请注意,它与 java 等其他语言中的重载工作方式并不完全相同。您不能使用不同数量的参数创建重载。
来自文档:
@overload
def process(response: None) -> None:
...
@overload
def process(response: int) -> tuple[int, str]:
...
@overload
def process(response: bytes) -> str:
...
def process(response):
<actual implementation>
https://docs.python.org/3/library/typing.html#typing.overload
当我使用联合类型时,我该如何具体说明,假设我编写了一个函数,它接受 str
或 list
并输出传入的任何类型,请考虑以下内容例子
from typing import Union
def concat(x1: Union[str, list], x2: Union[str, list]) -> Union[str, list]:
return x1 + x2
我希望上面的示例更具体,例如 x1
、x2
并且函数的返回值所有三个都必须匹配相同的类型,但这些类型必须是 str
或 list
.
from typing import TypeVar
T = TypeVar("T")
def concat(x1: T, x2: T) -> T:
return x1 + x2
打字库有一个 @overload
注释,可以执行您想要的操作。请注意,它与 java 等其他语言中的重载工作方式并不完全相同。您不能使用不同数量的参数创建重载。
来自文档:
@overload
def process(response: None) -> None:
...
@overload
def process(response: int) -> tuple[int, str]:
...
@overload
def process(response: bytes) -> str:
...
def process(response):
<actual implementation>
https://docs.python.org/3/library/typing.html#typing.overload