Py学习  »  Python

Python终将支持模式匹配

OSC开源社区 • 3 年前 • 331 次点击  

喜欢就关注我们吧!

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

一直以来,关于 Python 语言中指定多分支条件的实现(类似于 C/C++ 的 switch 语句),Python 社区提出了各种各样的建议,但是没有一个提案能最终实现。在过去 8 个月左右的时间里,Python 社区讨论了一个可能解决多分支条件问题(甚至更多)的提案并被采纳 —— 模式匹配(PEP 634、635 和 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 640、642。


Rust基金会正式成立

2021-02-10

JetBrains 2020年度亮点:IDEA中国用户最多、持续加大开源贡献力度

2021-02-09

Vuex 4 正式发布

2021-02-10



觉得不错,请点个在看

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/107621
 
331 次点击