Structural pattern matching introduces a match statement and two new soft
keywords: match and case. As the name suggests, it can be used to match a given value against a list of specified "cases" and act accordingly to the match.
for i in range(100):
match (i % 3, i % 5):
case (0, 0): print("3 and 5")
case (0, _): print("3")
case (_, 0): print("5")
case _: print(i)
• The (0, 0) pattern: This will match a two-element sequence if both elements are equal to 0.
• The (0, _) pattern: This will match a two-element sequence if the first
element is equal to 0. The other element can be of any value and type.
• The (_, 0) pattern: This will match a two-element sequence if the second element is equal to 0. The other element can be of any value and type.
• The _ pattern: This is a wildcard pattern that will match all values.
class Point:
x: int
y: int
def __init__(self, x, y):
self.x = x
self.y = y
def where_is(point):
match point:
case Point(x=0, y=0):
print("Origin")
case Point(x=0, y=y):
print(f"Y={y}")
case Point(x=x, y=0):
print(f"X={x}")
case Point():
print("Somewhere else")
case _:
print("Not a point")
• Point(x=0, y=0): This matches if point is an instance of the Point class and its x and y attributes are equal to 0.
• Point(x=0, y=y): This matches if point is an instance of the Point class and its x attribute is equal to 0. The y attribute is captured to the y variable, which can be used within the case block.
• Point(x=x, y=0): This matches if point is an instance of the Point class and its y attribute is equal to 0. The x attribute is captured to the x variable, which can be used within the case block.
• Point(): This matches if point is an instance of the Point class.
• _: This always matches.
Pattern matching can look deep into object attributes. Despite the
Point(x=0, y=0) pattern looking like a constructor call, Python does not call an object constructor when evaluating patterns. It also doesn't inspect arguments and keyword arguments of __init__() methods, so you can access any attribute value in your match pattern.
Match patterns can also use "positional attribute" syntax, but that requires a bit more work. (PEPs: 634, 635, and 636)