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.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 14 views 0 copies

Python code

11 lines
Python 3.9+
from 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

stdout
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

  1. Use Python 3.10's `int | float | str` syntax instead of `Union`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.