Python3.11正式版,它來了!
轉載請註明出處❤️
作者:測試蔡坨坨
原文鏈接:caituotuo.top/b055fbf2.html
你好,我是測試蔡坨坨。
就在前幾天,2022年10月24日,Python3.11正式版發布了!
Python官方在2020年1月1日結束了對Python2的維護,這也意味著Python2已經成為歷史,真正進入了Python3時代。自從進入Python3版本以來,官方已經發布了眾多修改版本分支,現在最新的正式版本就是前不久剛發布的Python3.11,這一版本歷經17個月的開發,現在公開可用,據說對用戶更友好。
今天,我們就來一起看看Python3.11都更新了些什麼呢。
官方文檔://docs.python.org/3.11/whatsnew/3.11.html
# author: 測試蔡坨坨
# datetime: 2022/10/29 15:14
# function: Python3.11 輸出版本資訊
import sys
print("Python Version: ", sys.version)
# Python Version: 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]
print("Python Version Info: ", sys.version_info)
# Python Version Info: sys.version_info(major=3, minor=11, micro=0, releaselevel='final', serial=0)
速度更快
首先第一點,也是最重要的,就是它更快了,官方說法是Python 3.11比Python 3.10快10-60%。
Python 3.11 is between 10-60% faster than Python 3.10. On average, we measured a 1.25x speedup on the standard benchmark suite. See Faster CPython for details.
眾所周知,Python語法簡潔、功能強大,特別容易上手,因此使用人數超級多,在眾多最受歡迎程式語言榜單中多次位列第一,但是它有一個明顯的劣勢就是純Python編寫的程式執行效率低,很多開發者都期待這門語言的性能有所提升。
更加人性化的報錯
PEP 657: Fine-grained error locations in tracebacks
官方文檔://docs.python.org/3.11/whatsnew/3.11.html#whatsnew311-pep657
When printing tracebacks, the interpreter will now point to the exact expression that caused the error, instead of just the line.
更加人性化的報錯,與之前顯示在某一行的報錯不同,這個版本的報錯會顯示具體原因,畫出具體位置。
Python程式語言對初學者非常友好,具有易於理解的語法和強大的數據結構,但是對於剛剛接觸Python的同學來說卻存在一個難題,即如何解釋當Python遇到錯誤時顯示的Traceback,有了這個功能就可以幫助用戶快速解釋錯誤消息。
舉栗:
# author: 測試蔡坨坨
# datetime: 2022/10/29 15:35
# function: PEP 657: Fine-grained error locations in tracebacks
# 定義一個函數
def data():
return {
"name": "測試蔡坨坨",
"studying": [
{
"language": "Python",
"version": "3.11"
}
]
}
if __name__ == '__main__':
# 調用函數並指定一個錯誤的索引
print(data()["studying"][2])


一個IndexError的例子,我們可以看到嵌入在Traceback中的~和^符號詳細地指嚮導致錯誤的程式碼,這種帶注釋的Traceback對於過於複雜的程式碼來說是比較友好的。
異常組
PEP 654: Exception Groups and except
官方文檔://docs.python.org/3.11/whatsnew/3.11.html#whatsnew311-pep654
Exception Groups 讓我們的Exception資訊具有層次感,之前的Python每次只能處理一個Exception,異常組的使用豐富了Exception的作用,可以引入多個Exception,同時也豐富了我們程式碼分析的資訊量。
舉栗:
# author: 測試蔡坨坨
# datetime: 2022/10/29 15:58
# function: PEP 654: Exception Groups and except *
from builtins import ExceptionGroup
def test():
raise ExceptionGroup(
"異常嵌套關係",
[
ValueError(456),
ExceptionGroup(
"引入第三方庫",
[
ImportError("無該模組"),
ModuleNotFoundError("你需要其他模組")
]
),
TypeError("int")
]
)
if __name__ == '__main__':
test()

支援TOML配置解析
PEP 680: tomllib — Support for parsing TOML in the Standard Library
官方文檔://docs.python.org/3/library/tomllib.html#module-tomllib
增加了TOML(Tom's Obvious Minimal Language 的縮寫)文件的讀取,toml文件與自動化測試框架或Web開發中的config、yaml文件類似,都是通過修改配置文件來保持框架源碼的不變。Python社區已將TOML作為首選格式,雖然TOML已被使用多年,但Python並沒有內置的TOML支援,而在Python3.11中tomllib已經是個內置模組,這個新模組建立在 toml 第三方庫之上,允許解析 TOML 文件。
舉栗:
demo.toml:
# This is a TOML document.
title = "測試蔡坨坨"
[info]
name = "caituotuo"
blog = "www.caituotuo.top"
hobby = ["吃飯", "睡覺", "學Python"]
[other]
enable = true
# author: 測試蔡坨坨
# datetime: 2022/10/29 16:15
# function: PEP 680: tomllib — Support for parsing TOML in the Standard Library
import tomllib
def read_toml():
with open("demo.toml", "rb") as f:
data = tomllib.load(f)
print(data)
if __name__ == '__main__':
read_toml()
# {'title': '測試蔡坨坨', 'info': {'name': 'caituotuo', 'blog': 'www.caituotuo.top', 'hobby': ['吃飯', '睡覺', '學Python']}, 'other': {'enable': True}}
更加安全
PEP 675: Arbitrary literal string type
官方文檔://docs.python.org/3/library/typing.html#typing.LiteralString
The new LiteralString annotation may be used to indicate that a function parameter can be of any literal string type. This allows a function to accept arbitrary literal string types, as well as strings created from other literal strings. Type checkers can then enforce that sensitive functions, such as those that execute SQL statements or shell commands, are called only with static arguments, providing protection against injection attacks.
防止SQL注入,指定參數為LiteralString,當傳入普通的String時就不可以工作。
# author: 測試蔡坨坨
# datetime: 2022/10/29 16:34
# function: PEP 675: Arbitrary literal string type
from typing import LiteralString
def run_query(sql: LiteralString):
pass
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
run_query("SELECT * FROM students") # ok
run_query(literal_string) # ok
run_query("SELECT * FROM " + literal_string) # ok
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)
異常Notes
PEP 678: Exceptions can be enriched with notes
官方文檔://docs.python.org/3/whatsnew/3.11.html#whatsnew311-pep678
常規異常具有添加任意 notes 的擴展能力,可以使用.add_note()向任何異常添加一個note,並通過檢查.__notes__屬性來查看現有notes。
# author: 測試蔡坨坨
# datetime: 2022/10/29 16:53
# function: PEP 678: Exceptions can be enriched with notes
try:
raise TypeError('str')
except TypeError as e:
e.add_note('類型錯了')
e.add_note('該用int')
raise e

以上幾點就是我認為 Python 3.11 比較有意思的部分,更多內容可參考官方文檔,想體驗新功能的小夥伴感覺去試試新版本吧 ~

