Python 类型提示联合
Python type hinting unions
我有一个带有两个参数的函数:
def same_type_params(param1: Union[str, int], param2: Union[str, int]):
pass
如何限制param1
和param2
的类型相等?即 str
或 int
使用 type variable:
from typing import TypeVar
T = TypeVar('T', str, int)
def same_type_params(param1: T, param2: T) -> None:
pass
我有一个带有两个参数的函数:
def same_type_params(param1: Union[str, int], param2: Union[str, int]):
pass
如何限制param1
和param2
的类型相等?即 str
或 int
使用 type variable:
from typing import TypeVar
T = TypeVar('T', str, int)
def same_type_params(param1: T, param2: T) -> None:
pass