Python 3.10來了,switch語法終于出現(xiàn)

轉(zhuǎn)自:機(jī)器之心
對于從事數(shù)據(jù)科學(xué)和人工智能領(lǐng)域的人們來說,Python 是大家的首選編程語言。根據(jù)最近的一項(xiàng)調(diào)查,27% 的程序員開發(fā)職位要求掌握 Python 語言,今年年初這一數(shù)字還只是 18.5%。
Python 流行的原因在于其擁有非常直觀的能力:這門語言擁有大量的庫、足夠高的生產(chǎn)效率,還相對易于學(xué)習(xí)。去年 10 月,Python 的 3.9 版正式發(fā)布了,從字典更新 / 合并到添加新的字符串方法,再到 zoneinfo 庫的引入,Python 3.9 添加了許多新特性.
Python3.10 的第二個(gè) alpha 版本也已于去年 11 月初發(fā)布,相比于不久前發(fā)布的 3.9 版本,新版本對類型注釋擴(kuò)展、zip、位計(jì)數(shù)、字典映射又有了新的改進(jìn)。就在昨天,Python 3.10 beta 版發(fā)布了,新的 beta 版最大的亮點(diǎn)可能就是引入了 switch-case 語句。
Python 3.10 beta 版新改進(jìn)
Switch 語句存在于很多編程語言中,但 Python 編程語言不支持 Switch 語句。早在 2016 年,PEP 3103 就被提出,建議 Python 支持 switch-case 語句。然而,在調(diào)查中發(fā)現(xiàn)很少人支持該特性,Python 開發(fā)人員放棄了它。
時(shí)間在推到 2020 年,Python 的創(chuàng)始人 Guido van Rossum,提交了顯示 switch 語句的第一個(gè)文檔,命名為 Structural Pattern Matching,見 PEP 634 。
如今,隨著 Python 3.10 beta 版的發(fā)布,終于將 switch-case 語句納入其中。
帶圓括號的上下文管理器:現(xiàn)在支持在上下文管理器中跨多行使用括號進(jìn)行延續(xù)。也可以在所包含組的末尾使用逗號。
with (
CtxManager1() as example1,
CtxManager2() as example2,
CtxManager3() as example3,
):
...

match subject:
case <pattern_1>:
<action_1>
case <pattern_2>:
<action_2>
case <pattern_3>:
<action_3>
case _:
<action_wildcard>
http_code = "418"
match http_code:
case "200":
print("OK")
do_something_good()
case "404":
print("Not Found")
do_something_bad()
case "418":
print("I'm a teapot")
make_coffee()
case _:
print("Code not found")

http_code = "418"
if http_code == "418":
print("OK")
do_something_good()
elif http_code == "404":
print("Not Found")
do_something_bad()
elif http_code == "418"
print("I'm a teapot")
make_coffee()
else:
print("Code not found")
點(diǎn)擊關(guān)注【python入門與進(jìn)階】,閱讀更多精彩內(nèi)容 ??????

