Flexible function parameters
A function accepts text or numeric input.
Python · Type Alias
A union type annotation allows a value to match one of several types. Modern Python uses X | Y; this is equivalent to Union[X, Y], whose shorthand is recommended.
A union type describes a value that may conform to any one of several types. Modern Python expresses this with the | operator; typing.Union[X, Y] remains equivalent, but the shorthand is recommended.
Union[X, Y]
X | Y| Name | Type | Description |
|---|---|---|
X, Y, ... | types | Types that may be accepted by the annotation; there must be at least one type argument. |
A union type describing values that match at least one of its member types.
Union[X, Y] describes a value that may be either X or Y; the modern equivalent is X | Y.Union form or, preferably, the concise | syntax.int | str over Union[int, str].Union is for type annotations; it is not a class to subclass or construct.def parse(value: int | str) -> int | str:
return value
print(parse(42))
print(parse("answer"))The parameter and return annotation each allow either an integer or a string.
A function accepts text or numeric input.
An API result may be one of several model types.
A value is optional without using legacy Optional syntax.
A union annotation allows a value to have one of several specified types. For example, int | str is equivalent to Union[int, str], and the documentation recommends the | form.
Follow-up: What happens with nested unions? They are generally flattened, so Union[Union[int, str], float] is equivalent to Union[int, str, float], except when a type alias prevents evaluation of the underlying alias.
Repeated members are removed, and argument order does not affect union equality. Thus Union[int, str, int] is equivalent to int | str, and reversing the members produces an equal union.
Follow-up: What does a one-member union become? Union[int] becomes int; the constructor returns the single type rather than a distinct union.
X | Y instead of Union[X, Y]?The | spelling became available for unions in Python 3.10. It is the modern spelling of typing.Union and works directly in annotations such as def f(x: int | str) -> str: ....
Follow-up: Can Union itself be instantiated or subclassed to customize this behavior? No; the documentation explicitly disallows both operations.
typingtypes.UnionTypeTypeAliasType