I have a function:
def foo(a, b):
return [a, b]
I want to add type hinting for return value, as you can see my function can return [srt, int]
or [str, str]
or [int, int]
etc. for example.
I tried:
def foo(a, b) -> List[str, int]:
return [a, b]
but it not working.
How can I specify possible value in list that my function can return?
You can use Union
. Specifically, Union[X, Y]
means either X or Y.
from typing import List, Union
def foo(a, b) -> List[Union[str, int]]:
return [a, b]
If your function can return a list containing any element, then use Any
(special type indicating an unconstrained type):
from typing import Any, List
def foo(a, b) -> List[Any]:
return [a, b]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.