Skip to content

Commit 8e203eb

Browse files
committed
abi3t docs
1 parent c1a4112 commit 8e203eb

File tree

3 files changed

+197
-84
lines changed

3 files changed

+197
-84
lines changed

Doc/c-api/stable.rst

Lines changed: 145 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -51,144 +51,204 @@ It is generally intended for specialized, low-level tools like debuggers.
5151
Projects that use this API are expected to follow
5252
CPython development and spend extra effort adjusting to changes.
5353

54+
.. _stable-abi:
5455
.. _stable-application-binary-interface:
5556

56-
Stable Application Binary Interface
57-
===================================
57+
Stable Application Binary Interfaces
58+
====================================
5859

59-
For simplicity, this document talks about *extensions*, but the Limited API
60-
and Stable ABI work the same way for all uses of the API – for example,
61-
embedding Python.
60+
Python's :dfn:`Stable ABI` allows extensions to be compatible with multiple
61+
versions of Python, without recompilation.
6262

63-
.. _limited-c-api:
63+
.. note::
6464

65-
Limited C API
66-
-------------
65+
For simplicity, this document talks about *extensions*, but the Stable ABI
66+
works the same way for all uses of the API – for example, embedding Python.
6767

68-
Python 3.2 introduced the *Limited API*, a subset of Python's C API.
69-
Extensions that only use the Limited API can be
70-
compiled once and be loaded on multiple versions of Python.
71-
Contents of the Limited API are :ref:`listed below <limited-api-list>`.
68+
A Stable ABI is *versioned* using the first two numbers of the Python version.
69+
For example, Stable ABI 3.14 corresponds to Python 3.14.
70+
An extension compiled for Stable ABI 3.x is ABI-compatible with Python 3.x
71+
and above.
7272

73-
.. c:macro:: Py_LIMITED_API
73+
There are two Stable ABIs:
7474

75-
Define this macro before including ``Python.h`` to opt in to only use
76-
the Limited API, and to select the Limited API version.
75+
- ``abi3``, introduced in Pyton 3.2, is compatible with
76+
non-:term:`free threaded <free-threaded build>` builds of CPython.
7777

78-
Define ``Py_LIMITED_API`` to the value of :c:macro:`PY_VERSION_HEX`
79-
corresponding to the lowest Python version your extension supports.
80-
The extension will be ABI-compatible with all Python 3 releases
81-
from the specified one onward, and can use Limited API introduced up to that
82-
version.
78+
- ``abi3t``, introduced in Pyton 3.15, is compatible with
79+
:term:`free threaded <free-threaded build>` builds of CPython.
80+
It has stricter API limitations than ``abi3``.
8381

84-
Rather than using the ``PY_VERSION_HEX`` macro directly, hardcode a minimum
85-
minor version (e.g. ``0x030A0000`` for Python 3.10) for stability when
86-
compiling with future Python versions.
82+
.. versionadded:: next
8783

88-
You can also define ``Py_LIMITED_API`` to ``3``. This works the same as
89-
``0x03020000`` (Python 3.2, the version that introduced Limited API).
84+
``abi3t`` was added in :pep:`803`
9085

91-
.. c:macro:: Py_TARGET_ABI3T
86+
It is possible for an extension to be compiled for *both* ``abi3`` and
87+
``abi3t`` at the same time.
88+
Currently, this has no downsides compared to compiling for ``abi3t`` only.
9289

93-
Define this macro before including ``Python.h`` to opt in to only use
94-
the Limited API for :term:`free-threaded builds <free-threaded build>`,
95-
and to select the Limited API version.
90+
The Stable ABIs come with several caveats:
9691

97-
.. seealso:: :pep:`803`
92+
- Extensions that target a stable ABI must only use a limited subset of
93+
the C API. This subset is known as the :dfn:`Limited API`; its contents
94+
are :ref:`listed below <limited-api-list>`.
9895

99-
.. versionadded:: next
96+
- Compiling for a Stable ABI will disable some optimizations.
97+
In particular, common functions cannot be inlined to take advantage of the
98+
internal implementation details.
10099

100+
- Stable ABI prevents *ABI* issues, like linker errors due to missing
101+
symbols or data corruption due to changes in structure layouts or function
102+
signatures.
103+
However, other changes in Python can change the *behavior* of extensions.
104+
See Python's Backwards Compatibility Policy (:pep:`387`) for details.
101105

102-
.. _stable-abi:
106+
On Windows, extensions that use a Stable ABI should be linked against
107+
``python3.dll`` rather than a version-specific library such as
108+
``python39.dll``.
109+
This library only exposes the relevant symbols.
110+
111+
On some platforms, Python will look for and load shared library files named
112+
with the ``abi3`` or ``abi3t`` tag (e.g. ``mymodule.abi3.so``).
113+
:term:`Free threaded <free-threaded build>` interpreters only recognize the
114+
``abi3t`` tag, while non-free threaded ones will prefer ``abi3`` but fall back
115+
to ``abi3t``.
116+
Thus, extensions compatible with both flavors should use the ``abi3t`` tag.
117+
118+
Python does not check if such extensions conform to a Stable ABI.
119+
Extension authors are encouraged to check using the :c:macro:`Py_mod_abi`
120+
slot or the :c:func:`PyABIInfo_Check` function, but, the user
121+
(or their packaging tool) is ultimately responsible for ensuring that,
122+
for example, extensions built for Stable ABI 3.10 are not installed for lower
123+
versions of Python.
124+
125+
All functions in the Stable ABI are present as functions in Python's shared
126+
library, not solely as macros.
127+
They are usable from languages that don't use the C preprocessor,
128+
such as Python via :py:mod:`ctypes`.
103129

104-
Stable ABI
105-
----------
106130

107-
To enable this, Python provides a *Stable ABI*: a set of symbols that will
108-
remain ABI-compatible across Python 3.x versions.
131+
Compiling for Stable ABI
132+
------------------------
109133

110134
.. note::
111135

112-
The Stable ABI prevents ABI issues, like linker errors due to missing
113-
symbols or data corruption due to changes in structure layouts or function
114-
signatures.
115-
However, other changes in Python can change the *behavior* of extensions.
116-
See Python's Backwards Compatibility Policy (:pep:`387`) for details.
136+
When using a build tool (for example, ``setuptools``), the tool is
137+
generally responsible for setting macros and synchronizing them with
138+
extension filenames and other metadata.
139+
Prefer using the tool's options over defining the macros manually.
117140

118-
The Stable ABI contains symbols exposed in the :ref:`Limited API
119-
<limited-c-api>`, but also other ones – for example, functions necessary to
120-
support older versions of the Limited API.
141+
The rest of this section is relevant for tool authors, and for people who
142+
compile extensions manually.
121143

122-
On Windows, extensions that use the Stable ABI should be linked against
123-
``python3.dll`` rather than a version-specific library such as
124-
``python39.dll``.
144+
.. seealso:: `list of recommended tools`_ in the Python Packaging User Guide
125145

126-
On some platforms, Python will look for and load shared library files named
127-
with the ``abi3`` tag (e.g. ``mymodule.abi3.so``).
128-
It does not check if such extensions conform to a Stable ABI.
129-
The user (or their packaging tools) need to ensure that, for example,
130-
extensions built with the 3.10+ Limited API are not installed for lower
131-
versions of Python.
146+
.. _list of recommended tools: https://packaging.python.org/en/latest/guides/tool-recommendations/#build-backends-for-extension-modules
132147

133-
All functions in the Stable ABI are present as functions in Python's shared
134-
library, not solely as macros. This makes them usable from languages that don't
135-
use the C preprocessor.
148+
To compile for a Stable ABI, define one or both of the following macros
149+
before including ``Python.h`` to the lowest Python version your extension
150+
should support, in :c:macro:`Py_PACK_VERSION` format.
151+
Typically, you should choose a specific value rather than the version of
152+
the Python headers you are compiling against.
136153

154+
Since the :c:macro:`Py_PACK_VERSION` is not available before including
155+
``Python.h``, you will need to use the number directly.
156+
For reference, the values for a few Python versions are:
137157

138-
Limited API Scope and Performance
139-
---------------------------------
158+
.. version-hex-cheatsheet::
140159

141-
The goal for the Limited API is to allow everything that is possible with the
160+
When the macro(s) are defined, ``Python.h`` will only expose API that is
161+
compatible with the given Stable ABI -- that is, the
162+
:ref:`Limited API <limited-api-list>` plus some definitions that need to be
163+
visible to the compiler but should not be used directly.
164+
165+
.. c:macro:: Py_LIMITED_API
166+
167+
Target ``abi3``, that is,
168+
non-:term:`free threaded <free-threaded build>` builds of CPython.
169+
170+
.. c:macro:: Py_TARGET_ABI3T
171+
172+
Target ``abi3t``, that is,
173+
:term:`free threaded <free-threaded build>` builds of CPython.
174+
175+
.. versionadded:: next
176+
177+
Despite the different naming, the macros are similar;
178+
the name :c:macro:`!Py_LIMITED_API` is kept for backwards compatibility.
179+
180+
.. admonition:: Historical note
181+
182+
You can also define ``Py_LIMITED_API`` as ``3``. This works the same as
183+
``0x03020000`` (Python 3.2, the version that introduced Stable ABI).
184+
185+
When both are defined, ``Python.h`` may, or may not, redefine
186+
:c:macro:`!Py_LIMITED_API` to match :c:macro:`!Py_TARGET_ABI3T`.
187+
188+
On a a :term:`free-threaded build` -- that is, when
189+
:c:macro:`Py_GIL_DISABLED` is defined -- :c:macro:`!Py_TARGET_ABI3T`
190+
defaults to the value of :c:macro:`!Py_TARGET_ABI3T`.
191+
This means that there are two ways to build for both ``abi3`` and ``abi3t``:
192+
193+
- define both :c:macro:`!Py_LIMITED_API` and :c:macro:`!Py_TARGET_ABI3T`, or
194+
- define only :c:macro:`!Py_LIMITED_API` and build for free-threaded Python.
195+
196+
197+
Stable ABI Scope and Performance
198+
--------------------------------
199+
200+
The goal for Stable ABI is to allow everything that is possible with the
142201
full C API, but possibly with a performance penalty.
202+
Generally, compatibility with Stable ABI will require some changes to an
203+
extension's source code.
143204

144-
For example, while :c:func:`PyList_GetItem` is available, its unsafe macro
205+
For example, while :c:func:`PyList_GetItem` is available, its "unsafe" macro
145206
variant :c:func:`PyList_GET_ITEM` is not.
146207
The macro can be faster because it can rely on version-specific implementation
147208
details of the list object.
148209

149-
Without ``Py_LIMITED_API`` defined, some C API functions are inlined or
150-
replaced by macros.
151-
Defining ``Py_LIMITED_API`` disables this inlining, allowing stability as
210+
For another example, when *not* compiling for Stable ABI, some C API
211+
functions are inlined or replaced by macros.
212+
Compiling for Stable ABI disables this inlining, allowing stability as
152213
Python's data structures are improved, but possibly reducing performance.
153214

154-
By leaving out the ``Py_LIMITED_API`` definition, it is possible to compile
155-
a Limited API extension with a version-specific ABI. This can improve
156-
performance for that Python version, but will limit compatibility.
157-
Compiling with ``Py_LIMITED_API`` will then yield an extension that can be
158-
distributed where a version-specific one is not available – for example,
159-
for prereleases of an upcoming Python version.
215+
By leaving out the :c:macro:`!Py_LIMITED_API`` or :c:macro:`!Py_TARGET_ABI3T`
216+
definition, it is possible to compile Stable-ABI-compatible source
217+
for a version-specific ABI, possibly improving performance for a specific
218+
Python version.
160219

161220

162221
Limited API Caveats
163222
-------------------
164223

165-
Note that compiling with ``Py_LIMITED_API`` is *not* a complete guarantee that
166-
code conforms to the :ref:`Limited API <limited-c-api>` or the :ref:`Stable ABI
167-
<stable-abi>`. ``Py_LIMITED_API`` only covers definitions, but an API also
168-
includes other issues, such as expected semantics.
224+
Note that compiling with :c:macro:`Py_LIMITED_API` or :c:macro:`Py_TARGET_ABI3T`
225+
is *not* a complete guarantee that code will be compatible with the
226+
expected Python versions.
227+
The macros only cover definitions, not other issues such as expected semantics.
169228

170-
One issue that ``Py_LIMITED_API`` does not guard against is calling a function
229+
One issue that the macros do not guard against is calling a function
171230
with arguments that are invalid in a lower Python version.
172231
For example, consider a function that starts accepting ``NULL`` for an
173232
argument. In Python 3.9, ``NULL`` now selects a default behavior, but in
174233
Python 3.8, the argument will be used directly, causing a ``NULL`` dereference
175234
and crash. A similar argument works for fields of structs.
176235

177236
Another issue is that some struct fields are currently not hidden when
178-
``Py_LIMITED_API`` is defined, even though they're part of the Limited API.
237+
the macros are defined, even though they're part of the Limited API.
179238

180239
For these reasons, we recommend testing an extension with *all* minor Python
181-
versions it supports, and preferably to build with the *lowest* such version.
240+
versions it supports.
182241

183242
We also recommend reviewing documentation of all used API to check
184243
if it is explicitly part of the Limited API. Even with ``Py_LIMITED_API``
185244
defined, a few private declarations are exposed for technical reasons (or
186245
even unintentionally, as bugs).
187246

188-
Also note that the Limited API is not necessarily stable: compiling with
189-
``Py_LIMITED_API`` with Python 3.8 means that the extension will
190-
run with Python 3.12, but it will not necessarily *compile* with Python 3.12.
191-
In particular, parts of the Limited API may be deprecated and removed,
247+
Also note that while compiling with ``Py_LIMITED_API`` 3.8 means that the
248+
extension will *load* on Python 3.12, and *compile* with Python 3.12,
249+
the same source will not necessarily compile with ``Py_LIMITED_API``
250+
set to 3.12.
251+
In general: parts of the Limited API may be deprecated and removed,
192252
provided that the Stable ABI stays stable.
193253

194254

@@ -199,12 +259,12 @@ Platform Considerations
199259

200260
ABI stability depends not only on Python, but also on the compiler used,
201261
lower-level libraries and compiler options. For the purposes of
202-
the :ref:`Stable ABI <stable-abi>`, these details define a “platform”. They
262+
the :ref:`Stable ABIs <stable-abi>`, these details define a “platform”. They
203263
usually depend on the OS type and processor architecture
204264

205265
It is the responsibility of each particular distributor of Python
206266
to ensure that all Python versions on a particular platform are built
207-
in a way that does not break the Stable ABI.
267+
in a way that does not break the Stable ABIs, or the version-specific ABIs.
208268
This is the case with Windows and macOS releases from ``python.org`` and many
209269
third-party distributors.
210270

@@ -365,12 +425,13 @@ The full API is described below for advanced use cases.
365425
.. versionadded:: 3.15
366426

367427

428+
.. _limited-c-api:
368429
.. _limited-api-list:
369430

370431
Contents of Limited API
371432
=======================
372433

373-
374-
Currently, the :ref:`Limited API <limited-c-api>` includes the following items:
434+
This is the definitive list of :ref:`Limited API <limited-c-api>` for
435+
Python |version|:
375436

376437
.. limited-api-list::

Doc/tools/extensions/c_annotations.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,31 @@ def run(self) -> list[nodes.Node]:
378378
return [node]
379379

380380

381+
class VersionHexCheatsheet(SphinxDirective):
382+
"""Show results of Py_PACK_VERSION(3, x) for a few relevant Python versions
383+
384+
This is useful for defining version before Python.h is included.
385+
It should auto-update to the version being documented, hence the extension.
386+
"""
387+
has_content = False
388+
required_arguments = 0
389+
optional_arguments = 0
390+
final_argument_whitespace = True
391+
392+
def run(self) -> list[nodes.Node]:
393+
content = [
394+
".. code-block:: c",
395+
"",
396+
]
397+
current_minor = int(self.config.version.removeprefix('3.'))
398+
for minor in range(current_minor - 5, current_minor + 1):
399+
value = (3 << 24) | (minor << 16)
400+
content.append(f' {value:#x} /* Py_PACK_VERSION(3.{minor}) */')
401+
node = nodes.paragraph()
402+
self.state.nested_parse(StringList(content), 0, node)
403+
return [node]
404+
405+
381406
class CorrespondingTypeSlot(SphinxDirective):
382407
"""Type slot annotations
383408
@@ -443,6 +468,7 @@ def setup(app: Sphinx) -> ExtensionMetadata:
443468
app.add_config_value("stable_abi_file", "", "env", types={str})
444469
app.add_config_value("threadsafety_file", "", "env", types={str})
445470
app.add_directive("limited-api-list", LimitedAPIList)
471+
app.add_directive("version-hex-cheatsheet", VersionHexCheatsheet)
446472
app.add_directive("corresponding-type-slot", CorrespondingTypeSlot)
447473
app.connect("builder-inited", init_annotations)
448474
app.connect("doctree-read", add_annotations)

Doc/whatsnew/3.15.rst

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ Summary -- Release highlights
8282
<whatsnew315-typeform>`
8383
* :pep:`782`: :ref:`A new PyBytesWriter C API to create a Python bytes object
8484
<whatsnew315-pybyteswriter>`
85+
* :pep:`803`: :ref:`Stable ABI for Free-Threaded Builds <whatsnew315-abi3t>`
8586
* :ref:`The JIT compiler has been significantly upgraded <whatsnew315-jit>`
8687
* :ref:`Improved error messages <whatsnew315-improved-error-messages>`
8788
* :ref:`The official Windows 64-bit binaries now use the tail-calling interpreter
@@ -381,6 +382,31 @@ agen() for x in a)``.
381382

382383
(Contributed by Adam Hartz in :gh:`143055`.)
383384

385+
.. _whatsnew315-abi3t:
386+
387+
:pep:`903`: ``abi3t`` -- Stable ABI for Free-Threaded Builds
388+
------------------------------------------------------------
389+
390+
C extensions that target the :ref:`Stable ABI <stable-abi>`
391+
can now be compiled to be compatible with
392+
both :term:`free-threaded build <free-threaded build>` builds of CPython
393+
and "traditional" builds with the :term:`GIL` enabled.
394+
This mode usually requires some non-trivial changes to the source code;
395+
specifically:
396+
397+
- Switching to API introduced in :pep:`697` (Python 3.12), such as
398+
negative :c:member:`~PyType_Spec.basicsize` and
399+
:c:func:`PyObject_GetTypeData`, rather than making :c:type:`PyObject`
400+
part of the instance struct; and
401+
- Switching from a ``PyInit_`` function to a new export hook,
402+
:c:func:`PyModExport_* <PyModExport_modulename>`, introduced for this
403+
purpose in :pep:`903`.
404+
405+
Note that Stable ABI does not offer all functionality CPython has to offer.
406+
Extensions that cannot switch to ``abi3t`` should continue to build for
407+
the existing Stable ABI (``abi3``) and the version-specific ABI for
408+
free-threading (``cp315t``) separately.
409+
384410

385411
.. _whatsnew315-improved-error-messages:
386412

0 commit comments

Comments
 (0)