In this lesson, you will learn how to use Union types to create flexible functions that safely handle multiple, unrelated data formats.
Beyond Optional Values
We have previously used Optional (a specific case of Union[T, None]) to handle values that might be missing. However, real-world applications often require functions to accept or return entirely different types of data based on the business logic. Instead of forcing a common base class or relying on loose Any types, we use Union to explicitly state: "This function accepts type A OR type B."
Implementing Union Types
Imagine you are writing an analytics tool that needs to identify a user. Sometimes you receive an int (the database ID), and other times you receive a str (the email address). By using Union, you tell both your teammates and the static type checker exactly what is expected.
from typing import Union
def get_user_identifier(identifier: Union[int, str]) -> str:
if isinstance(identifier, int):
return f"User ID: {identifier}"
else:
return f"User Email: {identifier}"
# Valid calls
print(get_user_identifier(101))
print(get_user_identifier("dev@example.com"))
Why this matters for code quality
When you define a parameter as Union[int, str], you are providing a contract. If you try to pass a float or a list to get_user_identifier, your static type checker (which we discussed in Lesson 21) will flag it immediately.
This approach forces you to use type narrowing techniques, such as isinstance() checks, inside your function. This is a powerful feature: because the type checker knows that the input must be either an int or a str, once you confirm it is an int, it knows the code inside that block can safely perform integer-specific operations. It transforms "defensive programming" into a structured, readable, and verifiable pattern.
Key Takeaway: Use Union types to explicitly declare that a function handles diverse data types, allowing you to build flexible interfaces without sacrificing the safety provided by static type checking.