简体   繁体   中英

Type-hint different number of return values with python mypy

I'm wondering how to type-hint something sucha s the following:

from typing import Any, Union, Dict, Tuple

# here x is 
def f(x : str) -> Union[Tuple[int, bool], Tuple[int, str, float]]:
    if 'something' in x:
        return 1, 'this', 3.0
    return 1, True


a,b = f(x = 'this is something')
x,y,z = f(x = 'this is')

This raises the error:

main.py:9: error: Too many values to unpack (2 expected, 3 provided)
main.py:10: error: Need more than 2 values to unpack (3 expected)

So the problem is fairly clear - i have a method which can return two different sets of values, but the expected solution ( Union ) doesn't work as I expected.

If the function is always returning a tuple of int s, you can try this solution:

def f() -> tuple[int, ...]:

The tuple[int,...] type is saying that this function is going to return a tuple containing integers only.

Guessing from the error messages: you are using mypy. This static type checker cannot determine the return type based on the function's arguments.

In your example you need to know which of the two possibilities the return type should be so you can use one of two solutiuons:

Constants for the return variants in the (changing) question:

CASE2 = 'this is something'
FReturn2 = Tuple[int, bool]

CASE3 = 'this is'
FReturn3 = Tuple[int, str, float]

Assert

f_return = f(x=CASE2)
assert len(f_return) == 2
a, b = f_return
f_return = f(x=CASE3)
assert len(f_return) == 3
x, y, z = f_return

Assert checks the length at run time and throws Assertion Error optionally with your error message when it is different.

Cast

a, b = cast(FReturn2, f(x=CASE2))
x, y, z = cast(FReturn3, f(x=CASE3))

Cast does not alter the run time behaviour. The assignment statement will fail then the number of the tuple elements will not match the left side. Of course you can specify the complex type directly, the type variable is there to accommodate the changing question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM