Python annotations: difference between Tuple and ()

Viewed 864

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 ?

1 Answers

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

Related