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

How to convert list[int, int, int] to tuple[int, int, int] and not tuple[int, …]

Suppose I have 2 functions, func1 and func2. func1 returns a list of 3 integers, and func2 takes a tuple of 3 integers, how would I convert the list to a tuple in such a way that I can prevent errors by type checkers (I am using mypy).
Here is the code that is throwing error:

var1: list[int, int, int] = func1()
func2(tuple(var1))

Error thrown at func2 call:
Expected type 'tuple[int, int, int]', got 'tuple[int, ...]' instead.

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 :

List types do not contain information about their length. (list[int, int, int] is not a list of length 3; mypy doesn’t even accept it.) Ideally, mypy could examine a hard-coded slice object to infer that tuple(var1[:2]]) has type tuple[int, int, int], but that is not the case (at least, today).

In the mean time, you can construct the tuple explicitly:

func2((var1[0], var1[1], var1[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