Python annotations: difference between Tuple and ()

Since python 3.6 (or 3.4? I don’t remember), we can annotate the function. Example:

def getVersion() -> str: 

Now, what happens when a function returns a tuple? We can do this:

 def func() -> tuple: 

But if we know that a tuple is a tuple of two integers? I read here: How to annotate multiple return types? that we can do this:

 def func() -> Tuple[int, int] 

But this requires importing a typing module.

Also I tried:

 def func() -> (int, int): 

And this is not a failure.

What is the right way?

+5
source share
1 answer

Annotations can be used for anything you like: they are arbitrary Python expressions (however, problems are currently being discussed with this in future releases of Python).

This is why (int, int) works like an annotation. (1 + 3) also works as an annotation.

Some annotations are understood by mypy and other types of python type checking as type annotations: Tuple[Int, Int] - such an annotation.

In short: use Tuple[Int, Int] .

+2
source

Source: https://habr.com/ru/post/1273177/


All Articles