15

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?

1 Answer 1

22

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'")
2
  • 6
    That's too bad that Python doesn't have conditional types. As an example, Typescript has this feature: typescriptlang.org/docs/handbook/release-notes/…. Hopefully Python will too in the future. Jan 14, 2020 at 14:45
  • what do you mean "doesn't have"? It's the same standard lib typing that you use for type annotations
    – Kukuster
    Sep 28 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.