In this lesson, you will learn how to use the Union type and Optional helper to allow variables or parameters to accept multiple distinct types or a None value.
Dealing with Uncertainty
In real-world applications, data isn't always predictable. Sometimes a function might return a specific type, or it might return nothing (like None) if a search fails. Other times, a function might accept either an int or a float. Python’s type hinting system allows us to be explicit about these possibilities using typing.Union and typing.Optional.
Using Union
The Union type hint tells static type checkers that a variable can be one of several different types. For example, if a function calculates a value that could be returned as either an int or a str, you would write:
from typing import Union
def process_data(value: Union[int, str]) -> None:
print(f"Processing: {value}")
Here, the type checker will accept both process_data(10) and process_data("hello") without error.
Using Optional
A common scenario is when a variable might be a specific type or None. Instead of writing Union[int, None], Python provides the Optional helper as a cleaner shorthand. Optional[T] is functionally identical to Union[T, None].
Consider a function that looks up a user in a database:
from typing import Optional
def find_user(user_id: int) -> Optional[str]:
# Suppose we return a name string, or None if the ID isn't found
if user_id == 1:
return "Alice"
return None
By annotating the return type as Optional[str], you signal to other developers (and your IDE) that the return value might be empty. This forces you to handle the None case in your code—for instance, by checking if result is not None:—which drastically reduces runtime bugs caused by "AttributeError: 'NoneType' object has no attribute..."
Key Takeaway: Use Union when a value can be one of several types, and use Optional as a convenient way to signal that a value might be either a specific type or None.