Meaning
Denotes a type that can be either an integer or a string.
Primary Function
Allows a variable, function parameter, or return value to accept either an integer or a string value.
Communicative Purpose
Indicates that a value may be of either integer or string type, enabling flexible APIs while retaining static type safety.
Pattern
Union[<type1>, <type2>]
Core Structure
Union[<type1>, <type2>]
Função primária
Allows a variable, function parameter, or return value to accept either an integer or a string value.
Propósito comunicativo
Indicates that a value may be of either integer or string type, enabling flexible APIs while retaining static type safety.
Situações de gatilho
When a function parameter or variable must accept either numeric IDs (int) or textual identifiers (str), such as functions that accept either a numeric ID or a name string.
Contextos
Used in type annotations for function arguments, return types, variable annotations, class attributes, and generic containers like List[Union[int, str]] or Dict[str, Union[int, str]].
Padrão
Union[<type1>, <type2>]
Estrutura central
Union[<type1>, <type2>]
Slots de substituição
type1: type, type2: type
Colocados típicos
- function parameters
- variable annotations
- return types
- generic containers such as List[Union[int
- str]] and Dict[str
- Union[int
- str]].
Substituições comuns
- Union[str
- int] (order irrelevant)
- Union[int
- str
- float] (adding more types)
- Union[int
- str] from typing_extensions for older Python versions
- using the union operator int | str (Python 3.10+).
Erros comuns
• Forgetting to import Union from typing (or typing_extensions) → NameError: name 'Union' is not defined. • Using the union operator | in Python <3.10 without proper import → SyntaxError. • Treating Union[int, str] as a value rather than a type annotation → runtime TypeError when trying to instantiate it. • Using Union[int, str] when Optional[int] or Optional[str] (i.e., Union[T, None]) is needed → accepts unintended None values causing bugs. • Confusing Union[int, str] with Union[int, str, bool] → overly permissive type that unexpectedly accepts boolean values.
Similar / contraste
• Union[int, str] vs Union[int, float] – differs in second type (string vs floating‑point number). • Union[int, str] vs Union[str, int] – order irrelevant; semantically identical. • Union[int, str] vs Union[int, str, bool] – adds bool, making the type accept True/False. • Union[int, str] vs Optional[int] (i.e., Union[int, None]) – Optional allows None instead of a string. • Union[int, str] vs int | str (Python 3.10+) – same meaning, newer syntax.
Interferências
Coming from Java: may use Object or a custom union type to accept multiple types; in Python use Union[int, str] or the \| operator (3.10+). → Use typing.Union or the union operator for static type checking. • Coming from TypeScript: may write string | number; in Python the equivalent is Union[int, str] or int | str. → Adopt Python’s typing.Union syntax or the new union operator.
Família do chunk
- Union types
- Optional types
- Union operator
Nuance
(1) Avoid using Union[int, str] when the function actually requires a single type or when None is a valid input (use Optional instead). (2) No runtime performance impact; Union[int, str] is a static type hint with zero overhead. (3) Boundary condition: a subclass of int (e.g., bool, which is a subclass of int) is accepted as an int, so True/False are considered valid int values under this union.
Efeito pragmático
Using Union[int, str] correctly enables APIs that accept either numeric IDs or textual names, improves IDE autocompletion, catches type mismatches early, and prevents runtime errors from passing the wrong type.
Dica de memória
Think of Union[int, str] as an ID badge that can display either a number or a name.
Nota
Note: Starting with Python 3.10, the built‑in union operator \| can be used as int \| str, which is functionally equivalent to Union[int, str] and often preferred for brevity.
Upgrade path
Consider migrating to the union operator (int | str) available in Python 3.10+ for more concise syntax.
Log in to save chunks.