I have a function
function(input: str) -> Tuple[str, str]:
return tuple(x for x in input.split(","))
The input is always ‘value1, value2’, however, I got an error message of: "Tuple[str, …]", expected "Tuple[str, str]")
Is there anyway force the return type to the expected one just use one line of code?
>Solution :
The interpreter has no idea how many elements x for x in input.split(",") will produce – from its perspective, input could be anything. Accordingly, it classifies the returned type as Tuple[str, ...].
To get it to use a return type of Tuple[str, str], which you marked the method as, you need to explicitly return exactly two elements:
def function(input: str) -> Tuple[str, str]:
tup = input.split(',')
return (tup[0], tup[1])
or otherwise, annotate the method differently.
as a one-liner you could use a list slice:
def function(input: str) -> Tuple[str, str]:
return tuple(input.split(','))[:2]