Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type hints for function returning multiple return values

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
like image 227
kivk02 Avatar asked Sep 25 '19 14:09

kivk02


People also ask

How do I return multiple values from a function in Python?

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.

How do I return more than 2 values in Python?

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.

Can a Python function return multiple?

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.

What is the best way to return multiple values from a function?

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.


3 Answers

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
like image 66
MrGeek Avatar answered Oct 02 '22 17:10

MrGeek


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
like image 33
kosayoda Avatar answered Oct 02 '22 16:10

kosayoda


Indexing on builtin tuple and list is now supported.

def greeting(name: str) -> tuple[str, list[float], int]:
    pass
like image 31
Luke Miles Avatar answered Oct 02 '22 15:10

Luke Miles