Typing and Generics

typing.Union

Allows any one of the listed types. Nested unions flatten in ordinary cases and duplicate members collapse; a union does not validate values at assignment. Prefer T1 | T2 in modern code.

Formal Syntax & Structure

python syntaxpython
typing.Union[T1, T2, ...]

Return Value

type expression

Typing construct or runtime result as described; static typing rules are not runtime validation.

Working Example

Example Snippetpython
from typing import Union
def size(value: Union[int, str]) -> int: return len(value) if isinstance(value, str) else valueprint((size('abc'), size(4)))
Python Reference