Sub topic 8
Naming a sub-pattern with as
This chapter assumes Python 3.10 or later. It also assumes you know literal patterns, or-patterns (|), sequence and mapping patterns, and class patterns.
The problem as solves
A capture pattern such as direction binds a name to one value. An or-pattern such as "go" | "walk" matches either alternative, but it leaves you without a name for the value that matched. An as-pattern fixes this. It matches a sub-pattern and, if that succeeds, binds the matched value to a name.
def parse(command):
match command.split():
case [("go" | "walk") as verb, direction]:
return f"{verb} -> {direction}"
case _:
return "unknown"
print(parse("walk east")) # walk -> east
print(parse("go north")) # go -> northThe parentheses group the or-pattern. verb receives whichever word matched.
Naming a whole element
You can also use as to keep a structured value intact while still checking its shape. This avoids rebuilding a tuple from its parts.
def first_pair(rows):
match rows:
case [(x, y) as pair, *rest]:
return pair, len(rest)
case _:
return None
print(first_pair([(1, 2), (3, 4), (5, 6)])) # ((1, 2), 2)Here x and y are bound too, so you get both the parts and the whole.
Combining as with class and mapping patterns
An as-pattern works anywhere a pattern is allowed, including inside a mapping pattern.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def describe(shape):
match shape:
case {"kind": "line", "start": Point(x=0) as start, "end": Point() as end}:
return f"line from {start} to {end}"
case _:
return "other"
print(describe({"kind": "line", "start": Point(0, 3), "end": Point(4, 5)}))
# line from Point(x=0, y=3) to Point(x=4, y=5)Point(x=0) as start requires the start point to lie on the y-axis and also gives you the whole object. Point() as end checks only the type.
Precedence and common errors
as has the lowest precedence of all pattern operators. It applies to everything on its left, up to the start of the enclosing pattern or the nearest parenthesis.
| Written | Meaning | Column |
|---|---|---|
| `case 1 \ | 2 as n` | `n` is bound to whichever of 1 or 2 matched |
| `case (1 \ | 2) as n` | Same meaning, with the grouping made explicit |
| `case int() as n \ | float()` | Syntax error, because `as` cannot sit inside an alternative without parentheses |
| `case (int() as n) \ | (float() as n)` | Allowed, because both alternatives bind the same name |
Two more points are worth remembering:
- Every alternative in an or-pattern must bind the same set of names. Writing
(int() as n) | float()fails to compile for that reason. Put theasoutside the group instead:(int() | float()) as n. - Names bound by
asare ordinary local variables. They stay set after thematchblock ends, and they stay set even if a later part of the same case fails. Do not rely on a name from a case that did not run to completion.
Recursion with as
The total function from earlier in the tutorial uses as to name a number of either type while collecting the remaining items.
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.5Without as, you could not name the first element and also require it to be an int or a float.
Exercise
What does case [("a" | "b") as letter, number] bind when the subject is ["b", 7], and what happens for the subject ["c", 7]?
Show answer
For ["b", 7] it binds letter to "b" and number to 7. For ["c", 7] the or-pattern fails, so nothing is bound and Python moves on to the next case.
Exercise
Why does case int() as n | float() raise a SyntaxError, and how do you write it so that n holds either an int or a float?
Show answer
as cannot appear inside one alternative of an or-pattern without parentheses. Write case (int() | float()) as n.