Sub topic 8
Naming a sub-pattern with as
This chapter assumes you can write match statements with literal, capture, sequence, mapping, and class patterns, and that you know how or-patterns (|) and guards work. You will learn how an as-pattern keeps a name for a value that a sub-pattern has already matched.
The problem as solves
Most patterns either test a value or break it apart. A literal pattern such as 301 tests the value but binds no name. A capture such as [x, y] binds the pieces but not the whole list. Sometimes you need to test or destructure a value and also keep the value itself.
An as-pattern has the form pattern as name. The pattern part must match first. If it does, Python binds name to the whole value that part matched. If it does not match, nothing is bound by this as-pattern and the case fails.
Here is the smallest useful case. It is the recursive sum from the plan:
def total(items):
match items:
case [(int() | float()) as first, *rest]:
return first + total(rest)
case []:
return 0
case _:
raise TypeError("expected a list of numbers")
print(total([1, 2.5, 3])) # 6.5The sub-pattern (int() | float()) only checks the type of the first element. It has no capture of its own. Without as first, the program would know the element is a number but would have no name for it.
Naming the result of an or-pattern
The most common use of as is with |. An or-pattern such as 301 | 302 succeeds when either alternative matches, but it does not say which one matched. Adding as gives you the value:
def http_class(code):
match code:
case (301 | 302 | 307 | 308) as status:
return f"redirect ({status})"
case (200 | 204) as status:
return f"success ({status})"
case _:
return "other"
print(http_class(307)) # redirect (307)
print(http_class(204)) # success (204)
print(http_class(500)) # otherBoth cases use the name status. That is fine because only one case runs, and each case is a separate pattern.
The diagram shows how Python evaluates the first case.
How tightly as binds
The as keyword has the lowest precedence of any pattern operator. It applies to the entire or-pattern on its left, not just the last alternative. So case 301 | 302 as code means (301 | 302) as code.
Parentheses are optional here, but I recommend them. They make the scope of as obvious to the next reader, and they matter when you want as to apply to only one alternative:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def axis_report(shape):
match shape:
case Point(x=0) | Point(y=0) as p:
return f"{p} lies on an axis"
case Point() as p:
return f"{p} is off the axes"
case _:
return "not a point"
print(axis_report(Point(0, 5))) # Point(x=0, y=5) lies on an axis
print(axis_report(Point(2, 3))) # Point(x=2, y=3) is off the axesIn the first case, p is bound whichever alternative matched. In the second case, Point() as p checks only the type and keeps the instance.
Keeping the whole while destructuring
As-patterns also work inside nested structures. You can name a piece and unpack it in one step:
def handle(event):
match event:
case {"type": "click", "pos": (x, y) as pos}:
return f"click at {pos}, x={x}, y={y}"
case {"type": "key", "key": ("a" | "b") as key}:
return f"letter {key}"
case _:
return "ignored"
print(handle({"type": "click", "pos": (3, 4)})) # click at (3, 4), x=3, y=4
print(handle({"type": "key", "key": "b"})) # letter b
print(handle({"type": "key", "key": "z"})) # ignoredThe first case binds three names from one value: pos is the tuple, and x and y are its parts. This is useful when you want to pass the tuple on unchanged but also need its parts for a calculation.
As-patterns also combine with guards. A guard runs after the pattern has matched and all names are bound, so it can use the as name:
def classify(seq):
match seq:
case [a, b] as pair if a == b:
return f"repeat {pair}"
case [_, _] as pair:
return f"pair {pair}"
case _:
return "other"
print(classify([4, 4])) # repeat [4, 4]
print(classify([4, 5])) # pair [4, 5]
print(classify("ab")) # otherThe string "ab" has two characters, but sequence patterns never match str, bytes, or bytearray. That is why the last call falls through to case _.
Choosing between as and a capture
A bare capture and an as-pattern both bind names. The choice depends on what you want to do with the value:
| Pattern | What it tests | What it binds | Column |
|---|---|---|---|
| `case [x, y]` | A two-element sequence | `x` and `y` | |
| `case [x, y] as pair` | A two-element sequence | `x`, `y`, and the whole sequence as `pair` | |
| `case (1 \ | 2) as n` | The value is 1 or 2 | `n` is the value |
| `case int() as n` | The value is an `int` | `n` is the value | |
| `case int(n)` | The value is an `int` | `n` is the value |
The last two rows do the same thing. Built-in types such as int, float, str, bytes, list, tuple, dict, set, and frozenset accept a single positional sub-pattern that matches the whole subject. str(s) is therefore shorthand for str() as s. The as form works for every class, including your own, so it is the more general habit.
Rules and errors
- The target must be a simple name. Dotted names such as
self.valueare not allowed afteras. To store the value somewhere else, assign it in the case body. _is not a valid target.case int() as _is aSyntaxError. If you do not need the value, drop theas.- A name can be bound only once per pattern.
case [x as a, y as a]is aSyntaxError, because the pattern would assignatwice. - Every alternative of an or-pattern must bind the same names.
case (1 as a) | (2 as b)is rejected. This rule exists so that the case body can always rely on the names being set. - No new scope is created. The name lives in the enclosing function, just like any other local variable, and it remains after the
matchstatement ends. - The name refers to the original object, not a copy. This matters for mutable values:
def alias_demo(data):
match data:
case [int(), int()] as pair:
return pair is data
case _:
return False
print(alias_demo([1, 2])) # TrueIf you mutate pair, you mutate the caller's list.
When to reach for as
Use as when the code needs both the verdict and the value:
- An or-pattern where the body needs to know which value matched.
- A type check such as
int() as n, where you want the checked value under a name. - A nested piece that you want to pass on whole, while also using its parts.
- A guard that refers to a value you did not otherwise capture.
If the sub-pattern already captures everything you need, as adds noise. case [x, y] is clearer than case [x, y] as _pair that nobody reads.
Exercise
What does describe(7) return, and why does the second case never run for the value 7?
def describe(n):
match n:
case (1 | 3 | 5 | 7 | 9) as odd:
return f"small odd {odd}"
case int() as other:
return f"integer {other}"
case _:
return "not an integer"
Show answer
It returns "small odd 7". Cases are tried from top to bottom, and the first case matches because 7 equals one of its alternatives. Python then binds odd to 7 and runs that body. The int() as other case is only reached for integers outside that list, such as 8 (it returns "integer 8"). A non-integer such as "x" falls through to case _ and gives "not an integer".
Exercise
Why is case (1 as a) | (2 as b): a SyntaxError, and how would you fix it so the body can use the matched number?
Show answer
The alternatives bind different names (a and b), so the case body could not know which name exists. Every alternative must bind the same names. Fix it by naming the whole or-pattern once: case (1 | 2) as n:.
Exercise
Write a case, as a single line, that matches a two-element list whose first element is a string, binds the whole list to pair, and binds the string to label.
Show answer
case [str() as label, _] as pair:. The inner str() as label checks the type and names the first element. The _ accepts any second element without binding it. The outer as pair names the entire list.