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