Answer a question

Suppose the following code:

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

It is easily seen that a str input leads to an int output and vice versa. Is there a way to specify the return type so that it encodes this inverse relationship?

Answers

There isn't really a natural way to specify a conditional type hint in Python at the moment.

That said, in your particular case, you can use @overload to express what you're trying to do:

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

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐