How do I write the function declaration using Python type hints for function returning multiple return values?
Is the below syntax allowed?
def greeting(name: str) -> str, List[float], int :
   # do something
   return a,b,c
                In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax.
To return multiple values from a function in Python, return a tuple of values. A tuple is a group of comma-separated values. You can create a tuple with or without parenthesis. To access/store the multiple values returned by a function, use tuple destructuring.
Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable, it can return zero, one, two or more variables. This is a unique property of Python, other programming languages such as C++ or Java do not support this by default.
We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.
EDIT: Since Python 3.9 and the acceptance of PEP 585, you should use the built-in tuple class to typehint tuples.
You can use a typing.Tuple type hint (to specify the type of the content of the tuple, if it is not necessary, the built-in class tuple can be used instead):
from typing import Tuple
def greeting(name: str) -> Tuple[str, List[float], int]:
    # do something
    return a, b, c
                        Multiple return values in python are returned as a tuple, and the type hint for a tuple is not the tuple class, but typing.Tuple.
import typing
def greeting(name: str) -> typing.Tuple[str, List[float], int]:
    # do something
    return a,b,c
                        Indexing on builtin tuple and list is now supported.
def greeting(name: str) -> tuple[str, list[float], int]:
    pass
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With