有没有办法在Python中指定条件类型提示?

问题描述:

假设以下代码:有没有办法在Python中指定条件类型提示?

from typing import Union 


def invert(value: Union[str, int]) -> Union[int, str]: 
    if isinstance(value, str): 
     return int(value) 
    elif isinstance(value, int): 
     return str(value) 
    else: 
     raise ValueError("value must be 'int' or 'str'") 

它很容易看出,str输入导致一个int输出,反之亦然。有没有办法指定返回类型,以便它编码这种反比关系?

目前没有一种真正自然的方式在Python中指定条件类型提示。

这就是说,你的具体情况,您可以使用overloads来表达你想要做什么:

from typing import overload, Union 

# Body of overloads must be empty 

@overload 
def invert(value: str) -> int: 
    pass 

@overload 
def invert(value: int) -> str: 
    pass 

# Implementation goes last, without an overload. 
# Adding type hints here are optional -- if they 
# exist, the function body is checked against the 
# provided hints. 
def invert(value: Union[int, str]) -> Union[int, str]: 
    if isinstance(value, str): 
     return int(value) 
    elif isinstance(value, int): 
     return str(value) 
    else: 
     raise ValueError("value must be 'int' or 'str'")