Python 3.10 有什麼新功能

編輯者:

Pablo Galindo Salgado

本文介紹了 Python 3.10 與 3.9 相比多了哪些新功能。Python 3.10 已於 2021 年 10 月 4 日發布。有關完整詳細資訊,請參閱 changelog

發布重點摘要

新增語法特性:

  • PEP 634,結構模式匹配 (Structural Pattern Matching):規範

  • PEP 635,結構模式匹配:動機和基本原理

  • PEP 636,結構模式匹配:教學

  • bpo-12782,現在正式允許帶括號的情境管理器 (context manager)。

標準函式庫中的新功能:

  • PEP 618,新增可選的長度檢查到 zip。

直譯器改進:

  • PEP 626,用於除錯和其他工具的精確列號。

新的 typing 功能:

  • PEP 604,允許將聯集型別 (union types) 寫為 X | Y

  • PEP 612,參數規範變數 (Parameter Specification Variables)

  • PEP 613,顯式型別別名 (Explicit Type Aliases)

  • PEP 647,使用者定義的型別防護 (User-Defined Type Guards)

重要的棄用、刪除或限制:

  • PEP 644,需要 OpenSSL 1.1.1 或更高版本

  • PEP 632,棄用 distutils 模組。

  • PEP 623,棄用並準備刪除 PyUnicodeObject 中的 wstr 成員。

  • PEP 624,刪除 Py_UNICODE 編碼器 API

  • PEP 597,新增可選的 EncodingWarning

新增功能

帶括號的情境管理器

現在支援使用成對的括號來將多個情境管理器以數行表示。這允許了與過去的引入陳述式 (import statement) 類似的方法來格式化一組多行的情境管理器集合。例如,以下範例現在都是有效的:

with (CtxManager() as example):
    ...

with (
    CtxManager1(),
    CtxManager2()
):
    ...

with (CtxManager1() as example,
      CtxManager2()):
    ...

with (CtxManager1(),
      CtxManager2() as example):
    ...

with (
    CtxManager1() as example1,
    CtxManager2() as example2
):
    ...

也可以在封閉群組的末尾使用逗號:

with (
    CtxManager1() as example1,
    CtxManager2() as example2,
    CtxManager3() as example3,
):
    ...

此新語法使用新剖析器的非 LL(1) 功能。檢查 PEP 617 了解更多詳細資訊。

(由 Guido van Rossum、Pablo Galindo 和 Lysandros Nikolaou 在 bpo-12782bpo-40334 中貢獻。)

更好的錯誤訊息

SyntaxErrors

當剖析包含未成對括號或方括號的程式碼時,直譯器現在會包含未成對括號的位置,而不是顯示 SyntaxError: unexpected EOF while parsing 或指向某些不正確的位置。例如,以下程式碼(注意未閉合的 { ):

expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
            38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,
some_other_code = foo()

以前版本的直譯器會在奇怪的地方顯示有語法錯誤:

File "example.py",