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.
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.
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.
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.
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.
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.
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