0

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?

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.