ADocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Union is a type hint construct in Python used to indicate that a variable, parameter, or return value can accept one of several distinct types. It instructs static type checkers (such as mypy or pyright) that an expression is valid if its resolved type matches any of the types specified within the union declaration.
Syntax
Python supports two distinct syntaxes for defining a union, depending on the Python version. Python 3.9 and earlier (typing.Union):
Requires importing Union from the typing module and passing the allowed types as arguments within square brackets.
| operator as syntactic sugar for union types, eliminating the need to import the typing module for this purpose.
Internal Mechanics and Evaluation Rules
At runtime, thetyping module applies strict algebraic rules to Union objects. Static type checkers enforce these same rules during static analysis.
- Flattening: Nested unions are automatically flattened into a single, one-dimensional union.
- Deduplication: Duplicate types are silently discarded.
- Commutativity: The order of the types declared in the union is irrelevant; they are evaluated as a mathematical set.
- Single Type Reduction: A union containing only a single type evaluates directly to that underlying type.
Relationship with Optional
The typing.Optional construct is strictly an alias for a Union where one of the valid types is NoneType. The following three declarations are semantically and technically identical to a static type checker:
Type Narrowing
When a variable is annotated with aUnion, static type checkers restrict operations on that variable to the intersection of attributes common to all types in the union. To access type-specific methods or attributes, the developer must perform type narrowing (typically via isinstance() checks or match statements). This proves to the static analyzer that the variable has been constrained to a specific type within a given execution block.
Master Python with Deep Grasping Methodology!Learn More





