PEP-0634 Structural Pattern Matching

../../_images/fenando_perez.png

Examples

Example class Point

 1 from dataclasses import dataclass
 2
 3 @dataclass
 4 class Point:
 5     x: int
 6     y: int
 7
 8 def whereis(point):
 9     match point:
10         case Point(0, 0):
11             print("Origin")
12         case Point(0, y):
13             print(f"Y={y}")
14         case Point(x, 0):
15             print(f"X={x}")
16         case Point():
17             print("Somewhere else")
18         case _:
19             print("Not a point")
20
21
22 def whereis(point):
23     match point:
24         case (0, 0):
25             print("Origin")
26         case (0, y):
27             print(f"Y={y}")
28         case (x, 0):
29             print(f"X={x}")
30         case (_, _):
31             print("Somewhere else")
32         case _:
33             print("Not a point")