IT资讯 Python 终将支持模式匹配

teno · 2021-02-10 09:00:06 · 热度: 10

在经过一些讨论后,Python 指导委员会接受了在 Python 中添加模式匹配(pattern-matching)的提议,具体情况为采纳 PEP 634635 636, 拒绝 PEP 640 642

Python 终将支持模式匹配

一直以来,关于 Python 语言中指定多分支条件的实现(类似于 C/C++ 的 switch 语句),Python 社区提出了各种各样的建议,但是没有一个提案能最终实现。在过去 8 个月左右的时间里,Python 社区讨论了一个可能解决多分支条件问题(甚至更多)的提案并被采纳 —— 模式匹配(PEP 634635 636),示例如下:

match command.split():  #以下拼凑而成,关注用法
    case ["quit"]:
        print("Goodbye!")
        quit_game()
    case ["get", obj]:
        character.get(obj, current_room)
    case ["go", direction]:
        current_room = current_room.neighbor(direction)
    case ["drop", *objects]:
        for obj in objects:
            character.drop(obj, current_room)
    case ["north"] | ["go", "north"]:
        current_room = current_room.neighbor("north")
    case ["go", ("north" | "south" | "east" | "west")]:
        current_room = current_room.neighbor(...)
    case ["go", direction] if direction in current_room.exits:
        current_room = current_room.neighbor(direction)
    case Click(position=(x, y)):
        handle_click_at(x, y)
    case Click((x, y)):
        handle_click_at(x, y)
    case Click((x, y), button=Button.LEFT):  # This is a left click
        handle_click_at(x, y)
    case {"sleep": duration}:
            ui.wait(duration)
    case {"sleep": float(duration)}:
            ui.wait(duration)
    case _:
        print(f"Sorry, I couldn't understand {command!r}")

在邮件中,Python 指导委员会认为该功能需要全面的文档和规范,包括文档的教程部分和语言参考,并且该文档必须随 Python 3.10 发出,因此直到完成这些内容才会发行 3.10。同时,指导委员会表示由于核心开发人员的支持较少等原因,拒绝试图改善模式匹配的 PEP 640 642

此外,尽管目前已经确定,但是在 Python 3.10 的功能冻结点之前(3.10 的日程表参见 PEP 619) ,开发人员仍可提交关于模式匹配的更改,包括已经接受的PEP 634 和拒绝的 PEP 640642。详细内容请查看原邮件

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册