Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function annotation with two or more return parameters

When I write an annotation for a function which returns one parameter, I have no problems.

def func() -> str:
    return "ok"

However, when I write an annotation with two or more parameters, my PyCharm gives me SyntaxError: invalid syntax.

def func() -> str, str:
    return "ok - 1", "ok - 2"

I think that the parameters can be combined with a tuple, but I don't think that's the best way to do it.

My question is: how can I properly annotate a function with two or more return parameters?

Please include a PEP link, if any, in your response. I looked for the answer at PEP 484 and PEP 3107 and could not find it.

like image 489
Pro Avatar asked May 07 '19 02:05

Pro


People also ask

Can a function have multiple return types Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

What Python data structure allows for the return of multiple items from a function?

Return multiple values using commas 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.

What is Typevar in Python?

It is a type variable. Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions.

What is type annotation in Python?

Type annotations — also known as type signatures — are used to indicate the datatypes of variables and input/outputs of functions and methods. In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype — the code will not run.


1 Answers

Use typing.Tuple:

from typing import Tuple

def func() -> Tuple[str, str]:
    return 'a', 'b'

This is appropriate because, conceptually, you are actually returning a single tuple containing those values. Note:

print(type(func()))

Output:

<class 'tuple'>

Except for the empty tuple (()), parentheses are not necessary to define a tuple, which means that 'a', 'b' is created as a tuple, rather than being separate values gathered into one by the return statement.

like image 159
gmds Avatar answered Sep 21 '22 11:09

gmds