> ## 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 Match Statement

The `match` statement, introduced in Python 3.10 via PEP 634, implements structural pattern matching. It evaluates a subject expression against a series of `case` blocks containing structural patterns, executing the block associated with the first successful match. Unlike traditional C-style `switch` statements, it performs data destructuring, variable binding, and type checking simultaneously.

Both `match` and `case` are **soft keywords**. This language semantic means they function as reserved keywords only within the specific syntax of a pattern matching block. Developers can still use `match` and `case` as variable, class, or function names elsewhere in their code without raising a `SyntaxError`.

```python theme={"dark"}
match subject_expression:
    case <pattern_1> [if <guard_condition>]:
        <action_1>
    case <pattern_2> | <pattern_3> as <variable>:
        <action_2>
    case _:
        <default_action>
```

## Core Components

* **Subject:** The expression evaluated once at the entry point of the `match` block.
* **Pattern:** The structural definition following the `case` keyword. Patterns are evaluated top-to-bottom.
* **Guard:** An optional `if` clause appended to a `case`. If the structural pattern matches, the guard expression is evaluated. If the guard evaluates to `False`, the match fails, and evaluation proceeds to the next `case`.
* **Wildcard (`_`):** An irrefutable pattern that matches any subject without binding it to a variable. It is typically used as the final `case` to act as a default fallback.

## Pattern Types and Mechanics

**Literal Patterns**
Matches the subject against constant values (e.g., integers, strings, booleans, `None`). Comparison is performed using equality (`==`), except for singletons like `None`, `True`, and `False`, which are compared using identity (`is`).

```python theme={"dark"}
match status_code:
    case 200:
        pass
    case None:
        pass
```

**Capture Patterns**
Binds the subject (or a destructured portion of it) to a local variable using a simple, bare name. The variable is overwritten if it already exists in the current scope. Because any bare name is treated as a capture pattern, it acts as an irrefutable match for whatever subject it evaluates against.

```python theme={"dark"}
match response:
    case error_message:
        pass # Binds the entire subject to the local variable 'error_message'
```

**Value Patterns**
Matches the subject against a named constant. To distinguish a value pattern from a capture pattern, Python strictly requires named constants to be referenced via **dotted names** (e.g., `Enum.VALUE`, `module.CONSTANT`, or `cls.CONSTANT`). Attempting to match a constant using a simple, non-dotted name (e.g., `case MY_CONSTANT:`) is a critical pitfall: Python will interpret it as a Capture Pattern, silently matching any value, shadowing the intended constant, and introducing logical bugs.

```python theme={"dark"}
match status:
    case HttpStatus.OK:
        pass # Value Pattern: Evaluates equality against the dotted name
    case MY_CONSTANT:
        pass # Capture Pattern: Matches ANYTHING, binding the subject to 'MY_CONSTANT'
```

**Sequence Patterns**
Matches subjects that are instances of `collections.abc.Sequence` (e.g., `list`, `tuple`, but explicitly excluding `str`, `bytes`, and `bytearray`). It supports exact length matching and variable-length unpacking using the `*` operator.

```python theme={"dark"}
match data_sequence:
    case [first, second]:
        pass # Matches a sequence of exactly two elements
    case [first, *rest, last]:
        pass # Binds the first, last, and packs all intermediate elements into 'rest'
```

**Mapping Patterns**
Matches subjects that are instances of `collections.abc.Mapping` (e.g., `dict`). It checks for the presence of specified keys and matches their corresponding values. Extra keys in the subject do not cause the match to fail. The `**` operator can capture remaining key-value pairs.

```python theme={"dark"}
match data_dict:
    case {"id": 1, "name": name_val, **remainder}:
        pass # Matches if "id"==1, binds "name" to name_val, and captures the rest
```

**Class Patterns**
Matches the subject against a specific class type and optionally destructurizes its attributes. It supports both keyword argument matching and positional argument matching. Positional matching relies on the class's `__match_args__` tuple to map positions to attribute names.

```python theme={"dark"}
match user_object:
    case User(role="admin", age=age):
        pass # Matches User instance where role is "admin", binds the age attribute
    case Point(0, y):
        pass # Positional matching based on Point.__match_args__
```

**OR Patterns (`|`)**
Combines multiple patterns into a single `case`. The match succeeds if any of the sub-patterns match. If capture variables are used, all sub-patterns must bind the exact same variables; otherwise, Python enforces this at compile time and will raise a `SyntaxError` (`SyntaxError: alternative patterns bind different names`).

```python theme={"dark"}
match value:
    case 401 | 403 | 404:
        pass
    case {"error": code} | ["error", code]:
        pass # Both sub-patterns bind the exact same variable 'code'
```

**AS Patterns (`as`)**
Binds a successfully matched pattern (or sub-pattern) to a specific variable name. This allows for capturing a value while simultaneously enforcing a structural or type constraint.

```python theme={"dark"}
match payload:
    case {"type": "auth", "token": str() as token_string}:
        pass # Enforces token is a string, then binds that string to 'token_string'
```

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