Python 3.15 有什么新变化

编者:

Hugo van Kemenade

本文介绍了 Python 3.15 相比 3.14 的新增特性。

详情请参阅 更新日志

备注

预发布版用户应当了解到此文档目前处于草稿状态。 它将随着 Python 3.15 的发布进程不断更新,因此即使已经阅读过较早的版本也仍然值得再次查看。

摘要 -- 发布重点

新的特性

PEP 810: 显式惰性导入

大型 Python 应用程序经常会有启动时间缓慢的困扰 。此问题有很大一部分是来自导入系统:当一个模块被导入时,Python 必须定位文件,将其从磁盘读入,将其编译为字节码,并执行全部的最高层级代码。 对于具有较深依赖树的应用程序来说,此过程耗时将以秒计,即使在大部分被导入代码在某次运行期间从未被实际使用时也是如此。

开发者要绕过此问题可通过将导入移至函数内部,使用 importlib 按需加载模块,或重新调整代码结构以避免不需要的依赖项。 这些方式有一定效果但会使代码变得更难阅读和维护,使代码库中的 import 语句到处零星散布,并需要严格制定规则才能持续应用。

Python 现在会使用新的 lazy 软关键字通过显式的 lazy 导入提供一种更清晰的解决方案。Python 将延迟实际的模块加载直到所导入的名称首次被使用。 这在组织方面给予你在文件顶部声明所有导入的便利同时只付出你实际使用模块的加载耗时。

lazy 关键字同时适用于 importfrom ... import 语句。 当你使用 lazy import heavy_module 的写法时,Python 不会立即加载该模块。 作为替代,它将创建一个轻量的代理对象。 实际的模块加载会在你首次访问该名称时透明地发生:

lazy import json
lazy from pathlib import Path

print("Starting up...")  # json 和 pathlib 尚未加载

data = json.loads('{"key": "value"}')  # json 在这里加载
p = Path(".")  # pathlib 在这里加载

这种机制特别适用于在最高层级导入大批模块但在任何给定运行中仅使用它们的一个子集的应用程序。 延迟加载可减少启动反应时间而无需代码重新调整结构或在代码库中零散使用有条件的导入。

对于加载惰性导入模块失败的情况(例如,当模块不存在时),Python 会在首次使用时而不是导入时引发异常。 相关的回溯将同时包括名称被访问的位置和初始的 import 语句,以使对失败的诊断和调试更为直观。

For cases where you want to enable lazy loading globally without modifying source code, Python provides the -X lazy_imports command-line option and the PYTHON_LAZY_IMPORTS environment variable. Both accept two values: all makes all imports lazy by default, and normal (the default) respects the lazy keyword in source code. The sys.set_lazy_imports() and sys.get_lazy_imports() functions allow changing and querying this mode at runtime.

想要更有选择性的控制,sys.set_lazy_imports_filter() 接受一个可调用对象决定是否应惰性加载特定的模块。 该过滤器接收三个参数:要导入模块的名称 (或 None),已导入模块的名称,以及 fromlist (或 None 表示用于常规导入)。它应返回 True 表示允许惰性导入,或 False 表示以强制立即加载。 这将允许只让你自己的应用的模块采用惰性导入而而让第三方依赖项采用立即导入的模式:

import sys

def myapp_filter(importing, imported, fromlist):
    return imported.startswith("myapp.")
sys.set_lazy_imports_filter(myapp_filter)
sys.set_lazy_imports("all")

import myapp.slow_module  # 惰性(匹配过滤器)
import json               # 立即(不匹配过滤器)

对于需要以编程方式检测惰性导入的代码代理类型本身可作为 types.LazyImportType 使用。

There are some restrictions on where the lazy keyword can be used. Lazy imports are only permitted at module scope; using lazy inside a function, class body, or try/except/finally block raises a SyntaxError. Neither star imports nor future imports can be lazy (lazy from module import * and lazy from __future__ import ... both raise SyntaxError).

For code that cannot use the lazy keyword directly (for example, when supporting Python versions older than 3.15 while still using lazy imports on 3.15+), a module can define __lazy_modules__ as a container of fully qualified module name strings. Regular import statements for those modules are then treated as lazy, with the same semantics as the lazy keyword:

__lazy_modules__ = ["json", "pathlib"]

import json     # lazy
import os       # still eager

参见

PEP 810 for the full specification and rationale.

(Contributed by Pablo Galindo Salgado and Dino Viehland in gh-142349.)

PEP 814: Add frozendict built-in type

A new immutable type, frozendict, is added to the builtins module. It does not allow modification after creation. A frozendict is not a subclass of dict; it inherits directly from object. A frozendict is hashable as long as all of its keys and values are hashable. A frozendict preserves insertion order, but comparison does not take order into account.

例如:

>>> a = frozendict(x=1, y=2)
>>> a
frozendict({'x': 1, 'y': 2})
>>> a['z'] = 3
Traceback (most recent call last):
  File "<python-input-2>", line 1, in <module>
    a['z'] = 3
    ~^^^^^
TypeError: 'frozendict' object does not support item assignment
>>> b = frozendict(y=2, x=1)
>>> hash(a) == hash(b)
True
>>> a == b
True

The following standard library modules have been updated to accept frozendict: copy, decimal, json, marshal, plistlib (only for serialization), pickle, pprint and xml.etree.ElementTree.

eval() and exec() accept frozendict for globals, and type() and str.maketrans() accept frozendict for dict.

Code checking for dict type using isinstance(arg, dict) can be updated to isinstance(arg, (dict, frozendict)) to accept also the frozendict type, or to isinstance(arg, collections.abc.Mapping) to accept also other mapping types such as MappingProxyType.

参见

PEP 814 for the full specification and rationale.

(Contributed by Victor Stinner and Donghee Na in gh-141510.)

PEP 661: Add sentinel built-in type

A new sentinel type is added to the builtins module for creating unique sentinel values with a concise representation. Sentinel objects preserve identity when copied, support use in type expressions with the | operator, and can be pickled when they are importable by module and name.

(PEP by Tal Einat; contributed by Jelle Zijlstra in gh-148829.)

参见

PEP 661 for further details.

PEP 799: A dedicated profiling package

A new profiling module has been added to organize Python's built-in profiling tools under a single, coherent namespace. This module contains:

The cProfile module remains as an alias for backwards compatibility. The profile module is deprecated and will be removed in Python 3.17.

参见

PEP 799 for further details.

(Contributed by Pablo Galindo and László Kiss Kollár in gh-138122.)

Tachyon: High frequency statistical sampling profiler

Tachyon profiler logo

A new statistical sampling profiler (Tachyon) has been added as profiling.sampling. This profiler enables low-overhead performance analysis of running Python processes without requiring code modification or process restart.

Unlike deterministic profilers (such as profiling.tracing) that instrument every function call, the sampling profiler periodically captures stack traces from running processes. This approach provides virtually zero overhead while achieving sampling rates of up to 1,000,000 Hz, making it the fastest sampling profiler available for Python (at the time of its contribution) and ideal for debugging performance issues in production environments. This capability is particularly valuable for debugging performance issues in production systems where traditional profiling approaches would be too intrusive.

Key features include:

  • Zero-overhead profiling: Attach to any running Python process without affecting its performance. Ideal for production debugging where you can't afford to restart or slow down your application.

  • No code modification required: Profile existing applications without restart. Simply point the profiler at a running process by PID and start collecting data.

  • Flexible target modes:

    • Profile running processes by PID (attach) - attach to already-running applications

    • Run and profile scripts directly (run) - profile from the very start of execution

    • Execute and profile modules (run -m) - profile packages run as python -m module

    • Capture a one-shot snapshot of a running process (dump) - print a traceback-style stack of every thread (or all asyncio tasks with --async-aware). Useful for investigating hung processes.

  • Multiple profiling modes: Choose what to measure based on your performance investigation:

    • Wall-clock time (--mode wall, default): Measures real elapsed time including I/O, network waits, and blocking operations. Use this to understand where your program spends calendar time, including when waiting for external resources.

    • CPU time (--mode cpu): Measures only active CPU execution time, excluding I/O waits and blocking. Use this to identify CPU-bound bottlenecks and optimize computational work.

    • GIL-holding time (--mode gil): Measures time spent holding Python's Global Interpreter Lock. Use this to identify which threads dominate GIL usage in multi-threaded applications.

    • Exception handling time (--mode exception): Captures samples only from threads with an active exception. Use this to analyze exception handling overhead.

  • Thread-aware profiling: Option to profile all threads (-a) or just the main thread, essential for understanding multi-threaded application behavior.

  • Multiple output formats: Choose the visualization that best fits your workflow:

    • --pstats: Detailed tabular statistics compatible with pstats. Shows function-level timing with direct and cumulative samples. Best for detailed analysis and integration with existing Python profiling tools.

    • --collapsed: Generates collapsed stack traces (one line per stack). This format is specifically designed for creating flame graphs with external tools like Brendan Gregg's FlameGraph scripts or speedscope.

    • --flamegraph: Generates a self-contained interactive HTML flame graph using D3.js. Opens directly in your browser for immediate visual analysis. Flame graphs show the call hierarchy where width represents time spent, making it easy to spot bottlenecks at a glance.

    • --gecko: Generates Gecko Profiler format compatible with Firefox Profiler. Upload the output to Firefox Profiler for advanced timeline-based analysis with features like stack charts, markers, and network activity.

    • --heatmap: Generates an interactive HTML heatmap visualization with line-level sample counts. Creates a directory with per-file heatmaps showing exactly where time is spent at the source code level.

  • Live interactive mode: Real-time TUI profiler with a top-like interface (--live). Monitor performance as your application runs with interactive sorting and filtering.

  • Async-aware profiling: Profile async/await code with task-based stack reconstruction (--async-aware). See which coroutines are consuming time, with options to show only running tasks or all tasks including those waiting.

  • Opcode-level profiling: Gather bytecode opcode information for instruction-level profiling (--opcodes). Shows which bytecode instructions are executing, including specializations from the adaptive interpreter.

See profiling.sampling for the complete documentation, including all available output formats, profiling modes, and configuration options.

(Contributed by Pablo Galindo and László Kiss Kollár in gh-135953 and gh-138122.)

PEP 831: Frame pointers enabled by default

CPython is now built with frame pointers by default on platforms that support them. This uses the compiler flags -fno-omit-frame-pointer and -mno-omit-leaf-frame-pointer, making native stack unwinding faster and more reliable for system profilers, debuggers, crash analysis tools, and eBPF-based observability tools.

The flags are exposed through sysconfig, so extension modules built by tools that consume Python's build configuration inherit frame pointers by default. This propagation is intentional: mixed Python/native profiling needs an unbroken frame-pointer chain through the interpreter, extension modules, embedding applications, and native libraries.

重要

Third-party build backends and native build systems should preserve these flags when they consume Python's sysconfig values. Build systems that compile C, C++, Rust, or other native code without inheriting Python's compiler flags should enable equivalent frame-pointer flags themselves. A single native component built without frame pointers can break stack unwinding for the whole Python process.

(Contributed by Pablo Galindo Salgado and Savannah Ostrowski in gh-149201; PEP 831 written by Pablo Galindo Salgado, Ken Jin, Savannah Ostrowski, and Diego Russo.)

参见

PEP 831 for further details.

PEP 798: Unpacking in comprehensions

List, set, and dictionary comprehensions, as well as generator expressions, now support unpacking with * and **. This extends the unpacking syntax from PEP 448 to comprehensions, providing a new syntax for combining an arbitrary number of iterables or dictionaries into a single flat structure. This new syntax is a direct alternative to nested comprehensions, itertools.chain(), and itertools.chain.from_iterable(). For example:

>>> lists = [[1, 2], [3, 4], [5]]
>>> [*L for L in lists]  # equivalent to [x for L in lists for x in L]
[1, 2, 3, 4, 5]

>>> sets = [{1, 2}, {2, 3}, {3, 4}]
>>> {*s for s in sets}  # equivalent to {x for s in sets for x in s}
{1, 2, 3, 4}

>>> dicts = [{'a': 1}, {'b': 2}, {'a': 3}]
>>> {**d for d in dicts}  # equivalent to {k: v for d in dicts for k,v in d.items()}
{'a': 3, 'b': 2}

Generator expressions can similarly use unpacking to yield values from multiple iterables:

>>> gen = (*L for L in lists)  # equivalent to (x for L in lists for x in L)
>>> list(gen)
[1, 2, 3, 4, 5]

This change also extends to asynchronous generator expressions, such that, for example, (*a async for a in agen()) is equivalent to (x async for a in agen() for x in a).

参见

PEP 798 for further details.

(Contributed by Adam Hartz in gh-143055.)

PEP 829: Package startup configuration files

Loaded by the site module when -S is not given, .pth files can contain lines that both extend sys.path and execute arbitrary code when the line starts with import (followed by a space or tab). The latter functionality can be problematic, since it is difficult to know exactly what gets executed when Python starts up.

As a step towards improving the ability to audit pre-start executable code, Python 3.15 introduces .start files which contain entry point specifications of the form pkg.mod:callable where pkg.mod is the import path to the given callable. When Python starts up, the callable is located and called with no arguments.

import lines in .pth files are silently deprecated. When a matching .start file is found, import lines in .pth files are ignored. There is no change to sys.path extension lines in .pth files.

(由 Barry Warsaw 在 gh-148641 中贡献。)

PEP 803 -- 自由线程构建版的稳定 ABI

C extensions that target the Stable ABI can now be compiled for the new Stable ABI for Free-Threaded Builds (also known as abi3t), which makes them compatible with free-threaded builds of CPython. This usually requires some non-trivial changes to the source code; specifically:

The reference documentation for these features is complete, but currently aimed at early adopters. A migration guide is planned for an upcoming beta release.

Note that Stable ABI does not offer all the functionality that CPython has to offer. Extensions that cannot switch to abi3t should continue to build for the existing Stable ABI (abi3) and the version-specific ABI for free-threading (cp315t) separately.

Stable ABI for Free-Threaded Builds should typically be selected in a build tool (such as, for example, Setuptools, meson-python, scikit-build-core, or Maturin). At the time of writing, these tools did not support abi3t. If this is the case for your tool, compile for cp315t separately. If not using a build tool -- or when writing such a tool -- you can select abi3t by setting the macro Py_TARGET_ABI3T as discussed in Compiling for Stable ABI.

参见

PEP 803 for further details.

PEP 788: Protecting the C API from interpreter finalization

In the C API, interpreter finalization can be problematic for many extensions, because attaching a thread state will permanently hang the thread, resulting in deadlocks and other spurious issues. Additionally, it has historically been impossible to safely check whether an interpreter is alive before using it, leading to crashes when a thread concurrently deletes an interpreter while another thread is trying to attach to it.

There are now several new suites of APIs to circumvent these problems:

  • Interpreter guards, which prevent an interpreter from finalizing.

  • Interpreter views, which allow thread-safe access to an interpreter that may be concurrently finalizing or deleted.

  • New APIs to automatically attach and detach thread states that come with built-in protection against finalization.

In addition, APIs in the PyGILState family (most notably PyGILState_Ensure() and PyGILState_Release()) have been soft deprecated. There is no plan to remove them, and existing code will continue to work, but there will be no new PyGILState APIs in future versions of Python.

参见

PEP 788 for further details.

(Contributed by Peter Bierma in gh-149101.)

改进的错误消息

  • The interpreter now provides more helpful suggestions in AttributeError exceptions when accessing an attribute on an object that does not exist, but a similar attribute is available through one of its members.

    For example, if the object has an attribute that itself exposes the requested name, the error message will suggest accessing it via that inner attribute:

    @dataclass
    class Circle:
       radius: float
    
       @property
       def area(self) -> float:
          return pi * self.radius**2
    
    class Container:
       def __init__(self, inner: Circle) -> None:
          self.inner = inner
    
    circle = Circle(radius=4.0)
    container = Container(circle)
    print(container.area)
    

    Running this code now produces a clearer suggestion:

    Traceback (most recent call last):
      File "/home/pablogsal/github/python/main/lel.py", line 42, in <module>
        print(container.area)
              ^^^^^^^^^^^^^^
    AttributeError: 'Container' object has no attribute 'area'. Did you mean '.inner.area' instead of '.area'?
    
  • When an AttributeError on a builtin type has no close match via Levenshtein distance, the error message now checks a static table of common method names from other languages (JavaScript, Java, Ruby, C#) and suggests the Python equivalent:

    >>> [1, 2, 3].push(4)
    Traceback (most recent call last):
    ...
    AttributeError: 'list' object has no attribute 'push'. Did you mean '.append'?
    
    >>> 'hello'.toUpperCase()
    Traceback (most recent call last):
    ...
    AttributeError: 'str' object has no attribute 'toUpperCase'. Did you mean '.upper'?
    

    When the Python equivalent is a language construct rather than a method, the hint describes the construct directly:

    >>> {}.put("a", 1)
    Traceback (most recent call last):
    ...
    AttributeError: 'dict' object has no attribute 'put'. Use d[k] = v.
    

    When a mutable method is called on an immutable type, the hint suggests the mutable counterpart:

    >>> (1, 2, 3).append(4)
    Traceback (most recent call last):
    ...
    AttributeError: 'tuple' object has no attribute 'append'. Did you mean to use a 'list' object?
    

    These hints also work for subclasses of builtin types.

    (Contributed by Matt Van Horn in gh-146406.)

  • The interpreter now tries to provide a suggestion when delattr() fails due to a missing attribute. When an attribute name that closely resembles an existing attribute is used, the interpreter will suggest the correct attribute name in the error message. For example:

    >>> class A:
    ...     pass
    >>> a = A()
    >>> a.abcde = 1
    >>> del a.abcdf
    Traceback (most recent call last):
    ...
    AttributeError: 'A' object has no attribute 'abcdf'. Did you mean: 'abcde'?
    

    (Contributed by Nikita Sobolev and Pranjal Prajapati in gh-136588.)

  • Several error messages incorrectly using the term "argument" have been corrected. (Contributed by Stan Ulbrych in gh-133382.)

其他语言特性修改

  • Python now uses UTF-8 as the default encoding, independent of the system's environment. This means that I/O operations without an explicit encoding, for example, open('flying-circus.txt'), will use UTF-8. UTF-8 is a widely-supported Unicode character encoding that has become a de facto standard for representing text, including nearly every webpage on the internet, many common file formats, programming languages, and more.

    This only applies when no encoding argument is given. For best compatibility between versions of Python, ensure that an explicit encoding argument is always provided. The opt-in encoding warning can be used to identify code that may be affected by this change. The special encoding='locale' argument uses the current locale encoding, and has been supported since Python 3.10.

    To retain the previous behaviour, Python's UTF-8 mode may be disabled with the PYTHONUTF8=0 environment variable or the -X utf8=0 command-line option.

    参见

    PEP 686 for further details.

    (Contributed by Adam Turner in gh-133711; PEP 686 written by Inada Naoki.)

  • The interpreter help (such as python --help) is now in color. This can be controlled by environment variables. (Contributed by Hugo van Kemenade in gh-148766.)

  • Unraisable exceptions are now highlighted with color by default. This can be controlled by environment variables. (Contributed by Peter Bierma in gh-134170.)

  • More color in argparse, ast, calendar, difflib, http.server, pickletools, PyREPL tab completion, python --help, sqlite3, timeit, tokenize, unraisable exceptions and stdlib (ast, compileall, doctest, gzip, inspect, json.tool, pdb, profiling.sampling, random, regrtest, sqlite3, timeit, tokenize, trace, unittest, uuid, zipapp, zipfile) CLI help.

  • The __repr__() of ImportError and ModuleNotFoundError now shows "name" and "path" as name=<name> and path=<path> if they were given as keyword arguments at construction time. (Contributed by Serhiy Storchaka, Oleg Iarygin, and Yoav Nir in gh-74185.)

  • The __dict__ and __weakref__ descriptors now use a single descriptor instance per interpreter, shared across all types that need them. This speeds up class creation, and helps avoid reference cycles. (Contributed by Petr Viktorin in gh-135228.)

  • The -W option and the PYTHONWARNINGS environment variable can now specify regular expressions instead of literal strings to match the warning message and the module name, if the corresponding field starts and ends with a forward slash (/). (Contributed by Serhiy Storchaka in gh-134716.)

  • Functions that take timestamp or timeout arguments now accept any real numbers (such as Decimal and Fraction), not only integers or floats, although this does not improve precision. (Contributed by Serhiy Storchaka in gh-67795.)

  • Added bytearray.take_bytes(n=None, /) to take bytes out of a bytearray without copying. This enables optimizing code which must return bytes after working with a mutable buffer of bytes such as data buffering, network protocol parsing, encoding, decoding, and compression. Common code patterns which can be optimized with take_bytes() are listed below.

    建议的优化重构

    描述

    旧消息

    New

    Return bytes after working with bytearray

    def read() -> bytes:
        buffer = bytearray(1024)
        ...
        return bytes(buffer)
    
    def read() -> bytes:
        buffer = bytearray(1024)
        ...
        return buffer.take_bytes()
    

    Empty a buffer getting the bytes

    buffer = bytearray(1024)
    ...
    data = bytes(buffer)
    buffer.clear()
    
    buffer = bytearray(1024)
    ...
    data = buffer.take_bytes()
    

    Split a buffer at a specific separator

    buffer = bytearray(b'abc\ndef')
    n = buffer.find(b'\n')
    data = bytes(buffer[:n + 1])
    del buffer[:n + 1]
    assert data == b'abc\n'
    assert buffer == bytearray(b'def')
    
    buffer = bytearray(b'abc\ndef')
    n = buffer.find(b'\n')
    data = buffer.take_bytes(n + 1)
    

    Split a buffer at a specific separator; discard after the separator

    buffer = bytearray(b'abc\ndef')
    n = buffer.find(b'\n')
    data = bytes(buffer[:n])
    buffer.clear()
    assert data == b'abc'
    assert len(buffer) == 0
    
    buffer = bytearray(b'abc\ndef')
    n = buffer.find(b'\n')
    buffer.resize(n)
    data = buffer.take_bytes()
    

    (Contributed by Cody Maloney in gh-139871.)

  • Many functions related to compiling or parsing Python code, such as compile(), ast.parse(), symtable.symtable(), and importlib.abc.InspectLoader.source_to_code(), now allow the module name to be passed. It is needed to unambiguously filter syntax warnings by module name. (Contributed by Serhiy Storchaka in gh-135801.)

  • Allowed defining the __dict__ and __weakref__ __slots__ for any class. (Contributed by Serhiy Storchaka in gh-41779.)

  • Allowed defining any __slots__ for a class derived from tuple (including classes created by collections.namedtuple()). (Contributed by Serhiy Storchaka in gh-41779.)

  • The slice type now supports subscription, making it a generic type. (Contributed by James Hilton-Balfe in gh-128335.)

  • The class memoryview now supports the float complex and double complex C types: formatting characters 'Zf' and 'Zd' respectively. (Contributed by Victor Stinner in gh-146151 and gh-148675.)

  • Allow the count argument of bytes.replace() to be a keyword. (Contributed by Stan Ulbrych in gh-147856.)

  • Unary plus is now accepted in match literal patterns, mirroring the existing support for unary minus. (Contributed by Bartosz Sławecki in gh-145239.)

  • The import system now acquires per-module locks in hierarchical order (parent packages before their submodules). This fixes a long-standing deadlock where one thread importing pkg.sub and another importing pkg.sub.mod could each block the other when pkg/sub/__init__.py imports pkg.sub.mod. (Contributed by Gregory P. Smith in gh-83065.)

默认的交互式 shell

新增模块

math.integer

This module provides access to the mathematical functions for integer arguments (PEP 791). (Contributed by Serhiy Storchaka in gh-81313.)

改进的模块

argparse

  • The BooleanOptionalAction action now supports single-dash long options and alternate prefix characters. (Contributed by Serhiy Storchaka in gh-138525.)

  • Changed the suggest_on_error parameter of argparse.ArgumentParser to default to True. This enables suggestions for mistyped arguments by default. (Contributed by Jakob Schluse in gh-140450.)

  • Added backtick markup support in ArgumentParser description and epilog text to highlight inline code when color output is enabled. (Contributed by Savannah Ostrowski in gh-142390.)

  • Extended backtick markup to argument help text and added support for double backticks (RST inline-literal style). (Contributed by Hugo van Kemenade in gh-149375.)

array

  • Support the float complex and double complex C types: formatting characters 'Zf' and 'Zd' respectively. (Contributed by Victor Stinner in gh-146151 and gh-148675.)

  • Support half-floats (16-bit IEEE 754 binary interchange format): formatting character 'e'. (Contributed by Sergey B Kirpichev in gh-146238.)

  • The array.typecodes type changed from str to tuple to support type codes longer than 1 character (Zf and Zd). (Contributed by Victor Stinner in gh-148675.)

ast

  • Add color parameter to dump(). If True, the returned string is syntax highlighted using ANSI escape sequences. If False (the default), colored output is always disabled. (Contributed by Stan Ulbrych in gh-148981.)

  • The command-line output is now syntax highlighted by default. This can be controlled using environment variables. (Contributed by Stan Ulbrych in gh-148981.)

asyncio

  • Added TaskGroup.cancel to allow early termination of a task group, for instance, when the goal of the tasks has been achieved or their services are no longer needed. Previously this would involve unintuitive boilerplate such as an extra task raising a custom exception which is then suppressed as it exits the task group. (Contributed by John Belmonte in gh-127214.)

base64

binascii

calendar

collections

  • Added collections.Counter.__xor__() and collections.Counter.__ixor__() to compute the symmetric difference between Counter objects. (Contributed by Raymond Hettinger in gh-138682.)

concurrent.futures

  • Improved error reporting when a child process in a concurrent.futures.ProcessPoolExecutor terminates abruptly. The resulting traceback will now tell you the PID and exit code of the terminated process. (Contributed by Jonathan Berg in gh-139486.)

contextlib

dataclasses

  • Annotations for generated __init__ methods no longer include internal type names.

dbm

  • Added new reorganize() methods to dbm.dumb and dbm.sqlite3 to recover unused free space previously occupied by deleted entries. (Contributed by Andrea Oliveri in gh-134004.)

difflib

email

  • Email generators now raise an error when an EmailMessage cannot be accurately flattened due to a non-ASCII email address (mailbox) in an address header. Options for supporting Email Address Internationalization (EAI) are discussed in EmailPolicy.utf8. (Contributed by R David Murray and Mike Edmunds in gh-122540.)

faulthandler

functools

gc

  • Python 3.14.0-3.14.4 shipped with a new incremental garbage collector. However, due to a number of reports of significant memory pressure in production environments, it has been reverted back to the generational GC from 3.13. This is the GC now used in Python 3.14.5 and later and Python 3.15.

hashlib

  • Ensure that hash functions guaranteed to be always available exist as attributes of hashlib even if they will not work at runtime due to missing backend implementations. For instance, hashlib.md5 will no longer raise AttributeError if OpenSSL is not available and Python has been built without MD5 support. (Contributed by Bénédikt Tran in gh-136929.)

http.client

  • A new max_response_headers keyword-only parameter has been added to HTTPConnection and HTTPSConnection constructors. This parameter overrides the default maximum number of allowed response headers. (Contributed by Alexander Enrique Urieles Nieto in gh-131724.)

http.server

importlib.metadata

  • Previously, when accessing a distribution metadata directory not containing a metadata file, metadata() and Distribution.metadata() would return an empty PackageMetadata object as if the file was present but empty. Now, a MetadataNotFound exception is raised. See importlib_metadata#493 for background and rationale and and gh-143387 for rationale on the compatibility concerns. (Contributed by Jason R. Coombs.)

inspect

  • Add parameters inherit_class_doc and fallback_to_class_doc for getdoc(). (Contributed by Serhiy Storchaka in gh-132686.)

json

  • Add the array_hook parameter to load() and loads() functions: allow a callback for JSON literal array types to customize Python lists in the resulting decoded object. Passing combined frozendict to object_pairs_hook param and tuple to array_hook will yield a deeply nested immutable Python structure representing the JSON data. (Contributed by Joao S. O. Bueno in gh-146440.)

locale

math

mimetypes

mmap

  • mmap.mmap now has a trackfd parameter on Windows; if it is False, the file handle corresponding to fileno will not be duplicated. (Contributed by Serhiy Storchaka in gh-78502.)

  • Added the mmap.mmap.set_name() method to annotate an anonymous memory mapping if Linux kernel supports PR_SET_VMA_ANON_NAME (Linux 5.17 or newer). (Contributed by Donghee Na in gh-142419.)

os

  • Add os.statx() on Linux kernel versions 4.11 and later with glibc versions 2.28 and later. (Contributed by Jeffrey Bosboom and Victor Stinner in gh-83714.)

  • os.makedirs() function now has a parent_mode parameter that allows specifying the mode for intermediate directories. This can be used to match the behavior from Python 3.6 and earlier by passing parent_mode=mode. (Contributed by Zackery Spytz and Gregory P. Smith in gh-86533.)

os.path

pdb

  • Use the new interactive shell as the default input shell for pdb. (Contributed by Tian Gao in gh-145379.)

pickle

  • Add support for pickling private methods and nested classes. (Contributed by Zackery Spytz and Serhiy Storchaka in gh-77188.)

pickletools

pprint

  • pprint now uses modern defaults: indent=4, width=88, and the default compact=False output is now formatted similar to pretty-printed json.dumps(). (Contributed by Stefan Todoran, Semyon Moroz and Hugo van Kemenade in gh-112632 and gh-149189.)

  • Add t-string support to pprint. (Contributed by Loïc Simon and Hugo van Kemenade in gh-134551.)

re

  • re.prefixmatch() and a corresponding re.Pattern.prefixmatch() have been added as alternate, more explicit names for the existing and now soft deprecated re.match() and re.Pattern.match() APIs. These are intended to be used to alleviate confusion around what match means by following the Zen of Python's "Explicit is better than implicit" mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search. (Contributed by Gregory P. Smith in gh-86519.)

resource

shelve

  • Added new reorganize() method to shelve used to recover unused free space previously occupied by deleted entries. (Contributed by Andrea Oliveri in gh-134004.)

  • Add support for custom serialization and deserialization functions in the shelve module. (Contributed by Furkan Onder in gh-99631.)

socket

  • Add constants for the ISO-TP CAN protocol. (Contributed by Patrick Menschel and Stefan Tatschner in gh-86819.)

sqlite3

  • The command-line interface has several new features:

    • SQL keyword completion on <tab>. (Contributed by Long Tan in gh-133393.)

    • Prompts, error messages, and help text are now colored. This is enabled by default, see 控制颜色 for details. (Contributed by Stan Ulbrych and Łukasz Langa in gh-133461.)

    • Table, index, trigger, view, column, function, and schema completion on <tab>. (Contributed by Long Tan in gh-136101.)

ssl

  • Indicate through ssl.HAS_PSK_TLS13 whether the ssl module supports "External PSKs" in TLSv1.3, as described in RFC 9258. (Contributed by Will Childs-Klein in gh-133624.)

  • Added new methods for managing groups used for SSL key agreement

    • ssl.SSLContext.set_groups() sets the groups allowed for doing key agreement, extending the previous ssl.SSLContext.set_ecdh_curve() method. This new API provides the ability to list multiple groups and supports fixed-field and post-quantum groups in addition to ECDH curves. This method can also be used to control what key shares are sent in the TLS handshake.

    • ssl.SSLSocket.group() returns the group selected for doing key agreement on the current connection after the TLS handshake completes. This call requires OpenSSL 3.2 or later.

    • ssl.SSLContext.get_groups() returns a list of all available key agreement groups compatible with the minimum and maximum TLS versions currently set in the context. This call requires OpenSSL 3.5 or later.

    (Contributed by Ron Frederick in gh-136306.)

  • Added a new method ssl.SSLContext.set_ciphersuites() for setting TLS 1.3 ciphers. For TLS 1.2 or earlier, ssl.SSLContext.set_ciphers() should continue to be used. Both calls can be made on the same context and the selected cipher suite will depend on the TLS version negotiated when a connection is made. (Contributed by Ron Frederick in gh-137197.)

  • Added new methods for managing signature algorithms:

    (Contributed by Ron Frederick in gh-138252.)

subprocess

  • subprocess.Popen.wait(): when timeout is not None and the platform supports it, an efficient event-driven mechanism is used to wait for process termination:

    If none of these mechanisms are available, the function falls back to the traditional busy loop (non-blocking call and short sleeps). (Contributed by Giampaolo Rodola in gh-83069.)

symtable

sys

  • Add sys.abi_info namespace to improve access to ABI information. (Contributed by Klaus Zimmermann in gh-137476.)

sys.monitoring

tarfile

threading

timeit

  • The output of the timeit command-line interface is colored by default. This can be controlled with environment variables. (Contributed by Hugo van Kemenade in gh-146609.)

  • The command-line interface now colorizes error tracebacks by default. This can be controlled with environment variables. (Contributed by Yi Hong in gh-139374.)

  • Make the target time of timeit.Timer.autorange() configurable and add --target-time option to the command-line interface. (Contributed by Alessandro Cucci and Miikka Koskinen in gh-80642.)

tkinter

  • The tkinter.Text.search() method now supports two additional arguments: nolinestop which allows the search to continue across line boundaries; and strictlimits which restricts the search to within the specified range. (Contributed by Rihaan Meher in gh-130848.)

  • A new method tkinter.Text.search_all() has been introduced. This method allows for searching for all matches of a pattern using Tcl's -all and -overlap options. (Contributed by Rihaan Meher in gh-130848.)

  • Added new methods pack_content(), place_content() and grid_content() which use Tk commands with new names (introduced in Tk 8.6) instead of *_slaves() methods which use Tk commands with outdated names. (Contributed by Serhiy Storchaka in gh-143754.)

  • Added Event attributes user_data for Tk virtual events and detail for Enter, Leave, FocusIn, FocusOut, and ConfigureRequest events. (Contributed by Matthias Kievernagel and Serhiy Storchaka in gh-47655.)

tokenize

tomllib

  • The tomllib module now supports TOML 1.1.0. This is a backwards compatible update, meaning that all valid TOML 1.0.0 documents are parsed the same way.

    The changes, according to the official TOML changelog, are:

    • Allow newlines and trailing commas in inline tables.

      Previously an inline table had to be on a single line and couldn't end with a trailing comma. This is now relaxed so that the following is valid:

      tbl = {
         key      = "a string",
         moar-tbl =  {
            key = 1,
         },
      }
      
    • Add \xHH notation to basic strings for codepoints under 255, and the \e escape for the escape character:

      null = "null byte: \x00; letter a: \x61"
      csi = "\e["
      
    • Seconds in datetime and time values are now optional. The following are now valid:

      dt = 2010-02-03 14:15
      t  = 14:15
      

    (Contributed by Taneli Hukkinen in gh-142956.)

types

typing

  • PEP 747: Add TypeForm, a new special form for annotating values that are themselves type expressions. TypeForm[T] means "a type form object describing T (or a type assignable to T)". At runtime, TypeForm(x) simply returns x, which allows explicit annotation of type-form values without changing behavior.

    This helps libraries that accept user-provided type expressions (for example int, str | None, TypedDict classes, or list[int]) expose precise signatures:

    from typing import Any, TypeForm
    
    def cast[T](typ: TypeForm[T], value: Any) -> T: ...
    

    (Contributed by Jelle Zijlstra in gh-145033.)

  • PEP 728: Add support in TypedDict for the closed and extra_items class arguments. A closed TypedDict does not allow extra keys beyond those specified in the class body, while a TypedDict with extra_items allows arbitrary extra items where the values are of the specified type. (Contributed by Angela Liss in gh-137840.)

  • Code like class ExtraTypeVars(P1[S], Protocol[T, T2]): ... now raises a TypeError, because S is not listed in Protocol parameters. (Contributed by Nikita Sobolev in gh-137191.)

  • Code like class B2(A[T2], Protocol[T1, T2]): ... now correctly handles type parameters order: it is (T1, T2), not (T2, T1) as it was incorrectly inferred at runtime before. (Contributed by Nikita Sobolev in gh-137191.)

  • PEP 800: Add @typing.disjoint_base, a new decorator marking a class as a disjoint base. This is an advanced feature primarily intended to allow type checkers to faithfully reflect the runtime semantics of types defined as builtins or in compiled extensions. If a class C is a disjoint base, then child classes of that class cannot inherit from other disjoint bases that are not parent or child classes of C. (Contributed by Jelle Zijlstra in gh-148639.)

  • TypeVarTuple now accepts bound, covariant, contravariant, and infer_variance keyword arguments, matching the interface of TypeVar and ParamSpec. bound semantics remain undefined in the specification.

unicodedata

unittest

urllib.parse

venv

  • On POSIX platforms, platlib directories will be created if needed when creating virtual environments, instead of using a lib64 -> lib symlink. This means purelib and platlib of virtual environments no longer share the same lib directory on platforms where sys.platlibdir is not equal to lib. (Contributed by Rui Xi in gh-133951.)

warnings

  • Improve filtering by module in warnings.warn_explicit() if no module argument is passed. It now tests the module regular expression in the warnings filter not only against the filename with .py stripped, but also against module names constructed starting from different parent directories of the filename (with /__init__.py, .py and, on Windows, .pyw stripped). (Contributed by Serhiy Storchaka in gh-135801.)

wave

(Contributed by Lionel Koenig and Michiel W. Beijen in gh-60729.)

webbrowser

  • On macOS, the new webbrowser.MacOS class opens URLs via /usr/bin/open instead of constructing and executing AppleScript via osascript. The default browser is detected from the LaunchServices preferences file using plistlib, with com.apple.Safari as the fallback on fresh installations. For non-HTTP(S) URLs, open -b <bundle-id> is used to route the URL through a browser rather than the OS file handler, preventing file injection attacks. (Contributed by Jeff Lyon in gh-137586.)

xml

  • Add the xml.is_valid_name() function to check whether a string can be used as an element or attribute name in XML. (Contributed by Serhiy Storchaka in gh-139489.)

  • Add the xml.is_valid_text() function, which allows to check whether a string can be used in the XML document. (Contributed by Serhiy Storchaka in gh-139489.)

xml.parsers.expat

zlib

性能优化

base64 & binascii

  • CPython's underlying base64 implementation now encodes 2x faster and decodes 3x faster thanks to simple CPU pipelining optimizations. (Contributed by Gregory P. Smith and Serhiy Storchaka in gh-143262.)

  • Implementation for Ascii85, Base85, and Z85 encoding has been rewritten in C. Encoding and decoding is now two orders of magnitude faster and consumes two orders of magnitude less memory. (Contributed by James Seo and Serhiy Storchaka in gh-101178.)

  • Implementation for Base32 has been rewritten in C. Encoding and decoding is now two orders of magnitude faster. (Contributed by James Seo in gh-146192.)

csv

Upgraded JIT compiler

Results from the pyperformance benchmark suite report 8-9% geometric mean performance improvement for the JIT over the standard CPython interpreter built with all optimizations enabled on x86-64 Linux. On AArch64 macOS, the JIT has a 12-13% speedup over the tail calling interpreter with all optimizations enabled. The speedups for JIT builds versus no JIT builds range from roughly 15% slowdown to over 100% speedup (ignoring the unpack_sequence microbenchmark) on x86-64 Linux and AArch64 macOS systems.

注意

These results are not yet final.

The major upgrades to the JIT are:

  • LLVM 21 build-time dependency

  • New tracing frontend

  • Basic register allocation in the JIT

  • More JIT optimizations

  • GDB and GNU backtrace() unwinding support

  • Better machine code generation

LLVM 21 build-time dependency

The JIT compiler now uses LLVM 21 for build-time stencil generation. As always, LLVM is only needed when building CPython with the JIT enabled; end users running Python do not need LLVM installed. Instructions for installing LLVM can be found in the JIT compiler documentation for all supported platforms. (Contributed by Savannah Ostrowski in gh-140973.)

A new tracing frontend

The JIT compiler now supports significantly more bytecode operations and control flow than in Python 3.14, enabling speedups on a wider variety of code. For example, simple Python object creation is now understood by the 3.15 JIT compiler. Overloaded operations and generators are also partially supported. This was made possible by an overhauled JIT tracing frontend that records actual execution paths through code, rather than estimating them as the previous implementation did. (Contributed by Ken Jin in gh-139109. Support for Windows added by Mark Shannon in gh-141703.)

Basic register allocation in the JIT

A basic form of register allocation has been added to the JIT compiler's optimizer. This allows the JIT compiler to avoid certain stack operations altogether and instead operate on registers. This allows the JIT to produce more efficient traces by avoiding reads and writes to memory. (Contributed by Mark Shannon in gh-135379.)

More JIT optimizations

More constant-propagation is now performed. This means when the JIT compiler detects that certain user code results in constants, the code can be simplified by the JIT. (Contributed by Ken Jin and Savannah Ostrowski in gh-132732.)

Reference counts are avoided whenever it is safe to do so. This generally reduces the cost of most operations in Python. (Contributed by Ken Jin, Donghee Na, Zheao Li, Hai Zhu, Savannah Ostrowski, Reiden Ong, Noam Cohen, Tomas Roun, PuQing, Cajetan Rodrigues, and Sacul in gh-134584.)

By tracking unique references to objects, the JIT optimizer can now eliminate reference count updates and perform in-place operations on ints and floats. (Contributed by Reiden Ong, and Pieter Eendebak in gh-143414 and gh-146306.)

The JIT optimizer now supports significantly more operations than in 3.14. (Contributed by Kumar Aditya, Ken Jin, Jiahao Li, and Sacul in gh-131798.)

GDB and GNU backtrace() unwinding support

The JIT compiler now publishes unwind information for generated machine code to the GDB interface on supported Linux ELF platforms. When libgcc frame registration is available, the same unwind information is also registered for GNU backtrace() stack walkers. This allows native debuggers, crash handlers, and diagnostic tools using these mechanisms to unwind through JIT frames instead of stopping at generated code. (Contributed by Diego Russo and Pablo Galindo Salgado in gh-146071 and gh-149104.)

Better machine code generation

The JIT compiler's machine code generator now produces better machine code for x86-64 and AArch64 macOS and Linux targets. In general, users should experience lower memory usage for generated machine code and more efficient machine code versus 3.14. (Contributed by Brandt Bucher in gh-136528 and gh-135905. Implementation for AArch64 contributed by Mark Shannon in gh-139855. Additional optimizations for AArch64 contributed by Mark Shannon and Diego Russo in gh-140683 and gh-142305.)

Maintainability

The JIT optimizer's operations have been simplified. This was made possible by a refactoring of JIT data structures. (Contributed by Zhongtian Zheng in gh-148211 and Hai Zhu in gh-143421.)

移除

ast

  • The constructors of AST nodes now raise a TypeError when a required argument is omitted or when a keyword argument that does not map to a field on the AST node is passed. These cases had previously raised a DeprecationWarning since Python 3.13. (Contributed by Brian Schubert and Jelle Zijlstra in gh-137600 and gh-105858.)

collections.abc

  • collections.abc.ByteString has been removed from collections.abc.__all__. collections.abc.ByteString has been deprecated since Python 3.12, and is scheduled for removal in Python 3.17.

ctypes

datetime

  • strptime() now raises ValueError when the format string contains %d (day of month) without a year directive. This has been deprecated since Python 3.13. (Contributed by Stan Ulbrych and Gregory P. Smith in gh-70647.)

glob

  • Removed the undocumented glob.glob0() and glob.glob1() functions, which have been deprecated since Python 3.13. Use glob.glob() and pass a directory to its root_dir argument instead. (Contributed by Barney Gale in gh-137466.)

http.server

  • Removed the CGIHTTPRequestHandler class and the --cgi flag from the python -m http.server command-line interface. They were deprecated in Python 3.13. (Contributed by Bénédikt Tran in gh-133810.)

importlib.resources

pathlib

  • pathlib.Path.mkdir() now has a parent_mode parameter that allows specifying the mode for intermediate directories when parents=True. (Contributed by Gregory P. Smith in gh-86533.)

  • Removed deprecated pathlib.PurePath.is_reserved(). Use os.path.isreserved() to detect reserved paths on Windows. (Contributed by Nikita Sobolev in gh-133875.)

平台

  • Removed the platform.java_ver() function, which was deprecated since Python 3.13. (Contributed by Alexey Makridenko in gh-133604.)

sre_*

  • Removed sre_compile, sre_constants and sre_parse modules. (Contributed by Stan Ulbrych in gh-135994.)

sysconfig

threading

  • Remove support for arbitrary positional or keyword arguments in the C implementation of RLock objects. This was deprecated in Python 3.14. (Contributed by Bénédikt Tran in gh-134087.)

types

typing

  • typing.ByteString has been removed from typing.__all__. typing.ByteString has been deprecated since Python 3.9, and is scheduled for removal in Python 3.17.

  • The undocumented keyword argument syntax for creating NamedTuple classes (for example, Point = NamedTuple("Point", x=int, y=int)) is no longer supported. Use the class-based syntax or the functional syntax instead. (Contributed by Bénédikt Tran in gh-133817.)

  • Using TD = TypedDict("TD") or TD = TypedDict("TD", None) to construct a TypedDict type with zero fields is no longer supported. Use class TD(TypedDict): pass or TD = TypedDict("TD", {}) instead. (Contributed by Bénédikt Tran in gh-133823.)

  • Deprecated typing.no_type_check_decorator() has been removed. (Contributed by Nikita Sobolev in gh-133601.)

wave

  • Removed the getmark(), setmark() and getmarkers() methods of the Wave_read and Wave_write classes, which were deprecated since Python 3.13. (Contributed by Bénédikt Tran in gh-133873.)

zipimport

弃用

新的弃用

  • ast

    • 创建抽象 AST 节点 (如 ast.ASTast.expr) 的做法已被弃用并将在 Python 3.20 中引发错误。

      (Contributed by Brian Schubert in gh-116021.)

  • base64:

    • Accepting the + and / characters with an alternative alphabet in b64decode() and urlsafe_b64decode() is now deprecated. In future Python versions they will be errors in the strict mode and discarded in the non-strict mode. (Contributed by Serhiy Storchaka in gh-125346.)

  • CLI:

    • Deprecate -b and -bb command-line options and schedule them to become no-ops in Python 3.17. These were primarily helpers for the Python 2 -> 3 transition. Starting with Python 3.17, no BytesWarning will be raised for these cases; use a type checker instead.

      (Contributed by Nikita Sobolev in gh-136355.)

  • collections.abc

    • The following statements now cause DeprecationWarnings to be emitted at runtime:

      • from collections.abc import ByteString

      • import collections.abc; collections.abc.ByteString.

      DeprecationWarnings were already emitted if collections.abc.ByteString was subclassed or used as the second argument to isinstance() or issubclass(), but warnings were not previously emitted if it was merely imported or accessed from the collections.abc module.

  • hashlib:

    • In hash function constructors such as new() or the direct hash-named constructors such as md5() and sha256(), the optional initial data parameter could also be passed as a keyword argument named data= or string= in various hashlib implementations.

      Support for the string keyword argument name is now deprecated and is slated for removal in Python 3.19. Prefer passing the initial data as a positional argument for maximum backwards compatibility.

      (Contributed by Bénédikt Tran in gh-134978.)

  • http.cookies:

  • imaplib:

    • Altering IMAP4.file is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not explicitly close the current file.

  • re:

    • re.match() and re.Pattern.match() are now soft deprecated in favor of the new re.prefixmatch() and re.Pattern.prefixmatch() APIs, which have been added as alternate, more explicit names. These are intended to be used to alleviate confusion around what match means by following the Zen of Python's "Explicit is better than implicit" mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search.

      We do not plan to remove the older match() name, as it has been used in code for over 30 years. Code supporting older versions of Python should continue to use match(), while new code should prefer prefixmatch(). See prefixmatch() vs. match().

      (由 Gregory P. Smith 在 gh-86519 以及 Hugo van Kemenade 在 gh-148100 中贡献。)

  • struct:

    • Calling Struct.__new__() without a required argument is now deprecated and will be removed in Python 3.20. Calling the __init__() method on an initialized Struct object is deprecated and will be removed in Python 3.20.

      (Contributed by Sergey B Kirpichev and Serhiy Storchaka in gh-143715.)

  • typing:

    • The following statements now cause DeprecationWarnings to be emitted at runtime:

      • from typing import ByteString

      • import typing; typing.ByteString.

      DeprecationWarnings were already emitted if typing.ByteString was subclassed or used as the second argument to isinstance() or issubclass(), but warnings were not previously emitted if it was merely imported or accessed from the typing module.

  • webbrowser:

    • webbrowser.MacOSXOSAScript is deprecated in favour of webbrowser.MacOS and scheduled for removal in Python 3.17. (Contributed by Jeff Lyon in gh-137586.)

  • __version__

计划在 Python 3.16 中移除

  • 导入系统:

    • 当设置 __spec__.loader 失败时在模块上设置 __loader__ 的做法已被弃用。在 Python 3.16 中,__loader__ 将不会再被设置或是被导入系统或标准库纳入考虑。

  • array:

    • 'u' 格式代码 (wchar_t) 自 Python 3.3 起已在文档中弃用并自 Python 3.13 起在运行时弃用。对于 Unicode 字符请改用 'w' 格式代码 (Py_UCS4)。

  • asyncio:

  • builtins:

    • 对布尔类型 ~True~False 执行按位取反的操作自 Python 3.12 起已被弃用,因为它会产生奇怪和不直观的结果 (-2-1)。请改用 not x 来对布尔值执行逻辑否操作。 对于需要对下层整数执行按位取反操作的少数场合,请显式地将其转换为 int (~int(x))。

  • functools:

    • 调用 functools.reduce() 的 Python 实现并传入 functionsequence 作为关键字参数的做法自 Python 3.14 起已被弃用。

  • logging:

    • 使用 strm 参数对自定义日志记录处理器提供支持的做法已被弃用并计划在 Python 3.16 中移除。改为使用 stream 参数定义处理器。 (由 Mariusz Felisiak 在 gh-115032 中贡献。)

  • mimetypes:

  • shutil:

    • ExecError 异常自 Python 3.14 起已被弃用。它自 Python 3.4 起就未被 shutil 中的任何函数所使用,现在是 RuntimeError 的一个别名。

  • symtable:

    • The symtable.Class.get_methods() method has been deprecated since Python 3.14.

  • sys:

    • The _enablelegacywindowsfsencoding() function has been deprecated since Python 3.13. Use the PYTHONLEGACYWINDOWSFSENCODING environment variable instead.

  • sysconfig:

    • 自 Python 3.14 起 sysconfig.expand_makefile_vars() 函数已被弃用。请使用 sysconfig.get_paths()vars 参数代替。

  • tarfile:

    • The undocumented and unused TarInfo.tarfile attribute has been deprecated since Python 3.13.

计划在 Python 3.17 中移除

  • datetime:

    • 使用不带年份的包含 %e (月份日期序号) 的格式字符串的 strptime() 调用自 Python 3.15 起已被弃用。 (由 Stan Ulbrych 在 gh-70647 中贡献。)

  • collections.abc:

    • collections.abc.ByteString 计划在 Python 3.17 中移除。

      使用 isinstance(obj, collections.abc.Buffer) 来在运行时测试 obj 是否实现了 缓冲区协议。要用于类型标注,则使用 Buffer 或者显式指明你的代码所支持的类型的并集 (例如 bytes | bytearray | memoryview)。

      ByteString 原本是想作为 bytesbytearray 的超类型的抽象基类提供。 不过,由于该 ABC 从未有过任何方法,知道一个对象是 ByteString 的实例并不能真正告诉你有关该对象的任何有用信息。 其他常见缓冲区类型如 memoryview 同样不能被当作是 ByteString 的子类型(无论是在运行时还是对于静态类型检查器)。

      请参阅 PEP 688 了解详情。 (由 Shantanu Jain 在 gh-91896 中贡献。)

  • encodings:

  • webbrowser:

    • webbrowser.MacOSXOSAScript 已被弃用并改用 webbrowser.MacOS。 (gh-137586)

  • typing:

    • 在 Python 3.14 之前,旧式的联合是通过私有类 typing._UnionGenericAlias 实现的。实现已不再需要该类,但为向后兼容性保留了该类,并计划在 Python 3.17 中删除。用户应使用记录在案的内省助手函数,如 typing.get_origin()typing.get_args(),而不是依赖于私有的实现细节。

    • typing.ByteString 自 Python 3.9 起已被弃用,计划在 Python 3.17 中移除。

      使用 isinstance(obj, collections.abc.Buffer) 来在运行时测试 obj 是否实现了 缓冲区协议。要用于类型标注,则使用 Buffer 或者显式指明你的代码所支持的类型的并集 (例如 bytes | bytearray | memoryview)。

      ByteString 原本是想作为 bytesbytearray 的超类型的抽象基类提供。 不过,由于该 ABC 从未有过任何方法,知道一个对象是 ByteString 的实例并不能真正告诉你有关该对象的任何有用信息。 其他常见缓冲区类型如 memoryview 同样不能被当作是 ByteString 的子类型(无论是在运行时还是对于静态类型检查器)。

      请参阅 PEP 688 了解详情。 (由 Shantanu Jain 在 gh-91896 中贡献。)

计划在 Python 3.18 中移除

  • 当需要一个文件描述符时将不再接受布尔值。 (由 Serhiy Storchaka 在 gh-82626 中贡献。)

  • decimal:

    • 非标准且未写入文档的 Decimal 格式说明符 'N',它仅在 decimal 模块的 C 实现中受到支持,自 Python 3.13 起已被弃用。 (由 Serhiy Storchaka 在 gh-89902 中贡献。)

  • PEP 829 定义的弃用:

    • name.pth 文件中的 import 行会被静默地忽略。

    (由 Barry Warsaw 在 gh-148641 中贡献。)

计划在 Python 3.19 中移除

  • ctypes:

    • 在非 Windows 平台上,通过设置 _pack_ 而非 _layout_,隐式切换到与 MSVC 兼容的结构布局。

  • hashlib:

    • 在哈希函数构造器如 new() 或者直接使用哈希算法名称的构造器如 md5()sha256() 中,它们可选的初始数据形参在不同的 hashlib 实现中也可使用名为 data=string= 的关键字参数形式传入。

      string 关键字参数名称的支持现已被弃用并计划在 Python 3.19 中移除。

      在 Python 3.13 之前,string 关键字形参没有根据哈希函数的后端实现得到正确的支持。 建议将初始数据作为位置参数传入以获得最大的向下兼容性。

  • http.cookies:

  • imaplib:

    • Altering IMAP4.file is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not automatically close the current file.

      Before Python 3.14, this property was used to implement the corresponding read() and readline() methods for IMAP4 but this is no longer the case since then.

Pending removal in Python 3.20

计划在未来版本中移除

以下 API 将会被移除,尽管具体时间还未确定。

  • argparse:

    • 嵌套参数组和嵌套互斥组已被弃用。

    • 将未写入文档的关键字参数 prefix_chars 传递给 add_argument_group() 的做法现在已被弃用。

    • argparse.FileType 类型转换器已弃用。

  • builtins:

    • 生成器: throw(type, exc, tb)athrow(type, exc, tb) 签名已被弃用:请改用 throw(exc)athrow(exc),即单参数签名。

    • 目前 Python 接受数字类字面值后面紧跟关键字的写法,例如 0in x, 1or x, 0if 1else 2。它允许像 [0x1for x in y] 这样令人困惑且有歧义的表达式 (它可以被解读为 [0x1 for x in y] 或者 [0x1f or x in y])。如果数字类字面值后面紧跟关键字 and, else, for, if, in, isor 中的一个将会引发语法警告。在未来的版本中它将改为语法错误。 (gh-87999)

    • __index__()__int__() 方法返回非 int 类型的支持:将要求这些方法必须返回 int 的严格子类的实例。

    • __float__() 方法返回 float 的子类的支持:将要求这些方法必须返回 float 的实例。

    • __complex__() 方法返回 complex 的子类的支持:将要求这些方法必须返回 complex 的实例。

    • 传入一个复数作为 complex() 构造器中的 realimag 参数的做法现在已被弃用;它应当仅作为单个位置参数被传入。(由 Serhiy Storchaka 在 gh-109218 中贡献。)

  • calendar: calendar.Januarycalendar.February 常量已被弃用并由 calendar.JANUARYcalendar.FEBRUARY 替代。 (由 Prince Roshan 在 gh-103636 中贡献。)

  • codecs: codecs.open() 请改用 open() 。 (gh-133038)

  • codeobject.co_lnotab: 改用 codeobject.co_lines() 方法。

  • datetime:

    • utcnow(): 使用 datetime.datetime.now(tz=datetime.UTC)

    • utcfromtimestamp(): 使用 datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC)

  • gettext: 复数值必须是一个整数。

  • importlib:

  • importlib.metadata:

    • EntryPoints 元组接口。

    • 返回值中隐式的 None

  • logging: warn() 方法自 Python 3.3 起已被弃用,请改用 warning().

  • mailbox: 对 StringIO 输入和文本模式的使用已被弃用,改用 BytesIO 和二进制模式。

  • os: 在多线程的进程中调用 os.register_at_fork()

  • os.path: os.path.commonprefix() is deprecated, use os.path.commonpath() for path prefixes. The os.path.commonprefix() function is being deprecated due to having a misleading name and module. The function is not safe to use for path prefixes despite being included in a module about path manipulation, meaning it is easy to accidentally introduce path traversal vulnerabilities into Python programs by using this function.

  • pydoc.ErrorDuringImport: 使用元组值作为 exc_info 形参的做法已被弃用,应使用异常实例。

  • re: 现在对于正则表达式中的数字分组引用和分组名称将应用更严格的规则。现在只接受 ASCII 数字序列作为数字引用。 字节串模式和替换字符串中的分组名称现在只能包含 ASCII 字母和数字以及下划线。 (由 Serhiy Storchaka 在 gh-91760 中贡献。)

  • shutil: rmtree()onerror 形参在 Python 3.12 中已被弃用;请改用 onexc 形参。

  • ssl 选项和协议:

    • ssl.SSLContext 不带 protocol 参数的做法已被弃用。

    • ssl.SSLContext: set_npn_protocols()selected_npn_protocol() 已被弃用:请改用 ALPN。

    • ssl.OP_NO_SSL* 选项

    • ssl.OP_NO_TLS* 选项

    • ssl.PROTOCOL_SSLv3

    • ssl.PROTOCOL_TLS

    • ssl.PROTOCOL_TLSv1

    • ssl.PROTOCOL_TLSv1_1

    • ssl.PROTOCOL_TLSv1_2

    • ssl.TLSVersion.SSLv3

    • ssl.TLSVersion.TLSv1

    • ssl.TLSVersion.TLSv1_1

  • threading 的方法:

  • typing.Text (gh-92332).

  • 内部类 typing._UnionGenericAlias 不再用于实现 typing.Union。 为了保持与使用该私有类的用户的兼容性,将至少在 Python 3.17 之前提供兼容性垫片。 (由 Jelle Zijlstra 在 gh-105499 中贡献。)

  • unittest.IsolatedAsyncioTestCase: 从测试用例返回不为 None 的值的做法已被弃用。

  • urllib.parse 已弃用的函数:改用 urlparse()

    • splitattr()

    • splithost()

    • splitnport()

    • splitpasswd()

    • splitport()

    • splitquery()

    • splittag()

    • splittype()

    • splituser()

    • splitvalue()

    • to_bytes()

  • wsgiref: SimpleHandler.stdout.write() 不应执行部分写入。

  • xml.etree.ElementTree: 对 Element 进行真值检测已被弃用。在未来的发布版中它将始终返回 True。建议改用显式的 len(elem)elem is not None 检测。

  • sys._clear_type_cache() 已弃用,请改用 sys._clear_internal_caches()

软弃用

尚无计划移除 soft deprecated API。

  • re.match() and re.Pattern.match() are now soft deprecated in favor of the new re.prefixmatch() and re.Pattern.prefixmatch() APIs, which have been added as alternate, more explicit names. These are intended to be used to alleviate confusion around what match means by following the Zen of Python's "Explicit is better than implicit" mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search.

    We do not plan to remove the older match() name, as it has been used in code for over 30 years. Code supporting older versions of Python should continue to use match(), while new code should prefer prefixmatch(). See prefixmatch() vs. match().

    (由 Gregory P. Smith 在 gh-86519 以及 Hugo van Kemenade 在 gh-148100 中贡献。)

C API 的变化

新的特性

被改变的 C API

被移除的 C API

  • Remove deprecated PyUnicode functions:

    • PyUnicode_AsDecodedObject(): 改用 PyCodec_Decode()

    • PyUnicode_AsDecodedUnicode(): Use PyCodec_Decode() instead; note that some codecs (for example, "base64") may return a type other than str, such as bytes.

    • PyUnicode_AsEncodedObject(): 改用 PyCodec_Encode()

    • PyUnicode_AsEncodedUnicode(): Use PyCodec_Encode() instead; note that some codecs (for example, "base64") may return a type other than bytes, such as str.

    (Contributed by Stan Ulbrych in gh-133612.)

  • PyImport_ImportModuleNoBlock(): deprecated alias of PyImport_ImportModule(). (Contributed by Bénédikt Tran in gh-133644.)

  • PyWeakref_GetObject() and PyWeakref_GET_OBJECT: use PyWeakref_GetRef() instead. The pythoncapi-compat project can be used to get PyWeakref_GetRef() on Python 3.12 and older. (Contributed by Bénédikt Tran in gh-133644.)

  • Remove deprecated PySys_ResetWarnOptions(). Clear sys.warnoptions and warnings.filters instead.

    (Contributed by Nikita Sobolev in gh-138886.)

The following functions are removed in favor of PyConfig_Get(). The pythoncapi-compat project can be used to get PyConfig_Get() on Python 3.13 and older.

已弃用的 C API

构建的改变

  • Removed implicit fallback to the bundled copy of the libmpdec library. Now this should be explicitly enabled with --with-system-libmpdec set to no or with --without-system-libmpdec. (Contributed by Sergey B Kirpichev in gh-115119.)

  • The new configure option --with-missing-stdlib-config=FILE allows distributors to pass a JSON configuration file containing custom error messages for standard library modules that are missing or packaged separately. (Contributed by Stan Ulbrych and Petr Viktorin in gh-139707.)

  • The new configure option --with-pymalloc-hugepages enables huge page support for pymalloc arenas. When enabled, arena size increases to 2 MiB and allocation uses MAP_HUGETLB (Linux) or MEM_LARGE_PAGES (Windows) with automatic fallback to regular pages. On Windows, use build.bat --pymalloc-hugepages. At runtime, huge pages must be explicitly enabled by setting the PYTHON_PYMALLOC_HUGEPAGES environment variable to 1.

  • Annotating anonymous mmap usage is now supported if Linux kernel supports PR_SET_VMA_ANON_NAME (Linux 5.17 or newer). Annotations are visible in /proc/<pid>/maps if the kernel supports the feature and -X dev is passed to the Python or Python is built in debug mode. (Contributed by Donghee Na in gh-141770.)

  • CPython is now built with frame pointers enabled by default (PEP 831). Pass --without-frame-pointers to opt out.

    Authors of C extensions and native libraries built with custom build systems should ensure the unwind chain is intact. This is usually done by adding -fno-omit-frame-pointer and similar flags to CFLAGS. See --without-frame-pointers documentation for the specific flags Python uses.

    (Contributed by Pablo Galindo Salgado and Savannah Ostrowski in gh-149201.)

  • 64-bit builds using Visual Studio 2026 (MSVC 18) may now use the new tail-calling interpreter. Results on Visual Studio 18.1.1 report between 15-20% speedup on the geometric mean of pyperformance on Windows x86-64 over the switch-case interpreter on an AMD Ryzen 7 5800X. We have observed speedups ranging from 14% for large pure-Python libraries to 40% for long-running small pure-Python scripts on Windows. This was made possible by a new feature introduced in MSVC 18, which the official Windows 64-bit binaries on python.org now use. (Contributed by Chris Eibl, Ken Jin, and Brandt Bucher in gh-143068. Special thanks to Steve Dower, and the MSVC team including Hulon Jenkins.)

移植到 Python 3.15

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正。