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) 功能。檢查