๐ Union Types
Union types are used when a variable or function can accept more than one specific type.
๐น Using Union
Union comes from the typing module.
from typing import Union
age: Union[int, str]This means age can be either an integer or a string.
age = 23
age = "23"Both are valid according to the type hint.
๐น Union in Functions
from typing import Union
def display(value: Union[int, str]) -> None:
print(value)Now the function can accept:
display(100)
display("Hello")๐ Modern Syntax
In modern Python, you can use | instead of Union:
def display(value: int | str) -> None:
print(value)This is equivalent to:
Union[int, str]Union Type = A type hint that allows multiple possible types.
Optional is actually a special case of Union:
Optional[str]means:
str | None