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

Lea*_*ima 6 python types type-hinting

假设以下代码:

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'")
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*x2a 6

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

也就是说,在您的特定情况下,您可以使用重载来表达您要执行的操作:

from typing import overload, Union

# Body of overloads must be empty

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

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

# 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'")
Run Code Online (Sandbox Code Playgroud)

  • 遗憾的是 Python 没有条件类型。例如,Typescript 具有此功能:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types。希望 Python 将来也能如此。 (7认同)