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