Skip to content

Easily Implementing Python Type Hints in Lists/Tuples

[

How to Use Type Hints for Multiple Return Types in Python

Use Python’s Type Hints for One Piece of Data of Alternative Types

In Python, type hinting is an optional yet useful feature to make your code easier to read, reason about, and debug. With type hints, you let other developers know the expected data types for variables, function arguments, and return values. As you write code for applications that require greater flexibility, you may need to specify multiple return types to make your code more robust and adaptable to different situations.

You’ll encounter different use cases where you may want to annotate multiple return types within a single function in Python. In other words, the data returned can vary in type. In this tutorial, you’ll walk through examples of how to specify multiple return types for a function that parses a string from an email address to grab the domain name.

Conditional Statements

When a function uses conditional statements that return different types of results, you can convey this by specifying alternative return types for your function using type hints.

from typing import Union
def parse_email(email: str) -> Union[str, None]:
if "@" in email:
name, domain = email.split("@")
return domain
else:
return None

In the example above, the parse_email function takes a string email as an argument and returns either a string (the domain name) or None, depending on whether the string contains an @ symbol or not.

Optional Values

A function may sometimes return no value, in which case you can use type hints to signal the occasional absence of a return value.

from typing import Optional
def divide(a: int, b: int) -> Optional[float]:
if b != 0:
return a / b
else:
return None

In the example above, the divide function takes two integers a and b as arguments and returns either a float (the result of dividing a by b) or None, if b is equal to 0.

Error Handling

When a function encounters an error, you may want to return a specific error object that’s different from the normal results’ return type. Doing so could help other developers handle errors in the code.

from typing import Union
def process_data(data: str) -> Union[str, ValueError]:
if len(data) > 10:
return data.upper()
else:
return ValueError("Invalid data length")

In the example above, the process_data function takes a string data as an argument and returns either a string (the uppercase version of data) or a ValueError object, if the length of data is less than or equal to 10.

Flexibility

When designing and writing code, you generally want it to be versatile, flexible, and reusable. This could mean writing functions that can handle a range of data types. Specifying this in type hints helps other developers understand your code’s versatility and its intended uses in different cases.

from typing import Union
def add_numbers(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
return a + b

In the example above, the add_numbers function takes two arguments a and b, which can be either integers or floats, and returns the sum of a and b, which can also be either an integer or a float.

Conclusion

Type hints in Python allow you to specify the expected data types for variables, function arguments, and return values, making your code more readable and maintainable. When dealing with multiple return types in a function, you can use type hints to convey this variability, helping other developers understand and use your code effectively. By using type hints effectively, you can write more robust and adaptable code in Python.