Functions
Specify return type
In Python, you can specify the return type of a function using type hints. Type hints are a way to document the expected types of function arguments and return values. However, Python’s runtime does not enforce these type annotations. They are intended to be used by tools like type checkers, IDEs, and linters.
To specify the return type of a function, you can follow the function definition with an arrow (->) and the type. For example:
def greeting(name: str) -> str:
return 'Hello ' + nameIn this example, the function greeting takes one argument name of type str and returns a value of type str.
If your function can return multiple types, you can use the Union type from the typing module to specify multiple possible return types. Here’s an example:
from typing import Union
def parse_email(email: str) -> Union[str, tuple]:
# ... parse the email ...
if email_is_valid:
return 'valid'
else:
return 'invalid', 42In this example, the function parse_email can return either a string (if the email is valid) or a tuple (if the email is invalid).
For more complex scenarios, where you want to specify the type of the elements in a tuple, you can use a tuple type. Here’s an example:
from typing import Tuple
def parse_node_info() -> Tuple[str, str, int]:
# ... parse node info ...
return node_id, node_name, uptime_minutesIn this example, the function parse_node_info returns a tuple with three elements: a string, a string, and an integer.
Note that type hints are optional in Python and are intended to help with readability and maintainability, rather than enforcing strict type checking at runtime.
Examples
def func(data: str) -> str:
return datadef func(numbers: list[int]) -> list[int]:
numbers.reverse()
return numbers# *args, *numbers, *foobar
def sum_numbers(*args: float) -> float:
return sum(args)
print(sum_numbers(1, 2, 3, 4, 5, 10, 20)) Last updated