【问题标题】:Is there a way to specify a conditional type hint in Python?有没有办法在 Python 中指定条件类型提示?
【发布时间】:2017-10-29 06:09:24
【问题描述】:

假设如下代码:

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 types type-hinting


    【解决方案1】:

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

    也就是说,在您的特定情况下,您可以使用@overload 来表达您想要做的事情:

    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'")
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 2021-01-04
    • 2021-07-24
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 2018-10-18
    相关资源
    最近更新 更多