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 fromPython.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.
安定 ABI (Stable Appliction Binary Interface)¶
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
をインクルードする前に定義することで、 Limited API のみを使用することを選択し、 Limited API バージョンを選択することができます。Define
Py_LIMITED_API
to the value ofPY_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
マクロを直接使うのではなく、将来の Python のバージョンでコンパイルするときの安定性のために、最小のマイナーバージョン(例えば、 Python 3.10なら0x030A0000
)をハードコードします。また、
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 では、 Stable ABI を使用する拡張機能は、 python39.dll
のようなバージョン固有のライブラリではなく、 python3.dll
に対してリンクする必要があります。
いくつかのプラットフォームでは、 Python は abi3
タグで名付けられた共有ライブラリファイルを探して読み込みます(例: mymodule.abi3.so
)。このような拡張モジュールが Stable ABI に適合しているかどうかはチェックされません。ユーザー(またはそのパッケージングツール)は、たとえば 3.10+ Limited API でビルドされた拡張モジュールが、それ以下のバージョンの Python にインストールされないことを確認する必要があります。
Stable ABI に含まれるすべての関数は、マクロとしてだけでなく、 Python の共有ライブラリの関数として存在します。そのため、Cプリプロセッサを使用しない言語から使用することができます。
APIスコープとパフォーマンスの制限¶
Limited API の目標は、フル C API で可能なすべてのことを実現することですが、おそらく性能上の制約があります。
例えば、 PyList_GetItem()
は利用可能ですが、その “unsafe” マクロの変種 PyList_GET_ITEM()
は利用できません。このマクロは、リストオブジェクトのバージョン固有の実装の詳細に依存することができるため、より高速に処理することができます。
Py_LIMITED_API
を定義しないと、いくつかの C API 関数がインライン化されたり、マクロに置き換わったりします。Py_LIMITED_API
を定義すると、このインライン化が無効になり、 Python のデータ構造が改善されても安定した動作が可能になりますが、性能が低下する可能性があります。
Py_LIMITED_API
の定義を省くことで、 Limited 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
が防げない問題の1つは、 Python の下位バージョンでは無効な引数を持つ関数を呼び出すことです。例えば、引数に NULL
を受け取る関数を考えてみましょう。Python 3.9 では NULL
はデフォルトの挙動を選択しますが、Python 3.8 ではこの引数は直接使用され、 NULL
の参照外れを起こしクラッシュします。同様の引数は、構造体のフィールドに対しても機能します。
もう一つの問題は、一部の構造体フィールドがLimited APIの一部であるにもかかわらず、 Py_LIMITED_API
が定義されたときに現在非表示になっていないことです。
これらの理由から、私たちは拡張モジュールがサポートする すべての マイナーな Python バージョンでテストすること、そしてできれば 最も低い バージョンでビルドすることを推奨します。
また、使用するすべての API のドキュメントを確認し、それが明示的に Limited API の一部であるかどうかをチェックすることをお勧めします。Py_LIMITED_API
が定義されていても、技術的な理由で(あるいはバグとして意図せず)いくつかのプライベート宣言が公開されることがあります。
Python 3.8 で Py_LIMITED_API
をコンパイルすると、その拡張モジュールは Python 3.12 で動作しますが、必ずしも Python 3.12 で コンパイル できるとは限らないことに注意してください。特に、Limited API の一部は、 Stable 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 バージョンが安定版 ABI を破壊しない方法でビルドされていることを保証するのは、 Python の各特定配布者の責任です。これは python.org
や多くのサードパーティーの配布元からの Windows と macOS のリリースの場合です。
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)¶
- 次に属します: Stable ABI (バージョン 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)¶
- 次に属します: Stable ABI (バージョン 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¶
- 次に属します: Stable ABI (すべてのメンバーを含む) (バージョン 3.15 より).
-
uint8_t abiinfo_major_version¶
The major version of
PyABIInfo
. Can be set to:0
to skip all checking, or1
to specify this version ofPyABIInfo
.
-
uint8_t abiinfo_minor_version¶
The major version of
PyABIInfo
. Must be set to0
; larger values are reserved for backwards-compatible future versions ofPyABIInfo
.
-
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
andPy_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:
Free-threading compatibility -- one of:
-
PyABIInfo_FREETHREADED¶
Specifies ABI compatible with free-threading builds of CPython. (That is, ones compiled with
--disable-gil
; witht
insys.abiflags
)
-
PyABIInfo_GIL¶
Specifies ABI compatible with non-free-threading builds of CPython (ones compiled without
--disable-gil
).
-
PyABIInfo_DEFAULT_FLAGS¶
-
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 ifPy_LIMITED_API
is3
; 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
andPy_GIL_DISABLED
.
-
PyABIInfo_DEFAULT_ABI_VERSION¶
Added in version 3.15.0a0 (unreleased).
-
uint8_t abiinfo_major_version¶
限定版APIの内容¶
Currently, the Limited API includes the following items:
PyByteArrayIter_Type
PyBytesIter_Type
PyBytes_DecodeEscape()
PyBytes_Repr()
PyCFunction_GetFlags()
PyCFunction_GetFunction()
PyCFunction_GetSelf()
PyCFunction_Type
PyCapsule_Type
PyClassMethodDescr_Type
PyDictItems_Type
PyDictIterItem_Type
PyDictIterKey_Type
PyDictIterValue_Type
PyDictKeys_Type
PyDictProxy_Type
PyDictRevIterItem_Type
PyDictRevIterKey_Type
PyDictRevIterValue_Type
PyDictValues_Type
PyEnum_Type
PyErr_Display()
PyErr_ProgramText()
PyFilter_Type
PyGILState_STATE
PyGetSetDescr_Type
PyListIter_Type
PyListRevIter_Type
PyLongRangeIter_Type
PyMap_Type
PyMemberDescr_Type
PyMemoryView_Type
PyMethodDescr_Type
PyModuleDef_Base
PyModuleDef_Type
PyOS_InterruptOccurred()
PyOS_mystricmp()
PyOS_mystrnicmp()
PyRangeIter_Type
PyRange_Type
PyReversed_Type
PySetIter_Type
PySuper_Type
PyThread_GetInfo()
PyThread_acquire_lock()
PyThread_acquire_lock_timed()
PyThread_allocate_lock()
PyThread_exit_thread()
PyThread_free_lock()
PyThread_get_stacksize()
PyThread_get_thread_ident()
PyThread_get_thread_native_id()
PyThread_init_thread()
PyThread_release_lock()
PyThread_set_stacksize()
PyThread_start_new_thread()
PyTraceBack_Here()
PyTraceBack_Print()
PyTraceBack_Type
PyTupleIter_Type
PyVarObject.ob_base
PyWeakReference
PyWrapperDescr_Type
PyZip_Type
Py_FileSystemDefaultEncodeErrors
Py_FileSystemDefaultEncoding
Py_GetRecursionLimit()
Py_HasFileSystemDefaultEncoding
Py_MakePendingCalls()
Py_SetRecursionLimit()
Py_UTF8Mode
Py_intptr_t
Py_uintptr_t
ssizessizeargfunc
ssizessizeobjargproc
symtable