Guido van Rossum
The new implementation is much like the "match" operator provided in Scala, Rust, and F#, which compares the result of executing a specified expression against a list of patterns listed in blocks based on the "case" operator. Unlike the "switch" operator available in C, Java, and JavaScript, "match"-based expressions offer much more
def http_error(status):
match status:
case 400:
return "Bad request"
case 401|403|404:
return "Not allowed"
case 418:
return "I'm a teapot"
case_:
return "Something else"
For example, you can unpack objects, tuples, lists, and arbitrary sequences to bind variables based on available values. It is allowed to define nested templates, use additional "if" conditions in the template, use masks ("[x, y, *rest]"), mapping key/value bindings (for example, {"bandwidth": b, "latency": l} to extract "bandwidth" and "latency" values ββand a dictionary), extract subpatterns (the ":=" operator), use named constants in the template. In classes, it is possible to customize the matching behavior using the "__match__()" method.
from dataclasses import dataclass
@dataclass
classPoint:
x:int
y:int
def whereis(point):
match point:
case Point(0, 0):
print("Origin")
case Point(0, y):
print(f"Y={y}")
casePoint(x, 0):
print(f"X={x}")
casePoint():
print("somewhere else")
case_:
print("Not a point")
match point:
case Point(x, y) if x == y:
print(f"Y=X at {x}")
casePoint(x, y):
print(f"Not on the diagonal")
RED, GREEN, BLUE = 0, 1, 2
match color:
case .RED:
print("I see red!")
case .GREEN:
print("Grass is green")
case .BLU
E:
print("I'm feeling the blues :(")
A set has been prepared for review
Source: opennet.ru