Return type annotation for Tuple in Python

Question:

I have function:

def func() -> tuple(str, list(str)):
    var_a = "four"
    var_b = ["one","two","three"]
    return var_a, var_b

And when I call it, it gives me the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not iterable

I have also tried it this way:

from typing import Tuple
def func() -> Tuple[str, list(str)]:
    var_a = "four"
    var_b = ["one","two","three"]
    return var_a, var_b

And, I am met with the exact same error.

How to have the proper return type annotation for this case?

Asked By: raghavsikaria

||

Answers:

By using List[str], the generic version of list:

from typing import List, Tuple

def func() -> Tuple[str, List[str]]:
    var_a = "four"
    var_b = ["one","two","three"]
    return var_a, var_b
Answered By: Brad Solomon

Instead of parentheses, try using square brackets ([ and ]):

def func() -> tuple[str, list[str]]:
    var_a = "four"
    var_b = ["one", "two", "three"]
    return var_a, var_b
Answered By: Joao-3
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.