C API and ABI Stability

Unless documented otherwise, Python’s C API is covered by the Backwards Compatibility Policy, PEP 387. Most changes to it are source-compatible (typically by only adding new API). Changing existing API or removing API is only done after a deprecation period or to fix serious issues.

CPython’s Application Binary Interface (ABI) is forward- and backwards-compatible across a minor release (if these are compiled the same way; see Розгляд платформи below). So, 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.

There are two tiers of C API with different stability expectations:

  • Unstable API, may change in minor versions without a deprecation period. It is marked by the PyUnstable prefix in names.

  • Limited API, is compatible across several minor releases. When Py_LIMITED_API is defined, only this subset is exposed from Python.h.

These are discussed in more detail below.

Names prefixed by an underscore, such as _Py_InternalState, are private API that can change without notice even in patch releases. If you need to use this API, consider reaching out to CPython developers to discuss adding public API for your use case.

Unstable C API

Any API named with the PyUnstable prefix exposes CPython implementation details, and may change in every minor release (e.g. from 3.9 to 3.10) without any deprecation warnings. However, it will not change in a bugfix release (e.g. from 3.10.0 to 3.10.1).

It is generally intended for specialized, low-level tools like debuggers.

Projects that use this API are expected to follow CPython development and spend extra effort adjusting to changes.

Стабільний бінарний інтерфейс програми

For simplicity, this document talks about extensions, but the Limited API and Stable ABI work the same way for all uses of the API – for example, embedding Python.

Limited C API

Python 3.2 introduced the Limited API, a subset of Python’s C API. Extensions that only use the Limited API can be compiled once and be loaded on multiple versions of Python. Contents of the Limited API are listed below.

Py_LIMITED_API

Визначте цей макрос, перш ніж включати Python.h, щоб увімкнути використання лише обмеженого API та вибрати обмежену версію API.

Define Py_LIMITED_API to the value of PY_VERSION_HEX corresponding to the lowest Python version your extension supports. The extension will be ABI-compatible with all Python 3 releases from the specified one onward, and can use Limited API introduced up to that version.

Замість безпосереднього використання макросу PY_VERSION_HEX жорстко закодуйте мінімальну проміжну версію (наприклад, 0x030A0000 для Python 3.10) для стабільності під час компіляції з майбутніми версіями Python.

Ви також можете визначити Py_LIMITED_API як 3. Це працює так само, як 0x03020000 (Python 3.2, версія, яка представила Limited API).

Stable ABI

To enable this, Python provides a Stable ABI: a set of symbols that will remain ABI-compatible across Python 3.x versions.

Примітка

The Stable ABI prevents ABI issues, like linker errors due to missing symbols or data corruption due to changes in structure layouts or function signatures. However, other changes in Python can change the behavior of extensions. See Python’s Backwards Compatibility Policy (PEP 387) for details.

The Stable ABI contains symbols exposed in the Limited API, but also other ones – for example, functions necessary to support older versions of the Limited API.

У Windows розширення, які використовують стабільний ABI, слід пов’язувати з python3.dll, а не з бібліотекою для певної версії, такою як python39.dll.

На деяких платформах Python шукатиме та завантажуватиме спільні бібліотечні файли, названі тегом abi3 (наприклад, mymodule.abi3.so). Він не перевіряє, чи такі розширення відповідають стабільному ABI. Користувач (або його інструменти пакування) повинні переконатися, що, наприклад, розширення, створені за допомогою обмеженого API 3.10+, не встановлено для нижчих версій Python.

Усі функції в Stable ABI присутні як функції в спільній бібліотеці Python, а не лише як макроси. Це робить їх придатними для використання з мов, які не використовують препроцесор C.

Обмежений обсяг і продуктивність API

Мета обмеженого API полягає в тому, щоб дозволити все, що можливо з повним API C, але, можливо, зі зниженням продуктивності.

Наприклад, хоча PyList_GetItem() доступний, його «небезпечний» варіант макросу PyList_GET_ITEM() ні. Макрос може бути швидшим, оскільки він може покладатися на специфічні для версії деталі реалізації об’єкта списку.

Без визначення Py_LIMITED_API деякі функції C API вбудовані або замінені макросами. Визначення Py_LIMITED_API вимикає це вбудовування, забезпечуючи стабільність у міру вдосконалення структур даних Python, але, можливо, знижуючи продуктивність.

Виключивши визначення Py_LIMITED_API, можна скомпілювати обмежене розширення API із спеціальним ABI для версії. Це може покращити продуктивність цієї версії Python, але обмежить сумісність. Компіляція за допомогою Py_LIMITED_API дасть розширення, яке можна розповсюджувати там, де недоступне розширення для конкретної версії – наприклад, для попередніх версій майбутньої версії Python.

Обмежені застереження щодо API

Note that compiling with Py_LIMITED_API is not a complete guarantee that code conforms to the Limited API or the Stable ABI. Py_LIMITED_API only covers definitions, but an API also includes other issues, such as expected semantics.

Одна проблема, від якої Py_LIMITED_API не захищає, це виклик функції з аргументами, які недійсні в старішій версії Python. Наприклад, розглянемо функцію, яка починає приймати NULL для аргументу. У Python 3.9 NULL тепер вибирає поведінку за замовчуванням, але в Python 3.8 аргумент використовуватиметься безпосередньо, спричиняючи розіменування NULL і збій. Подібний аргумент працює для полів структур.

Інша проблема полягає в тому, що деякі поля структури наразі не приховані, коли визначено Py_LIMITED_API, навіть якщо вони є частиною обмеженого API.

З цих причин ми рекомендуємо тестувати розширення з усіма проміжними версіями Python, які воно підтримує, і бажано створювати з найнижчою такою версією.

Ми також рекомендуємо переглянути документацію щодо всіх використовуваних API, щоб перевірити, чи вони є частиною обмеженого API. Навіть якщо визначено Py_LIMITED_API, кілька приватних заяв виявляються з технічних причин (або навіть ненавмисно, як помилки).

Також зауважте, що обмежений API не обов’язково є стабільним: компіляція за допомогою Py_LIMITED_API з Python 3.8 означає, що розширення працюватиме з Python 3.12, але воно не обов’язково компілюється з Python 3.12. Зокрема, частини обмеженого API можуть бути застарілими та видалені за умови, що стабільний ABI залишається стабільним.

Розгляд платформи

ABI stability depends not only on Python, but also on the compiler used, lower-level libraries and compiler options. For the purposes of the Stable ABI, these details define a “platform”. They usually depend on the OS type and processor architecture

Кожен окремий розповсюджувач Python несе відповідальність за те, щоб усі версії Python на певній платформі створювалися таким чином, щоб не порушувати стабільний ABI. Це стосується випусків Windows і macOS від python.org і багатьох сторонніх розповсюджувачів.

ABI Checking

Added in version 3.15.0a0 (unreleased).

Python includes a rudimentary check for ABI compatibility.

This check is not comprehensive. It only guards against common cases of incompatible modules being installed for the wrong interpreter. It also does not take platform incompatibilities into account. It can only be done after an extension is successfully loaded.

Despite these limitations, it is recommended that extension modules use this mechanism, so that detectable incompatibilities raise exceptions rather than crash.

Most modules can use this check via the Py_mod_abi slot and the PyABIInfo_VAR macro, for example like this:

PyABIInfo_VAR(abi_info);

static PyModuleDef_Slot mymodule_slots[] = {
   {Py_mod_abi, &abi_info},
   ...
};

The full API is described below for advanced use cases.

int PyABIInfo_Check(PyABIInfo *info, const char *module_name)
Part of the Stable ABI since version 3.15.

Verify that the given info is compatible with the currently running interpreter.

Return 0 on success. On failure, raise an exception and return -1.

If the ABI is incompatible, the raised exception will be ImportError.

The module_name argument can be NULL, or point to a NUL-terminated UTF-8-encoded string used for error messages.

Note that if info describes the ABI that the current code uses (as defined by PyABIInfo_VAR, for example), using any other Python C API may lead to crashes. In particular, it is not safe to examine the raised exception.

Added in version 3.15.0a0 (unreleased).

PyABIInfo_VAR(NAME)
Part of the Stable ABI since version 3.15.

Define a static PyABIInfo variable with the given NAME that describes the ABI that the current code will use. This macro expands to:

static PyABIInfo NAME = {
    1, 0,
    PyABIInfo_DEFAULT_FLAGS,
    PY_VERSION_HEX,
    PyABIInfo_DEFAULT_ABI_VERSION
}

Added in version 3.15.0a0 (unreleased).

type PyABIInfo
Part of the Stable ABI (including all members) since version 3.15.
uint8_t abiinfo_major_version

The major version of PyABIInfo. Can be set to:

  • 0 to skip all checking, or

  • 1 to specify this version of PyABIInfo.

uint8_t abiinfo_minor_version

The major version of PyABIInfo. Must be set to 0; larger values are reserved for backwards-compatible future versions of PyABIInfo.

uint16_t flags

This field is usually set to the following macro:

PyABIInfo_DEFAULT_FLAGS

Default flags, based on current values of macros such as Py_LIMITED_API and Py_GIL_DISABLED.

Alternately, the field can be set to to the following flags, combined by bitwise OR. Unused bits must be set to zero.

ABI variant – one of:

PyABIInfo_STABLE

Specifies that the stable ABI is used.

PyABIInfo_INTERNAL

Specifies ABI specific to a particular build of CPython. Internal use only.

Free-threading compatibility – one of:

PyABIInfo_FREETHREADED

Specifies ABI compatible with free-threading builds of CPython. (That is, ones compiled with --disable-gil; with t in sys.abiflags)

PyABIInfo_GIL

Specifies ABI compatible with non-free-threading builds of CPython (ones compiled without --disable-gil).

uint32_t build_version

The version of the Python headers used to build the code, in the format used by PY_VERSION_HEX.

This can be set to 0 to skip any checks related to this field. This option is meant mainly for projects that do not use the CPython headers directly, and do not emulate a specific version of them.

uint32_t abi_version

The ABI version.

For the Stable ABI, this field should be the value of Py_LIMITED_API (except if Py_LIMITED_API is 3; use Py_PACK_VERSION(3, 2) in that case).

Otherwise, it should be set to PY_VERSION_HEX.

It can also be set to 0 to skip any checks related to this field.

PyABIInfo_DEFAULT_ABI_VERSION

The value that should be used for this field, based on current values of macros such as Py_LIMITED_API, PY_VERSION_HEX and Py_GIL_DISABLED.

Added in version 3.15.0a0 (unreleased).

Вміст обмеженого API

Currently, the Limited API includes the following items: