defcommand_split(command): match command.split(): case ["make"]: print("default make") case ["make", cmd]: # 这里有新变量cmd,case语句会将第二部分的任何对象绑定到cmd变量上(注意不是assign) print(f"make command found: {cmd}") case ["restart"]: print("restarting") case ["rm", *files]: # files: list print(f"deleting files: {files}") case _: print("didn't match")
1 2 3 4 5 6 7
defmatch_alternatives(command): match command.split(): case ["north"] | ["go", "north"]: # | represents 'or' print("going north") case ["get", obj] | ["pick", "up", obj] | ["pick", obj, "up"]: print(f"picking up: {obj}")
1 2 3 4 5
# 子模式-模式可以嵌套 defmatch_capture_subpattern(command): match command.split(): case ["go", ("north" | "south" | "east" | "west") as direction]: print(f"going {direction}")
1 2 3 4 5 6 7
# go only for "allowable direction" defmatch_guard(command, exits): match command.split(): case ["go", direction] if direction in exits: print(f"going {direction}") case ["go", _]: print(f"can't go that way")
defmatch_by_class(event): match event: case Click(position=(x,y), button="left"): # is `Click` intance? with attr `button=left`? # and position is a tuple? # 不会构建一个intance. print(f"handling left click at {x,y}") case Click(position=(x,y)): print(f"handling other click at {x,y}") case KeyPress("Q"|"q") | Quit(): print("quitting") case KeyPress(key_name="up arrow"): print("going up") case KeyPress(): pass#ignore other keystrokes case other_event: raise ValueError(f'unrecognized event: {other_event}')
匹配字典
1 2 3 4 5 6 7 8 9 10
defmatch_json_event(event): match event: case {"transport": "http"}: # 是否有一个key:value组合为上述内容 print("insecure event ignored") case {"verb": "GET", "page": "articles", "pageno": n}: # "pageno"是否出现?出现的话,把值赋给n print(f"let me get that article for you on page {n}...") case {"verb": "POST", "page": "signup"}: print("handling signup")