def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
6 match-case
Implemented in Python 3.10
6.1 Basic
6.1.1 Simple
400)
http_error(418)
http_error(0) http_error(
"Something's wrong with the internet"
6.1.2 Combined
def http_error2(status):
match status:
case 400:
return "Bad request"
case 401 | 403 | 404: # combine
return "Not allowed"
case _:
return "Something's wrong with the internet"
401)
http_error2(403) http_error2(
'Not allowed'
class Point:
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(0, 0)
p0 where_is(p0)
Origin
= Point(1, 1)
p1 where_is(p1)
Somewhere else
6.1.3 Match By length
= [200, 300, 404, 500]
today_responses match today_responses:
case [a]:print(f"One response today: {a}")
case [a, b]:print(f"Two responses today: {a} and {b}")
*rest]:
case [a, b, print(f"All responses: {a}, {b}, {rest}")
All responses: 200, 300, [404, 500]
6.1.4 Using __match_args__
class Point:
__match_args__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
# Suppose you have an instance of Point
= Point(1, 2) point
You can use pattern matching to destructure the point:
match point:
case Point(x, y):
print(f"The point is at ({x}, {y}).")
The point is at (1, 2).
Is equivalent to:
if isinstance(point, Point):
print(f"The point is at ({point.x}, {point.y}).")
The point is at (1, 2).
In this example, the match statement checks if point is an instance of Point and then automatically unpacks its x and y attributes according to the order specified in __match_args__
.