Sobes.tech
Junior

What is the Union type annotation in Python?

sobes.tech AI

Answer from AI

Union in Python (from the typing module) indicates that a variable or return value can have one of several types.

For example:

# Indicates that the variable 'value' can be either int or str
from typing import Union

def process_data(value: Union[int, str]) -> Union[int, str]:
    if isinstance(value, int):
        return value * 2
    else:
        return value.upper()

# Usage example
result1 = process_data(10)
result2 = process_data("hello")

print(result1) # Outputs 20
print(result2) # Outputs HELLO

From Python 3.10, you can use the | operator as syntactic sugar:

# Equivalent to Union[int, str] in Python 3.10+
def process_data(value: int | str) -> int | str:
    if isinstance(value, int):
        return value * 2
    else:
        return value.upper()

result1 = process_data(10)
result2 = process_data("hello")

print(result1) # Outputs 20
print(result2) # Outputs HELLO

Union is useful for improving code readability, supporting static analyzers (like MyPy), and informing developers about possible data types. It does not provide runtime type checks; that is the job of static analyzers or explicit checks like isinstance.