Python 3.5+Annotations & typingterm
Union[X, Y] / X | Y
union
Union[X, Y] — the value may be of type X or of type Y. Since Python 3.10 the shorthand X | Y is supported.
Syntax
from typing import Union
Union[int, str] # int или str
# Python 3.10+: int | str
A classic mix-up: Optional[X], which is just X | None, only says the value may be None — it has nothing to do with the argument being optional, that is what a default value is for. The annotation checks nothing by itself; the type checker will simply demand that you narrow, typically with isinstance, before calling a method that exists on only one branch. The X | Y spelling works in annotations and in isinstance from Python 3.10 onward; older versions need Union from typing.
Examples
from typing import Union
def double(x: Union[int, float]) -> Union[int, float]:
return x * 2
print(double(3)) # → 6
print(double(1.5)) # → 3.0
# Python 3.10+
def parse(val: int | str) -> str:
return str(val)
print(parse(42)) # → '42'
print(parse('hi')) # → 'hi'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy