Featureresearch
The limited API and the stable ABI
Also called Limited API, Stable ABI, Limited C API, abi3, abi3t, Py_LIMITED_API, Py_TARGET_ABI3T, abi3 wheel, python3.dll, Py_PACK_VERSION, Py_mod_abi, PEP 384, PEP 652, PEP 803.
The limited API is a subset of the C API. An extension that uses only this subset gets the stable ABI (abi3), so one binary loads on its target version of CPython and on all later 3.x versions.
- Language
- Python
Synopsis
import ctypes
import sys
def pack_version(major, minor):
return (major << 24) | (minor << 16)
print(hex(pack_version(3, 13)))
version = ctypes.c_ulong.in_dll(ctypes.pythonapi, 'Py_Version').value
print(version == sys.hexversion, version >= pack_version(3, 11))
for name in ['PyList_GetItem', 'PyList_GET_ITEM']:
print(name, hasattr(ctypes.pythonapi, name))
0x30d0000
True True
PyList_GetItem True
PyList_GET_ITEM False
The limited API is a subset of the Python C API. The stable ABI is the promise that an extension that uses only this subset loads on later versions of CPython without a new build. The extension defines the macro Py_LIMITED_API before it includes Python.h, and the value of the macro is the lowest Python version that the extension supports. The build then makes one file, for example spam.abi3.so, in place of one file for each Python version. The example packs a version number in the format that the macro uses. It also reads the run-time version Py_Version, which is in the stable ABI, and shows that the function PyList_GetItem is exported from the Python library but the macro PyList_GET_ITEM is not.
Semantics
r1. The two names are for two related things. "The Stable ABI is a promise that certain extensions compiled with CPython 3.x will be binary compatible with all subsequent versions of CPython 3.x."1 "The Limited API is a subset of CPython’s C API that produces such extensions."1 Without the stable ABI, the binary interface changes with each minor version: "code compiled for Python 3.10.0 will work on 3.10.8 and vice versa, but will need to be compiled separately for 3.9.x and 3.11.x."2
r2. "There are two Stable ABIs:"2 abi3 is from Python 3.2, and abi3t is from Python 3.15.2 abi3 "is compatible with non-free-threaded builds of CPython."2 abi3t "is compatible with free-threaded builds of CPython. It has stricter API limitations than abi3."2 "It is possible for an extension to be compiled for both abi3 and abi3t at the same time; the result will be compatible with both free-threaded and non-free-threaded builds of Python."2
r3. To use the limited API, define Py_LIMITED_API (for abi3) or Py_TARGET_ABI3T (for abi3t). Define it "to the lowest Python version your extension should support, in Py_PACK_VERSION format."2 "The macros must be defined before including Python.h."2 The value for Python 3.13 is 0x30d0000, and the value for 3.15 is 0x30f0000.2 "When one of the macros is defined, Python.h will only expose API that is compatible with the given Stable ABI".2 An older form is the value 3: it "works the same as 0x03020000 (Python 3.2, the version that introduced Stable ABI)."2 Example: exported.
r4. "Each Stable ABI is versioned using the first two numbers of the Python version."2 "An extension compiled for Stable ABI 3.x is ABI-compatible with Python 3.x and above."2 The promise is for one major version: "It will not necessarily be compatible with CPython 4.0".1 The run-time version is in Py_Version, which is in the stable ABI from Python 3.11 on.3 It uses the encoding of Py_PACK_FULL_VERSION, with 8 bits each for the major, minor and micro numbers, 4 bits for the release level and 4 bits for the serial. The documentation uses 3.4.1a2 as its example, and gives the levels "0xA for alpha, 0xB for beta, 0xC for release candidate or 0xF for final."3 Example: hexversion.
r5. The limited API leaves out the parts of the C API that depend on the layout of a structure. "For example, while PyList_GetItem() is available, its “unsafe” macro variant PyList_GET_ITEM() is not. The macro can be faster because it can rely on version-specific implementation details of the list object."2 "Compiling for Stable ABI disables this inlining, allowing stability as Python’s data structures are improved, but possibly reducing performance."2 "All functions in Stable ABI are present as functions in Python’s shared library, not solely as macros. This makes them usable in languages that don’t use the C preprocessor, including Python’s ctypes."2 For example, Py_IncRef is "A function version of Py_XINCREF()", and "It can be used for runtime dynamic embedding of Python."4 The function form also checks its arguments. PyList_GetItem sets an IndexError when the index is out of bounds, and PyList_GET_ITEM is "Similar to PyList_GetItem(), but without error checking."5 Examples: exported, incref, range.
r6. The file name and the wheel tag tell which ABI a binary uses. "On some platforms, Python will look for and load shared library files named with the abi3 or abi3t tag (for example, mymodule.abi3.so)."2 "On Windows, extensions that use a Stable ABI should be linked against python3.dll rather than a version-specific library such as python39.dll."2 For wheels, "The CPython stable ABI is abi3 as in the shared library suffix."6 The Python tag of an abi3 wheel gives the lowest version, so a wheel tagged cp311-abi3 installs on 3.11 and later. Example: tags.
r7. CPython does not fully check the ABI when it loads a module. "Python does not necessarily check that extensions it loads have compatible ABI."2 "the user (or their packaging tool) is ultimately responsible for ensuring that, for example, extensions built for Stable ABI 3.10 are not installed for lower versions of Python."2 Python 3.15 adds the slot Py_mod_abi and the function PyABIInfo_Check, so that "detectable incompatibilities raise exceptions rather than crash."2
r8. The stable ABI keeps the binary interface, not the behavior. "Note that compiling for Stable ABI is not a complete guarantee that code will be compatible with the expected Python versions."2 "For these reasons, we recommend testing an extension with all minor Python versions it supports."2 Also, "the same source will not necessarily compile with Py_LIMITED_API set to 3.12", and "parts of the Limited API may be deprecated and removed, provided that Stable ABI stays stable."2
r9. The free-threaded build had no stable ABI before 3.15. "Extensions built for GIL-enabled builds of CPython will fail to load (or crash) on free-threaded builds."7 PEP 803 adds abi3t: it "will be based on the existing Stable ABI (abi3), but make the PyObject structure opaque."7 With an opaque PyObject, "Expressions such as sizeof(PyObject) will no longer work."7 The source changes are "Switching to API introduced in PEP 697 (Python 3.12), such as negative basicsize and PyObject_GetTypeData(), rather than making PyObject part of the instance struct" and "Switching from a PyInit_ function to a new export hook, PyModExport_*".8 A build script can ask if the current Python is a free-threaded build: "The sysconfig.get_config_var("Py_GIL_DISABLED") configuration variable can be used to determine whether the build supports free threading."9 Example: build. A wheel for both builds uses the compressed tag abi3.abi3t: "a wheel tagged cp315-abi3.abi3t will be compatible with 3.15, 3.16, and later versions".7
r10. PEP 384 defined the stable ABI in 2009 for Python 3.2.10 Its reason was: "The primary source of ABI incompatibility are changes to the lay-out of in-memory structures."10 A binary that reads a field at a fixed offset reads the wrong field when a new version adds a field before it. A binary that calls a function of the library does not depend on the layout. Examples: layout, stale, opaque. PEP 652, for Python 3.10, says that the limited API and the stable ABI "will be formalized in a single definitive file, tested, and documented."1
Examples
This C file is a module that defines Py_LIMITED_API as Python 3.13 (rule r3). It uses PyList_GetItem, which is in the limited API:
#define Py_LIMITED_API 0x030d0000
#include <Python.h>
static PyObject *
spam_first(PyObject *module, PyObject *list)
{
PyObject *item = PyList_GetItem(list, 0); /* in the limited API */
return Py_XNewRef(item);
}
static PyMethodDef spam_methods[] = {
{"first", spam_first, METH_O, "Return list[0]."},
{NULL, NULL, 0, NULL}
};
static PyModuleDef_Slot spam_module_slots[] = {
{Py_mod_gil, Py_MOD_GIL_NOT_USED},
{0, NULL}
};
static struct PyModuleDef spam_module = {
.m_base = PyModuleDef_HEAD_INIT,
.m_name = "spam",
.m_methods = spam_methods,
.m_slots = spam_module_slots,
};
PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModuleDef_Init(&spam_module);
}
Compile it one time with the headers of Python 3.13, which are in the directory that sysconfig.get_path('include') gives for that version. Use the options -shared -fPIC, and name the result spam.abi3.so.
On Linux, the same file then imports on CPython 3.13, 3.14 and 3.15, because .abi3.so is in the list importlib.machinery.EXTENSION_SUFFIXES of each version (rule r6). Python 3.15 also has .abi3t.so in the list. On Python 3.12, the import fails with SystemError: module spam uses unknown slot ID 4, because Python 3.13 added the slot Py_mod_gil. The file is for 3.13 and later only, and nothing stops a user from putting it on 3.12 (rule r7).
If you change the function to use the macro PyList_GET_ITEM, Python.h does not declare it, because the macro is not in the limited API (rule r5). GCC 13 gives only a warning about an implicit declaration of PyList_GET_ITEM, and the file still builds. Make this warning an error with -Werror=implicit-function-declaration, so that a call outside the limited API stops the build.
This model of the wheel tag rules tells if a wheel can install on a Python version (rules r6 and r9). A GIL-enabled build needs the tag abi3, and a free-threaded build needs the tag abi3t:
def fits(wheel, version, free_threaded=False):
python_tag, abi_tag = wheel[:-len('.whl')].split('-')[2:4]
lowest = (3, int(python_tag[len('cp3'):]))
wanted = 'abi3t' if free_threaded else 'abi3'
return wanted in abi_tag.split('.') and version >= lowest
wheels = ['spam-1.0-cp311-abi3-manylinux_2_28_x86_64.whl',
'spam-1.0-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl']
pythons = [((3, 10), False), ((3, 14), False), ((3, 15), False), ((3, 15), True)]
for wheel in wheels:
tag = '-'.join(wheel.split('-')[2:4])
for version, ft in pythons:
name = '%d.%d%s' % (version[0], version[1], 't' if ft else '')
print(tag, name, fits(wheel, version, ft))
cp311-abi3 3.10 False
cp311-abi3 3.14 True
cp311-abi3 3.15 True
cp311-abi3 3.15t False
cp315-abi3.abi3t 3.10 False
cp315-abi3.abi3t 3.14 False
cp315-abi3.abi3t 3.15 True
cp315-abi3.abi3t 3.15t True
The model is simple. A real installer makes the full list of the tags that the interpreter supports, in order of preference, and picks the first wheel that matches.6
This model packs a version in the format of Py_PACK_FULL_VERSION (rule r4). The result for the documentation's example 3.4.1a2 is 0x30401a2, and the result for the running interpreter is equal to sys.hexversion:
import sys
LEVELS = {'alpha': 0xA, 'beta': 0xB, 'candidate': 0xC, 'final': 0xF}
def pack_full(major, minor, micro, level, serial):
return (major << 24) | (minor << 16) | (micro << 8) | (level << 4) | serial
v = sys.version_info
print(hex(pack_full(3, 4, 1, 0xA, 2)))
print(pack_full(v.major, v.minor, v.micro, LEVELS[v.releaselevel], v.serial) == sys.hexversion)
0x30401a2
True
Py_IncRef and Py_DecRef are functions in the library, so ctypes can call them. Py_INCREF is a macro, and the library does not export it (rule r5):
import ctypes
import sys
api = ctypes.pythonapi
api.Py_IncRef.argtypes = [ctypes.py_object]
api.Py_DecRef.argtypes = [ctypes.py_object]
item = object()
before = sys.getrefcount(item)
api.Py_IncRef(item)
print(sys.getrefcount(item) - before)
api.Py_DecRef(item)
print(sys.getrefcount(item) - before)
print(hasattr(api, 'Py_IncRef'), hasattr(api, 'Py_INCREF'))
1
0
True False
The function PyList_GetItem checks the index. Index 1 gives the address of the item, and index 5 sets an IndexError, which ctypes.pythonapi raises (rule r5). The macro PyList_GET_ITEM does no check:
This code raises IndexError, on purpose.
import ctypes
api = ctypes.pythonapi
api.PyList_GetItem.restype = ctypes.c_void_p
api.PyList_GetItem.argtypes = [ctypes.py_object, ctypes.c_ssize_t]
items = ['first', 'second']
print(api.PyList_GetItem(items, 1) == id(items[1]))
api.PyList_GetItem(items, 5)
A build script picks the ABI tag from the build configuration (rule r9). The interpreter of this site has the GIL, so it needs abi3:
import sysconfig
free_threaded = bool(sysconfig.get_config_var('Py_GIL_DISABLED'))
print(free_threaded)
print('abi3t' if free_threaded else 'abi3')
False
abi3
The next three C programs show the reason for the stable ABI (rule r10). Version 2 of a structure adds the field y, so the field count moves:
#include <stddef.h>
#include <stdio.h>
struct point_v1 { long x; long count; };
struct point_v2 { long x; long y; long count; };
int
main(void)
{
printf("count at byte %zu in version 1\n", offsetof(struct point_v1, count));
printf("count at byte %zu in version 2\n", offsetof(struct point_v2, count));
return 0;
}
count at byte 8 in version 1
count at byte 16 in version 2
Code that was compiled with version 1 reads the bytes of a version 2 object at the old offset. It gets the value of y, which is 2, and not the value of count, which is 3. Nothing reports an error:
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
#include <string.h>
struct point_v1 { long x; long count; }; /* the layout at build time */
struct point_v2 { long x; long y; long count; }; /* the layout at run time */
static long
count_built_for_v1(const void *object)
{
struct point_v1 view;
memcpy(&view, object, sizeof view);
return view.count;
}
int
main(void)
{
struct point_v2 object = {1, 2, 3};
printf("count = %ld\n", count_built_for_v1(&object));
return 0;
}
count = 2
When the extension calls a function of the library to read the field, only the library uses the layout. The extension gets the correct value with each version of the library. This is how the limited API works: the extension calls PyList_GetItem, and only the library knows the layout of a list (rule r5):
#include <stdio.h>
/* The library. Only the library knows the fields. */
struct point { long x; long y; long count; };
long
point_count(const struct point *p)
{
return p->count;
}
/* The extension. It uses only the function. */
static long
count_from_extension(const struct point *p)
{
return point_count(p);
}
int
main(void)
{
struct point object = {1, 2, 3};
printf("count = %ld\n", count_from_extension(&object));
return 0;
}
count = 3
Pitfalls
Set Py_LIMITED_API to the lowest version that you support, not to the version of the headers that you build with. The documentation says: "Typically, you should choose a specific value rather than the version of the Python headers you are compiling against."2
Do not trust a successful build as proof. Even with the macro defined, "a few private declarations are exposed for technical reasons (or even unintentionally, as bugs)."2 Check the documentation of each function that you use, and test the extension on each minor version that it supports (rule r8).
Do not install an abi3 file on a version lower than its target. Python can load it and then fail or crash (rule r7). Use the correct wheel tag, and in 3.15 add the Py_mod_abi slot.
Do not expect abi3 to load on the free-threaded build. Build for abi3t, or for both with the tag abi3.abi3t, or build a separate cp315t wheel (rule r9).
Expect a cost in speed. Measure the hot paths. You can ship a version-specific build next to the abi3 build: "A potentially faster version-specific extension can then be distributed alongside a version compiled for Stable ABI".2 The abi3 build is then the slower fallback that works on more versions.
Comparison
Node.js has a similar layer for native add-ons. "This API will be Application Binary Interface (ABI) stable across versions of Node.js."11 It is intended to "allow modules compiled for one major version to run on later major versions of Node.js without recompilation."11 Like the stable ABI of Python, the promise covers only that API: "Although Node-API provides an ABI stability guarantee, other parts of Node.js do not".11 A difference is that Node-API is a separate API, while the limited API of Python is a subset of the full C API, so one source file can build for abi3 or for one version.
References
- C API and ABI Stability, introduction; Stable Application Binary Interfaces; Compiling for Stable ABI; Stable ABI Scope and Performance; Stable ABI Caveats; ABI Checking
- PEP 652: Maintaining the Stable ABI, header; Abstract; Stable ABI vs. Limited API
- PEP 384: Defining a Stable ABI, header; Abstract; Rationale
- PEP 803: abi3t, Stable ABI for Free-Threaded Builds, Abstract; Motivation; Opaque PyObject; the wheel tag section
- What's new in Python 3.15, PEP 803: Stable ABI for free-threaded builds
- Platform compatibility tags, ABI Tag; Use
- API and ABI Versioning, Py_Version; Py_PACK_VERSION
- Node-API, introduction; Implications of ABI stability
- List Objects, PyList_GetItemRef; PyList_GetItem; PyList_GET_ITEM
- Reference Counting, Py_IncRef; Py_DecRef
- Python support for free threading, Identifying free-threaded Python
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 2BQKRB Edit this page History Report an error Markdown