develop comprehensive q&a that covers everything mentioned in this guide on pattern matching in python.
by comprehensive, you generate as many as you can as long as in total, they can cover all the topics introduced from the article.
"""
# pattern matching in python with match-case
similar to the `switch-case` statement in C#
## Two functionalities
1. Pattern Matching: match against literals, sequences, mappings, wildcards
2. Variable Binding: capturing and binding values within matched patterns

## Basic syntax
- Pattern matching uses `match-case` construct
- Cases evaluated from top to bottom
```python
match value:
    case pattern1:
        # code for pattern1
    case pattern2:
        # code for pattern2
```
- Only first matched `case` executes, no fall-through unlike other languages
```python
match 1:
    case 1:
        print("First case")
    case 1:
        print("Second case")  # This will never be reached
# Output: First case
```


## Literal value pattern matching
```python
case literal_value:
```
Literal value: value that is compile-time constructed

```python
def describe_type(value):
    match value:
        case 0:
            return "Zero"
	    case b"hello"
		    return "Greeting"
		case True:
			return "Boolean True"
		case None:
			return "None value"
```

### Enum matching
Enums are inherently literal values and can be matched directly
```python
```python
from enum import Enum, auto

class HttpStatus(Enum):
    OK = auto()
    NOT_FOUND = auto()
    SERVER_ERROR = auto()

def handle_response(status):
    match status:
        case HttpStatus.OK:
            return "Request successful"
        case HttpStatus.NOT_FOUND:
            return "Resource not found"
        case HttpStatus.SERVER_ERROR:
            return "Internal server error"
        case _:
            return "Unknown status"

print(handle_response(HttpStatus.OK))  # Output: Request successful
print(handle_response(HttpStatus.NOT_FOUND))  # Output: Resource not found
```


## Capture Patterns/variable Binding, if-guard
```python
case variable:
```
- Binds matched value to a variable directly
- Useful for further processing or condition checking
- Captured variable acts as a **wildcard**, matching any value
- Often used in combination **with if-guards** for more specific conditions
- Pure capture pattern (no if-guards) can only be the **last pattern**
	- otherwise syntax error, says `remaining patterns unreachable`
- Example:
```python
match "foo":
	# Capture pattern with if-guard
	case bar if bar.startswith("f"):
		print(bar) # logs "foo"
	
	# Pure capture pattern must be the last pattern
	case bar: 
		...
```

### Captured Variable Scope

- Variables bound in `case` patterns are accessible in the outer scope
- Unlike other languages, they're not limited to the `case` block

```python
def test():
    match 42:
        case value:  # 'value' is bound to 42
            pass     # case body can be empty
    print(value)     # 'value' is accessible here
test()  # Output: 42
```

A more practical example to assign local variable within `case`:
```python
def check_value(x):
    match x:
        case 0:
            result = "zero"
        case matched:  # binds any non-zero value to 'matched'
            result = f"non-zero: {matched}"
    return result     # 'result' is accessible here

print(check_value(5))  # Output: "non-zero: 5"
````

### Reusing variable
- No two variable names can be identical at any nesting level except or-patterns
```python
case (x, x):  # Error: binding `x` to two values
case (x, [[x]]): # Error: binding `x` to two values
```
- Or-patterns: variable names can be reused across alternative patterns
```python
case (1, x) | (x, 3):  # No error: `x` is either of two value
case (1, x) | (3, x): # No error: `x` is either of two value
```

### If-guard
```python
case pattern if condition:
```
- Provides additional conditions for pattern matching
- Placed at the end of a case
- Has access to variables from deeply nested pattern
- Evaluates dynamically
```python
# using and
case n if n > 0 and n == 42:            
	return (n, "god-liked")
# using nested variables
case [_, (x, y)] if x > 0 and y == 42:  
	return (x, y, "Special Match")
# dont have to use capture; evaluates dynamically
case n if random.random() > 0.5: 
	return "Foo"
```

### Common Usage Pattern: If-Else Logic

Capture patterns and if-guards can be used to implement if-else logic within a match statement:

```python
def process_command(command, current_room):
    match command.split():
	    # if
        case ["go", direction] if direction in current_room.exits:
            return current_room.move(direction)
        # else
        case ["go", _]:
            return "Invalid direction. You can't go that way."
        case ["look"]:
            return current_room.description
        case ["inventory"]:
            return player.inventory_list()
        case _:
            return "Unknown command. Try 'go', 'look', or 'inventory'."
```


## Wildcard pattern `_`
```python
case _:
```
- Denoted by `_`
- Matches anything like capture pattern
- Does not bind to name 
```python
match 42:
	case _:  # ok
		print(_) # error: name '_' is not defined
```
- Can repeat in sequence pattern, unlike named variables:
```python
case [_, _]:  # Valid: Matches any list with exactly two elements
case [x, x]:  # Invalid: Cannot use the same name twice in a pattern
```
- Can't be used as targets for the `as` keyword:
```python
case pattern as _:  # syntax error: cannot use '_' as a target
case pattern as foo:  # ok
```

### Use cases for `_`
- As last default case to not overshadow other cases
```python
match value:
    case pattern1: ...
        # code for pattern1
    case pattern2: ...
        # code for pattern2
    case _: ...
	    # default case
	    
	# uncomment below pattern would raise SyntaxError
	# case pattern3: ...
	# this is never reached
```
 - Partial matching while not capturing value
```python
case [1, _, 3]:
		return "List with 1 and 3 at specific positions"
case {"id": _, "value": value} if value > 100:
		return f"High-value item: {value}"
case {"error": _}:
		return "Error occurred"
case _:
		return "Unrecognized data format"
```
 - In dictionary patterns, wildcards can be used to ignore values but not keys:
```python
case {"known_key": _}:  # Valid: Matches any value for "known_key"
case {_: "known_value"}:  # Invalid: Can't use wildcard as a key
```
 - With splat operators (`*` and `**`) to ignore multiple elements in sequences or key-value pairs in dictionaries
```python
case [first, *_, last]:
    return f"First: {first}, Last: {last}"
case {"mode": "production", **_}:
	return "Production mode"
```


## Partial Matching
Combines fixed values and wildcard/capture patterns

Examples:
- Sequence pattern:
```python 
match data:  
	case [1, x, _]: # Matches any 3-element sequence starting with 1  
		print(f"Second element is {x}")  
```
- Dictionary pattern:
```python
match user:  
	case {"name": str() as name, "age": int()}: # Matches dict with specific keys and types  
		print(f"{name}'s age is an integer")  
```
- Class pattern:
```python
match point:  
	case Point(0, y): # Matches Point objects with x=0  
		print(f"On y-axis at {y}")  
```
- Nested pattern:
```python
match config:  
	case {"database": {"host": "localhost", "port": port}}: # Partially matches nested structure  
		print(f"Local database on port {port}")
```


## Sequence pattern: unpacking and length matching
```python
case pattern1,:
case pattern1, pattern2, ..., *rest:
case [pattern1, pattern2, ..., *rest]:
case (pattern1, pattern2, ..., *rest):
```
- Length validation
- Sequence unpacking for member variable binding
### Compatible Types
-  Classes inheriting from `collections.abc.Sequence`:
	- `list`, `tuple`, `range`, `memoryview`, `deque`, `array`
	- Exceptions: `str`, `bytes`, `bytearray` (these use literal matching instead)
- Built-in classes with `Py_TPFLAGS_SEQUENCE` flag:
	- `array.array`, `collections.deque`, `list`, `memoryview`, `range`, `tuple`
### Syntax Features
1. Brackets are optional except for empty sequence
- Both `[]` and `()` work for unpacking
```python
case x, y:
	return f"2D point: ({x}, {y})"
case (x, y, z):
	return f"3D point: ({x}, {y}, {z})"
case [w, x, y, z]: ...
```
- Only required when matching empty sequence
2. Splat operator `*` for variable-length unpacking:
    - Maximum one per sequence pattern
    - Can appear at any position
```python
case x, y, z, *rest:
	return f"High-D point: ({x}, {y}, {z}, ...)"
case first, *rest, last: ...
```
### Sequence Length Matching
- **Matching empty sequence**
```python
case []:
```
- **Matching length-1 sequence**
```python
case [_]:
case _,:
```
- **Fixed Length Matching**
```python
case [_, _, _]:  # Matches a sequence with exactly 3 elements
```
- **Variable Length Matching**
```python
case [*_] as sequence if len(sequence) > 2:  # Matches a sequence with more than 2 elements
```
#### Pitfalls of Simple Length Checks
- Direct length check if-guard errs when target has no `__len__`
```python
match 1:
	case seq if len(seq) > 2:  # Error: '1' is not a sequence
		...
```
- Have to verify the instance type first:
```python
case seq if isinstance(seq, collections.abc.Sequence) and len(seq) > 2:
```
### Sequence pattern matching over manual unpacking
Use structural pattern matching to handle different input patterns without explicit length checks or indexing, reducing code complexity.

Instead of:
```python
parts = command.split()
if len(parts) == 2:
    action, obj = parts
    # interpret action, obj
elif len(parts) >= 1:
    action = parts[0]
    # handle action with variable arguments
```
Use:
```python
match command.split():
    case [action, obj]:
        # interpret action, obj
    case [action, *args]:
        # handle action with variable arguments
    case _:
        # handle invalid input
```


## Mapping pattern: Dictionary Key Matching and Value Binding
```python
case {}: # match all dicts
case {key1: pattern1, key2, pattern2, ..., **rest_key_values}:
```
- Match keys
- Bind values to variables
```python
case {"name": name, "age": age}:
	return f"{name} is {age} years old"
```
- Use `**` (double star) to capture remaining key-value pairs
```python
case {"name": name, **rest}:
	return f"Name: {name}" + (f", extras: {rest}" if rest else "")
```
- Keys are compared using the `==` operator
- Key-value pairs are matched using the `get()` method

### Supported Types:
- Classes inheriting from `collections.abc.Mapping`:
    - `dict`
    - `types.MappingProxyType`
    - `collections.defaultdict`
    - `collections.OrderedDict`
    - `collections.Counter`
    - `collections.ChainMap`
    - `types.SimpleNamespace`
- Built-in classes with `Py_TPFLAGS_MAPPING` bit set:
    - `dict`
    - `mappingproxy`

### Matching with `{}`
- `{}` is wildcard dictionary match (all dicts); while `[]` matches empty sequence
```python
case {} as dict:
	# match every dict
	...
```
- To match empty/non-empty dict, use `{}` with if-guard
```python
case {} as dict if dict: # match non-empty dict
case {} as dict if not dict: # match empty dict
```

### Practical Example: Processing User Actions

```python
def process_actions(actions, ui):
    for action in actions:
        match action:
            case {"type": "message", "text": msg, "color": color}:
                ui.display_message(msg, color)
            case {"type": "wait", "duration": duration}:
                ui.wait(duration)
            case {"type": "sound", "url": url, "format": "ogg"}:
                ui.play_sound(url)
            case {"type": "sound", "format": format}:
                print(f"Unsupported audio format: {format}")
            case _:
                print(f"Unknown action: {action}")

# Example usage
ui = UserInterface()
actions = [
    {"type": "message", "text": "Welcome!", "color": "32"},
    {"type": "wait", "duration": 1},
    {"type": "message", "text": "Loading...", "color": "33"},
    {"type": "wait", "duration": 2},
    {"type": "sound", "url": "notification.ogg", "format": "ogg"},
    {"type": "sound", "url": "music.mp3", "format": "mp3"},
    {"type": "message", "text": "Goodbye!", "color": "31"},
]

process_actions(actions, ui)
```


## `or`-pattern
```python
case pattern1 | pattern2 | ...:		
```
- Contains 2 or more alternate patterns delimited by `|`
- Easy to construct when used without variable binding
```python
match value:
	case "foo" | "bar":
		...
	# equivalent to
	case value if value == "foo" | value == "bar":
		...
```
- Single-value or-patterns are useless
```python
case foo | foo: # useless, just foo is enough
	...
```
- Alternate patterns require identical variable names at the same structural positions
```python
match value:
	case foo | bar: # error: binding to a different variable
		...
	case [foo] | [foo, "bar"]: # ok
		...
	case [foo] | [bar, "bar"]: # error
		...
	case {"foo": foo} | {"foo" : foo, "bar": _}: # ok
		...
	case {"foo": foo} | {"foo" : bar, "bar": _}: # error
		...
```
- Different positions can use same or different names
```python
case ["get", obj] | ["pick", "up", obj] | ["pick", obj, "up"]: # valid
```
- Reminder: cannot rebind variables within a single sub-pattern
```python
case ["get", obj] | [obj, obj]: # error
```
### Common Use Case
- Matching different literal values with fixed variable binding:
```python
def process_command(sequence):
	match sequence:
		case ["create", item] | ["add", item]:
			print(f"Creating or adding {item}")
		case ["delete", item] | ["remove", item]:
			print(f"Deleting or removing {item}")
```
- Alternate wildcard patterns:
	- For matching patterns with partially defined structures
```python
match value:
    case (1, _) | (_, 1):
        print("Tuple with 1 in either position")
```

### if-guard with or-patterns
- if-guard applies to the entire `or` pattern, not individual alternates:
```python
case pattern1 | pattern2 if condition:  # Correct
```
- Cannot use separate guards for each alternate:
```python
case pattern1 if condition1 | pattern2 if condition2:  # Error
```

### Practical Example: Shape Processing

```python
def process_shape(shape):
    match shape:
        # Circles or squares with the same radius logic
        case ('circle', r) | ('square', r) if 1 <= r <= 10:
            area = 3.14 * r**2 if shape[0] == 'circle' else r**2
            print(f"{shape[0].capitalize()} with radius {r}")
            print(f"Area: {area:.2f}")
        
        # Rectangles or triangles with width and height
        case ('rectangle', w, h) | ('triangle', w, h) \
            if 1 <= w <= 10 and 1 <= h <= 10:
            if shape[0] == 'rectangle':
                area = w * h
                shape_name = "Rectangle"
            else:
                area = 0.5 * w * h
                shape_name = "Triangle"
            print(f"{shape_name} {w}x{h}")
            print(f"Area: {area:.2f}")
        
        # Catch-all case
        case _:
            print("Invalid shape or dimensions out of range")

# Test cases
process_shape(('circle', 5))       # Circle with radius 5. Area: 78.50
process_shape(('square', 7))       # Square with radius 7. Area: 49.00
process_shape(('rectangle', 4, 6)) # Rectangle 4x6. Area: 24.00
process_shape(('triangle', 3, 8))  # Triangle 3x8. Area: 12.00
process_shape(('circle', 15))      # Invalid shape or dimensions out of range
process_shape(('hexagon', 5))      # Invalid shape or dimensions out of range
```


## Understanding the Absence of an `and` Pattern
#### Concept of an `and` Pattern
- Theoretically, an `and` pattern would require two or more sub-patterns to be satisfied simultaneously.
- In practice, any pattern inherently functions as an `and` pattern since satisfying it means satisfying all of its components

#### When `and` is Theoretically Possible
An `and` pattern could be relevant for structural variations with multiplicity, such as checking for multiple keys or items within a structure.
    
**Matching Multiple Keys in a Dictionary:**
- Hypothetical `and` pattern:
```python
case {"foo": _, **_} and {"bar": _, **_}:
```
- is effectively one mapping pattern
```python
case {"foo": _, "bar": _}:
```

**Matching Specific Indices in a List:**
- Hypothetical `and` pattern:
```python
case [0,*_] and [_, 1, *_]
```
- is effectively one sequence pattern
```python
case [0, 1, *_]:
```

**Matching a Sequence Containing 2 specific items:
- There is no direct `and` pattern formulation.
- Instead, you must check all possible positions
- Here is an `or`-pattern for permutations
```python
case [1, 2] | [2, 1]:
```
#### When `and` is Impossible
- **Identity Constraints:** Value cannot simultaneously satisfy different identities/types:
	- A value cannot be both a dictionary and a list
	- A value cannot be both a literal string and an integer
- **Structural Constraints:** Structural components cannot simultaneously satisfy different properties/identities
	- A sequence cannot simultaneously have different lengths 
	  (e.g., length 1 and length 2 at the same time)
	- A sequence cannot have different values at the same position
	  (e.g., one pattern cannot require a value at a specific position while another requires a different value at the same position)




## Class Pattern
```python
case ClassName([pos_pattern1, ...,] [keyword1=kw_pattern1, ...])
```
- can include both positional and keyword patterns
- resembles function call syntax
- positional patterns match the attributes defined in `__match_args__`
- keyword patterns match specific attributes by name (keyword)
- positional patterns must precede before keyword patterns
### Class keyword pattern: Instance attribute-value matching
```python
case ClassName(keyword=pattern):
```

- Similar to dictionary matching
- Checks for
	- instance type
	- each keyword (attribute name) and value pattern
		- attribute meaning: recall `getattr`
#### Common Use Cases

1. Keyword pattern with sequence unpacking:
```python
case Click(position=(x, y)) if y > 50:
	print(f"Clicked at ({x}, {y})")
```
2. Literal value match:
```python
case Event(name="click") as ev:
	print(f"Event: {ev.name}")
```
3. Pure instance check:
```python
case Click():
	print("Any click event")
```
4. Primitive type checking:
```python
case str():
	print("String input")
```
5. Alternate instance check:
```python
case float() | int():
	print("Numeric input")
```

#### Practical Example: Event Handling

```python
def handle_event(event):
    match event:
        case Click(position=(x, y)):
            print(f"Mouse clicked at ({x}, {y})")
        case KeyPress(key="Q") | Quit():
            print("Quitting application")
        case KeyPress(key="Up"):
            print("Moving north")
        case KeyPress():
            print("Key pressed, but not handled")
        case _:
            print(f"Unrecognized event: {event}")

# Simulated events
from collections import namedtuple
Click = namedtuple('Click', ['position'])
KeyPress = namedtuple('KeyPress', ['key'])
Quit = namedtuple('Quit', [])

# Test cases
handle_event(Click((100, 200)))
handle_event(KeyPress("Q"))
handle_event(KeyPress("Up"))
handle_event(KeyPress("Left"))
handle_event(Quit())
handle_event("Unknown")
```
### Class positional pattern
```python
case ClassName(pattern1, pattern2, ...):
```
- Matches object attributes based on their position
- Converts to keyword pattern internally
#### `__match_args__` class attribute
- Specifies which attributes are matched and their position
- Converts each positional pattern to keyword pattern using `__match_args__[i]` as the keyword

For example, given `__match_args__ = ("x", "y")`:
- Positional patterns `a, b` are converted to keyword patterns `x=a, y=b`

#### Custom Class
`Point(a,b)` becomes `Point(x=a, y=b)`

```python
class Point:
    __match_args__ = ("x", "y")
    
    def __init__(self, x, y):
        self.x = x
        self.y = y

def classify_point(point):
    match point:
        case Point(0, 0):
            return "Origin"
        case Point(0, y):
            return f"On Y-axis at y={y}"
        case Point(x, 0):
            return f"On X-axis at x={x}"
        case Point(x, y):
            return f"Point at ({x}, {y})"

print(classify_point(Point(0, 0)))  # Output: Origin
print(classify_point(Point(0, 5)))  # Output: On Y-axis at y=5
print(classify_point(Point(3, 0)))  # Output: On X-axis at x=3
print(classify_point(Point(2, 4)))  # Output: Point at (2, 4)
```


#### Dataclasses
`dataclass` automatically implements `__match_args__`

```python
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

point = Point(1, 2)

match point:
    case Point(1, 2):
        print("Matched Point at (1, 2)")
    case Point(x, y):
        print(f"Matched Point at ({x}, {y})")
```

#### Built-in Class Positional Pattern
- Several built-in classes define the first position attribute to return the instance itself:
    - `bool`, `bytearray`, `bytes`, `dict`, `float`, `frozenset`, `int`, `list`, `set`, `str`, and `tuple`
- This behavior is equivalent to:
```python
class C:
    __match_args__ = ("__match_self_prop__",)
    @property
    def __match_self_prop__(self):
        return self
```
- This allows for instance checking while assigning the instance to a variable at the first attribute position:
```python
case str(text): ...
# is equivalent to
case str() as text: ...
```
- `str(text)` converts to `str(__match_self_prop_=text)`

##### Customizing Built-in Positional Patterns
- Inherit builtin classes to customize
- `Path` example:
	- `Path(path)` converts to `Path(__match_self_prop__==path)`
```python
import pathlib

class Path(pathlib.Path):
    __match_args__ = ("__match_self_prop__",)

    @property
    def __match_self_prop__(self):
        return self.__fspath__()

def process_path(path):
    match path:
        case str(p) | Path(p):
            return f"Processing path: {p}"
        case _:
            return "Not a valid path"

print(process_path("path/to/file")) # Processing path: path/to/file
print(process_path(Path("another/path"))) # Processing path: another/path
print(process_path(42)) # Not a valid path
```

#### Practical Example
```python
from dataclasses import dataclass

@dataclass
class Circle:
    radius: float

@dataclass
class Rectangle:
    width: float
    height: float

def classify_shape(shape):
    match shape:
        case Circle(radius):
            return f"Circle with radius {radius}"
        case Rectangle(width, height) if width == height:
            return f"Square with side {width}"
        case Rectangle(width, height):
            return f"Rectangle with width {width} and height {height}"
        case _:
            return "Unknown shape"
```

### Combining class positional and keyword patterns
Examples:
```python
class Person:
    __match_args__ = ("name", "age")
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

def describe_person(person):
    match person:
        case Person(name, age, city="New York"):
            return f"{name}, {age} years old, lives in New York"
        case Person(name, age=30):
            return f"{name} is 30 years old"
        case Person(name):
            return f"Person named {name}"
```

```python
class Product:
    __match_args__ = ("name", "price")
    def __init__(self, name, price, category):
        self.name = name
        self.price = price
        self.category = category

def categorize_product(product):
    match product:
        case Product("Book", price, category="Fiction"):
            return f"Fiction book priced at ${price}"
        case Product(name, 0.99, category=cat):
            return f"{cat} item on sale: {name}"
        case Product(name, price) if price > 100:
            return f"Expensive item: {name}"
        case Product(_, _, category="Electronics"):
            return "Some electronic device"
```


## `as` Pattern: Variable Binding
```python
case pattern as variable_name:
```
- Bind entire patterns, sub-patterns, or literal values to variables
- Allows reuse of matched values in if-guards and case block
- Enhances readability and reduces redundancy in pattern matching
- Cannot bind to `_` variable
```python
case foo as _: # error
```
### Examples

- Bind to sequence
```python
case [x, y] as point:
```
- Bind to literal value with guard
```python
case "foo" as foo if len(foo) > 1:
```
- Bind to unpacked literal value
```python
case ["bar" as bar]:
```
- Bind to unpacked or-pattern
```python
case ["go", ("fast" | "slow") as speed]:
```
- Bind to class pattern
```python
case str() as text:
```
- Bind to dict value with instance check
```python
case {"foo": int() as foo}:
```
### Positional Parameter Shorthand for `as` with Primitives

Some built-in classes have a shorthand notation for `as` pattern:
`bool`, `bytearray`, `bytes`, `dict`, `float`, `frozenset`, `int`, `list`, `set`, `str`, and `tuple`

```python
# These are equivalent
case str() as text: ...
case str(text): ...
```

See [[#Built-in Class Positional Attribute Matching]]

### Practical Examples
Parsing command-line arguments:
```python
def parse_command(cmd):
    match cmd.split():
        case ["quit" | "exit" as action]:
            return f"Exiting program ({action})"
        case ["create", ("file" | "directory") as item_type, name]:
            return f"Creating {item_type}: {name}"
        case ["delete", path as target] if "/" in target:
            return f"Deleting file at path: {target}"
        case ["move", source, destination] as full_cmd:
            return f"Moving from {source} to {destination} (Full command: {' '.join(full_cmd)})"
        case _:
            return "Invalid command"
```


## Patterns are nestable
### Unique Variable Bindings Across Nested Patterns
- No two variable names can be identical at any nesting level except or-patterns
```python
case (x, x):  # Error: binding `x` to two values
case [[x], [x]] # Error: binding `x` to two values
case [x, "foo"] | [x, "bar"] # Ok
```
### Examples
#### Sequence Length with Literal Value/Wildcard Matching
```python
def process_coordinates(coords):
    match coords:
        case [0, 0]:
            return "Origin"
        case [x, y] if x == y:
            return f"On diagonal: ({x}, {y})"
        case [_, _]:
            return "2D point"
        case [_, _, _]:
            return "3D point"
        case _:
            return "Unknown coordinate system"
```

#### Sequence with Nested Dictionary Matching
```python
def process_weather_data(data):
    match data:
        case [{"city": str(city), "temp": int(temp)}, {"humidity": int(humidity)}]:
            return f"{city}: {temp}°C, Humidity: {humidity}%"
        case _:
            return "Invalid weather data"
```

#### Sequence with Nested Class Pattern Matching
```python
def process_library_data(data):
    match data:
        case [Book(title=str(title), author="Unknown"), *rest]:
            return f"First book: {title} by Unknown author"
        case [Book(title=str(title), author=str(author)), Book(title=str(title2), author=str(author2))]:
            return f"Two books: {title} by {author}, and {title2} by {author2}"
        case _:
            return "Invalid library data"
```

#### Dictionary with Literal Value Matching
```python
def process_http_response(response):
    match response:
        case {"status": 200, "body": body}:
            return f"Success: {body}"
        case {"status": 404, "error": error}:
            return f"Not found: {error}"
        case {"status": 500, "error": error}:
            return f"Server error: {error}"
        case _:
            return "Unknown response"
```

#### Dictionary with Nested Sequence Matching
```python
def process_student_grades(data):
    match data:
        case {"name": str(name), "grades": [int(math), int(science), int(english)]}:
            average = (math + science + english) / 3
            return f"{name}'s average grade: {average:.2f}"
        case _:
            return "Invalid student data"
```

#### Dictionary with Nested OR Patterns
```python
def process_user_input(input_data):
    match input_data:
        case {"action": "search", "query": str(query) | list(query)}:
            return f"Searching for: {query}"
        case {"action": "filter", "criteria": {"age": int(age)} | {"category": str(category)}}:
            return f"Filtering by: {age if 'age' in locals() else category}"
        case _:
            return "Invalid input"
```

#### Dictionary with Nested Class Patterns
```python
def process_system_event(event):
    match event:
        case {"type": "login", "user": User(name=str(name), role="admin")}:
            return f"Admin login: {name}"
        case {"type": "login", "user": User(name=str(name), role=str(role))}:
            return f"User login: {name} ({role})"
        case {"type": "logout", "user": User(name=str(name))}:
            return f"Logout: {name}"
        case _:
            return "Unknown event"
```

#### OR Pattern with Nested Sequence and Dictionary Matching

```python
def process_data(data):
    match data:
        case [str(name), int(age)] | {"name": str(name), "age": int(age)}:
            return f"Name: {name}, Age: {age}"
        case _:
            return "Invalid data format"
```

#### Class Pattern with Nested Dictionary and Sequence Matching
```python
class Report:
    def __init__(self, title, data):
        self.title = title
        self.data = data

def analyze_report(report):
    match report:
        case Report(title=str(title), data={"summary": [int(total), int(average)]}):
            return f"Report '{title}': Total {total}, Average {average}"
        case Report(title=str(title), data={"details": [*items]}):
            return f"Detailed report '{title}' with {len(items)} items"
        case _:
            return "Invalid report format"
```
"""