Meaning
The annotation declares that variable `x` can hold a value of either `int` or `str` type, and it assigns the initial value `5`. This helps static type checkers detect mismatched assignments and clarifies intent for readers. Use it when a variable may legitimately contain values of multiple possible types, such as when parsing JSON fields that can be numeric or textual.
Primary Function
Type hinting
Communicative Purpose
Express that a variable may hold values of multiple possible types.
Pattern
variable: Union[type_a, type_b] = value
Core Structure
...: Union[..., ...] = ...
Função primária
Type hinting
Propósito comunicativo
Express that a variable may hold values of multiple possible types.
Situações de gatilho
Python: a function returns either int or str; Python: parsing JSON where a field can be numeric or textual; Python: interfacing with loosely‑typed external APIs
Contextos
Python projects that use the typing module, data‑validation libraries, API client code, and static analysis tools like mypy.
Padrão
variable: Union[type_a, type_b] = value
Estrutura central
...: Union[..., ...] = ...
Slots de substituição
variable_name: identifier, first_type: type, second_type: type, initial_value: expression
Colocados típicos
- from typing import Union
- mypy
- isinstance
- type checking
Substituições comuns
- Using the pipe syntax (int | str) in Python 3.10+
- or Optional[int] when one of the types is None.
Erros comuns
Forgetting to import Union, assuming Union enforces runtime type checks, mixing unrelated types that make static analysis noisy.
Similar / contraste
Union[int, str] vs Any (no restriction) vs Protocol (structural typing) – Union lists concrete alternatives, Any accepts everything, Protocol defines required attributes.
Interferências
Coming from Java: using <> generics syntax instead of Union → use Union from typing module. Coming from Java: assuming Union creates a runtime combined type → Union is only for static type checking.
Família do chunk
- type hinting
- Union
- Optional
- Literal
- Protocol
- TypedDict
Nuance
Union is only checked by static type checkers; it does not affect runtime behavior, so over‑using it can hide real type errors.
Efeito pragmático
Improves IDE autocompletion and static analysis, making code intent explicit without affecting performance.
Dica de memória
Union variable can be int or str
Nota
Union is enforced only by static type checkers; it has no runtime effect, so it does not prevent assigning invalid types at runtime.
Upgrade path
Use PEP 604 pipe syntax: `x: int | str = 5`.
Log in to save chunks.