Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python annotations: difference between Tuple and ()

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 ?

like image 694
JPFrancoia Avatar asked Nov 07 '17 16:11

JPFrancoia


People also ask

What is __ annotations __ in Python?

Annotations were introduced in Python 3.0 originally without any specific purpose. They were simply a way to associate arbitrary expressions to function arguments and return values. Years later, PEP 484 defined how to add type hints to your Python code, based off work that Jukka Lehtosalo had done on his Ph. D.

How do you annotate type in Python?

To annotate return value type, add -> immediately after closing the parameter parentheses, just before the function definition colon( : ): def announcement(language: str, version: float) -> str: ... The function now has type hints showing that it receives str and float arguments, and returns str .

How do you specify a tuple type in Python?

Tuple[int, float, str] is a tuple of an int, a float and a string. To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...] . A plain Tuple is equivalent to Tuple[Any, ...] , and in turn to tuple .

Should you use type annotations Python?

Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.


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

like image 114
Clément Avatar answered Oct 03 '22 03:10

Clément