Skip to content

Latest commit

 

History

History
2145 lines (1629 loc) · 86.7 KB

3.12.rst

File metadata and controls

2145 lines (1629 loc) · 86.7 KB

What's New In Python 3.12

Editor:TBD

This article explains the new features in Python 3.12, compared to 3.11.

For full details, see the :ref:`changelog <changelog>`.

Note

Prerelease users should be aware that this document is currently in draft form. It will be updated substantially as Python 3.12 moves towards release, so it's worth checking back even after reading earlier versions.

Summary -- Release highlights

New grammar features:

Interpreter improvements:

New typing features:

Important deprecations, removals or restrictions:

Improved Error Messages

  • Modules from the standard library are now potentially suggested as part of the error messages displayed by the interpreter when a :exc:`NameError` is raised to the top level. Contributed by Pablo Galindo in :gh:`98254`.

    >>> sys.version_info
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'sys' is not defined. Did you forget to import 'sys'?
  • Improve the error suggestion for :exc:`NameError` exceptions for instances. Now if a :exc:`NameError` is raised in a method and the instance has an attribute that's exactly equal to the name in the exception, the suggestion will include self.<NAME> instead of the closest match in the method scope. Contributed by Pablo Galindo in :gh:`99139`.

    >>> class A:
    ...    def __init__(self):
    ...        self.blech = 1
    ...
    ...    def foo(self):
    ...        somethin = blech
    >>> A().foo()
    Traceback (most recent call last):
      File "<stdin>", line 1
        somethin = blech
                   ^^^^^
    NameError: name 'blech' is not defined. Did you mean: 'self.blech'?
  • Improve the :exc:`SyntaxError` error message when the user types import x from y instead of from y import x. Contributed by Pablo Galindo in :gh:`98931`.

    >>> import a.y.z from b.y.z
    Traceback (most recent call last):
      File "<stdin>", line 1
        import a.y.z from b.y.z
        ^^^^^^^^^^^^^^^^^^^^^^^
    SyntaxError: Did you mean to use 'from ... import ...' instead?
  • :exc:`ImportError` exceptions raised from failed from <module> import <name> statements now include suggestions for the value of <name> based on the available names in <module>. Contributed by Pablo Galindo in :gh:`91058`.

    >>> from collections import chainmap
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: cannot import name 'chainmap' from 'collections'. Did you mean: 'ChainMap'?

New Features

PEP 701: Syntactic formalization of f-strings

PEP 701 lifts some restrictions on the usage of f-strings. Expression components inside f-strings can now be any valid Python expression including backslashes, unicode escaped sequences, multi-line expressions, comments and strings reusing the same quote as the containing f-string. Let's cover these in detail:

  • Quote reuse: in Python 3.11, reusing the same quotes as the containing f-string raises a :exc:`SyntaxError`, forcing the user to either use other available quotes (like using double quotes or triple quotes if the f-string uses single quotes). In Python 3.12, you can now do things like this:

    >>> songs = ['Take me back to Eden', 'Alkaline', 'Ascensionism']
    >>> f"This is the playlist: {", ".join(songs)}"
    'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'

    Note that before this change there was no explicit limit in how f-strings can be nested, but the fact that string quotes cannot be reused inside the expression component of f-strings made it impossible to nest f-strings arbitrarily. In fact, this is the most nested f-string that could be written:

    >>> f"""{f'''{f'{f"{1+1}"}'}'''}"""
    '2'

    As now f-strings can contain any valid Python expression inside expression components, it is now possible to nest f-strings arbitrarily:

    >>> f"{f"{f"{f"{f"{f"{1+1}"}"}"}"}"}"
    '2'
  • Multi-line expressions and comments: In Python 3.11, f-strings expressions must be defined in a single line even if outside f-strings expressions could span multiple lines (like literal lists being defined over multiple lines), making them harder to read. In Python 3.12 you can now define expressions spanning multiple lines and include comments on them:

    >>> f"This is the playlist: {", ".join([
    ...     'Take me back to Eden',  # My, my, those eyes like fire
    ...     'Alkaline',              # Not acid nor alkaline
    ...     'Ascensionism'           # Take to the broken skies at last
    ... ])}"
    'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'
  • Backslashes and unicode characters: before Python 3.12 f-string expressions couldn't contain any \ character. This also affected unicode escaped sequences (such as \N{snowman}) as these contain the \N part that previously could not be part of expression components of f-strings. Now, you can define expressions like this:

    >>> print(f"This is the playlist: {"\n".join(songs)}")
    This is the playlist: Take me back to Eden
    Alkaline
    Ascensionism
    >>> print(f"This is the playlist: {"\N{BLACK HEART SUIT}".join(songs)}")
    This is the playlist: Take me back to Eden♥Alkaline♥Ascensionism

See PEP 701 for more details.

As a positive side-effect of how this feature has been implemented (by parsing f-strings with the PEG parser (see PEP 617), now error messages for f-strings are more precise and include the exact location of the error. For example, in Python 3.11, the following f-string raises a :exc:`SyntaxError`:

>>> my_string = f"{x z y}" + f"{1 + 1}"
  File "<stdin>", line 1
    (x z y)
     ^^^
SyntaxError: f-string: invalid syntax. Perhaps you forgot a comma?

but the error message doesn't include the exact location of the error within the line and also has the expression artificially surrounded by parentheses. In Python 3.12, as f-strings are parsed with the PEG parser, error messages can be more precise and show the entire line:

>>> my_string = f"{x z y}" + f"{1 + 1}"
  File "<stdin>", line 1
    my_string = f"{x z y}" + f"{1 + 1}"
                   ^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

(Contributed by Pablo Galindo, Batuhan Taskaya, Lysandros Nikolaou, Cristián Maureira-Fredes and Marta Gómez in :gh:`102856`. PEP written by Pablo Galindo, Batuhan Taskaya, Lysandros Nikolaou and Marta Gómez).

PEP 709: Comprehension inlining

Dictionary, list, and set comprehensions are now inlined, rather than creating a new single-use function object for each execution of the comprehension. This speeds up execution of a comprehension by up to 2x.

Comprehension iteration variables remain isolated; they don't overwrite a variable of the same name in the outer scope, nor are they visible after the comprehension. This isolation is now maintained via stack/locals manipulation, not via separate function scope.

Inlining does result in a few visible behavior changes:

  • There is no longer a separate frame for the comprehension in tracebacks, and tracing/profiling no longer shows the comprehension as a function call.
  • The :mod:`symtable` module will no longer produce child symbol tables for each comprehension; instead, the comprehension's locals will be included in the parent function's symbol table.
  • Calling :func:`locals` inside a comprehension now includes variables from outside the comprehension, and no longer includes the synthetic .0 variable for the comprehension "argument".
  • A comprehension iterating directly over locals() (e.g. [k for k in locals()]) may see "RuntimeError: dictionary changed size during iteration" when run under tracing (e.g. code coverage measurement). This is the same behavior already seen in e.g. for k in locals():. To avoid the error, first create a list of keys to iterate over: keys = list(locals()); [k for k in keys].

Contributed by Carl Meyer and Vladimir Matveev in PEP 709.

PEP 688: Making the buffer protocol accessible in Python

PEP 688 introduces a way to use the :ref:`buffer protocol <bufferobjects>` from Python code. Classes that implement the :meth:`~object.__buffer__` method are now usable as buffer types.

The new :class:`collections.abc.Buffer` ABC provides a standard way to represent buffer objects, for example in type annotations. The new :class:`inspect.BufferFlags` enum represents the flags that can be used to customize buffer creation. (Contributed by Jelle Zijlstra in :gh:`102500`.)

PEP 684: A Per-Interpreter GIL

Sub-interpreters may now be created with a unique GIL per interpreter. This allows Python programs to take full advantage of multiple CPU cores.

Use the new :c:func:`Py_NewInterpreterFromConfig` function to create an interpreter with its own GIL:

PyInterpreterConfig config = {
    .check_multi_interp_extensions = 1,
    .gil = PyInterpreterConfig_OWN_GIL,
};
PyThreadState *tstate = NULL;
PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
if (PyStatus_Exception(status)) {
    return -1;
}
/* The new interpreter is now active in the current thread. */

For further examples how to use the C-API for sub-interpreters with a per-interpreter GIL, see :source:`Modules/_xxsubinterpretersmodule.c`.

A Python API is anticipated for 3.13. (See PEP 554.)

(Contributed by Eric Snow in :gh:`104210`, etc.)

PEP 669: Low impact monitoring for CPython

CPython 3.12 now supports the ability to monitor calls, returns, lines, exceptions and other events using instrumentation. This means that you only pay for what you use, providing support for near-zero overhead debuggers and coverage tools.

See :mod:`sys.monitoring` for details.

New Features Related to Type Hints

This section covers major changes affecting PEP 484 type hints and the :mod:`typing` module.

PEP 692: Using TypedDict for more precise **kwargs typing

Typing **kwargs in a function signature as introduced by PEP 484 allowed for valid annotations only in cases where all of the **kwargs were of the same type.

This PEP specifies a more precise way of typing **kwargs by relying on typed dictionaries:

from typing import TypedDict, Unpack

class Movie(TypedDict):
  name: str
  year: int

def foo(**kwargs: Unpack[Movie]): ...

See PEP 692 for more details.

(Contributed by Franek Magiera in :gh:`103629`.)

PEP 698: Override Decorator for Static Typing

A new decorator :func:`typing.override` has been added to the :mod:`typing` module. It indicates to type checkers that the method is intended to override a method in a superclass. This allows type checkers to catch mistakes where a method that is intended to override something in a base class does not in fact do so.

Example:

from typing import override

class Base:
  def get_color(self) -> str:
    return "blue"

class GoodChild(Base):
  @override  # ok: overrides Base.get_color
  def get_color(self) -> str:
    return "yellow"

class BadChild(Base):
  @override  # type checker error: does not override Base.get_color
  def get_colour(self) -> str:
    return "red"

(Contributed by Steven Troxler in :gh:`101561`.)

PEP 695: Type Parameter Syntax

Generic classes and functions under PEP 484 were declared using a verbose syntax that left the scope of type parameters unclear and required explicit declarations of variance.

PEP 695 introduces a new, more compact and explicit way to create :ref:`generic classes <generic-classes>` and :ref:`functions <generic-functions>`:

def max[T](args: Iterable[T]) -> T:
    ...

class list[T]:
    def __getitem__(self, index: int, /) -> T:
        ...

    def append(self, element: T) -> None:
        ...

In addition, the PEP introduces a new way to declare :ref:`type aliases <type-aliases>` using the :keyword:`type` statement, which creates an instance of :class:`~typing.TypeAliasType`:

type Point = tuple[float, float]

Type aliases can also be :ref:`generic <generic-type-aliases>`:

type Point[T] = tuple[T, T]

The new syntax allows declaring :class:`~typing.TypeVarTuple` and :class:`~typing.ParamSpec` parameters, as well as :class:`~typing.TypeVar` parameters with bounds or constraints:

type IntFunc[**P] = Callable[P, int]  # ParamSpec
type LabeledTuple[*Ts] = tuple[str, *Ts]  # TypeVarTuple
type HashableSequence[T: Hashable] = Sequence[T]  # TypeVar with bound
type IntOrStrSequence[T: (int, str)] = Sequence[T]  # TypeVar with constraints

The value of type aliases and the bound and constraints of type variables created through this syntax are evaluated only on demand (see :ref:`lazy-evaluation`). This means type aliases are able to refer to other types defined later in the file.

Type parameters declared through a type parameter list are visible within the scope of the declaration and any nested scopes, but not in the outer scope. For example, they can be used in the type annotations for the methods of a generic class or in the class body. However, they cannot be used in the module scope after the class is defined. See :ref:`type-params` for a detailed description of the runtime semantics of type parameters.

In order to support these scoping semantics, a new kind of scope is introduced, the :ref:`annotation scope <annotation-scopes>`. Annotation scopes behave for the most part like function scopes, but interact differently with enclosing class scopes. In Python 3.13, :term:`annotations <annotation>` will also be evaluated in annotation scopes.

See PEP 695 for more details.

(PEP written by Eric Traut. Implementation by Jelle Zijlstra, Eric Traut, and others in :gh:`103764`.)

Other Language Changes

New Modules

  • None.

Improved Modules

array

asyncio

calendar

csv

dis

  • Pseudo instruction opcodes (which are used by the compiler but do not appear in executable bytecode) are now exposed in the :mod:`dis` module. :opcode:`HAVE_ARGUMENT` is still relevant to real opcodes, but it is not useful for pseudo instructions. Use the new :data:`dis.hasarg` collection instead. (Contributed by Irit Katriel in :gh:`94216`.)

fractions

importlib.resources

inspect

itertools

math

os

os.path

pathlib

pdb

  • Add convenience variables to hold values temporarily for debug session and provide quick access to values like the current frame or the return value. (Contributed by Tian Gao in :gh:`103693`.)

random

shutil

  • :func:`shutil.make_archive` now passes the root_dir argument to custom archivers which support it. In this case it no longer temporarily changes the current working directory of the process to root_dir to perform archiving. (Contributed by Serhiy Storchaka in :gh:`74696`.)

  • :func:`shutil.rmtree` now accepts a new argument onexc which is an error handler like onerror but which expects an exception instance rather than a (typ, val, tb) triplet. onerror is deprecated and will be removed in Python 3.14. (Contributed by Irit Katriel in :gh:`102828`.)

  • :func:`shutil.which` now consults the PATHEXT environment variable to find matches within PATH on Windows even when the given cmd includes a directory component. (Contributed by Charles Machalow in :gh:`103179`.)

    :func:`shutil.which` will call NeedCurrentDirectoryForExePathW when querying for executables on Windows to determine if the current working directory should be prepended to the search path. (Contributed by Charles Machalow in :gh:`103179`.)

    :func:`shutil.which` will return a path matching the cmd with a component from PATHEXT prior to a direct match elsewhere in the search path on Windows. (Contributed by Charles Machalow in :gh:`103179`.)

sqlite3

statistics

sys

tempfile

threading

tkinter

  • tkinter.Canvas.coords() now flattens its arguments. It now accepts not only coordinates as separate arguments (x1, y1, x2, y2, ...) and a sequence of coordinates ([x1, y1, x2, y2, ...]), but also coordinates grouped in pairs ((x1, y1), (x2, y2), ... and [(x1, y1), (x2, y2), ...]), like create_*() methods. (Contributed by Serhiy Storchaka in :gh:`94473`.)

tokenize

types

typing

  • :func:`isinstance` checks against :func:`runtime-checkable protocols <typing.runtime_checkable>` now use :func:`inspect.getattr_static` rather than :func:`hasattr` to lookup whether attributes exist. This means that descriptors and :meth:`~object.__getattr__` methods are no longer unexpectedly evaluated during isinstance() checks against runtime-checkable protocols. However, it may also mean that some objects which used to be considered instances of a runtime-checkable protocol may no longer be considered instances of that protocol on Python 3.12+, and vice versa. Most users are unlikely to be affected by this change. (Contributed by Alex Waygood in :gh:`102433`.)

  • The members of a runtime-checkable protocol are now considered "frozen" at runtime as soon as the class has been created. Monkey-patching attributes onto a runtime-checkable protocol will still work, but will have no impact on :func:`isinstance` checks comparing objects to the protocol. For example:

    >>> from typing import Protocol, runtime_checkable
    >>> @runtime_checkable
    ... class HasX(Protocol):
    ...     x = 1
    ...
    >>> class Foo: ...
    ...
    >>> f = Foo()
    >>> isinstance(f, HasX)
    False
    >>> f.x = 1
    >>> isinstance(f, HasX)
    True
    >>> HasX.y = 2
    >>> isinstance(f, HasX)  # unchanged, even though HasX now also has a "y" attribute
    True
    

    This change was made in order to speed up isinstance() checks against runtime-checkable protocols.

  • The performance profile of :func:`isinstance` checks against :func:`runtime-checkable protocols <typing.runtime_checkable>` has changed significantly. Most isinstance() checks against protocols with only a few members should be at least 2x faster than in 3.11, and some may be 20x faster or more. However, isinstance() checks against protocols with fourteen or more members may be slower than in Python 3.11. (Contributed by Alex Waygood in :gh:`74690` and :gh:`103193`.)

  • All :data:`typing.TypedDict` and :data:`typing.NamedTuple` classes now have the __orig_bases__ attribute. (Contributed by Adrian Garcia Badaracco in :gh:`103699`.)

  • Add frozen_default parameter to :func:`typing.dataclass_transform`. (Contributed by Erik De Bonte in :gh:`99957`.)

unicodedata

  • The Unicode database has been updated to version 15.0.0. (Contributed by Benjamin Peterson in :gh:`96734`).

unittest

Added --durations command line option, showing the N slowest test cases:

python3 -m unittest --durations=3 lib.tests.test_threading
.....
Slowest test durations
----------------------------------------------------------------------
1.210s     test_timeout (Lib.test.test_threading.BarrierTests)
1.003s     test_default_timeout (Lib.test.test_threading.BarrierTests)
0.518s     test_timeout (Lib.test.test_threading.EventTests)

(0.000 durations hidden.  Use -v to show these durations.)
----------------------------------------------------------------------
Ran 158 tests in 9.869s

OK (skipped=3)

(Contributed by Giampaolo Rodola in :issue:`4080`)

uuid

Optimizations

CPython bytecode changes

Demos and Tools

  • Remove the Tools/demo/ directory which contained old demo scripts. A copy can be found in the old-demos project. (Contributed by Victor Stinner in :gh:`97681`.)
  • Remove outdated example scripts of the Tools/scripts/ directory. A copy can be found in the old-demos project. (Contributed by Victor Stinner in :gh:`97669`.)

Deprecated

Pending Removal in Python 3.13

The following modules and APIs have been deprecated in earlier Python releases, and will be removed in Python 3.13.

Modules (see PEP 594):

Other modules:

APIs:

Pending Removal in Python 3.14

Pending Removal in Future Versions

The following APIs were deprecated in earlier Python versions and will be removed, although there is currently no date scheduled for their removal.

Removed

asynchat and asyncore

  • These two modules have been removed according to the schedule in PEP 594, having been deprecated in Python 3.6. Use :mod:`asyncio` instead. (Contributed by Nikita Sobolev in :gh:`96580`.)

configparser

distutils

  • Remove the :py:mod:`!distutils` package. It was deprecated in Python 3.10 by PEP 632 "Deprecate distutils module". For projects still using distutils and cannot be updated to something else, the setuptools project can be installed: it still provides distutils. (Contributed by Victor Stinner in :gh:`92584`.)

ensurepip

  • Remove the bundled setuptools wheel from :mod:`ensurepip`, and stop installing setuptools in environments created by :mod:`venv`.

    pip (>= 22.1) does not require setuptools to be installed in the environment. setuptools-based (and distutils-based) packages can still be used with pip install, since pip will provide setuptools in the build environment it uses for building a package.

    easy_install, pkg_resources, setuptools and distutils are no longer provided by default in environments created with venv or bootstrapped with ensurepip, since they are part of the setuptools package. For projects relying on these at runtime, the setuptools project should be declared as a dependency and installed separately (typically, using pip).

    (Contributed by Pradyun Gedam in :gh:`95299`.)

enum

  • Remove :mod:`enum`'s EnumMeta.__getattr__, which is no longer needed for enum attribute access. (Contributed by Ethan Furman in :gh:`95083`.)

ftplib

  • Remove :mod:`ftplib`'s FTP_TLS.ssl_version class attribute: use the context parameter instead. (Contributed by Victor Stinner in :gh:`94172`.)

gzip

hashlib

importlib

  • Many previously deprecated cleanups in :mod:`importlib` have now been completed:
    • References to, and support for :meth:`!module_repr()` has been removed. (Contributed by Barry Warsaw in :gh:`97850`.)
    • importlib.util.set_package, importlib.util.set_loader and importlib.util.module_for_loader have all been removed. (Contributed by Brett Cannon and Nikita Sobolev in :gh:`65961` and :gh:`97850`.)
    • Support for find_loader() and find_module() APIs have been removed. (Contributed by Barry Warsaw in :gh:`98040`.)
    • importlib.abc.Finder, pkgutil.ImpImporter, and pkgutil.ImpLoader have been removed. (Contributed by Barry Warsaw in :gh:`98040`.)

imp

io

locale

sqlite3

  • The following undocumented :mod:`sqlite3` features, deprecated in Python 3.10, are now removed:

    • sqlite3.enable_shared_cache()
    • sqlite3.OptimizedUnicode

    If a shared cache must be used, open the database in URI mode using the cache=shared query parameter.

    The sqlite3.OptimizedUnicode text factory has been an alias for :class:`str` since Python 3.3. Code that previously set the text factory to OptimizedUnicode can either use str explicitly, or rely on the default value which is also str.

    (Contributed by Erlend E. Aasland in :gh:`92548`.)

ssl

unittest

webbrowser

  • Remove support for obsolete browsers from :mod:`webbrowser`. Removed browsers include: Grail, Mosaic, Netscape, Galeon, Skipstone, Iceape, Firebird, and Firefox versions 35 and below (:gh:`102871`).

xml.etree.ElementTree

  • Remove the ElementTree.Element.copy() method of the pure Python implementation, deprecated in Python 3.10, use the :func:`copy.copy` function instead. The C implementation of :mod:`xml.etree.ElementTree` has no copy() method, only a __copy__() method. (Contributed by Victor Stinner in :gh:`94383`.)

zipimport

  • Remove :mod:`zipimport`'s find_loader() and find_module() methods, deprecated in Python 3.10: use the find_spec() method instead. See PEP 451 for the rationale. (Contributed by Victor Stinner in :gh:`94379`.)

Others

Porting to Python 3.12

This section lists previously described changes and other bugfixes that may require changes to your code.

Changes in the Python API

  • More strict rules are now applied for numerical group references and group names in regular expressions. Only sequence of ASCII digits is now accepted as a numerical reference. The group name in bytes patterns and replacement strings can now only contain ASCII letters and digits and underscore. (Contributed by Serhiy Storchaka in :gh:`91760`.)

  • Removed randrange() functionality deprecated since Python 3.10. Formerly, randrange(10.0) losslessly converted to randrange(10). Now, it raises a :exc:`TypeError`. Also, the exception raised for non-integer values such as randrange(10.5) or randrange('10') has been changed from :exc:`ValueError` to :exc:`TypeError`. This also prevents bugs where randrange(1e25) would silently select from a larger range than randrange(10**25). (Originally suggested by Serhiy Storchaka :gh:`86388`.)

  • :class:`argparse.ArgumentParser` changed encoding and error handler for reading arguments from file (e.g. fromfile_prefix_chars option) from default text encoding (e.g. :func:`locale.getpreferredencoding(False) <locale.getpreferredencoding>`) to :term:`filesystem encoding and error handler`. Argument files should be encoded in UTF-8 instead of ANSI Codepage on Windows.

  • Removed the asyncore-based smtpd module deprecated in Python 3.4.7 and 3.5.4. A recommended replacement is the :mod:`asyncio`-based aiosmtpd PyPI module.

  • :func:`shlex.split`: Passing None for s argument now raises an exception, rather than reading :data:`sys.stdin`. The feature was deprecated in Python 3.9. (Contributed by Victor Stinner in :gh:`94352`.)

  • The :mod:`os` module no longer accepts bytes-like paths, like :class:`bytearray` and :class:`memoryview` types: only the exact :class:`bytes` type is accepted for bytes strings. (Contributed by Victor Stinner in :gh:`98393`.)

  • :func:`syslog.openlog` and :func:`syslog.closelog` now fail if used in subinterpreters. :func:`syslog.syslog` may still be used in subinterpreters, but now only if :func:`syslog.openlog` has already been called in the main interpreter. These new restrictions do not apply to the main interpreter, so only a very small set of users might be affected. This change helps with interpreter isolation. Furthermore, :mod:`syslog` is a wrapper around process-global resources, which are best managed from the main interpreter. (Contributed by Dong-hee Na in :gh:`99127`.)

  • The undocumented locking behavior of :func:`~functools.cached_property` is removed, because it locked across all instances of the class, leading to high lock contention. This means that a cached property getter function could now run more than once for a single instance, if two threads race. For most simple cached properties (e.g. those that are idempotent and simply calculate a value based on other attributes of the instance) this will be fine. If synchronization is needed, implement locking within the cached property getter function or around multi-threaded access points.

  • :func:`sys._current_exceptions` now returns a mapping from thread-id to an exception instance, rather than to a (typ, exc, tb) tuple. (Contributed by Irit Katriel in :gh:`103176`.)

  • When extracting tar files using :mod:`tarfile` or :func:`shutil.unpack_archive`, pass the filter argument to limit features that may be surprising or dangerous. See :ref:`tarfile-extraction-filter` for details.

  • The output of the :func:`tokenize.tokenize` and :func:`tokenize.generate_tokens` functions is now changed due to the changes introduced in PEP 701. This means that STRING tokens are not emitted any more for f-strings and the tokens described in PEP 701 are now produced instead: FSTRING_START, FSTRING_MIDDLE and FSTRING_END are now emitted for f-string "string" parts in addition to the appropriate tokens for the tokenization in the expression components. For example for the f-string f"start {1+1} end" the old version of the tokenizer emitted:

    1,0-1,18:           STRING         'f"start {1+1} end"'
    

    while the new version emits:

    1,0-1,2:            FSTRING_START  'f"'
    1,2-1,8:            FSTRING_MIDDLE 'start '
    1,8-1,9:            OP             '{'
    1,9-1,10:           NUMBER         '1'
    1,10-1,11:          OP             '+'
    1,11-1,12:          NUMBER         '1'
    1,12-1,13:          OP             '}'
    1,13-1,17:          FSTRING_MIDDLE ' end'
    1,17-1,18:          FSTRING_END    '"'
    

    Additionally, there may be some minor behavioral changes as a consequence of the changes required to support PEP 701. Some of these changes include:

    • The type attribute of the tokens emitted when tokenizing some invalid Python characters such as ! has changed from ERRORTOKEN to OP.
    • Incomplete single-line strings now also raise :exc:`tokenize.TokenError` as incomplete multiline strings do.
    • Some incomplete or invalid Python code now raises :exc:`tokenize.TokenError` instead of returning arbitrary ERRORTOKEN tokens when tokenizing it.
    • Mixing tabs and spaces as indentation in the same file is not supported anymore and will raise a :exc:`TabError`.

Build Changes

  • Python no longer uses setup.py to build shared C extension modules. Build parameters like headers and libraries are detected in configure script. Extensions are built by Makefile. Most extensions use pkg-config and fall back to manual detection. (Contributed by Christian Heimes in :gh:`93939`.)

  • va_start() with two parameters, like va_start(args, format), is now required to build Python. va_start() is no longer called with a single parameter. (Contributed by Kumar Aditya in :gh:`93207`.)

  • CPython now uses the ThinLTO option as the default link time optimization policy if the Clang compiler accepts the flag. (Contributed by Dong-hee Na in :gh:`89536`.)

  • Add COMPILEALL_OPTS variable in Makefile to override :mod:`compileall` options (default: -j0) in make install. Also merged the 3 compileall commands into a single command to build .pyc files for all optimization levels (0, 1, 2) at once. (Contributed by Victor Stinner in :gh:`99289`.)

  • Add platform triplets for 64-bit LoongArch:

    • loongarch64-linux-gnusf
    • loongarch64-linux-gnuf32
    • loongarch64-linux-gnu

    (Contributed by Zhang Na in :gh:`90656`.)

  • PYTHON_FOR_REGEN now require Python 3.10 or newer.

  • Autoconf 2.71 and aclocal 1.16.4 is now required to regenerate :file:`!configure`. (Contributed by Christian Heimes in :gh:`89886`.)

C API Changes

New Features

Porting to Python 3.12

Deprecated

Removed