B15 - match
sources: python docs, ArjanCodes
- compares a given expression with successive patterns in the case block(s)
- several literals can be combined using pipes (
|)
def run_command(command: str) -> None:
match command:
case "quit":
print("quitting")
quit()
case "help":
print("getting help")
case other:
print(f"unknown command: {other!r}")
def run_command_2(command: str) -> None:
match command.split():
case ["load", filename]:
print(f"loading {filename}")
case ["save", filename]:
print(f"saving {filename}")
case ["quit" | "exit" | "bye"]:
print("quitting")
quit()
case other:
print(f"unknown command: {other!r}")
- if
otheris not used in the case, it can be replaced with_
...
case _:
print("unknown command")
case ["quit" | "exit" | "bye", "--force"]:
print("quitting")
- here,
"--force"needs to be added to the string to quit
case ["quit" | "exit" | "bye", *rest]:
if "--force" in rest or "-f" in rest:
print("force quitting")
else:
print("quitting")
case ["quit" | "exit" | "bye", *rest] if "--force" in rest or "-f" in rest:
print("force quitting")
quit()
case ["quit" | "exit" | "bye"]:
print("quitting")
quit()
- patterns can look like unpacking assignments
- they can be used to bind variables
# point is an (x, y) tuple
match point:
case (0, 0):
print("origin")
case (0, y):
print(f"y={y}")
case (x, 0):
print(f"x={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")
-
the second and the third patterns combine a literal and a variable
-
the variable binds a value from the subject
-
classes can be used as well
from dataclasses import dataclass
from typing import list
import shlex
@dataclass
class Command:
"""class that represents a command"""
command: str
arguments: list[str]
def run_command_4(command: Command) -> None:
match command:
case Command(command = "load", arguments = [filename]):
print(f"loading {filename}")
case Command(command = "save", arguments = [filename]):
print(f"saving {filename}")
case Command(command = "quit" | "exit" | "bye", arguments = ["--force" | "-f"]):
print("force quitting")
quit()
case Command(command = "quit" | "exit" | "bye"):
print("quitting")
quit()
case _:
print(f"Unknown command: {command!r}")
def main() -> None:
while True:
command, arguments = shlex.split(input("Enter command: "))
run_command_4(Command(command, arguments))
- note: the order of the cases matter
- if the
quitcase is placed beforequit -f, it will take precedent and enteringquit ifwill simply quit
- if the