aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Doc
diff options
context:
space:
mode:
Diffstat (limited to 'Doc')
-rw-r--r--Doc/c-api/extension-modules.rst247
-rw-r--r--Doc/c-api/index.rst1
-rw-r--r--Doc/c-api/intro.rst26
-rw-r--r--Doc/c-api/module.rst271
-rw-r--r--Doc/conf.py4
-rw-r--r--Doc/data/refcounts.dat3
-rw-r--r--Doc/extending/building.rst49
-rw-r--r--Doc/howto/free-threading-extensions.rst4
-rw-r--r--Doc/howto/free-threading-python.rst17
-rw-r--r--Doc/howto/perf_profiling.rst4
-rw-r--r--Doc/library/ctypes.rst2
-rw-r--r--Doc/library/email.header.rst34
-rw-r--r--Doc/library/math.rst4
-rw-r--r--Doc/library/stdtypes.rst27
-rw-r--r--Doc/library/sys.rst7
-rw-r--r--Doc/library/threading.rst2
-rw-r--r--Doc/library/uuid.rst2
-rw-r--r--Doc/reference/expressions.rst5
-rw-r--r--Doc/using/configure.rst12
-rw-r--r--Doc/using/mac.rst113
-rw-r--r--Doc/whatsnew/3.14.rst106
21 files changed, 619 insertions, 321 deletions
diff --git a/Doc/c-api/extension-modules.rst b/Doc/c-api/extension-modules.rst
new file mode 100644
index 00000000000..4c8212f2f5e
--- /dev/null
+++ b/Doc/c-api/extension-modules.rst
@@ -0,0 +1,247 @@
+.. highlight:: c
+
+.. _extension-modules:
+
+Defining extension modules
+--------------------------
+
+A C extension for CPython is a shared library (for example, a ``.so`` file
+on Linux, ``.pyd`` DLL on Windows), which is loadable into the Python process
+(for example, it is compiled with compatible compiler settings), and which
+exports an :ref:`initialization function <extension-export-hook>`.
+
+To be importable by default (that is, by
+:py:class:`importlib.machinery.ExtensionFileLoader`),
+the shared library must be available on :py:attr:`sys.path`,
+and must be named after the module name plus an extension listed in
+:py:attr:`importlib.machinery.EXTENSION_SUFFIXES`.
+
+.. note::
+
+ Building, packaging and distributing extension modules is best done with
+ third-party tools, and is out of scope of this document.
+ One suitable tool is Setuptools, whose documentation can be found at
+ https://setuptools.pypa.io/en/latest/setuptools.html.
+
+Normally, the initialization function returns a module definition initialized
+using :c:func:`PyModuleDef_Init`.
+This allows splitting the creation process into several phases:
+
+- Before any substantial code is executed, Python can determine which
+ capabilities the module supports, and it can adjust the environment or
+ refuse loading an incompatible extension.
+- By default, Python itself creates the module object -- that is, it does
+ the equivalent of :py:meth:`object.__new__` for classes.
+ It also sets initial attributes like :attr:`~module.__package__` and
+ :attr:`~module.__loader__`.
+- Afterwards, the module object is initialized using extension-specific
+ code -- the equivalent of :py:meth:`~object.__init__` on classes.
+
+This is called *multi-phase initialization* to distinguish it from the legacy
+(but still supported) *single-phase initialization* scheme,
+where the initialization function returns a fully constructed module.
+See the :ref:`single-phase-initialization section below <single-phase-initialization>`
+for details.
+
+.. versionchanged:: 3.5
+
+ Added support for multi-phase initialization (:pep:`489`).
+
+
+Multiple module instances
+.........................
+
+By default, extension modules are not singletons.
+For example, if the :py:attr:`sys.modules` entry is removed and the module
+is re-imported, a new module object is created, and typically populated with
+fresh method and type objects.
+The old module is subject to normal garbage collection.
+This mirrors the behavior of pure-Python modules.
+
+Additional module instances may be created in
+:ref:`sub-interpreters <sub-interpreter-support>`
+or after Python runtime reinitialization
+(:c:func:`Py_Finalize` and :c:func:`Py_Initialize`).
+In these cases, sharing Python objects between module instances would likely
+cause crashes or undefined behavior.
+
+To avoid such issues, each instance of an extension module should
+be *isolated*: changes to one instance should not implicitly affect the others,
+and all state owned by the module, including references to Python objects,
+should be specific to a particular module instance.
+See :ref:`isolating-extensions-howto` for more details and a practical guide.
+
+A simpler way to avoid these issues is
+:ref:`raising an error on repeated initialization <isolating-extensions-optout>`.
+
+All modules are expected to support
+:ref:`sub-interpreters <sub-interpreter-support>`, or otherwise explicitly
+signal a lack of support.
+This is usually achieved by isolation or blocking repeated initialization,
+as above.
+A module may also be limited to the main interpreter using
+the :c:data:`Py_mod_multiple_interpreters` slot.
+
+
+.. _extension-export-hook:
+
+Initialization function
+.......................
+
+The initialization function defined by an extension module has the
+following signature:
+
+.. c:function:: PyObject* PyInit_modulename(void)
+
+Its name should be :samp:`PyInit_{<name>}`, with ``<name>`` replaced by the
+name of the module.
+
+For modules with ASCII-only names, the function must instead be named
+:samp:`PyInit_{<name>}`, with ``<name>`` replaced by the name of the module.
+When using :ref:`multi-phase-initialization`, non-ASCII module names
+are allowed. In this case, the initialization function name is
+:samp:`PyInitU_{<name>}`, with ``<name>`` encoded using Python's
+*punycode* encoding with hyphens replaced by underscores. In Python:
+
+.. code-block:: python
+
+ def initfunc_name(name):
+ try:
+ suffix = b'_' + name.encode('ascii')
+ except UnicodeEncodeError:
+ suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
+ return b'PyInit' + suffix
+
+It is recommended to define the initialization function using a helper macro:
+
+.. c:macro:: PyMODINIT_FUNC
+
+ Declare an extension module initialization function.
+ This macro:
+
+ * specifies the :c:expr:`PyObject*` return type,
+ * adds any special linkage declarations required by the platform, and
+ * for C++, declares the function as ``extern "C"``.
+
+For example, a module called ``spam`` would be defined like this::
+
+ static struct PyModuleDef spam_module = {
+ .m_base = PyModuleDef_HEAD_INIT,
+ .m_name = "spam",
+ ...
+ };
+
+ PyMODINIT_FUNC
+ PyInit_spam(void)
+ {
+ return PyModuleDef_Init(&spam_module);
+ }
+
+It is possible to export multiple modules from a single shared library by
+defining multiple initialization functions. However, importing them requires
+using symbolic links or a custom importer, because by default only the
+function corresponding to the filename is found.
+See the `Multiple modules in one library <https://peps.python.org/pep-0489/#multiple-modules-in-one-library>`__
+section in :pep:`489` for details.
+
+The initialization function is typically the only non-\ ``static``
+item defined in the module's C source.
+
+
+.. _multi-phase-initialization:
+
+Multi-phase initialization
+..........................
+
+Normally, the :ref:`initialization function <extension-export-hook>`
+(``PyInit_modulename``) returns a :c:type:`PyModuleDef` instance with
+non-``NULL`` :c:member:`~PyModuleDef.m_slots`.
+Before it is returned, the ``PyModuleDef`` instance must be initialized
+using the following function:
+
+
+.. c:function:: PyObject* PyModuleDef_Init(PyModuleDef *def)
+
+ Ensure a module definition is a properly initialized Python object that
+ correctly reports its type and a reference count.
+
+ Return *def* cast to ``PyObject*``, or ``NULL`` if an error occurred.
+
+ Calling this function is required for :ref:`multi-phase-initialization`.
+ It should not be used in other contexts.
+
+ Note that Python assumes that ``PyModuleDef`` structures are statically
+ allocated.
+ This function may return either a new reference or a borrowed one;
+ this reference must not be released.
+
+ .. versionadded:: 3.5
+
+
+.. _single-phase-initialization:
+
+Legacy single-phase initialization
+..................................
+
+.. attention::
+ Single-phase initialization is a legacy mechanism to initialize extension
+ modules, with known drawbacks and design flaws. Extension module authors
+ are encouraged to use multi-phase initialization instead.
+
+In single-phase initialization, the
+:ref:`initialization function <extension-export-hook>` (``PyInit_modulename``)
+should create, populate and return a module object.
+This is typically done using :c:func:`PyModule_Create` and functions like
+:c:func:`PyModule_AddObjectRef`.
+
+Single-phase initialization differs from the :ref:`default <multi-phase-initialization>`
+in the following ways:
+
+* Single-phase modules are, or rather *contain*, “singletons”.
+
+ When the module is first initialized, Python saves the contents of
+ the module's ``__dict__`` (that is, typically, the module's functions and
+ types).
+
+ For subsequent imports, Python does not call the initialization function
+ again.
+ Instead, it creates a new module object with a new ``__dict__``, and copies
+ the saved contents to it.
+ For example, given a single-phase module ``_testsinglephase``
+ [#testsinglephase]_ that defines a function ``sum`` and an exception class
+ ``error``:
+
+ .. code-block:: python
+
+ >>> import sys
+ >>> import _testsinglephase as one
+ >>> del sys.modules['_testsinglephase']
+ >>> import _testsinglephase as two
+ >>> one is two
+ False
+ >>> one.__dict__ is two.__dict__
+ False
+ >>> one.sum is two.sum
+ True
+ >>> one.error is two.error
+ True
+
+ The exact behavior should be considered a CPython implementation detail.
+
+* To work around the fact that ``PyInit_modulename`` does not take a *spec*
+ argument, some state of the import machinery is saved and applied to the
+ first suitable module created during the ``PyInit_modulename`` call.
+ Specifically, when a sub-module is imported, this mechanism prepends the
+ parent package name to the name of the module.
+
+ A single-phase ``PyInit_modulename`` function should create “its” module
+ object as soon as possible, before any other module objects can be created.
+
+* Non-ASCII module names (``PyInitU_modulename``) are not supported.
+
+* Single-phase modules support module lookup functions like
+ :c:func:`PyState_FindModule`.
+
+.. [#testsinglephase] ``_testsinglephase`` is an internal module used \
+ in CPython's self-test suite; your installation may or may not \
+ include it.
diff --git a/Doc/c-api/index.rst b/Doc/c-api/index.rst
index ba56b03c6ac..e9df2a304d9 100644
--- a/Doc/c-api/index.rst
+++ b/Doc/c-api/index.rst
@@ -17,6 +17,7 @@ document the API functions in detail.
veryhigh.rst
refcounting.rst
exceptions.rst
+ extension-modules.rst
utilities.rst
abstract.rst
concrete.rst
diff --git a/Doc/c-api/intro.rst b/Doc/c-api/intro.rst
index 41856922110..acce3dc215d 100644
--- a/Doc/c-api/intro.rst
+++ b/Doc/c-api/intro.rst
@@ -111,33 +111,11 @@ Useful macros
=============
Several useful macros are defined in the Python header files. Many are
-defined closer to where they are useful (e.g. :c:macro:`Py_RETURN_NONE`).
+defined closer to where they are useful (for example, :c:macro:`Py_RETURN_NONE`,
+:c:macro:`PyMODINIT_FUNC`).
Others of a more general utility are defined here. This is not necessarily a
complete listing.
-.. c:macro:: PyMODINIT_FUNC
-
- Declare an extension module ``PyInit`` initialization function. The function
- return type is :c:expr:`PyObject*`. The macro declares any special linkage
- declarations required by the platform, and for C++ declares the function as
- ``extern "C"``.
-
- The initialization function must be named :samp:`PyInit_{name}`, where
- *name* is the name of the module, and should be the only non-\ ``static``
- item defined in the module file. Example::
-
- static struct PyModuleDef spam_module = {
- .m_base = PyModuleDef_HEAD_INIT,
- .m_name = "spam",
- ...
- };
-
- PyMODINIT_FUNC
- PyInit_spam(void)
- {
- return PyModuleDef_Init(&spam_module);
- }
-
.. c:macro:: Py_ABS(x)
diff --git a/Doc/c-api/module.rst b/Doc/c-api/module.rst
index 710135dca89..c8edcecc5b4 100644
--- a/Doc/c-api/module.rst
+++ b/Doc/c-api/module.rst
@@ -127,25 +127,36 @@ Module Objects
unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead.
-.. _initializing-modules:
+.. _pymoduledef:
-Initializing C modules
-^^^^^^^^^^^^^^^^^^^^^^
+Module definitions
+------------------
-Modules objects are usually created from extension modules (shared libraries
-which export an initialization function), or compiled-in modules
-(where the initialization function is added using :c:func:`PyImport_AppendInittab`).
-See :ref:`building` or :ref:`extending-with-embedding` for details.
+The functions in the previous section work on any module object, including
+modules imported from Python code.
-The initialization function can either pass a module definition instance
-to :c:func:`PyModule_Create`, and return the resulting module object,
-or request "multi-phase initialization" by returning the definition struct itself.
+Modules defined using the C API typically use a *module definition*,
+:c:type:`PyModuleDef` -- a statically allocated, constant “description" of
+how a module should be created.
+
+The definition is usually used to define an extension's “main” module object
+(see :ref:`extension-modules` for details).
+It is also used to
+:ref:`create extension modules dynamically <moduledef-dynamic>`.
+
+Unlike :c:func:`PyModule_New`, the definition allows management of
+*module state* -- a piece of memory that is allocated and cleared together
+with the module object.
+Unlike the module's Python attributes, Python code cannot replace or delete
+data stored in module state.
.. c:type:: PyModuleDef
The module definition struct, which holds all information needed to create
- a module object. There is usually only one statically initialized variable
- of this type for each module.
+ a module object.
+ This structure must be statically allocated (or be otherwise guaranteed
+ to be valid while any modules created from it exist).
+ Usually, there is only one variable of this type for each extension module.
.. c:member:: PyModuleDef_Base m_base
@@ -170,13 +181,15 @@ or request "multi-phase initialization" by returning the definition struct itsel
and freed when the module object is deallocated, after the
:c:member:`~PyModuleDef.m_free` function has been called, if present.
- Setting ``m_size`` to ``-1`` means that the module does not support
- sub-interpreters, because it has global state.
-
Setting it to a non-negative value means that the module can be
re-initialized and specifies the additional amount of memory it requires
- for its state. Non-negative ``m_size`` is required for multi-phase
- initialization.
+ for its state.
+
+ Setting ``m_size`` to ``-1`` means that the module does not support
+ sub-interpreters, because it has global state.
+ Negative ``m_size`` is only allowed when using
+ :ref:`legacy single-phase initialization <single-phase-initialization>`
+ or when :ref:`creating modules dynamically <moduledef-dynamic>`.
See :PEP:`3121` for more details.
@@ -189,7 +202,7 @@ or request "multi-phase initialization" by returning the definition struct itsel
An array of slot definitions for multi-phase initialization, terminated by
a ``{0, NULL}`` entry.
- When using single-phase initialization, *m_slots* must be ``NULL``.
+ When using legacy single-phase initialization, *m_slots* must be ``NULL``.
.. versionchanged:: 3.5
@@ -249,96 +262,9 @@ or request "multi-phase initialization" by returning the definition struct itsel
.. versionchanged:: 3.9
No longer called before the module state is allocated.
-Single-phase initialization
-...........................
-
-The module initialization function may create and return the module object
-directly. This is referred to as "single-phase initialization", and uses one
-of the following two module creation functions:
-
-.. c:function:: PyObject* PyModule_Create(PyModuleDef *def)
-
- Create a new module object, given the definition in *def*. This behaves
- like :c:func:`PyModule_Create2` with *module_api_version* set to
- :c:macro:`PYTHON_API_VERSION`.
-
-
-.. c:function:: PyObject* PyModule_Create2(PyModuleDef *def, int module_api_version)
-
- Create a new module object, given the definition in *def*, assuming the
- API version *module_api_version*. If that version does not match the version
- of the running interpreter, a :exc:`RuntimeWarning` is emitted.
-
- Return ``NULL`` with an exception set on error.
-
- .. note::
-
- Most uses of this function should be using :c:func:`PyModule_Create`
- instead; only use this if you are sure you need it.
-Before it is returned from in the initialization function, the resulting module
-object is typically populated using functions like :c:func:`PyModule_AddObjectRef`.
-
-.. _multi-phase-initialization:
-
-Multi-phase initialization
-..........................
-
-An alternate way to specify extensions is to request "multi-phase initialization".
-Extension modules created this way behave more like Python modules: the
-initialization is split between the *creation phase*, when the module object
-is created, and the *execution phase*, when it is populated.
-The distinction is similar to the :py:meth:`~object.__new__` and
-:py:meth:`~object.__init__` methods of classes.
-
-Unlike modules created using single-phase initialization, these modules are not
-singletons.
-For example, if the :py:attr:`sys.modules` entry is removed and the module
-is re-imported, a new module object is created, and typically populated with
-fresh method and type objects.
-The old module is subject to normal garbage collection.
-This mirrors the behavior of pure-Python modules.
-
-Additional module instances may be created in
-:ref:`sub-interpreters <sub-interpreter-support>`
-or after after Python runtime reinitialization
-(:c:func:`Py_Finalize` and :c:func:`Py_Initialize`).
-In these cases, sharing Python objects between module instances would likely
-cause crashes or undefined behavior.
-
-To avoid such issues, each instance of an extension module should
-be *isolated*: changes to one instance should not implicitly affect the others,
-and all state, including references to Python objects, should be specific to
-a particular module instance.
-See :ref:`isolating-extensions-howto` for more details and a practical guide.
-
-A simpler way to avoid these issues is
-:ref:`raising an error on repeated initialization <isolating-extensions-optout>`.
-
-All modules created using multi-phase initialization are expected to support
-:ref:`sub-interpreters <sub-interpreter-support>`, or otherwise explicitly
-signal a lack of support.
-This is usually achieved by isolation or blocking repeated initialization,
-as above.
-A module may also be limited to the main interpreter using
-the :c:data:`Py_mod_multiple_interpreters` slot.
-
-To request multi-phase initialization, the initialization function
-(PyInit_modulename) returns a :c:type:`PyModuleDef` instance with non-empty
-:c:member:`~PyModuleDef.m_slots`. Before it is returned, the ``PyModuleDef``
-instance must be initialized with the following function:
-
-.. c:function:: PyObject* PyModuleDef_Init(PyModuleDef *def)
-
- Ensures a module definition is a properly initialized Python object that
- correctly reports its type and reference count.
-
- Returns *def* cast to ``PyObject*``, or ``NULL`` if an error occurred.
-
- .. versionadded:: 3.5
-
-The *m_slots* member of the module definition must point to an array of
-``PyModuleDef_Slot`` structures:
+Module slots
+............
.. c:type:: PyModuleDef_Slot
@@ -352,8 +278,6 @@ The *m_slots* member of the module definition must point to an array of
.. versionadded:: 3.5
-The *m_slots* array must be terminated by a slot with id 0.
-
The available slot types are:
.. c:macro:: Py_mod_create
@@ -464,21 +388,48 @@ The available slot types are:
.. versionadded:: 3.13
-See :PEP:`489` for more details on multi-phase initialization.
-Low-level module creation functions
-...................................
+.. _moduledef-dynamic:
+
+Creating extension modules dynamically
+--------------------------------------
+
+The following functions may be used to create a module outside of an
+extension's :ref:`initialization function <extension-export-hook>`.
+They are also used in
+:ref:`single-phase initialization <single-phase-initialization>`.
+
+.. c:function:: PyObject* PyModule_Create(PyModuleDef *def)
+
+ Create a new module object, given the definition in *def*.
+ This is a macro that calls :c:func:`PyModule_Create2` with
+ *module_api_version* set to :c:macro:`PYTHON_API_VERSION`, or
+ to :c:macro:`PYTHON_ABI_VERSION` if using the
+ :ref:`limited API <limited-c-api>`.
+
+.. c:function:: PyObject* PyModule_Create2(PyModuleDef *def, int module_api_version)
+
+ Create a new module object, given the definition in *def*, assuming the
+ API version *module_api_version*. If that version does not match the version
+ of the running interpreter, a :exc:`RuntimeWarning` is emitted.
+
+ Return ``NULL`` with an exception set on error.
+
+ This function does not support slots.
+ The :c:member:`~PyModuleDef.m_slots` member of *def* must be ``NULL``.
+
-The following functions are called under the hood when using multi-phase
-initialization. They can be used directly, for example when creating module
-objects dynamically. Note that both ``PyModule_FromDefAndSpec`` and
-``PyModule_ExecDef`` must be called to fully initialize a module.
+ .. note::
+
+ Most uses of this function should be using :c:func:`PyModule_Create`
+ instead; only use this if you are sure you need it.
.. c:function:: PyObject * PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)
- Create a new module object, given the definition in *def* and the
- ModuleSpec *spec*. This behaves like :c:func:`PyModule_FromDefAndSpec2`
- with *module_api_version* set to :c:macro:`PYTHON_API_VERSION`.
+ This macro calls :c:func:`PyModule_FromDefAndSpec2` with
+ *module_api_version* set to :c:macro:`PYTHON_API_VERSION`, or
+ to :c:macro:`PYTHON_ABI_VERSION` if using the
+ :ref:`limited API <limited-c-api>`.
.. versionadded:: 3.5
@@ -491,6 +442,10 @@ objects dynamically. Note that both ``PyModule_FromDefAndSpec`` and
Return ``NULL`` with an exception set on error.
+ Note that this does not process execution slots (:c:data:`Py_mod_exec`).
+ Both ``PyModule_FromDefAndSpec`` and ``PyModule_ExecDef`` must be called
+ to fully initialize a module.
+
.. note::
Most uses of this function should be using :c:func:`PyModule_FromDefAndSpec`
@@ -504,35 +459,29 @@ objects dynamically. Note that both ``PyModule_FromDefAndSpec`` and
.. versionadded:: 3.5
-.. c:function:: int PyModule_SetDocString(PyObject *module, const char *docstring)
+.. c:macro:: PYTHON_API_VERSION
- Set the docstring for *module* to *docstring*.
- This function is called automatically when creating a module from
- ``PyModuleDef``, using either ``PyModule_Create`` or
- ``PyModule_FromDefAndSpec``.
+ The C API version. Defined for backwards compatibility.
- .. versionadded:: 3.5
+ Currently, this constant is not updated in new Python versions, and is not
+ useful for versioning. This may change in the future.
-.. c:function:: int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)
+.. c:macro:: PYTHON_ABI_VERSION
- Add the functions from the ``NULL`` terminated *functions* array to *module*.
- Refer to the :c:type:`PyMethodDef` documentation for details on individual
- entries (due to the lack of a shared module namespace, module level
- "functions" implemented in C typically receive the module as their first
- parameter, making them similar to instance methods on Python classes).
- This function is called automatically when creating a module from
- ``PyModuleDef``, using either ``PyModule_Create`` or
- ``PyModule_FromDefAndSpec``.
+ Defined as ``3`` for backwards compatibility.
+
+ Currently, this constant is not updated in new Python versions, and is not
+ useful for versioning. This may change in the future.
- .. versionadded:: 3.5
Support functions
-.................
+-----------------
-The module initialization function (if using single phase initialization) or
-a function called from a module execution slot (if using multi-phase
-initialization), can use the following functions to help initialize the module
-state:
+The following functions are provided to help initialize a module
+state.
+They are intended for a module's execution slots (:c:data:`Py_mod_exec`),
+the initialization function for legacy :ref:`single-phase initialization <single-phase-initialization>`,
+or code that creates modules dynamically.
.. c:function:: int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
@@ -681,12 +630,39 @@ state:
.. versionadded:: 3.9
+.. c:function:: int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)
+
+ Add the functions from the ``NULL`` terminated *functions* array to *module*.
+ Refer to the :c:type:`PyMethodDef` documentation for details on individual
+ entries (due to the lack of a shared module namespace, module level
+ "functions" implemented in C typically receive the module as their first
+ parameter, making them similar to instance methods on Python classes).
+
+ This function is called automatically when creating a module from
+ ``PyModuleDef`` (such as when using :ref:`multi-phase-initialization`,
+ ``PyModule_Create``, or ``PyModule_FromDefAndSpec``).
+ Some module authors may prefer defining functions in multiple
+ :c:type:`PyMethodDef` arrays; in that case they should call this function
+ directly.
+
+ .. versionadded:: 3.5
+
+.. c:function:: int PyModule_SetDocString(PyObject *module, const char *docstring)
+
+ Set the docstring for *module* to *docstring*.
+ This function is called automatically when creating a module from
+ ``PyModuleDef`` (such as when using :ref:`multi-phase-initialization`,
+ ``PyModule_Create``, or ``PyModule_FromDefAndSpec``).
+
+ .. versionadded:: 3.5
+
.. c:function:: int PyUnstable_Module_SetGIL(PyObject *module, void *gil)
Indicate that *module* does or does not support running without the global
interpreter lock (GIL), using one of the values from
:c:macro:`Py_mod_gil`. It must be called during *module*'s initialization
- function. If this function is not called during module initialization, the
+ function when using :ref:`single-phase-initialization`.
+ If this function is not called during module initialization, the
import machinery assumes the module does not support running without the
GIL. This function is only available in Python builds configured with
:option:`--disable-gil`.
@@ -695,10 +671,11 @@ state:
.. versionadded:: 3.13
-Module lookup
-^^^^^^^^^^^^^
+Module lookup (single-phase initialization)
+...........................................
-Single-phase initialization creates singleton modules that can be looked up
+The legacy :ref:`single-phase initialization <single-phase-initialization>`
+initialization scheme creates singleton modules that can be looked up
in the context of the current interpreter. This allows the module object to be
retrieved later with only a reference to the module definition.
@@ -719,7 +696,8 @@ since multiple such modules can be created from a single definition.
Only effective on modules created using single-phase initialization.
- Python calls ``PyState_AddModule`` automatically after importing a module,
+ Python calls ``PyState_AddModule`` automatically after importing a module
+ that uses :ref:`single-phase initialization <single-phase-initialization>`,
so it is unnecessary (but harmless) to call it from module initialization
code. An explicit call is needed only if the module's own init code
subsequently calls ``PyState_FindModule``.
@@ -727,6 +705,9 @@ since multiple such modules can be created from a single definition.
mechanisms (either by calling it directly, or by referring to its
implementation for details of the required state updates).
+ If a module was attached previously using the same *def*, it is replaced
+ by the new *module*.
+
The caller must have an :term:`attached thread state`.
Return ``-1`` with an exception set on error, ``0`` on success.
diff --git a/Doc/conf.py b/Doc/conf.py
index b08f5452901..161c2986441 100644
--- a/Doc/conf.py
+++ b/Doc/conf.py
@@ -79,6 +79,10 @@ version, release = import_module('patchlevel').get_version_info()
rst_epilog = f"""
.. |python_version_literal| replace:: ``Python {version}``
.. |python_x_dot_y_literal| replace:: ``python{version}``
+.. |python_x_dot_y_t_literal| replace:: ``python{version}t``
+.. |python_x_dot_y_t_literal_config| replace:: ``python{version}t-config``
+.. |x_dot_y_b2_literal| replace:: ``{version}.0b2``
+.. |applications_python_version_literal| replace:: ``/Applications/Python {version}/``
.. |usr_local_bin_python_x_dot_y_literal| replace:: ``/usr/local/bin/python{version}``
.. Apparently this how you hack together a formatted link:
diff --git a/Doc/data/refcounts.dat b/Doc/data/refcounts.dat
index 59b31ccf7bc..f5f02f0a79c 100644
--- a/Doc/data/refcounts.dat
+++ b/Doc/data/refcounts.dat
@@ -1489,9 +1489,6 @@ PyModule_SetDocString:int:::
PyModule_SetDocString:PyObject*:module:0:
PyModule_SetDocString:const char*:docstring::
-PyModuleDef_Init:PyObject*::0:
-PyModuleDef_Init:PyModuleDef*:def::
-
PyNumber_Absolute:PyObject*::+1:
PyNumber_Absolute:PyObject*:o:0:
diff --git a/Doc/extending/building.rst b/Doc/extending/building.rst
index a58eb40d431..098dde39ea5 100644
--- a/Doc/extending/building.rst
+++ b/Doc/extending/building.rst
@@ -6,41 +6,10 @@
Building C and C++ Extensions
*****************************
-A C extension for CPython is a shared library (e.g. a ``.so`` file on Linux,
-``.pyd`` on Windows), which exports an *initialization function*.
+A C extension for CPython is a shared library (for example, a ``.so`` file on
+Linux, ``.pyd`` on Windows), which exports an *initialization function*.
-To be importable, the shared library must be available on :envvar:`PYTHONPATH`,
-and must be named after the module name, with an appropriate extension.
-When using setuptools, the correct filename is generated automatically.
-
-The initialization function has the signature:
-
-.. c:function:: PyObject* PyInit_modulename(void)
-
-It returns either a fully initialized module, or a :c:type:`PyModuleDef`
-instance. See :ref:`initializing-modules` for details.
-
-.. highlight:: python
-
-For modules with ASCII-only names, the function must be named
-:samp:`PyInit_{<name>}`, with ``<name>`` replaced by the name of the module.
-When using :ref:`multi-phase-initialization`, non-ASCII module names
-are allowed. In this case, the initialization function name is
-:samp:`PyInitU_{<name>}`, with ``<name>`` encoded using Python's
-*punycode* encoding with hyphens replaced by underscores. In Python::
-
- def initfunc_name(name):
- try:
- suffix = b'_' + name.encode('ascii')
- except UnicodeEncodeError:
- suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
- return b'PyInit' + suffix
-
-It is possible to export multiple modules from a single shared library by
-defining multiple initialization functions. However, importing them requires
-using symbolic links or a custom importer, because by default only the
-function corresponding to the filename is found.
-See the *"Multiple modules in one library"* section in :pep:`489` for details.
+See :ref:`extension-modules` for details.
.. highlight:: c
@@ -51,7 +20,11 @@ See the *"Multiple modules in one library"* section in :pep:`489` for details.
Building C and C++ Extensions with setuptools
=============================================
-Python 3.12 and newer no longer come with distutils. Please refer to the
-``setuptools`` documentation at
-https://setuptools.readthedocs.io/en/latest/setuptools.html
-to learn more about how build and distribute C/C++ extensions with setuptools.
+
+Building, packaging and distributing extension modules is best done with
+third-party tools, and is out of scope of this document.
+One suitable tool is Setuptools, whose documentation can be found at
+https://setuptools.pypa.io/en/latest/setuptools.html.
+
+The :mod:`distutils` module, which was included in the standard library
+until Python 3.12, is now maintained as part of Setuptools.
diff --git a/Doc/howto/free-threading-extensions.rst b/Doc/howto/free-threading-extensions.rst
index 175bb5dc831..02b45879ccf 100644
--- a/Doc/howto/free-threading-extensions.rst
+++ b/Doc/howto/free-threading-extensions.rst
@@ -6,8 +6,8 @@
C API Extension Support for Free Threading
******************************************
-Starting with the 3.13 release, CPython has experimental support for running
-with the :term:`global interpreter lock` (GIL) disabled in a configuration
+Starting with the 3.13 release, CPython has support for running with
+the :term:`global interpreter lock` (GIL) disabled in a configuration
called :term:`free threading`. This document describes how to adapt C API
extensions to support free threading.
diff --git a/Doc/howto/free-threading-python.rst b/Doc/howto/free-threading-python.rst
index c33cef2c8e9..24069617c47 100644
--- a/Doc/howto/free-threading-python.rst
+++ b/Doc/howto/free-threading-python.rst
@@ -1,18 +1,21 @@
.. _freethreading-python-howto:
-**********************************************
-Python experimental support for free threading
-**********************************************
+*********************************
+Python support for free threading
+*********************************
-Starting with the 3.13 release, CPython has experimental support for a build of
+Starting with the 3.13 release, CPython has support for a build of
Python called :term:`free threading` where the :term:`global interpreter lock`
(GIL) is disabled. Free-threaded execution allows for full utilization of the
available processing power by running threads in parallel on available CPU cores.
While not all software will benefit from this automatically, programs
designed with threading in mind will run faster on multi-core hardware.
-**The free-threaded mode is experimental** and work is ongoing to improve it:
-expect some bugs and a substantial single-threaded performance hit.
+The free-threaded mode is working and continues to be improved, but
+there is some additional overhead in single-threaded workloads compared
+to the regular build. Additionally, third-party packages, in particular ones
+with an :term:`extension module`, may not be ready for use in a
+free-threaded build, and will re-enable the :term:`GIL`.
This document describes the implications of free threading
for Python code. See :ref:`freethreading-extensions-howto` for information on
@@ -43,7 +46,7 @@ Identifying free-threaded Python
================================
To check if the current interpreter supports free-threading, :option:`python -VV <-V>`
-and :data:`sys.version` contain "experimental free-threading build".
+and :data:`sys.version` contain "free-threading build".
The new :func:`sys._is_gil_enabled` function can be used to check whether
the GIL is actually disabled in the running process.
diff --git a/Doc/howto/perf_profiling.rst b/Doc/howto/perf_profiling.rst
index b579d776576..96d757ac452 100644
--- a/Doc/howto/perf_profiling.rst
+++ b/Doc/howto/perf_profiling.rst
@@ -92,7 +92,7 @@ Then we can use ``perf report`` to analyze the data:
| | | |
| | | |--51.67%--_PyEval_EvalFrameDefault
| | | | |
- | | | | |--11.52%--_PyLong_Add
+ | | | | |--11.52%--_PyCompactLong_Add
| | | | | |
| | | | | |--2.97%--_PyObject_Malloc
...
@@ -142,7 +142,7 @@ Instead, if we run the same experiment with ``perf`` support enabled we get:
| | | |
| | | |--51.81%--_PyEval_EvalFrameDefault
| | | | |
- | | | | |--13.77%--_PyLong_Add
+ | | | | |--13.77%--_PyCompactLong_Add
| | | | | |
| | | | | |--3.26%--_PyObject_Malloc
diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst
index 2ee4450698a..e00fe9c8145 100644
--- a/Doc/library/ctypes.rst
+++ b/Doc/library/ctypes.rst
@@ -882,7 +882,7 @@ invalid non-\ ``NULL`` pointers would crash Python)::
Thread safety without the GIL
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-In Python 3.13, the :term:`GIL` may be disabled on :term:`experimental free threaded <free threading>` builds.
+From Python 3.13 onward, the :term:`GIL` can be disabled on :term:`free threaded <free threading>` builds.
In ctypes, reads and writes to a single object concurrently is safe, but not across multiple objects:
.. code-block:: pycon
diff --git a/Doc/library/email.header.rst b/Doc/library/email.header.rst
index 219fad0d2f6..c3392a62b8e 100644
--- a/Doc/library/email.header.rst
+++ b/Doc/library/email.header.rst
@@ -178,16 +178,36 @@ The :mod:`email.header` module also provides the following convenient functions.
Decode a message header value without converting the character set. The header
value is in *header*.
- This function returns a list of ``(decoded_string, charset)`` pairs containing
- each of the decoded parts of the header. *charset* is ``None`` for non-encoded
- parts of the header, otherwise a lower case string containing the name of the
- character set specified in the encoded string.
+ For historical reasons, this function may return either:
- Here's an example::
+ 1. A list of pairs containing each of the decoded parts of the header,
+ ``(decoded_bytes, charset)``, where *decoded_bytes* is always an instance of
+ :class:`bytes`, and *charset* is either:
+
+ - A lower case string containing the name of the character set specified.
+
+ - ``None`` for non-encoded parts of the header.
+
+ 2. A list of length 1 containing a pair ``(string, None)``, where
+ *string* is always an instance of :class:`str`.
+
+ An :exc:`email.errors.HeaderParseError` may be raised when certain decoding
+ errors occur (e.g. a base64 decoding exception).
+
+ Here are examples:
>>> from email.header import decode_header
>>> decode_header('=?iso-8859-1?q?p=F6stal?=')
[(b'p\xf6stal', 'iso-8859-1')]
+ >>> decode_header('unencoded_string')
+ [('unencoded_string', None)]
+ >>> decode_header('bar =?utf-8?B?ZsOzbw==?=')
+ [(b'bar ', None), (b'f\xc3\xb3o', 'utf-8')]
+
+ .. note::
+
+ This function exists for for backwards compatibility only. For
+ new code, we recommend using :class:`email.headerregistry.HeaderRegistry`.
.. function:: make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' ')
@@ -203,3 +223,7 @@ The :mod:`email.header` module also provides the following convenient functions.
:class:`Header` instance. Optional *maxlinelen*, *header_name*, and
*continuation_ws* are as in the :class:`Header` constructor.
+ .. note::
+
+ This function exists for for backwards compatibility only, and is
+ not recommended for use in new code.
diff --git a/Doc/library/math.rst b/Doc/library/math.rst
index c8061fb1638..ecb1d4102ca 100644
--- a/Doc/library/math.rst
+++ b/Doc/library/math.rst
@@ -387,8 +387,8 @@ Floating point manipulation functions
.. function:: issubnormal(x)
Return ``True`` if *x* is a subnormal number, that is a finite
- nonzero number with a magnitude smaller than the smallest positive normal
- number, see :data:`sys.float_info.min`. Return ``False`` otherwise.
+ nonzero number with a magnitude smaller than :data:`sys.float_info.min`.
+ Return ``False`` otherwise.
.. versionadded:: next
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index b75e5ceecf8..394c302fd35 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -1841,6 +1841,14 @@ expression support in the :mod:`re` module).
unless an encoding error actually occurs,
:ref:`devmode` is enabled
or a :ref:`debug build <debug-build>` is used.
+ For example::
+
+ >>> encoded_str_to_bytes = 'Python'.encode()
+ >>> type(encoded_str_to_bytes)
+ <class 'bytes'>
+ >>> encoded_str_to_bytes
+ b'Python'
+
.. versionchanged:: 3.1
Added support for keyword arguments.
@@ -1855,7 +1863,19 @@ expression support in the :mod:`re` module).
Return ``True`` if the string ends with the specified *suffix*, otherwise return
``False``. *suffix* can also be a tuple of suffixes to look for. With optional
*start*, test beginning at that position. With optional *end*, stop comparing
- at that position.
+ at that position. Using *start* and *end* is equivalent to
+ ``str[start:end].endswith(suffix)``. For example::
+
+ >>> 'Python'.endswith('on')
+ True
+ >>> 'a tuple of suffixes'.endswith(('at', 'in'))
+ False
+ >>> 'a tuple of suffixes'.endswith(('at', 'es'))
+ True
+ >>> 'Python is amazing'.endswith('is', 0, 9)
+ True
+
+ See also :meth:`startswith` and :meth:`removesuffix`.
.. method:: str.expandtabs(tabsize=8)
@@ -1871,12 +1891,15 @@ expression support in the :mod:`re` module).
(``\n``) or return (``\r``), it is copied and the current column is reset to
zero. Any other character is copied unchanged and the current column is
incremented by one regardless of how the character is represented when
- printed.
+ printed. For example::
>>> '01\t012\t0123\t01234'.expandtabs()
'01 012 0123 01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01 012 0123 01234'
+ >>> print('01\t012\n0123\t01234'.expandtabs(4))
+ 01 012
+ 0123 01234
.. method:: str.find(sub[, start[, end]])
diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst
index 55e442b20ff..71f9999464a 100644
--- a/Doc/library/sys.rst
+++ b/Doc/library/sys.rst
@@ -1933,6 +1933,13 @@ always available. Unless explicitly noted otherwise, all variables are read-only
interpreter is pre-release (alpha, beta, or release candidate) then the
local and remote interpreters must be the same exact version.
+ .. audit-event:: remote_debugger_script script_path
+
+ When the script is executed in the remote process, an
+ :ref:`auditing event <auditing>`
+ ``sys.remote_debugger_script`` is raised
+ with the path in the remote process.
+
.. availability:: Unix, Windows.
.. versionadded:: 3.14
diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst
index 7edcdcabdce..52fefd590da 100644
--- a/Doc/library/threading.rst
+++ b/Doc/library/threading.rst
@@ -102,7 +102,7 @@ CPU-bound tasks, as only one thread can execute Python bytecode at a time.
Despite this, threads remain a useful tool for achieving concurrency in many
scenarios.
-As of Python 3.13, experimental :term:`free-threaded <free threading>` builds
+As of Python 3.13, :term:`free-threaded <free threading>` builds
can disable the GIL, enabling true parallel execution of threads, but this
feature is not available by default (see :pep:`703`).
diff --git a/Doc/library/uuid.rst b/Doc/library/uuid.rst
index 747ee3ee0e1..92d58024e84 100644
--- a/Doc/library/uuid.rst
+++ b/Doc/library/uuid.rst
@@ -257,7 +257,7 @@ The :mod:`uuid` module defines the following functions:
non-specified arguments are substituted for a pseudo-random integer of
appropriate size.
- By default, *a*, *b* and *c* are generated by a non-cryptographically
+ By default, *a*, *b* and *c* are not generated by a cryptographically
secure pseudo-random number generator (CSPRNG). Use :func:`uuid4` when
a UUID needs to be used in a security-sensitive context.
diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst
index 2a550b504ca..3d3bf1d9840 100644
--- a/Doc/reference/expressions.rst
+++ b/Doc/reference/expressions.rst
@@ -406,8 +406,9 @@ brackets or curly braces.
Variables used in the generator expression are evaluated lazily when the
:meth:`~generator.__next__` method is called for the generator object (in the same
fashion as normal generators). However, the iterable expression in the
-leftmost :keyword:`!for` clause is immediately evaluated, so that an error
-produced by it will be emitted at the point where the generator expression
+leftmost :keyword:`!for` clause is immediately evaluated, and the
+:term:`iterator` is immediately created for that iterable, so that an error
+produced while creating the iterator will be emitted at the point where the generator expression
is defined, rather than at the point where the first value is retrieved.
Subsequent :keyword:`!for` clauses and any filter condition in the leftmost
:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may
diff --git a/Doc/using/configure.rst b/Doc/using/configure.rst
index b914d3397b6..df81a330549 100644
--- a/Doc/using/configure.rst
+++ b/Doc/using/configure.rst
@@ -290,8 +290,8 @@ General Options
.. option:: --disable-gil
- Enables **experimental** support for running Python without the
- :term:`global interpreter lock` (GIL): free threading build.
+ Enables support for running Python without the :term:`global interpreter
+ lock` (GIL): free threading build.
Defines the ``Py_GIL_DISABLED`` macro and adds ``"t"`` to
:data:`sys.abiflags`.
@@ -445,6 +445,14 @@ Options for third-party dependencies
C compiler and linker flags for ``libuuid``, used by :mod:`uuid` module,
overriding ``pkg-config``.
+.. option:: LIBZSTD_CFLAGS
+.. option:: LIBZSTD_LIBS
+
+ C compiler and linker flags for ``libzstd``, used by :mod:`compression.zstd` module,
+ overriding ``pkg-config``.
+
+ .. versionadded:: 3.14
+
.. option:: PANEL_CFLAGS
.. option:: PANEL_LIBS
diff --git a/Doc/using/mac.rst b/Doc/using/mac.rst
index 4b6c884f3d4..f88f3c2e078 100644
--- a/Doc/using/mac.rst
+++ b/Doc/using/mac.rst
@@ -20,13 +20,6 @@ the Pythons provided by the CPython release team for download from
the `python.org website <https://www.python.org/downloads/>`_. See
:ref:`alternative_bundles` for some other options.
-.. |usemac_x_dot_y| replace:: 3.13
-.. |usemac_python_x_dot_y_literal| replace:: ``python3.13``
-.. |usemac_python_x_dot_y_t_literal| replace:: ``python3.13t``
-.. |usemac_python_x_dot_y_t_literal_config| replace:: ``python3.13t-config``
-.. |usemac_applications_folder_name| replace:: ``Python 3.13``
-.. |usemac_applications_folder_version| replace:: ``/Applications/Python 3.13/``
-
.. _getting-osx:
.. _getting-and-installing-macpython:
@@ -64,7 +57,7 @@ Clicking on the **Continue** button brings up the **Read Me** for this installer
Besides other important information, the **Read Me** documents which Python version is
going to be installed and on what versions of macOS it is supported. You may need
to scroll through to read the whole file. By default, this **Read Me** will also be
-installed in |usemac_applications_folder_version| and available to read anytime.
+installed in |applications_python_version_literal| and available to read anytime.
.. image:: mac_installer_02_readme.png
@@ -83,7 +76,7 @@ display. For most uses, the standard set of installation operations is appropria
By pressing the **Customize** button, you can choose to omit or select certain package
components of the installer. Click on each package name to see a description of
what it installs.
-To also install support for the optional experimental free-threaded feature,
+To also install support for the optional free-threaded feature,
see :ref:`install-freethreaded-macos`.
.. image:: mac_installer_05_custom_install.png
@@ -97,7 +90,7 @@ When the installation is complete, the **Summary** window will appear.
.. image:: mac_installer_06_summary.png
Double-click on the :command:`Install Certificates.command`
-icon or file in the |usemac_applications_folder_version| window to complete the
+icon or file in the |applications_python_version_literal| window to complete the
installation.
.. image:: mac_installer_07_applications.png
@@ -114,7 +107,7 @@ Close this terminal window and the installer window.
A default install will include:
-* A |usemac_applications_folder_name| folder in your :file:`Applications` folder. In here
+* A |python_version_literal| folder in your :file:`Applications` folder. In here
you find :program:`IDLE`, the development environment that is a standard part of official
Python distributions; and :program:`Python Launcher`, which handles double-clicking Python
scripts from the macOS `Finder <https://support.apple.com/en-us/HT201732>`_.
@@ -141,7 +134,7 @@ How to run a Python script
There are two ways to invoke the Python interpreter.
If you are familiar with using a Unix shell in a terminal
-window, you can invoke |usemac_python_x_dot_y_literal| or ``python3`` optionally
+window, you can invoke |python_x_dot_y_literal| or ``python3`` optionally
followed by one or more command line options (described in :ref:`using-on-general`).
The Python tutorial also has a useful section on
:ref:`using Python interactively from a shell <tut-interac>`.
@@ -160,7 +153,7 @@ for more information.
To run a Python script file from the terminal window, you can
invoke the interpreter with the name of the script file:
- |usemac_python_x_dot_y_literal| ``myscript.py``
+ |python_x_dot_y_literal| ``myscript.py``
To run your script from the Finder, you can either:
@@ -259,20 +252,20 @@ Advanced Topics
Installing Free-threaded Binaries
---------------------------------
-.. versionadded:: 3.13 (Experimental)
-
-.. note::
-
- Everything described in this section is considered experimental,
- and should be expected to change in future releases.
+.. versionadded:: 3.13
The ``python.org`` :ref:`Python for macOS <getting-and-installing-macpython>`
installer package can optionally install an additional build of
-Python |usemac_x_dot_y| that supports :pep:`703`, the experimental free-threading feature
+Python |version| that supports :pep:`703`, the free-threading feature
(running with the :term:`global interpreter lock` disabled).
Check the release page on ``python.org`` for possible updated information.
-Because this feature is still considered experimental, the support for it
+The free-threaded mode is working and continues to be improved, but
+there is some additional overhead in single-threaded workloads compared
+to the regular build. Additionally, third-party packages, in particular ones
+with an :term:`extension module`, may not be ready for use in a
+free-threaded build, and will re-enable the :term:`GIL`.
+Therefore, the support for free-threading
is not installed by default. It is packaged as a separate install option,
available by clicking the **Customize** button on the **Installation Type**
step of the installer as described above.
@@ -282,46 +275,54 @@ step of the installer as described above.
If the box next to the **Free-threaded Python** package name is checked,
a separate :file:`PythonT.framework` will also be installed
alongside the normal :file:`Python.framework` in :file:`/Library/Frameworks`.
-This configuration allows a free-threaded Python |usemac_x_dot_y| build to co-exist
-on your system with a traditional (GIL only) Python |usemac_x_dot_y| build with
-minimal risk while installing or testing. This installation layout is itself
-experimental and is subject to change in future releases.
+This configuration allows a free-threaded Python |version| build to co-exist
+on your system with a traditional (GIL only) Python |version| build with
+minimal risk while installing or testing. This installation layout may
+change in future releases.
Known cautions and limitations:
- The **UNIX command-line tools** package, which is selected by default,
- will install links in :file:`/usr/local/bin` for |usemac_python_x_dot_y_t_literal|,
- the free-threaded interpreter, and |usemac_python_x_dot_y_t_literal_config|,
+ will install links in :file:`/usr/local/bin` for |python_x_dot_y_t_literal|,
+ the free-threaded interpreter, and |python_x_dot_y_t_literal_config|,
a configuration utility which may be useful for package builders.
Since :file:`/usr/local/bin` is typically included in your shell ``PATH``,
in most cases no changes to your ``PATH`` environment variables should
- be needed to use |usemac_python_x_dot_y_t_literal|.
+ be needed to use |python_x_dot_y_t_literal|.
- For this release, the **Shell profile updater** package and the
- :file:`Update Shell Profile.command` in |usemac_applications_folder_version|
+ :file:`Update Shell Profile.command` in |applications_python_version_literal|
do not support the free-threaded package.
- The free-threaded build and the traditional build have separate search
paths and separate :file:`site-packages` directories so, by default,
if you need a package available in both builds, it may need to be installed in both.
The free-threaded package will install a separate instance of :program:`pip` for use
- with |usemac_python_x_dot_y_t_literal|.
+ with |python_x_dot_y_t_literal|.
- To install a package using :command:`pip` without a :command:`venv`:
- |usemac_python_x_dot_y_t_literal| ``-m pip install <package_name>``
+ .. parsed-literal::
+
+ python\ |version|\ t -m pip install <package_name>
- When working with multiple Python environments, it is usually safest and easiest
to :ref:`create and use virtual environments <tut-venv>`.
This can avoid possible command name conflicts and confusion about which Python is in use:
- |usemac_python_x_dot_y_t_literal| ``-m venv <venv_name>``
+ .. parsed-literal::
+
+ python\ |version|\ t -m venv <venv_name>
+
then :command:`activate`.
- To run a free-threaded version of IDLE:
- |usemac_python_x_dot_y_t_literal| ``-m idlelib``
+ .. parsed-literal::
+
+ python\ |version|\ t -m idlelib
+
- The interpreters in both builds respond to the same
:ref:`PYTHON environment variables <using-on-envvars>`
@@ -337,28 +338,28 @@ Known cautions and limitations:
thus it only needs to be run once.
- If you cannot depend on the link in ``/usr/local/bin`` pointing to the
- ``python.org`` free-threaded |usemac_python_x_dot_y_t_literal| (for example, if you want
+ ``python.org`` free-threaded |python_x_dot_y_t_literal| (for example, if you want
to install your own version there or some other distribution does),
you can explicitly set your shell ``PATH`` environment variable to
include the ``PythonT`` framework ``bin`` directory:
- .. code-block:: sh
+ .. parsed-literal::
- export PATH="/Library/Frameworks/PythonT.framework/Versions/3.13/bin":"$PATH"
+ export PATH="/Library/Frameworks/PythonT.framework/Versions/\ |version|\ /bin":"$PATH"
The traditional framework installation by default does something similar,
except for :file:`Python.framework`. Be aware that having both framework ``bin``
directories in ``PATH`` can lead to confusion if there are duplicate names
- like ``python3.13`` in both; which one is actually used depends on the order
+ like |python_x_dot_y_literal| in both; which one is actually used depends on the order
they appear in ``PATH``. The ``which python3.x`` or ``which python3.xt``
commands can show which path is being used. Using virtual environments
can help avoid such ambiguities. Another option might be to create
a shell :command:`alias` to the desired interpreter, like:
- .. code-block:: sh
+ .. parsed-literal::
- alias py3.13="/Library/Frameworks/Python.framework/Versions/3.13/bin/python3.13"
- alias py3.13t="/Library/Frameworks/PythonT.framework/Versions/3.13/bin/python3.13t"
+ alias py\ |version|\ ="/Library/Frameworks/Python.framework/Versions/\ |version|\ /bin/python\ |version|\ "
+ alias py\ |version|\ t="/Library/Frameworks/PythonT.framework/Versions/\ |version|\ /bin/python\ |version|\ t"
Installing using the command line
---------------------------------
@@ -369,22 +370,22 @@ the macOS command line :command:`installer` utility lets you select non-default
options, too. If you are not familiar with :command:`installer`, it can be
somewhat cryptic (see :command:`man installer` for more information).
As an example, the following shell snippet shows one way to do it,
-using the ``3.13.0b2`` release and selecting the free-threaded interpreter
+using the |x_dot_y_b2_literal| release and selecting the free-threaded interpreter
option:
-.. code-block:: sh
+.. parsed-literal::
- RELEASE="python-3.13.0b2-macos11.pkg"
+ RELEASE="python-\ |version|\ 0b2-macos11.pkg"
# download installer pkg
- curl -O https://www.python.org/ftp/python/3.13.0/${RELEASE}
+ curl -O \https://www.python.org/ftp/python/\ |version|\ .0/${RELEASE}
# create installer choicechanges to customize the install:
- # enable the PythonTFramework-3.13 package
+ # enable the PythonTFramework-\ |version|\ package
# while accepting the other defaults (install all other packages)
cat > ./choicechanges.plist <<EOF
<?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "\http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
@@ -393,7 +394,7 @@ option:
<key>choiceAttribute</key>
<string>selected</string>
<key>choiceIdentifier</key>
- <string>org.python.Python.PythonTFramework-3.13</string>
+ <string>org.python.Python.PythonTFramework-\ |version|\ </string>
</dict>
</array>
</plist>
@@ -404,19 +405,19 @@ option:
You can then test that both installer builds are now available with something like:
-.. code-block:: console
+.. parsed-literal::
$ # test that the free-threaded interpreter was installed if the Unix Command Tools package was enabled
- $ /usr/local/bin/python3.13t -VV
- Python 3.13.0b2 experimental free-threading build (v3.13.0b2:3a83b172af, Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
+ $ /usr/local/bin/python\ |version|\ t -VV
+ Python \ |version|\ .0b2 free-threading build (v\ |version|\ .0b2:3a83b172af, Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
$ # and the traditional interpreter
- $ /usr/local/bin/python3.13 -VV
- Python 3.13.0b2 (v3.13.0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]
+ $ /usr/local/bin/python\ |version|\ -VV
+ Python \ |version|\ .0b2 (v\ |version|\ .0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]
$ # test that they are also available without the prefix if /usr/local/bin is on $PATH
- $ python3.13t -VV
- Python 3.13.0b2 experimental free-threading build (v3.13.0b2:3a83b172af, Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
- $ python3.13 -VV
- Python 3.13.0b2 (v3.13.0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]
+ $ python\ |version|\ t -VV
+ Python \ |version|\ .0b2 free-threading build (v\ |version|\ .0b2:3a83b172af, Jun 5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
+ $ python\ |version|\ -VV
+ Python \ |version|\ .0b2 (v\ |version|\ .0b2:3a83b172af, Jun 5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]
.. note::
diff --git a/Doc/whatsnew/3.14.rst b/Doc/whatsnew/3.14.rst
index ca330a32b33..f0a87a9ada7 100644
--- a/Doc/whatsnew/3.14.rst
+++ b/Doc/whatsnew/3.14.rst
@@ -82,9 +82,10 @@ and improvements in user-friendliness and correctness.
.. PEP-sized items next.
+* :ref:`PEP 779: Free-threaded Python is officially supported <whatsnew314-pep779>`
* :ref:`PEP 649 and 749: deferred evaluation of annotations <whatsnew314-pep649>`
-* :ref:`PEP 734: Multiple Interpreters in the Stdlib <whatsnew314-pep734>`
-* :ref:`PEP 741: Python Configuration C API <whatsnew314-pep741>`
+* :ref:`PEP 734: Multiple interpreters in the stdlib <whatsnew314-pep734>`
+* :ref:`PEP 741: Python configuration C API <whatsnew314-pep741>`
* :ref:`PEP 750: Template strings <whatsnew314-pep750>`
* :ref:`PEP 758: Allow except and except* expressions without parentheses <whatsnew314-pep758>`
* :ref:`PEP 761: Discontinuation of PGP signatures <whatsnew314-pep761>`
@@ -124,9 +125,35 @@ of Python. See :ref:`below <whatsnew314-refcount>` for details.
New features
============
+.. _whatsnew314-pep779:
+
+PEP 779: Free-threaded Python is officially supported
+-----------------------------------------------------
+
+The free-threaded build of Python is now supported and no longer experimental.
+This is the start of phase II where free-threaded Python is officially supported
+but still optional.
+
+We are confident that the project is on the right path, and we appreciate the
+continued dedication from everyone working to make free-threading ready for
+broader adoption across the Python community.
+
+With these recommendations and the acceptance of this PEP, we as the Python
+developer community should broadly advertise that free-threading is a supported
+Python build option now and into the future, and that it will not be removed
+without a proper deprecation schedule.
+
+Any decision to transition to phase III, with free-threading as the default or
+sole build of Python is still undecided, and dependent on many factors both
+within CPython itself and the community. This decision is for the future.
+
+.. seealso::
+ :pep:`779` and its `acceptance
+ <https://discuss.python.org/t/pep-779-criteria-for-supported-status-for-free-threaded-python/84319/123>`__.
+
.. _whatsnew314-pep734:
-PEP 734: Multiple Interpreters in the Stdlib
+PEP 734: Multiple interpreters in the stdlib
--------------------------------------------
The CPython runtime supports running multiple copies of Python in the
@@ -392,7 +419,7 @@ As can be seen, the API is similar to the APIs of the :mod:`!lzma` and
:mod:`!bz2` modules.
(Contributed by Emma Harper Smith, Adam Turner, Gregory P. Smith, Tomas Roun,
-Victor Stinner, and Rogdham in :gh:`132983`)
+Victor Stinner, and Rogdham in :gh:`132983`.)
.. seealso::
:pep:`784`.
@@ -727,7 +754,7 @@ Improved error messages
.. _whatsnew314-pep741:
-PEP 741: Python Configuration C API
+PEP 741: Python configuration C API
-----------------------------------
Add a :ref:`PyInitConfig C API <pyinitconfig_api>` to configure the Python
@@ -816,43 +843,58 @@ Executing the new tool on the running process will yield a table like this:
python -m asyncio ps 12345
- tid task id task name coroutine chain awaiter name awaiter id
- ---------------------------------------------------------------------------------------------------------------------------------------
- 8138752 0x564bd3d0210 Task-1 0x0
- 8138752 0x564bd3d0410 Sundowning _aexit -> __aexit__ -> main Task-1 0x564bd3d0210
- 8138752 0x564bd3d0610 TMBTE _aexit -> __aexit__ -> main Task-1 0x564bd3d0210
- 8138752 0x564bd3d0810 TNDNBTG _aexit -> __aexit__ -> album Sundowning 0x564bd3d0410
- 8138752 0x564bd3d0a10 Levitate _aexit -> __aexit__ -> album Sundowning 0x564bd3d0410
- 8138752 0x564bd3e0550 DYWTYLM _aexit -> __aexit__ -> album TMBTE 0x564bd3d0610
- 8138752 0x564bd3e0710 Aqua Regia _aexit -> __aexit__ -> album TMBTE 0x564bd3d0610
+ tid task id task name coroutine stack awaiter chain awaiter name awaiter id
+ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ 1935500 0x7fc930c18050 Task-1 TaskGroup._aexit -> TaskGroup.__aexit__ -> main 0x0
+ 1935500 0x7fc930c18230 Sundowning TaskGroup._aexit -> TaskGroup.__aexit__ -> album TaskGroup._aexit -> TaskGroup.__aexit__ -> main Task-1 0x7fc930c18050
+ 1935500 0x7fc93173fa50 TMBTE TaskGroup._aexit -> TaskGroup.__aexit__ -> album TaskGroup._aexit -> TaskGroup.__aexit__ -> main Task-1 0x7fc930c18050
+ 1935500 0x7fc93173fdf0 TNDNBTG sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album Sundowning 0x7fc930c18230
+ 1935500 0x7fc930d32510 Levitate sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album Sundowning 0x7fc930c18230
+ 1935500 0x7fc930d32890 DYWTYLM sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album TMBTE 0x7fc93173fa50
+ 1935500 0x7fc93161ec30 Aqua Regia sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album TMBTE 0x7fc93173fa50
-
-or:
+or a tree like this:
.. code-block:: bash
python -m asyncio pstree 12345
└── (T) Task-1
- └── main
- └── __aexit__
- └── _aexit
+ └── main example.py:13
+ └── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
+ └── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
├── (T) Sundowning
- │ └── album
- │ └── __aexit__
- │ └── _aexit
+ │ └── album example.py:8
+ │ └── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
+ │ └── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
│ ├── (T) TNDNBTG
+ │ │ └── play example.py:4
+ │ │ └── sleep Lib/asyncio/tasks.py:702
│ └── (T) Levitate
+ │ └── play example.py:4
+ │ └── sleep Lib/asyncio/tasks.py:702
└── (T) TMBTE
- └── album
- └── __aexit__
- └── _aexit
+ └── album example.py:8
+ └── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
+ └── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
├── (T) DYWTYLM
+ │ └── play example.py:4
+ │ └── sleep Lib/asyncio/tasks.py:702
└── (T) Aqua Regia
+ └── play example.py:4
+ └── sleep Lib/asyncio/tasks.py:702
If a cycle is detected in the async await graph (which could indicate a
programming issue), the tool raises an error and lists the cycle paths that
-prevent tree construction.
+prevent tree construction:
+
+.. code-block:: bash
+
+ python -m asyncio pstree 12345
+
+ ERROR: await-graph contains cycles - cannot print a tree!
+
+ cycle: Task-2 → Task-3 → Task-2
(Contributed by Pablo Galindo, Łukasz Langa, Yury Selivanov, and Marta
Gomez Macias in :gh:`91048`.)
@@ -1244,6 +1286,14 @@ concurrent.futures
buffer.
(Contributed by Enzo Bonnal and Josh Rosenberg in :gh:`74028`.)
+configparser
+------------
+
+* Security fix: will no longer write config files it cannot read. Attempting
+ to :meth:`configparser.ConfigParser.write` keys containing delimiters or
+ beginning with the section header pattern will raise a
+ :class:`configparser.InvalidWriteError`.
+ (Contributed by Jacob Lincoln in :gh:`129270`.)
contextvars
-----------
@@ -2732,8 +2782,8 @@ New features
* Add :c:func:`PyType_GetBaseByToken` and :c:data:`Py_tp_token` slot for easier
superclass identification, which attempts to resolve the `type checking issue
- <https://peps.python.org/pep-0630/#type-checking>`__ mentioned in :pep:`630`
- (:gh:`124153`).
+ <https://peps.python.org/pep-0630/#type-checking>`__ mentioned in :pep:`630`.
+ (Contributed in :gh:`124153`.)
* Add :c:func:`PyUnicode_Equal` function to the limited C API:
test if two strings are equal.