Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python force tuple return type to required one use one line

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading