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?
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
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
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?
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
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