How to Use Union Type Hints in Python
This code demonstrates how to use Union type hints to specify that a parameter can accept multiple types (int, float, str) and handle them accordingly.
Python code
11 linesfrom typing import Union
def process_value(value: Union[int, float, str]) -> str:
if isinstance(value, (int, float)):
return f"Number: {value * 2}"
return f"String: {value.upper()}"
if __name__ == "__main__":
print(process_value(10))
print(process_value(3.14))
print(process_value("hello"))
Output
Number: 20
Number: 6.28
String: HELLO
How it works
The Union[int, float, str] type hint tells static type checkers (like mypy) that the value parameter can be an int, float, or str. Inside the function, isinstance is used to check the runtime type and branch the logic accordingly. The Union type hint improves code clarity and helps tools catch type-related bugs early, while isinstance ensures the correct handling at runtime. In Python 3.10+, you can use the int | float | str syntax as a more concise alternative. This pattern is essential for functions that legitimately accept multiple types and need type-safe behavior.
Common mistakes
- Forgetting that `Union` only helps static checkers, not runtime behavior
- Using `Union` with incompatible types and then doing operations that fail for some types
- Not handling all possible types in the `Union` inside the function body
Variations
- Use Python 3.10's `int | float | str` syntax instead of `Union`
- Use `isinstance` with multiple types in a tuple to check for multiple types at once
Real-world use cases
- Writing a config parser that accepts environment variables as strings or numbers and normalizes them.
- Creating a logging wrapper that can accept messages as strings or exception objects.
- Implementing a flexible API endpoint parameter that can be an ID as int or string.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.