Blog 2025/4/11
Python's match
statement is more powerful than I had at first realized.
Here's a quick demo of what it can do:
#!/usr/bin/env python3
# a demo of Python 3.10's 'match' keyword.
# see https://peps.python.org/pep-0636/
@dataclass
class Branch():
left
right
@dataclass
class Leaf():
value
def matchdemo(x):
match x:
# matching None:
case None:
print("matched None")
# matching specific bools:
case True:
print("matched a specific bool")
# matching specific strings:
case "":
print("matched the empty string")
case "foo":
print("matched a specific string")
# matching specific ints:
case 42:
print("matched a specific int")
# nested arrays
case [[a,b],c]:
# note: this case must come before 'case [a,b]'.
print("matched a nested array")
# matching sequences:
case ["foo", b] if isinstance(b,str) and len(b) > 10:
# note: this case must come before 'case ["foo",b]'.
print("matched with a conditional:", b)
case ["foo",b]:
# note: this case must come before 'case [a,b]'.
print("matched specific item in array of len 2:", b)
case ["shift", ("down"|"up") as direction]:
# note: this case must come before 'case [a,b]'.
print("matched a captured OR group:", direction)
case []:
print("matched array of len 0")
case [a]:
print("matched array of len 1:", a)
case [a,b]:
print("matched array of len 2:", a, b)
case [a,b,c,*rest]:
print("matched array of 3 or more:", a, b, c, rest)
# fallthrough:
case _:
print("default match")
matchdemo(None)
matchdemo(True)
matchdemo("")
matchdemo("foo")
matchdemo(42)
matchdemo([])
matchdemo([10])
matchdemo([10,20])
matchdemo(["foo",30])
matchdemo([10,20,30])
matchdemo([10,20,30,40])
matchdemo([10,20,30,40,50])
matchdemo("fallthrough")
matchdemo([[10,20],30])
matchdemo(["shift", "up"])
matchdemo(["foo", "baaaaaaaar"])
matchdemo(["foo", "baaaaaaaaar"])