Can I declare a function return value if it returns multiple types?

Viewed 120

Suppose I have a function like this:

def A(test=False):
    if test:
        return 1
    return "no value passed in for test"

In Typescript, you can do something like

function A(test=false) <number | string> {
    ...
}

But if I try to do same thing with Python, I get an error.

def A(test=False) -> (int, str):

def A(test=False) -> [int, str]:

def A(test=False) -> int or str:

I understand Python better with dealing with ambiguity in type checking. So this probably is a non issue. but I am interested if there is a correct way of doing that.

1 Answers

Use typing.Union for an "either or" relation of multiple types.

from typing import Union

def fn(test=False) -> Union[str, int]:
    if test:
        return 1
    return "no value passed in for test"

In Python 3.10, the binary-or operator | can be used to create unions as per PEP 604:

def fn(test=False) -> str | int:
    if test:
        return 1
    return "no value passed in for test"
Related