Pro
Pro

Reputation: 727

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.

Upvotes: 19

Views: 5402

Answers (1)

gmds
gmds

Reputation: 19885

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.

Upvotes: 27

Related Questions