2017-05-29 54 views
2

假設以下代碼:有沒有辦法在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輸出,反之亦然。有沒有辦法指定返回類型,以便它編碼這種反比關係?

回答

3

目前沒有一種真正自然的方式在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'")