Python annotations: difference between Tuple and ()
9 votes
Since python 3.6 (or 3.4 ? I don't remember) we can annotate a function. Ex:
def getVersion() -> str:
Now what happens when a function returns a tuple ? We can do that:
def func() -> tuple:
But if we know the tuple is a tuple of two integers ? I read here: How to annotate types of multiple return values? that we can do that:
def func() -> Tuple[int, int]
But it requires to import the typing module.
Also I tried that:
def func() -> (int, int):
And it doesn't crash.
What is the right way ?
edited Jul 23, 2024 at 5:13 by InSync
asked Nov 7, 2017 at 16:37 by JPFrancoia
1 answers
7 votes
Annotations can be used for anything you like: they are arbitrary Python expressions (there are ongoing discussions about breaking this in future Python releases, though).
That's why (int, int) works as an annotation. (1 + 3) also works as an annotation.
Some annotations are understood by mypy and other python type-checkers as type annotations: Tuple[Int, Int] is such an annotation.
In short: use Tuple[int, int].