close

How to specify multiple return types using type-hints

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to specify multiple return types using type-hints in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to specify multiple return types using type-hints?

  1. How to specify multiple return types using type-hints?

    In case anyone landed here in search of “how to specify types of multiple return values?”, use Tuple[type_value1, ..., type_valueN]

  2. specify multiple return types using type-hints

    In case anyone landed here in search of “how to specify types of multiple return values?”, use Tuple[type_value1, ..., type_valueN]

Method 1

In case anyone landed here in search of “how to specify types of multiple return values?”, use Tuple[type_value1, ..., type_valueN]

from typing import Tuple

def f() -> Tuple[dict, str]:
    a = {1: 2}
    b = "hello"
    return a, b

Method 2

Python 3.10 (use |): Example for a function which takes a single argument that is either an int or str and returns either an int or str:

def func(arg: int | str) -> int | str:
              ^^^^^^^^^     ^^^^^^^^^ 
             type of arg   return type

Python 3.5 – 3.9 (use typing.Union):

from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
              ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
                type of arg         return type

For the special case of X | None you can use Optional[X].

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read