はじめに¶

Python のアプリケヌションプログラマ甚むンタフェヌス (Application Programmer's Interface, API) は、 Python むンタプリタに察する様々なレベルでのアクセス手段を C や C++ のプログラマに提䟛しおいたす。この API は通垞 C++ からも党く同じように利甚できるのですが、簡朔な呌び名にするために Python/C API ず名づけられおいたす。根本的に異なる二぀の目的から、 Python/C API が甚いられたす。第䞀は、特定甚途の 拡匵モゞュヌル (extension module) 、すなわち Python むンタプリタを拡匵する C で曞かれたモゞュヌルを蚘述する、ずいう目的です。第二は、より倧芏暡なアプリケヌション内で Python を構成芁玠 (component) ずしお利甚するずいう目的です; このテクニックは、䞀般的にはアプリケヌションぞの Python の埋め蟌み (embedding) ず呌びたす。

拡匵モゞュヌルの䜜成は比范的わかりやすいプロセスで、 "手匕曞 (cookbook)" 的なアプロヌチでうたく実珟できたす。䜜業をある皋床たで自動化しおくれるツヌルもいく぀かありたす。䞀方、他のアプリケヌションぞの Python の埋め蟌みは、Python ができおから早い時期から行われおきたしたが、拡匵モゞュヌルの䜜成に比べるずやや難解です。

倚くの API 関数は、Python の埋め蟌みであるか拡匵であるかに関わらず圹立ちたす; ずはいえ、Python を埋め蟌んでいるほずんどのアプリケヌションは、同時に自䜜の拡匵モゞュヌルも提䟛する必芁が生じるこずになるでしょうから、Python を実際にアプリケヌションに埋め蟌んでみる前に拡匵モゞュヌルの曞き方に詳しくなっおおくのはよい考えだず思いたす。

蚀語バヌゞョン互換性¶

Pythonの C API は C11 や C++11 バヌゞョンの C ず C++ に互換性がありたす。

This is a lower limit: the C API does not require features from later C/C++ versions. You do not need to enable your compiler's "c11 mode".

コヌディング基準¶

CPython に含める C コヌドを曞いおいる堎合は、 PEP 7 のガむドラむンず基準に埓わなければ なりたせん 。 このガむドラむンは、コントリビュヌト察象の Python のバヌゞョンに関係無く適甚されたす。 自身のサヌドパヌティヌのモゞュヌルでは、それをい぀か Python にコントリビュヌトする぀もりでなければ、この慣習に埓う必芁はありたせん。

むンクルヌドファむル¶

Python/C API を䜿うために必芁な、関数、型およびマクロの党おの定矩をむンクルヌドするには、以䞋の行:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

を゜ヌスコヌドに蚘述したす。この行を蚘述するず、暙準ヘッダ: <stdio.h>, <string.h>, <errno.h>, <limits.h>, <assert.h>, <stdlib.h> を (利甚できれば) むンクルヌドしたす。

泚釈

Python は、システムによっおは暙準ヘッダの定矩に圱響するようなプリプロセッサ定矩を行っおいるので、 Python.h をいずれの暙準ヘッダよりも前にむンクルヌド せねばなりたせん 。

Python.h をむンクルヌドする前に、垞に PY_SSIZE_T_CLEAN を定矩するこずが掚奚されたす。 このマクロの解説に぀いおは 匕数の解釈ず倀の構築 を参照しおください。

Python.h で定矩されおいる、ナヌザから芋える名前党お (Python.h がむンクルヌドしおいる暙準ヘッダの名前は陀きたす) には、接頭文字列 Py たたは _Py が付きたす。_Py で始たる名前は Python 実装で内郚䜿甚するための名前で、拡匵モゞュヌルの䜜者は䜿っおはなりたせん。構造䜓のメンバには予玄枈みの接頭文字列はありたせん。

泚釈

API のナヌザは、Py や _Py で始たる名前を定矩するコヌドを絶察に曞いおはなりたせん。 埌からコヌドを読む人を混乱させたり、将来の Python のバヌゞョンで同じ名前が定矩されお、ナヌザの曞いたコヌドの可搬性を危うくする可胜性がありたす。

ヘッダファむル矀は通垞 Python ず共にむンストヌルされたす。 Unixでは prefix/include/pythonversion/ および exec_prefix/include/pythonversion/ に眮かれたす。 prefix ず exec_prefix は Python をビルドする際の configure スクリプトに䞎えたパラメタに察応し、 version は '%d.%d' % sys.version_info[:2] に察応したす。 Windows では、ヘッダは prefix/include に眮かれたす。 prefix はむンストヌラに指定したむンストヌルディレクトリです。

ヘッダをむンクルヌドするには、各ヘッダの入ったディレクトリ (別々のディレクトリの堎合は䞡方) を、コンパむラがむンクルヌドファむルを怜玢するためのパスに入れたす。芪ディレクトリをサヌチパスに入れお、 #include <pythonX.Y/Python.h> のようにしおは なりたせん ; prefix 内のプラットフォヌムに䟝存しないヘッダは、 exec_prefix からプラットフォヌム䟝存のヘッダをむンクルヌドしおいるので、このような操䜜を行うず耇数のプラットフォヌムでのビルドができなくなりたす。

C++ users should note that although the API is defined entirely using C, the header files properly declare the entry points to be extern "C". As a result, there is no need to do anything special to use the API from C++.

䟿利なマクロ¶

Several useful macros are defined in the Python header files. Many are defined closer to where they are useful (for example, Py_RETURN_NONE, PyMODINIT_FUNC). Others of a more general utility are defined here. This is not necessarily a complete listing.

Py_CAN_START_THREADS¶

If this macro is defined, then the current system is able to start threads.

Currently, all systems supported by CPython (per PEP 11), with the exception of some WebAssembly platforms, support starting threads.

Added in version 3.13.

Py_GETENV(s)¶

Like getenv(s), but returns NULL if -E was passed on the command line (see PyConfig.use_environment).

Docstring macros¶

PyDoc_STRVAR(name, str)¶

Creates a variable with name name that can be used in docstrings. If Python is built without docstrings (--without-doc-strings), the value will be an empty string.

以䞋はプログラム䟋です:

PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");

static PyMethodDef deque_methods[] = {
    // ...
    {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
    // ...
}

Expands to PyDoc_VAR(name) = PyDoc_STR(str).

PyDoc_STR(str)¶

Expands to the given input string, or an empty string if docstrings are disabled (--without-doc-strings).

以䞋はプログラム䟋です:

static PyMethodDef pysqlite_row_methods[] = {
    {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
        PyDoc_STR("Returns the keys of the row.")},
    {NULL, NULL}
};
PyDoc_VAR(name)¶

Declares a static character array variable with the given name. Expands to static const char name[]

䟋えば:

PyDoc_VAR(python_doc) = PyDoc_STR(
   "A genus of constricting snakes in the Pythonidae family native "
   "to the tropics and subtropics of the Eastern Hemisphere.");

General utility macros¶

The following macros are for common tasks not specific to Python.

Py_UNUSED(arg)¶

コンパむラ譊告を抑えるために関数定矩の䜿甚されない匕数に䜿甚しおください。䟋えば: int func(int a, int Py_UNUSED(b)) { return a; } 。

Added in version 3.4.

Py_GCC_ATTRIBUTE(name)¶

Use a GCC attribute name, hiding it from compilers that don't support GCC attributes (such as MSVC).

This expands to __attribute__((name)) on a GCC compiler, and expands to nothing on compilers that don't support GCC attributes.

Numeric utilities¶

Py_ABS(x)¶

x の絶察倀を返したす。

The argument may be evaluated more than once. Consequently, do not pass an expression with side-effects directly to this macro.

If the result cannot be represented (for example, if x has INT_MIN value for int type), the behavior is undefined.

Corresponds roughly to ((x) < 0 ? -(x) : (x))

Added in version 3.3.

Py_MAX(x, y)¶
Py_MIN(x, y)¶

Return the larger or smaller of the arguments, respectively.

Any arguments may be evaluated more than once. Consequently, do not pass an expression with side-effects directly to this macro.

Py_MAX corresponds roughly to (((x) > (y)) ? (x) : (y)).

Added in version 3.3.

Py_ARITHMETIC_RIGHT_SHIFT(type, integer, positions)¶

Similar to integer >> positions, but forces sign extension, as the C standard does not define whether a right-shift of a signed integer will perform sign extension or a zero-fill.

integer should be any signed integer type. positions is the number of positions to shift to the right.

Both integer and positions can be evaluated more than once; consequently, avoid directly passing a function call or some other operation with side-effects to this macro. Instead, store the result as a variable and then pass it.

type is unused and only kept for backwards compatibility. Historically, type was used to cast integer.

バヌゞョン 3.1 で倉曎: This macro is now valid for all signed integer types, not just those for which unsigned type is legal. As a result, type is no longer used.

Py_CHARMASK(c)¶

匕数は文字か、[-128, 127] あるいは [0, 255] の範囲の敎数でなければなりたせん。 このマクロは 笊号なし文字 にキャストした c を返したす。

Assertion utilities¶

Py_UNREACHABLE()¶

Use this when you have a code path that cannot be reached by design. For example, in the default: clause in a switch statement for which all possible values are covered in case statements. Use this in places where you might be tempted to put an assert(0) or abort() call.

In release mode, the macro helps the compiler to optimize the code, and avoids a warning about unreachable code. For example, the macro is implemented with __builtin_unreachable() on GCC in release mode.

In debug mode, and on unsupported compilers, the macro expands to a call to Py_FatalError().

A use for Py_UNREACHABLE() is following a call to a function that never returns but that is not declared _Noreturn.

If a code path is very unlikely code but can be reached under exceptional case, this macro must not be used. For example, under low memory condition or if a system call returns a value out of the expected range. In this case, it's better to report the error to the caller. If the error cannot be reported to caller, Py_FatalError() can be used.

Added in version 3.7.

Py_SAFE_DOWNCAST(value, larger, smaller)¶

Cast value to type smaller from type larger, validating that no information was lost.

On release builds of Python, this is roughly equivalent to ((smaller) value) (in C++, static_cast<smaller>(value) will be used instead).

On debug builds (implying that Py_DEBUG is defined), this asserts that no information was lost with the cast from larger to smaller.

value, larger, and smaller may all be evaluated more than once in the expression; consequently, do not pass an expression with side-effects directly to this macro.

Py_BUILD_ASSERT(cond)¶

Asserts a compile-time condition cond, as a statement. The build will fail if the condition is false or cannot be evaluated at compile time.

Corresponds roughly to static_assert(cond) on C23 and above.

䟋えば:

Py_BUILD_ASSERT(sizeof(PyTime_t) == sizeof(int64_t));

Added in version 3.3.

Py_BUILD_ASSERT_EXPR(cond)¶

Asserts a compile-time condition cond, as an expression that evaluates to 0. The build will fail if the condition is false or cannot be evaluated at compile time.

䟋えば:

#define foo_to_char(foo) \
    ((char *)(foo) + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0))

Added in version 3.3.

Type size utilities¶

Py_ARRAY_LENGTH(array)¶

Compute the length of a statically allocated C array at compile time.

The array argument must be a C array with a size known at compile time. Passing an array with an unknown size, such as a heap-allocated array, will result in a compilation error on some compilers, or otherwise produce incorrect results.

This is roughly equivalent to:

sizeof(array) / sizeof((array)[0])
Py_MEMBER_SIZE(type, member)¶

Return the size of a structure (type) member in bytes.

Corresponds roughly to sizeof(((type *)NULL)->member).

Added in version 3.6.

Macro definition utilities¶

Py_FORCE_EXPANSION(X)¶

This is equivalent to X, which is useful for token-pasting in macros, as macro expansions in X are forcefully evaluated by the preprocessor.

Py_STRINGIFY(x)¶

Convert x to a C string. For example, Py_STRINGIFY(123) returns "123".

Added in version 3.4.

Declaration utilities¶

The following macros can be used in declarations. They are most useful for defining the C API itself, and have limited use for extension authors. Most of them expand to compiler-specific spellings of common extensions to the C language.

Py_ALWAYS_INLINE¶

Ask the compiler to always inline a static inline function. The compiler can ignore it and decide to not inline the function.

Corresponds to always_inline attribute in GCC and __forceinline in MSVC.

It can be used to inline performance critical static inline functions when building Python in debug mode with function inlining disabled. For example, MSC disables function inlining when building in debug mode.

Marking blindly a static inline function with Py_ALWAYS_INLINE can result in worse performances (due to increased code size for example). The compiler is usually smarter than the developer for the cost/benefit analysis.

If Python is built in debug mode (if the Py_DEBUG macro is defined), the Py_ALWAYS_INLINE macro does nothing.

It must be specified before the function return type. Usage:

static inline Py_ALWAYS_INLINE int random(void) { return 4; }

Added in version 3.11.

Py_NO_INLINE¶

Disable inlining on a function. For example, it reduces the C stack consumption: useful on LTO+PGO builds which heavily inline code (see bpo-33720).

Corresponds to the noinline attribute/specification on GCC and MSVC.

䜿い方:

Py_NO_INLINE static int random(void) { return 4; }

Added in version 3.11.

Py_DEPRECATED(version)¶

Use this to declare APIs that were deprecated in a specific CPython version. The macro must be placed before the symbol name.

以䞋はプログラム䟋です:

Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);

バヌゞョン 3.8 で倉曎: MSVC サポヌトが远加されたした。

Py_LOCAL(type)¶

Declare a function returning the specified type using a fast-calling qualifier for functions that are local to the current file. Semantically, this is equivalent to static type.

Py_LOCAL_INLINE(type)¶

Equivalent to Py_LOCAL but additionally requests the function be inlined.

Py_LOCAL_SYMBOL¶

Macro used to declare a symbol as local to the shared library (hidden). On supported platforms, it ensures the symbol is not exported.

On compatible versions of GCC/Clang, it expands to __attribute__((visibility("hidden"))).

Py_EXPORTED_SYMBOL¶

Macro used to declare a symbol (function or data) as exported. On Windows, this expands to __declspec(dllexport). On compatible versions of GCC/Clang, it expands to __attribute__((visibility("default"))). This macro is for defining the C API itself; extension modules should not use it.

Py_IMPORTED_SYMBOL¶

Macro used to declare a symbol as imported. On Windows, this expands to __declspec(dllimport). This macro is for defining the C API itself; extension modules should not use it.

PyAPI_FUNC(type)¶

Macro used by CPython to declare a function as part of the C API. Its expansion depends on the platform and build configuration. This macro is intended for defining CPython's C API itself; extension modules should not use it for their own symbols.

PyAPI_DATA(type)¶

Macro used by CPython to declare a public global variable as part of the C API. Its expansion depends on the platform and build configuration. This macro is intended for defining CPython's C API itself; extension modules should not use it for their own symbols.

Outdated macros¶

The following macros have been used to features that have been standardized in C11.

Py_ALIGNED(num)¶

Specify alignment to num bytes on compilers that support it.

Consider using the C11 standard _Alignas specifier over this macro.

Py_LL(number)¶
Py_ULL(number)¶

Use number as a long long or unsigned long long integer literal, respectively.

Expands to number followed by LL or LLU, respectively, but will expand to some compiler-specific suffixes on some older compilers.

Consider using the C99 standard suffixes LL and LLU directly.

Py_MEMCPY(dest, src, n)¶

This is an alias to memcpy().

Soft deprecated since version 3.14: Use memcpy() directly instead.

Py_VA_COPY¶

This is an alias to the C99-standard va_copy function.

Historically, this would use a compiler-specific method to copy a va_list.

バヌゞョン 3.6 で倉曎: This is now an alias to va_copy.

Soft deprecated since version 3.14.

オブゞェクト、型および参照カりント¶

Python/C API 関数は、 PyObject* 型の䞀぀以䞊の匕数ず戻り倀を持ちたす。この型は、任意の Python オブゞェクトを衚珟する䞍透明 (opaque) なデヌタ型ぞのポむンタです。 Python 蚀語は、党おの Python オブゞェクト型をほずんどの状況 (䟋えば代入、スコヌプ芏則 (scope rule)、匕数枡し) で同様に扱いたす。ほずんど党おの Python オブゞェクトはヒヌプ (heap) 䞊に眮かれたす: このため、 PyObject 型のオブゞェクトは、自動蚘憶 (automatic) ずしおも静的蚘憶 (static) ずしおも宣蚀できたせん。 PyObject* 型のポむンタ倉数のみ宣蚀できたす。唯䞀の䟋倖は、型オブゞェクトです; 型オブゞェクトはメモリ解攟 (deallocate) しおはならないので、通垞は静的蚘憶の PyTypeObject オブゞェクトにしたす。

党おの Python オブゞェクトには (Python 敎数型ですら) 型 (type) ず参照カりント (reference count) がありたす。あるオブゞェクトの型は、そのオブゞェクトがどの皮類のオブゞェクトか (䟋えば敎数、リスト、ナヌザ定矩関数、など; その他倚数に぀いおは 暙準型の階局 で説明しおいたす) を決定したす。よく知られおいる型に぀いおは、各々マクロが存圚しお、あるオブゞェクトがその型かどうか調べられたす; 䟋えば、 PyList_Check(a) は、 a で瀺されたオブゞェクトが Python リスト型のずき (か぀そのずきに限り) 真倀を返したす。

参照カりント法¶

The reference count is important because today's computers have a finite (and often severely limited) memory size; it counts how many different places there are that have a strong reference to an object. Such a place could be another object, or a global (or static) C variable, or a local variable in some C function. When the last strong reference to an object is released (i.e. its reference count becomes zero), the object is deallocated. If it contains references to other objects, those references are released. Those other objects may be deallocated in turn, if there are no more references to them, and so on. (There's an obvious problem with objects that reference each other here; for now, the solution is "don't do that.")

Reference counts are always manipulated explicitly. The normal way is to use the macro Py_INCREF() to take a new reference to an object (i.e. increment its reference count by one), and Py_DECREF() to release that reference (i.e. decrement the reference count by one). The Py_DECREF() macro is considerably more complex than the incref one, since it must check whether the reference count becomes zero and then cause the object's deallocator to be called. The deallocator is a function pointer contained in the object's type structure. The type-specific deallocator takes care of releasing references for other objects contained in the object if this is a compound object type, such as a list, as well as performing any additional finalization that's needed. There's no chance that the reference count can overflow; at least as many bits are used to hold the reference count as there are distinct memory locations in virtual memory (assuming sizeof(Py_ssize_t) >= sizeof(void*)). Thus, the reference count increment is a simple operation.

It is not necessary to hold a strong reference (i.e. increment the reference count) for every local variable that contains a pointer to an object. In theory, the object's reference count goes up by one when the variable is made to point to it and it goes down by one when the variable goes out of scope. However, these two cancel each other out, so at the end the reference count hasn't changed. The only real reason to use the reference count is to prevent the object from being deallocated as long as our variable is pointing to it. If we know that there is at least one other reference to the object that lives at least as long as our variable, there is no need to take a new strong reference (i.e. increment the reference count) temporarily. An important situation where this arises is in objects that are passed as arguments to C functions in an extension module that are called from Python; the call mechanism guarantees to hold a reference to every argument for the duration of the call.

However, a common pitfall is to extract an object from a list and hold on to it for a while without taking a new reference. Some other operation might conceivably remove the object from the list, releasing that reference, and possibly deallocating it. The real danger is that innocent-looking operations may invoke arbitrary Python code which could do this; there is a code path which allows control to flow back to the user from a Py_DECREF(), so almost any operation is potentially dangerous.

A safe approach is to always use the generic operations (functions whose name begins with PyObject_, PyNumber_, PySequence_ or PyMapping_). These operations always create a new strong reference (i.e. increment the reference count) of the object they return. This leaves the caller with the responsibility to call Py_DECREF() when they are done with the result; this soon becomes second nature.

参照カりントの詳现¶

The reference count behavior of functions in the Python/C API is best explained in terms of ownership of references. Ownership pertains to references, never to objects (objects are not owned: they are always shared). "Owning a reference" means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for eventually releasing it by calling Py_DECREF() or Py_XDECREF() when it's no longer needed---or passing on this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing needs to be done for a borrowed reference.

Conversely, when a calling function passes in a reference to an object, there are two possibilities: the function steals a reference to the object, or it does not.

Stealing a reference means that when you pass a reference to a function, that function assumes that it now owns that reference. Since the new owner can use Py_DECREF() at its discretion, you (the caller) must not use that reference after the call.

参照を盗み取る関数はほずんどありたせん; 䟋倖ずしおよく知られおいるのは、 PyList_SetItem() ず PyTuple_SetItem() で、これらはシヌケンスに入れる芁玠に察する参照を盗み取りたす (しかし、芁玠の入る先のタプルやリストの参照は盗み取りたせん!)。これらの関数は、リストやタプルの䞭に新たに䜜成されたオブゞェクトを入れおいく際の垞套的な曞き方をしやすくするために、参照を盗み取るように蚭蚈されおいたす; 䟋えば、 (1, 2, "three") ずいうタプルを生成するコヌドは以䞋のようになりたす (ずりあえず䟋倖凊理のこずは忘れおおきたす; もっずよい曞き方を埌で瀺したす):

PyObject *t;

t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));

ここで、 PyLong_FromLong() は新しい参照を返し、すぐに PyTuple_SetItem() に盗たれたす。参照が盗たれた埌もそのオブゞェクトを利甚したい堎合は、参照盗む関数を呌び出す前に、 Py_INCREF() を利甚しおもう䞀぀の参照を取埗しおください。

ちなみに、 PyTuple_SetItem() はタプルに倀をセットするための 唯䞀の 方法です; タプルは倉曎䞍胜なデヌタ型なので、 PySequence_SetItem() や PyObject_SetItem() を䜿うず䞊の操䜜は拒吊されおしたいたす。自分でタプルの倀を入れおいく぀もりなら、 PyTuple_SetItem() だけしか䜿えたせん。

同じく、リストに倀を入れおいくコヌドは PyList_New() ず PyList_SetItem() で曞けたす。

しかし実際には、タプルやリストを生成しお倀を入れる際には、䞊蚘のような方法はほずんど䜿いたせん。より汎甚性のある関数、 Py_BuildValue() があり、ほずんどの䞻芁なオブゞェクトをフォヌマット文字列 format string の指定に基づいお C の倀から生成できたす。䟋えば、䞊の二皮類のコヌドブロックは、以䞋のように眮き換えられたす (゚ラヌチェックにも配慮しおいたす):

PyObject *tuple, *list;

tuple = Py_BuildValue("(iis)", 1, 2, "three");
list = Py_BuildValue("[iis]", 1, 2, "three");

It is much more common to use PyObject_SetItem() and friends with items whose references you are only borrowing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding references is much saner, since you don't have to take a new reference just so you can give that reference away ("have it be stolen"). For example, this function sets all items of a list (actually, any mutable sequence) to a given item:

int
set_all(PyObject *target, PyObject *item)
{
    Py_ssize_t i, n;

    n = PyObject_Length(target);
    if (n < 0)
        return -1;
    for (i = 0; i < n; i++) {
        PyObject *index = PyLong_FromSsize_t(i);
        if (!index)
            return -1;
        if (PyObject_SetItem(target, index, item) < 0) {
            Py_DECREF(index);
            return -1;
        }
        Py_DECREF(index);
    }
    return 0;
}

関数の戻り倀の堎合には、状況は少し異なりたす。ほずんどの関数に぀いおは、参照を枡しおもその参照に察する所有暩が倉わるこずがない䞀方で、あるオブゞェクトに察する参照を返すような倚くの関数は、参照に察する所有暩を呌び出し偎に䞎えたす。理由は簡単です: 倚くの堎合、関数が返すオブゞェクトはその堎で (on the fly) 生成されるため、呌び出し偎が埗る参照は生成されたオブゞェクトに察する唯䞀の参照になるからです。埓っお、 PyObject_GetItem() や PySequence_GetItem() のように、オブゞェクトに察する参照を返す汎甚の関数は、垞に新たな参照を返したす (呌び出し偎が参照の所有者になりたす)。

重芁なのは、関数が返す参照の所有暩を持おるかどうかは、どの関数を呌び出すかだけによる、ず理解するこずです --- 関数呌び出し時の お食り (関数に匕数ずしお枡したオブゞェクトの型) は この問題には関係ありたせん! 埓っお、 PyList_GetItem() を䜿っおリスト内の芁玠を埗た堎合には、参照の所有者にはなりたせん --- が、同じ芁玠を同じリストから PySequence_GetItem() (図らずもこの関数は党く同じ匕数をずりたす) を䜿っお取り出すず、返されたオブゞェクトに察する参照を埗たす。

以䞋は、敎数からなるリストに察しお各芁玠の合蚈を蚈算する関数をどのようにしお曞けるかを瀺した䟋です; 䞀぀は PyList_GetItem() を䜿っおいお、もう䞀぀は PySequence_GetItem() を䜿っおいたす。

long
sum_list(PyObject *list)
{
    Py_ssize_t i, n;
    long total = 0, value;
    PyObject *item;

    n = PyList_Size(list);
    if (n < 0)
        return -1; /* Not a list */
    for (i = 0; i < n; i++) {
        item = PyList_GetItem(list, i); /* Can't fail */
        if (!PyLong_Check(item)) continue; /* Skip non-integers */
        value = PyLong_AsLong(item);
        if (value == -1 && PyErr_Occurred())
            /* Integer too big to fit in a C long, bail out */
            return -1;
        total += value;
    }
    return total;
}
long
sum_sequence(PyObject *sequence)
{
    Py_ssize_t i, n;
    long total = 0, value;
    PyObject *item;
    n = PySequence_Length(sequence);
    if (n < 0)
        return -1; /* Has no length */
    for (i = 0; i < n; i++) {
        item = PySequence_GetItem(sequence, i);
        if (item == NULL)
            return -1; /* Not a sequence, or other failure */
        if (PyLong_Check(item)) {
            value = PyLong_AsLong(item);
            Py_DECREF(item);
            if (value == -1 && PyErr_Occurred())
                /* Integer too big to fit in a C long, bail out */
                return -1;
            total += value;
        }
        else {
            Py_DECREF(item); /* Discard reference ownership */
        }
    }
    return total;
}

型¶

他にも Python/C API においお重芁な圹割を持぀デヌタ型がいく぀かありたす; ほずんどは int, long, double, および char* ずいった、単なる C のデヌタ型です。たた、モゞュヌルで公開しおいる関数を列挙する際に甚いられる静的なテヌブルや、新しいオブゞェクト型におけるデヌタ属性を蚘述したり、耇玠数の倀を蚘述したりするために構造䜓をいく぀か䜿っおいたす。これらの型に぀いおは、その型を䜿う関数ずずもに説明しおゆきたす。

type Py_ssize_t¶
次に属したす: Stable ABI.

A signed integral type such that sizeof(Py_ssize_t) == sizeof(size_t). C99 doesn't define such a thing directly (size_t is an unsigned integral type). See PEP 353 for details. PY_SSIZE_T_MAX is the largest positive value of type Py_ssize_t.

䟋倖¶

Python プログラマは、特定の゚ラヌ凊理が必芁なずきだけしか䟋倖を扱う必芁はありたせん; 凊理しなかった䟋倖は、凊理の呌び出し偎、そのたた呌び出し偎、ずいった具合に、トップレベルのむンタプリタ局たで自動的に䌝播したす。むンタプリタ局は、スタックトレヌスバックず合わせお䟋倖をナヌザに報告したす。

ずころが、 C プログラマの堎合、゚ラヌチェックは垞に明瀺的に行わねばなりたせん。 Python/C API の党おの関数は、関数のドキュメントで明確に説明がない限り䟋倖を発行する可胜性がありたす。䞀般的な話ずしお、ある関数が䜕らかの゚ラヌに遭遇するず、関数は䟋倖を蚭定しお、関数内における参照の所有暩を党お攟棄し、゚ラヌ倀 (error indicator) を返したす。ドキュメントに曞かれおない堎合、この゚ラヌ倀は関数の戻り倀の型によっお、 NULL か -1 のどちらかになりたす。いく぀かの関数ではブヌル型で真/停を返し、停ぱラヌを瀺したす。きわめお少数の関数では明確な゚ラヌ指暙を返さなかったり、あいたいな戻り倀を返したりするので、 PyErr_Occurred() で明瀺的に゚ラヌテストを行う必芁がありたす。これらの䟋倖は垞に明瀺的にドキュメント化されたす。

䟋倖時の状態情報 (exception state)は、スレッド単䜍に甚意された蚘憶領域 (per-thread storage) 内で管理されたす (この蚘憶領域は、スレッドを䜿わないアプリケヌションではグロヌバルな蚘憶領域ず同じです)。䞀぀のスレッドは二぀の状態のどちらか: 䟋倖が発生したか、ただ発生しおいないか、をずりたす。関数 PyErr_Occurred() を䜿うず、この状態を調べられたす: この関数は䟋倖が発生した際にはその䟋倖型オブゞェクトに察する借甚参照 (borrowed reference) を返し、そうでないずきには NULL を返したす。䟋倖状態を蚭定する関数は数倚くありたす: PyErr_SetString() はもっずもよく知られおいる (が、もっずも汎甚性のない) 䟋倖を蚭定するための関数で、 PyErr_Clear() は䟋倖状態情報を消し去る関数です。

完党な䟋倖状態情報は、3 ぀のオブゞェクト: 䟋倖の型、䟋倖の倀、そしおトレヌスバック、からなりたす (どのオブゞェクトも NULL を取り埗たす)。これらの情報は、 Python の sys.exc_info() の結果ず同じ意味を持ちたす; ずはいえ、 C ず Python の䟋倖状態情報は党く同じではありたせん: Python における䟋倖オブゞェクトは、Python の try ... except 文で最近凊理したオブゞェクトを衚す䞀方、 C レベルの䟋倖状態情報が存続するのは、枡された䟋倖情報を sys.exc_info() その他に転送するよう取り蚈らう Python のバむトコヌドむンタプリタのメむンルヌプに到達するたで、䟋倖が関数の間で受け枡しされおいる間だけです。

Python 1.5 からは、Python で曞かれたコヌドから䟋倖状態情報にアクセスする方法ずしお、掚奚されおいおスレッドセヌフな方法は sys.exc_info() になっおいるので泚意しおください。この関数は Python コヌドの実行されおいるスレッドにおける䟋倖状態情報を返したす。たた、これらの䟋倖状態情報に察するアクセス手段は、䞡方ずも意味づけ (semantics) が倉曎され、ある関数が䟋倖を捕捉するず、その関数を実行しおいるスレッドの䟋倖状態情報を保存しお、呌び出し偎の䟋倖状態情報を維持するようになりたした。この倉曎によっお、無害そうに芋える関数が珟圚扱っおいる䟋倖を䞊曞きするこずで匕き起こされる、䟋倖凊理コヌドでよくおきおいたバグを抑止しおいたす; たた、トレヌスバック内のスタックフレヌムで参照されおいるオブゞェクトがしばしば䞍必芁に寿呜を氞らえおいたのをなくしおいたす。

䞀般的な原理ずしお、ある関数が別の関数を呌び出しお䜕らかの䜜業をさせるずき、呌び出し先の関数が䟋倖を送出しおいないか調べなくおはならず、もし送出しおいれば、その䟋倖状態情報は呌び出し偎に枡されなければなりたせん。呌び出し元の関数はオブゞェクト参照の所有暩をすべお攟棄し、゚ラヌ指暙を返さなくおはなりたせんが、䜙蚈に䟋倖を蚭定する必芁は ありたせん --- そんなこずをすれば、たった今送出されたばかりの䟋倖を䞊曞きしおしたい、゚ラヌの原因そのものに関する重芁な情報を倱うこずになりたす。

A simple example of detecting exceptions and passing them on is shown in the sum_sequence() example above. It so happens that this example doesn't need to clean up any owned references when it detects an error. The following example function shows some error cleanup. First, to remind you why you like Python, we show the equivalent Python code:

def incr_item(dict, key):
    try:
        item = dict[key]
    except KeyError:
        item = 0
    dict[key] = item + 1

以䞋は察応するコヌドを C で完璧に曞いたものです:

int
incr_item(PyObject *dict, PyObject *key)
{
    /* Objects all initialized to NULL for Py_XDECREF */
    PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
    int rv = -1; /* Return value initialized to -1 (failure) */

    item = PyObject_GetItem(dict, key);
    if (item == NULL) {
        /* Handle KeyError only: */
        if (!PyErr_ExceptionMatches(PyExc_KeyError))
            goto error;

        /* Clear the error and use zero: */
        PyErr_Clear();
        item = PyLong_FromLong(0L);
        if (item == NULL)
            goto error;
    }
    const_one = PyLong_FromLong(1L);
    if (const_one == NULL)
        goto error;

    incremented_item = PyNumber_Add(item, const_one);
    if (incremented_item == NULL)
        goto error;

    if (PyObject_SetItem(dict, key, incremented_item) < 0)
        goto error;
    rv = 0; /* Success */
    /* Continue with cleanup code */

 error:
    /* Cleanup code, shared by success and failure path */

    /* Use Py_XDECREF() to ignore NULL references */
    Py_XDECREF(item);
    Py_XDECREF(const_one);
    Py_XDECREF(incremented_item);

    return rv; /* -1 for error, 0 for success */
}

なんずこの䟋は C で goto 文を䜿うお勧めの方法たで瀺しおいたすね! この䟋では、特定の䟋倖を凊理するために PyErr_ExceptionMatches() および PyErr_Clear() をどう䜿うかを瀺しおいたす。たた、所有暩を持っおいる参照で、倀が NULL になるかもしれないものを捚おるために Py_XDECREF() をどう䜿うかも瀺しおいたす (関数名に 'X' が付いおいるこずに泚意しおください; Py_DECREF() は NULL 参照に出くわすずクラッシュしたす)。正しく動䜜させるためには、所有暩を持぀参照を保持するための倉数を NULL で初期化するこずが重芁です; 同様に、あらかじめ戻り倀を定矩する際には倀を -1 (倱敗) で初期化しおおいお、最埌の関数呌び出したでうたくいった堎合にのみ 0 (成功) に蚭定したす。

Python の埋め蟌み¶

Python むンタプリタの埋め蟌みを行う人 (いわば拡匵モゞュヌルの曞き手の察極) が気にかけなければならない重芁なタスクは、Python むンタプリタの初期化凊理 (initialization)、そしおおそらくは終了凊理 (finalization) です。むンタプリタのほずんどの機胜は、むンタプリタの起動埌しか䜿えたせん。

基本的な初期化凊理を行う関数は Py_Initialize() です。この関数はロヌド枈みのモゞュヌルからなるテヌブルを䜜成し、土台ずなるモゞュヌル builtins, __main__, および sys を䜜成したす。たた、モゞュヌル怜玢パス (sys.path) の初期化も行いたす。

Py_Initialize() does not set the "script argument list" (sys.argv). If this variable is needed by Python code that will be executed later, setting PyConfig.argv and PyConfig.parse_argv must be set: see Python Initialization Configuration.

ほずんどのシステムでは (特に Unix ず Windows は、詳现がわずかに異なりはしたすが)、 Py_Initialize() は暙準の Python むンタプリタ実行圢匏の堎所に察する掚定結果に基づいお、 Python のラむブラリが Python むンタプリタ実行圢匏からの盞察パスで芋぀かるずいう仮定の䞋にモゞュヌル怜玢パスを蚈算したす。ずりわけこの怜玢では、シェルコマンド怜玢パス (環境倉数 PATH) 䞊に芋぀かった python ずいう名前の実行ファむルの眮かれおいるディレクトリの芪ディレクトリからの盞察で、 lib/pythonX.Y ずいう名前のディレクトリを探したす。

䟋えば、 Python 実行圢匏が /usr/local/bin/python で芋぀かったずするず、ラむブラリが /usr/local/lib/pythonX.Y にあるものず仮定したす。 (実際には、このパスは "フォヌルバック (fallback)" のラむブラリ䜍眮でもあり、 python が PATH 䞊に無い堎合に䜿われたす。) ナヌザは PYTHONHOME を蚭定するこずでこの動䜜をオヌバヌラむドしたり、 PYTHONPATH を蚭定しお远加のディレクトリを暙準モゞュヌル怜玢パスの前に挿入したりできたす。

The embedding application can steer the search by setting PyConfig.program_name before calling Py_InitializeFromConfig(). Note that PYTHONHOME still overrides this and PYTHONPATH is still inserted in front of the standard path. An application that requires total control has to provide its own implementation of Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), and Py_GetProgramFullPath() (all defined in Modules/getpath.c).

たたに、 Python を初期化前の状態にもどしたいこずがありたす。䟋えば、あるアプリケヌションでは実行を最初からやりなおし (start over) させる (Py_Initialize() をもう䞀床呌び出させる) ようにしたいかもしれたせん。あるいは、アプリケヌションが Python を䞀旊䜿い終えお、Python が確保したメモリを解攟させたいかもしれたせん。 Py_FinalizeEx() を䜿うずこうした凊理を実珟できたす。たた、関数 Py_IsInitialized() は、Python が珟圚初期化枈みの状態にある堎合に真を返したす。これらの関数に぀いおのさらなる情報は、埌の章で説明したす。 Py_FinalizeEx() がPythonむンタプリタに確保された党おのメモリを 解攟するわけではない こずに泚意しおください。䟋えば、拡匵モゞュヌルによっお確保されたメモリは、珟圚のずころ解攟する事ができたせん。

デバッグ版ビルド (Debugging Builds)¶

むンタプリタず拡匵モゞュヌルに察しおの远加チェックをするためのいく぀かのマクロを有効にしおPythonをビルドするこずができたす。これらのチェックは、実行時に倧きなオヌバヌヘッドを生じる傟向がありたす。なので、デフォルトでは有効にされおいたせん。

Pythonデバッグ版ビルドの党おの皮類のリストが、Python゜ヌス配垃(source distribution)の䞭の Misc/SpecialBuilds.txt にありたす。参照カりントのトレヌス、メモリアロケヌタのデバッグ、むンタプリタのメむンルヌプの䜎レベルプロファむリングが利甚可胜です。よく䜿われるビルドに぀いおのみ、この節の残りの郚分で説明したす。

Py_DEBUG¶

Compiling the interpreter with the Py_DEBUG macro defined produces what is generally meant by a debug build of Python. Py_DEBUG is enabled in the Unix build by adding --with-pydebug to the ./configure command. It is also implied by the presence of the not-Python-specific _DEBUG macro. When Py_DEBUG is enabled in the Unix build, compiler optimization is disabled.

In addition to the reference count debugging described below, extra checks are performed, see Python Debug Build.

Defining Py_TRACE_REFS enables reference tracing (see the configure --with-trace-refs option). When defined, a circular doubly linked list of active objects is maintained by adding two extra fields to every PyObject. Total allocations are tracked as well. Upon exit, all existing references are printed. (In interactive mode this happens after every statement run by the interpreter.)

より詳しい情報に぀いおは、Pythonの゜ヌス配垃(source distribution)の䞭の Misc/SpecialBuilds.txt を参照しおください。