> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Union

A `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.

```python theme={"dark"}
from typing import Union

VariableType = Union[int, str, float]
```

**Python 3.10+ (PEP 604 Bitwise OR Operator):**
Introduces the `|` operator as syntactic sugar for union types, eliminating the need to import the `typing` module for this purpose.

```python theme={"dark"}
VariableType = int | str | float
```

## Internal Mechanics and Evaluation Rules

At runtime, the `typing` module applies strict algebraic rules to `Union` objects. Static type checkers enforce these same rules during static analysis.

1. **Flattening:** Nested unions are automatically flattened into a single, one-dimensional union.
2. **Deduplication:** Duplicate types are silently discarded.
3. **Commutativity:** The order of the types declared in the union is irrelevant; they are evaluated as a mathematical set.
4. **Single Type Reduction:** A union containing only a single type evaluates directly to that underlying type.

```python theme={"dark"}
from typing import Union


# 1. Flattening
assert Union[Union[int, str], float] == Union[int, str, float]


# 2. Deduplication
assert Union[int, int, str] == Union[int, str]


# 3. Commutativity
assert Union[int, str] == Union[str, int]


# 4. Single Type Reduction
assert Union[int] == int
```

## 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:

```python theme={"dark"}
from typing import Optional, Union

TypeA = Optional[int]
TypeB = Union[int, None]
TypeC = int | None  # Python 3.10+
```

## Type Narrowing

When a variable is annotated with a `Union`, 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.

```python theme={"dark"}
def process(value: int | str) -> None:
    # At this scope, 'value' is (int | str). 
    # Only operations valid for BOTH int and str are permitted.
    
    if isinstance(value, str):
        # Type narrowed to 'str'. String methods are now valid.
        value.upper()
    else:
        # Type narrowed to 'int' via exhaustive fallback.
        value.bit_length()
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
