型オブジェクトの構造体

新しい型を定義する PyTypeObject 構造体は、Python のオブジェクトシステムで特に重要な構造体の 1 つです。 型オブジェクトは PyObject_* 関数や PyType_* 関数で扱えますが、ほとんどの Python アプリケーションにとって関心のある機能はあまり提供しません。 これらのオブジェクトはオブジェクトの動作を決める基盤なので、インタープリタ自体や新しい型を実装する拡張モジュールにとっては非常に重要です。

型オブジェクトは標準の型 (standard type) に比べるとかなり大きな構造体です。各型オブジェクトは多くの値を保持しており、そのほとんどは C 関数へのポインタで、それぞれの関数はその型の機能の小さい部分を実装しています。この節では、型オブジェクトの各フィールドについて詳細を説明します。各フィールドは、構造体内で出現する順番に説明されています。

以下のクイックリファレンスに加えて、 使用例 節では PyTypeObject の意味と使い方を一目で理解できる例を載せています。

クイックリファレンス

tp スロット

PyTypeObject スロット [1]

型

特殊メソッド/特殊属性

Info [2]

O

T

D

I

<R> tp_name

const char *

__name__

X

X

tp_basicsize

Py_ssize_t

X

X

X

tp_itemsize

Py_ssize_t

X

X

tp_dealloc

destructor

X

X

X

tp_vectorcall_offset

Py_ssize_t

X

X

(tp_getattr)

getattrfunc

__getattribute__, __getattr__

G

(tp_setattr)

setattrfunc

__setattr__, __delattr__

G

tp_as_async

PyAsyncMethods *

sub-slots

%

tp_repr

reprfunc

__repr__

X

X

X

tp_as_number

PyNumberMethods *

sub-slots

%

tp_as_sequence

PySequenceMethods *

sub-slots

%

tp_as_mapping

PyMappingMethods *

sub-slots

%

tp_hash

hashfunc

__hash__

X

G

tp_call

ternaryfunc

__call__

X

X

tp_str

reprfunc

__str__

X

X

tp_getattro

getattrofunc

__getattribute__, __getattr__

X

X

G

tp_setattro

setattrofunc

__setattr__, __delattr__

X

X

G

tp_as_buffer

PyBufferProcs *

sub-slots

%

tp_flags

unsigned long

X

X

?

tp_doc

const char *

__doc__

X

X

tp_traverse

traverseproc

X

G

tp_clear

inquiry

X

G

tp_richcompare

richcmpfunc

__lt__, __le__, __eq__, __ne__, __gt__, __ge__

X

G

(tp_weaklistoffset)

Py_ssize_t

X

?

tp_iter

getiterfunc

__iter__

X

tp_iternext

iternextfunc

__next__

X

tp_methods

PyMethodDef []

X

X

tp_members

PyMemberDef []

X

tp_getset

PyGetSetDef []

X

X

tp_base

PyTypeObject *

__base__

X

tp_dict

PyObject *

__dict__

?

tp_descr_get

descrgetfunc

__get__

X

tp_descr_set

descrsetfunc

__set__, __delete__

X

(tp_dictoffset)

Py_ssize_t

X

?

tp_init

initproc

__init__

X

X

X

tp_alloc

allocfunc

X

?

?

tp_new

newfunc

__new__

X

X

?

?

tp_free

freefunc

X

X

?

?

tp_is_gc

inquiry

X

X

<tp_bases>

PyObject *

__bases__

~

<tp_mro>

PyObject *

__mro__

~

[tp_cache]

PyObject *

[tp_subclasses]

void *

__subclasses__

[tp_weaklist]

PyObject *

(tp_del)

destructor

[tp_version_tag]

unsigned int

tp_finalize

destructor

__del__

X

tp_vectorcall

vectorcallfunc

[tp_watched]

unsigned char

sub-slots

Slot

型

特殊メソッド

am_await

unaryfunc

__await__

am_aiter

unaryfunc

__aiter__

am_anext

unaryfunc

__anext__

am_send

sendfunc

nb_add

binaryfunc

__add__ __radd__

nb_inplace_add

binaryfunc

__iadd__

nb_subtract

binaryfunc

__sub__ __rsub__

nb_inplace_subtract

binaryfunc

__isub__

nb_multiply

binaryfunc

__mul__ __rmul__

nb_inplace_multiply

binaryfunc

__imul__

nb_remainder

binaryfunc

__mod__ __rmod__

nb_inplace_remainder

binaryfunc

__imod__

nb_divmod

binaryfunc

__divmod__ __rdivmod__

nb_power

ternaryfunc

__pow__ __rpow__

nb_inplace_power

ternaryfunc

__ipow__

nb_negative

unaryfunc

__neg__

nb_positive

unaryfunc

__pos__

nb_absolute

unaryfunc

__abs__

nb_bool

inquiry

__bool__

nb_invert

unaryfunc

__invert__

nb_lshift

binaryfunc

__lshift__ __rlshift__

nb_inplace_lshift

binaryfunc

__ilshift__

nb_rshift

binaryfunc

__rshift__ __rrshift__

nb_inplace_rshift

binaryfunc

__irshift__

nb_and

binaryfunc

__and__ __rand__

nb_inplace_and

binaryfunc

__iand__

nb_xor

binaryfunc

__xor__ __rxor__

nb_inplace_xor

binaryfunc

__ixor__

nb_or

binaryfunc

__or__ __ror__

nb_inplace_or

binaryfunc

__ior__

nb_int

unaryfunc

__int__

nb_reserved

void *

nb_float

unaryfunc

__float__

nb_floor_divide

binaryfunc

__floordiv__

nb_inplace_floor_divide

binaryfunc

__ifloordiv__

nb_true_divide

binaryfunc

__truediv__

nb_inplace_true_divide

binaryfunc

__itruediv__

nb_index

unaryfunc

__index__

nb_matrix_multiply

binaryfunc

__matmul__ __rmatmul__

nb_inplace_matrix_multiply

binaryfunc

__imatmul__

mp_length

lenfunc

__len__

mp_subscript

binaryfunc

__getitem__

mp_ass_subscript

objobjargproc

__setitem__, __delitem__

sq_length

lenfunc

__len__

sq_concat

binaryfunc

__add__

sq_repeat

ssizeargfunc

__mul__

sq_item

ssizeargfunc

__getitem__

sq_ass_item

ssizeobjargproc

__setitem__ __delitem__

sq_contains

objobjproc

__contains__

sq_inplace_concat

binaryfunc

__iadd__

sq_inplace_repeat

ssizeargfunc

__imul__

bf_getbuffer

getbufferproc()

__buffer__

bf_releasebuffer

releasebufferproc()

__release_buffer__

スロットの定義型 (typedef)

定義型 (typedef)

引数型

返り値型

allocfunc

PyObject *

destructor

PyObject *

void

freefunc

void *

void

traverseproc

void *

int

newfunc

PyObject *

initproc

int

reprfunc

PyObject *

PyObject *

getattrfunc

const char *

PyObject *

setattrfunc

const char *

int

getattrofunc

PyObject *

setattrofunc

int

descrgetfunc

PyObject *

descrsetfunc

int

hashfunc

PyObject *

Py_hash_t

richcmpfunc

int

PyObject *

getiterfunc

PyObject *

PyObject *

iternextfunc

PyObject *

PyObject *

lenfunc

PyObject *

Py_ssize_t

getbufferproc

int

releasebufferproc

void

inquiry

PyObject *

int

unaryfunc

PyObject *

binaryfunc

PyObject *

ternaryfunc

PyObject *

ssizeargfunc

PyObject *

ssizeobjargproc

int

objobjproc

int

objobjargproc

int

詳細は後述の Slot Type typedefs を参照してください。

PyTypeObject 定義

PyTypeObject の構造体定義は Include/cpython/object.h にあります。 参照しやすいように、その定義を以下に再掲します。

typedef struct _typeobject {
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    Py_ssize_t tp_vectorcall_offset;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    unsigned long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* Assigned meaning in release 2.0 */
    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* Assigned meaning in release 2.1 */
    /* rich comparisons */
    richcmpfunc tp_richcompare;

    /* weak reference enabler */
    Py_ssize_t tp_weaklistoffset;

    /* Iterators */
    getiterfunc tp_iter;
    iternextfunc tp_iternext;

    /* Attribute descriptor and subclassing stuff */
    struct PyMethodDef *tp_methods;
    struct PyMemberDef *tp_members;
    struct PyGetSetDef *tp_getset;
    // Strong reference on a heap type, borrowed reference on a static type
    struct _typeobject *tp_base;
    PyObject *tp_dict;
    descrgetfunc tp_descr_get;
    descrsetfunc tp_descr_set;
    Py_ssize_t tp_dictoffset;
    initproc tp_init;
    allocfunc tp_alloc;
    newfunc tp_new;
    freefunc tp_free; /* Low-level free-memory routine */
    inquiry tp_is_gc; /* For PyObject_IS_GC */
    PyObject *tp_bases;
    PyObject *tp_mro; /* method resolution order */
    PyObject *tp_cache;
    PyObject *tp_subclasses;
    PyObject *tp_weaklist;
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6 */
    unsigned int tp_version_tag;

    destructor tp_finalize;
    vectorcallfunc tp_vectorcall;

    /* bitset of which type-watchers care about this type */
    unsigned char tp_watched;
} PyTypeObject;

PyObject スロット

型オブジェクトの構造体は PyVarObject 構造体を拡張しています。 ob_size フィールドは動的な型 (type_new() で作成され、通常はクラス文から呼び出されるもの) に使われます。 PyType_Type (メタタイプ) は tp_itemsize を初期化するため、そのインスタンス (型オブジェクト) には ob_size フィールドが 必要です。

Py_ssize_t PyObject.ob_refcnt
次に属します: Stable ABI.

This is the type object's reference count, initialized to 1 by the PyObject_HEAD_INIT macro. Note that for statically allocated type objects, the type's instances (objects whose ob_type points back to the type) do not count as references. But for dynamically allocated type objects, the instances do count as references.

継承:

サブタイプはこのフィールドを継承しません。

PyTypeObject *PyObject.ob_type
次に属します: Stable ABI.

型自体の型、別の言い方をするとメタタイプです。 PyObject_HEAD_INIT マクロで初期化され、通常は &PyType_Type になります。しかし、(少なくとも) Windows で利用できる動的ロード可能な拡張モジュールでは、コンパイラは有効な初期化ではないと文句をつけます。そこで、ならわしとして、 PyObject_HEAD_INIT には NULL を渡して初期化しておき、他の操作を行う前にモジュールの初期化関数で明示的にこのフィールドを初期化することになっています。この操作は以下のように行います:

Foo_Type.ob_type = &PyType_Type;

これは型のインスタンスを作成する前に行うべきです。 PyType_Ready() は ob_type が NULL かどうかを調べ、NULL なら基底クラスの ob_type フィールドの値で初期化します。 ゼロでない場合、PyType_Ready() はこのフィールドを変更しません。

継承:

サブタイプはこのフィールドを継承します。

PyVarObject スロット

Py_ssize_t PyVarObject.ob_size
次に属します: Stable ABI.

静的にメモリ確保されている型オブジェクト の場合、このフィールドはゼロに初期化されます。動的にメモリ確保されている型オブジェクト の場合、このフィールドは内部使用される特殊な意味を持ちます。

This field should be accessed using the Py_SIZE() and Py_SET_SIZE() macros.

継承:

サブタイプはこのフィールドを継承しません。

PyTypeObject スロット

各スロットには継承についての説明があります。 フィールドが NULL のときに PyType_Ready() が値を設定する可能性がある場合は、「デフォルト」の説明もあります。 PyBaseObject_Type や PyType_Type に設定された多くのフィールドも、実質的にデフォルトとして働きます。

const char *PyTypeObject.tp_name

型の名前を含む NUL 終端文字列へのポインタです。 モジュールのグローバル変数としてアクセスできる型では、完全なモジュール名、ドット、型名の順で構成するべきです。 組み込み型では型名だけにします。 モジュールがパッケージのサブモジュールである場合、完全なモジュール名にはパッケージの完全な名前も含まれます。 例えば、パッケージ P のサブパッケージ Q のモジュール M で定義された T という型では、tp_name の初期値は "P.Q.M.T" にするべきです。

動的にメモリ確保される型オブジェクト の場合、このフィールドは単に型の名前になり、モジュール名は型の辞書内でキー '__module__' に対する値として明示的に保存されます。

静的に割り当てられた型オブジェクト では、tp_name フィールドにドットを含めるべきです。 最後のドットより前の部分が __module__ 属性、後の部分が __name__ 属性としてアクセス可能になります。

If no dot is present, the entire tp_name field is made accessible as the __name__ attribute, and the __module__ attribute is undefined (unless explicitly set in the dictionary, as explained above). This means your type will be impossible to pickle. Additionally, it will not be listed in module documentations created with pydoc.

このフィールドは NULL にできません。 PyTypeObject() で唯一必須のフィールドです (場合によっては tp_itemsize も必要です)。

継承:

サブタイプはこのフィールドを継承しません。

Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize

これらのフィールドは、型インスタンスのバイトサイズを計算できるようにします。

型には 2 種類あります。 インスタンスが固定長の型では tp_itemsize フィールドがゼロで、可変長の型では tp_itemsize フィールドがゼロ以外です。 固定長の型では、すべてのインスタンスのサイズは tp_basicsize で指定された同じ値になります。 PyUnstable_Object_GC_NewWithExtraData() を使うと、この規則の例外を作れます。

可変長の型のインスタンスには ob_size フィールドが必要です。 インスタンスのサイズは tp_basicsize に tp_itemsize の N 倍を加えた値で、N はオブジェクトの「長さ」です。

Functions like PyObject_NewVar() will take the value of N as an argument, and store in the instance's ob_size field. Note that the ob_size field may later be used for other purposes. For example, int instances use the bits of ob_size in an implementation-defined way.

注釈

ob_size フィールドには Py_SIZE() マクロと Py_SET_SIZE() マクロでアクセスするべきです。

また、インスタンスのレイアウトに ob_size フィールドがあっても、その構造体が可変長であるとは限りません。 例えば list 型のインスタンスは固定長ですが、ob_size フィールドを持ちます。 int と同様に、リストの ob_size を直接読むのは避け、代わりに PyList_Size() を呼び出してください。

tp_basicsize には、その型の tp_base のデータに必要なサイズと、各インスタンスに必要な追加データのサイズを含めます。

tp_basicsize を正しく設定するには、インスタンスのレイアウトを宣言する構造体に sizeof 演算子を使います。 この構造体は、基底型を宣言する構造体を含んでいなければなりません。 つまり tp_basicsize は、基底型の tp_basicsize 以上でなければなりません。

すべての型は object のサブタイプなので、この構造体には PyObject または PyVarObject を含める必要があります (ob_size を含めるかどうかによります)。 通常はそれぞれ PyObject_HEAD マクロまたは PyObject_VAR_HEAD マクロで定義します。

GC ヘッダーは PyObject_HEAD の一部ではないため、そのサイズは基本サイズに含めません。

基底型を宣言する構造体が不明な場合は、PyType_Spec.basicsize と PyType_FromMetaclass() を参照してください。

アラインメントに関する注意事項:

  • tp_basicsize は _Alignof(PyObject) の倍数でなければなりません。 推奨どおり PyObject_HEAD を含む struct に sizeof を使えば、コンパイラがこれを保証します。 C の struct を使わない場合や、__attribute__((packed)) などのコンパイラ拡張を使う場合は、自分で保証する必要があります。

  • 可変部分の要素に特定のアラインメントが必要な場合、tp_basicsize と tp_itemsize はそれぞれそのアラインメントの倍数でなければなりません。 例えば可変部分に double を格納する型では、両フィールドが _Alignof(double) の倍数になるようにする責任があります。

継承:

これらのフィールドはサブタイプに個別に継承されます。 フィールドがゼロに設定されている場合、PyType_Ready() は基底型から値をコピーし、インスタンスに追加の格納領域が不要であることを表します。

基底型の tp_itemsize がゼロ以外の場合、サブタイプの tp_itemsize を別のゼロ以外の値に設定するのは、一般に安全ではありません (ただし、基底型の実装によります)。

destructor PyTypeObject.tp_dealloc

The corresponding slot ID Py_tp_dealloc is part of the Stable ABI.

A pointer to the instance destructor function. This function must be defined unless the type guarantees that its instances will never be deallocated (as is the case for the singletons None and Ellipsis). The function signature is:

void tp_dealloc(PyObject *self);

The destructor function is called by the Py_DECREF() and Py_XDECREF() macros when the new reference count is zero. At this point, the instance is still in existence, but there are no references to it. The destructor function should free all references which the instance owns, free all memory buffers owned by the instance (using the freeing function corresponding to the allocation function used to allocate the buffer), and call the type's tp_free function. If the type is not subtypable (doesn't have the Py_TPFLAGS_BASETYPE flag bit set), it is permissible to call the object deallocator directly instead of via tp_free. The object deallocator should be the one used to allocate the instance; this is normally PyObject_Del() if the instance was allocated using PyObject_New or PyObject_NewVar, or PyObject_GC_Del() if the instance was allocated using PyObject_GC_New or PyObject_GC_NewVar.

If the type supports garbage collection (has the Py_TPFLAGS_HAVE_GC flag bit set), the destructor should call PyObject_GC_UnTrack() before clearing any member fields.

static void foo_dealloc(foo_object *self) {
    PyObject_GC_UnTrack(self);
    Py_CLEAR(self->ref);
    Py_TYPE(self)->tp_free((PyObject *)self);
}

Finally, if the type is heap allocated (Py_TPFLAGS_HEAPTYPE), the deallocator should release the owned reference to its type object (via Py_DECREF()) after calling the type deallocator. In order to avoid dangling pointers, the recommended way to achieve this is:

static void foo_dealloc(foo_object *self) {
    PyTypeObject *tp = Py_TYPE(self);
    // free references and buffers here
    tp->tp_free(self);
    Py_DECREF(tp);
}

警告

In a garbage collected Python, tp_dealloc may be called from any Python thread, not just the thread which created the object (if the object becomes part of a refcount cycle, that cycle might be collected by a garbage collection on any thread). This is not a problem for Python API calls, since the thread on which tp_dealloc is called will own the Global Interpreter Lock (GIL). However, if the object being destroyed in turn destroys objects from some other C or C++ library, care should be taken to ensure that destroying those objects on the thread which called tp_dealloc will not violate any assumptions of the library.

継承:

サブタイプはこのフィールドを継承します。

Py_ssize_t PyTypeObject.tp_vectorcall_offset

より単純な tp_call より効率的な vectorcall プロトコル を使ってオブジェクトの呼び出しを実装する、インスタンスごとの関数への省略可能なオフセットです。

このフィールドは Py_TPFLAGS_HAVE_VECTORCALL フラグが設定されている場合にのみ使われます。 その場合、インスタンス内の vectorcallfunc ポインタのオフセットを表す正の整数でなければなりません。

vectorcallfunc ポインタは NULL にできます。 その場合、インスタンスは Py_TPFLAGS_HAVE_VECTORCALL が設定されていないかのように動作し、呼び出しは tp_call にフォールバックします。

Py_TPFLAGS_HAVE_VECTORCALL を設定するクラスでは、tp_call も設定し、その動作が vectorcallfunc 関数と一致するようにしなければなりません。 tp_call を PyVectorcall_Call() に設定すれば実現できます。

バージョン 3.8 で変更: バージョン 3.8 より前では、このスロットの名前は tp_print でした。 Python 2.x ではファイルへの出力に使われ、Python 3.0 から 3.7 では使われていませんでした。

バージョン 3.12 で変更: バージョン 3.12 より前では、変更可能なヒープ型 による vectorcall プロトコルの実装は推奨されていませんでした。 利用者が Python コードで __call__ を設定すると tp_call だけが更新され、vectorcall 関数と不整合になる可能性が高いためです。 3.12 以降は、__call__ を設定すると Py_TPFLAGS_HAVE_VECTORCALL フラグがクリアされ、vectorcall による最適化が無効になります。

継承:

このフィールドは常に継承されます。 ただし、Py_TPFLAGS_HAVE_VECTORCALL フラグが常に継承されるとは限りません。 そのフラグがなければ、PyVectorcall_Call() を明示的に呼び出す場合を除いて、サブクラスは vectorcall を使いません。

getattrfunc PyTypeObject.tp_getattr

The corresponding slot ID Py_tp_getattr is part of the Stable ABI.

オプションのポインタで、get-attribute-string を行う関数を指します。

このフィールドは非推奨です。 このフィールドを定義するときは、 tp_getattro 関数と同じように動作し、属性名は Python 文字列 オブジェクトではなく C 文字列で指定するような関数を指すようにしなければなりません。

継承:

グループ: tp_getattr、tp_getattro

このフィールドは tp_getattro と共にサブタイプに継承されます: すなわち、サブタイプの tp_getattr および tp_getattro が共に NULL の場合、サブタイプは基底タイプから tp_getattr と tp_getattro を両方とも継承します。

setattrfunc PyTypeObject.tp_setattr

The corresponding slot ID Py_tp_setattr is part of the Stable ABI.

オプションのポインタで、属性の設定と削除を行う関数を指します。

このフィールドは非推奨です。 このフィールドを定義するときは、 tp_setattro 関数と同じように動作し、属性名は Python 文字列 オブジェクトではなく C 文字列で指定するような関数を指すようにしなければなりません。

継承:

グループ: tp_setattr、tp_setattro

このフィールドは tp_setattro と共にサブタイプに継承されます: すなわち、サブタイプの tp_setattr および tp_setattro が共に NULL の場合、サブタイプは基底タイプから tp_setattr と tp_setattro を両方とも継承します。

PyAsyncMethods *PyTypeObject.tp_as_async

追加の構造体を指すポインタです。 この構造体は、 C レベルで awaitable プロトコルと asynchronous iterator プロトコルを実装するオブジェクトだけに関係するフィールドを持ちます。 詳しいことは async オブジェクト構造体 を参照してください。

Added in version 3.5: 以前は tp_compare や tp_reserved として知られていました。

継承:

tp_as_async フィールドは継承されませんが、これに含まれるフィールドが個別に継承されます。

reprfunc PyTypeObject.tp_repr

The corresponding slot ID Py_tp_repr is part of the Stable ABI.

オプションのポインタで、組み込み関数 repr() を実装している関数を指します。

シグネチャは PyObject_Repr() と同じです。

PyObject *tp_repr(PyObject *self);

この関数は文字列オブジェクトか Unicode オブジェクトを返さなければなりません。 理想的には、適切な環境で eval() に渡すと同じ値のオブジェクトが得られる文字列を返すべきです。 それが難しい場合は、型と値を読み取れる、'<' で始まり '>' で終わる文字列を返すべきです。

継承:

サブタイプはこのフィールドを継承します。

デフォルト

このフィールドが設定されていない場合、 <%s object at %p> の形式をとる文字列が返されます。 %s は型の名前に、 %p はオブジェクトのメモリアドレスに置き換えられます。

PyNumberMethods *PyTypeObject.tp_as_number

数値プロトコルを実装した追加の構造体を指すポインタです。これらのフィールドについては 数値オブジェクト構造体 で説明されています。

継承:

tp_as_number フィールドは継承されませんが、そこの含まれるフィールドが個別に継承されます。

PySequenceMethods *PyTypeObject.tp_as_sequence

シーケンスプロトコルを実装した追加の構造体を指すポインタです。これらのフィールドについては シーケンスオブジェクト構造体 で説明されています。

継承:

tp_as_sequence フィールドは継承されませんが、これに含まれるフィールドが個別に継承されます。

PyMappingMethods *PyTypeObject.tp_as_mapping

マッピングプロトコルを実装した追加の構造体を指すポインタです。これらのフィールドについては マップオブジェクト構造体 で説明されています。

継承:

tp_as_mapping フィールドは継承されませんが、これに含まれるフィールドが個別に継承されます。

hashfunc PyTypeObject.tp_hash

The corresponding slot ID Py_tp_hash is part of the Stable ABI.

オプションのポインタで、組み込み関数 hash() を実装している関数を指します。

シグネチャは PyObject_Hash() と同じです。

Py_hash_t tp_hash(PyObject *);

通常時には -1 を戻り値にしてはなりません; ハッシュ値の計算中にエラーが生じた場合、関数は例外をセットして -1 を返さねばなりません。

このフィールドが設定されておらず、tp_richcompare も 設定されていない場合、オブジェクトのハッシュを求めると TypeError が送出されます。 PyObject_HashNotImplemented() を設定した場合と同じです。

このフィールドは明示的に PyObject_HashNotImplemented() に設定することで、親 type からのハッシュメソッドの継承をブロックすることができます。これは Python レベルでの __hash__ = None と同等に解釈され、 isinstance(o, collections.Hashable) が正しく False を返すようになります。逆もまた可能であることに注意してください - Python レベルで __hash__ = None を設定することで tp_hash スロットは PyObject_HashNotImplemented() に設定されます。

継承:

グループ: tp_hash、tp_richcompare

このフィールドは tp_richcompare と共にサブタイプに継承されます: すなわち、サブタイプの tp_richcompare および tp_hash が両方とも NULL のとき、サブタイプは基底タイプから tp_richcompare と tp_hash を両方とも継承します。

デフォルト

PyBaseObject_Type は PyObject_GenericHash() を使います。

ternaryfunc PyTypeObject.tp_call

The corresponding slot ID Py_tp_call is part of the Stable ABI.

オプションのポインタで、オブジェクトの呼び出しを実装している関数を指します。 オブジェクトが呼び出し可能でない場合には NULL にしなければなりません。 シグネチャは PyObject_Call() と同じです。

PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);

継承:

サブタイプはこのフィールドを継承します。

reprfunc PyTypeObject.tp_str

The corresponding slot ID Py_tp_str is part of the Stable ABI.

オプションのポインタで、組み込みの演算 str() を実装している関数を指します。(str が型の一つになったため、 str() は str のコンストラクタを呼び出すことに注意してください。このコンストラクタは実際の処理を行う上で PyObject_Str() を呼び出し、さらに PyObject_Str() がこのハンドラを呼び出すことになります。)

シグネチャは PyObject_Str() と同じです。

PyObject *tp_str(PyObject *self);

この関数は文字列オブジェクトか Unicode オブジェクトを返さなければなりません。それはオブジェクトを "分かりやすく (friendly)" 表現した文字列でなければなりません。というのは、この文字列はとりわけ print() 関数で使われることになる表記だからです。

継承:

サブタイプはこのフィールドを継承します。

デフォルト

このフィールドが設定されていない場合、文字列表現を返すためには PyObject_Repr() が呼び出されます。

getattrofunc PyTypeObject.tp_getattro

The corresponding slot ID Py_tp_getattro is part of the Stable ABI.

オプションのポインタで、get-attribute を実装している関数を指します。

シグネチャは PyObject_GetAttr() と同じです。

PyObject *tp_getattro(PyObject *self, PyObject *attr);

通常の属性検索を実装している PyObject_GenericGetAttr() をこのフィールドに設定しておくとたいていの場合は便利です。

継承:

グループ: tp_getattr、tp_getattro

このフィールドは tp_getattr と共にサブタイプに継承されます: すなわち、サブタイプの tp_getattr および tp_getattro が共に NULL の場合、サブタイプは基底タイプから tp_getattr と tp_getattro を両方とも継承します。

デフォルト

PyBaseObject_Type は PyObject_GenericGetAttr() を使います。

setattrofunc PyTypeObject.tp_setattro

The corresponding slot ID Py_tp_setattro is part of the Stable ABI.

オプションのポインタで、属性の設定と削除を行う関数を指します。

シグネチャは PyObject_SetAttr() と同じです。

int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);

さらに、value に NULL を指定して属性を削除できるようにしなければなりません。 通常のオブジェクト属性設定を実装している PyObject_GenericSetAttr() をこのフィールドに設定しておくとたいていの場合は便利です。

継承:

グループ: tp_setattr、tp_setattro

このフィールドは tp_setattr と共にサブタイプに継承されます: すなわち、サブタイプの tp_setattr および tp_setattro が共に NULL の場合、サブタイプは基底タイプから tp_setattr と tp_setattro を両方とも継承します。

デフォルト

PyBaseObject_Type は PyObject_GenericSetAttr() を使います。

PyBufferProcs *PyTypeObject.tp_as_buffer

バッファインターフェースを実装しているオブジェクトにのみ関連する、一連のフィールド群が入った別の構造体を指すポインタです。構造体内の各フィールドは バッファオブジェクト構造体 (buffer object structure) で説明します。

継承:

tp_as_buffer フィールド自体は継承されませんが、これに含まれるフィールドは個別に継承されます。

unsigned long PyTypeObject.tp_flags

このフィールドは様々なフラグからなるビットマスクです。いくつかのフラグは、特定の状況において変則的なセマンティクスが適用されることを示します; その他のフラグは、型オブジェクト (あるいは tp_as_number 、 tp_as_sequence 、 tp_as_mapping 、 および tp_as_buffer が参照している拡張機能構造体) の特定のフィールドのうち、過去から現在までずっと存在していたわけではないものが有効になっていることを示すために使われます; フラグビットがクリアされていれば、フラグが保護しているフィールドにはアクセスしない代わりに、その値はゼロか NULL になっているとみなさなければなりません。

継承:

Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if the extension structure is inherited, i.e. the base type's value of the flag bit is copied into the subtype together with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and tp_clear fields in the subtype exist and have NULL values. .. XXX are most flag bits really inherited individually?

デフォルト

PyBaseObject_Type は Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE を使います。

ビットマスク:

以下に挙げるビットマスクは現在定義されているものです; フラグは | 演算子で論理和を取って tp_flags フィールドの値を作成できます。 PyType_HasFeature() マクロは型とフラグ値、 tp および f をとり、 tp->tp_flags & f が非ゼロかどうか調べます。

Py_TPFLAGS_HEAPTYPE

型オブジェクト自体がヒープに割り当てられた場合に設定されるビットです。 例えば PyType_FromSpec() で動的に作成された型が該当します。 この場合、インスタンスの ob_type フィールドは型への参照とみなされ、新しいインスタンスの作成時に型オブジェクトが INCREF され、インスタンスの破棄時に DECREF されます。 これはサブタイプのインスタンスには適用されません。 INCREF や DECREF の対象になるのは、インスタンスの ob_type が参照する型だけです。 ヒープ型は自身のモジュールオブジェクトと循環参照を形成する可能性があるため、ガベージコレクションをサポート するべきです。

継承:

???

Py_TPFLAGS_BASETYPE
次に属します: Stable ABI.

型を別の型の基底タイプとして使える場合にセットされるビットです。このビットがクリアならば、この型のサブタイプは生成できません (Java における "final" クラスに似たクラスになります)。

継承:

???

Py_TPFLAGS_READY

型オブジェクトが PyType_Ready() で完全に初期化されるとセットされるビットです。

継承:

???

Py_TPFLAGS_READYING

PyType_Ready() による型オブジェクトの初期化処理中にセットされるビットです。

継承:

???

Py_TPFLAGS_HAVE_GC
次に属します: Stable ABI.

This bit is set when the object supports garbage collection. If this bit is set, instances must be created using PyObject_GC_New and destroyed using PyObject_GC_Del(). More information in section 循環参照ガベージコレクションをサポートする. This bit also implies that the GC-related fields tp_traverse and tp_clear are present in the type object.

継承:

グループ: Py_TPFLAGS_HAVE_GC、tp_traverse、tp_clear

Py_TPFLAGS_HAVE_GC フラグビットは tp_traverse フィールドおよび tp_clear フィールドとまとめて継承されます。 これは、サブタイプの Py_TPFLAGS_HAVE_GC フラグビットがクリアされており、tp_traverse と tp_clear が存在して、どちらも NULL の場合です。

Py_TPFLAGS_DEFAULT
次に属します: Stable ABI.

型オブジェクトとその拡張構造体に特定のフィールドが存在するかどうかに関する、すべてのビットをまとめたビットマスクです。 現在は Py_TPFLAGS_HAVE_STACKLESS_EXTENSION ビットを含みます。

継承:

???

Py_TPFLAGS_METHOD_DESCRIPTOR
次に属します: Stable ABI (バージョン 3.8 より).

このビットは、オブジェクトが未束縛のメソッドとして動作することを示します。

type(meth) にこのフラグが設定されている場合、次の条件を満たす必要があります。

  • meth.__get__(obj, cls)(*args, **kwds) (obj が None でない場合) は meth(obj, *args, **kwds) と同等でなければなりません。

  • meth.__get__(None, cls)(*args, **kwds) は meth(*args, **kwds) と同等でなければなりません。

このフラグは、obj.meth() のような一般的なメソッド呼び出しで、obj.meth の一時的な「束縛済みメソッド」オブジェクトを作成せずに済ませる最適化を有効にします。

Added in version 3.8.

継承:

このフラグは、Py_TPFLAGS_IMMUTABLETYPE フラグが設定されていない型には継承されません。 拡張型では、tp_descr_get が継承されるときに継承されます。

Py_TPFLAGS_MANAGED_DICT

This bit indicates that instances of the class have a __dict__ attribute, and that the space for the dictionary is managed by the VM.

このフラグを設定する場合は、Py_TPFLAGS_HAVE_GC も設定するべきです。

型の巡回関数は PyObject_VisitManagedDict() を、クリア関数は PyObject_ClearManagedDict() を呼び出さなければなりません。

Added in version 3.12.

継承:

このフラグは、基底クラスに tp_dictoffset フィールドが設定されていない限り継承されます。

Py_TPFLAGS_MANAGED_WEAKREF

このビットは、クラスのインスタンスに弱参照を作成できるようにすることを示します。

Added in version 3.12.

継承:

このフラグは、基底クラスに tp_weaklistoffset フィールドが設定されていない限り継承されます。

Py_TPFLAGS_ITEMS_AT_END
次に属します: Stable ABI (バージョン 3.12 より).

可変サイズの型、つまり tp_itemsize がゼロでない型でのみ使えます。

この型のインスタンスの可変サイズ部分が、インスタンスのメモリ領域の末尾、オフセット Py_TYPE(obj)->tp_basicsize にあることを示します。 このオフセットはサブクラスごとに異なる場合があります。

このフラグを設定する場合、すべての基底クラスがこのメモリレイアウトを使っているか、可変サイズでないことを確認してください。 Python はこれを検証しません。

Added in version 3.12.

継承:

このフラグは継承されます。

Py_TPFLAGS_LONG_SUBCLASS
Py_TPFLAGS_LIST_SUBCLASS
Py_TPFLAGS_TUPLE_SUBCLASS
Py_TPFLAGS_BYTES_SUBCLASS
Py_TPFLAGS_UNICODE_SUBCLASS
Py_TPFLAGS_DICT_SUBCLASS
Py_TPFLAGS_BASE_EXC_SUBCLASS
Py_TPFLAGS_TYPE_SUBCLASS

Functions such as PyLong_Check() will call PyType_FastSubclass() with one of these flags to quickly determine if a type is a subclass of a built-in type; such specific checks are faster than a generic check, like PyObject_IsInstance(). Custom types that inherit from built-ins should have their tp_flags set appropriately, or the code that interacts with such types will behave differently depending on what kind of check is used.

Py_TPFLAGS_HAVE_FINALIZE

型構造体に tp_finalize スロットが存在しているときにセットされるビットです。

Added in version 3.4.

バージョン 3.8 で非推奨: インタープリタは型構造体に tp_finalize スロットが常に存在すると仮定するため、このフラグはもはや必要ありません。

Py_TPFLAGS_HAVE_VECTORCALL
次に属します: Stable ABI (バージョン 3.12 より).

クラスが vectorcall プロトコル を実装する場合に設定されるビットです。 詳細は tp_vectorcall_offset を参照してください。

継承:

このビットは tp_call も継承される場合に継承されます。

Added in version 3.8: as _Py_TPFLAGS_HAVE_VECTORCALL

バージョン 3.9 で変更.

Renamed to the current name, without the leading underscore. The old provisional name is soft deprecated.

バージョン 3.12 で変更: クラスの __call__() メソッドが再代入されると、このフラグがクリアされるようになりました。

変更可能なクラスもこのフラグを継承できるようになりました。

Py_TPFLAGS_IMMUTABLETYPE

変更不能な型オブジェクトに設定されるビットです。 型の属性を設定したり削除したりできなくなります。

PyType_Ready() は 静的な型 にこのフラグを自動的に設定します。

継承:

このフラグは継承されません。

Added in version 3.10.

Py_TPFLAGS_DISALLOW_INSTANTIATION

この型のインスタンスの作成を禁止します。 tp_new を NULL に設定し、型の辞書に __new__ キーを作成しません。

このフラグは型の作成後ではなく、作成前に設定しなければなりません。 例えば、型に対して PyType_Ready() を呼び出す前に設定する必要があります。

tp_base が NULL または &PyBaseObject_Type で、tp_new が NULL の 静的な型 には、このフラグが自動的に設定されます。

継承:

このフラグは継承されません。 ただし、サブクラスも NULL でない tp_new を提供しない限りインスタンス化できません (提供できるのは C API を使う場合だけです)。

注釈

クラス自体のインスタンス化は禁止しても、サブクラスのインスタンス化は許可したい場合 (例えば 抽象基底クラス)、このフラグを使ってはいけません。 代わりに tp_new がサブクラスに対してのみ成功するようにしてください。

Added in version 3.10.

Py_TPFLAGS_MAPPING

このビットは、クラスのインスタンスが match ブロックの対象となる場合に、マッピングパターンにマッチできることを示します。 collections.abc.Mapping に登録するか、そのサブクラスになると自動的に設定され、collections.abc.Sequence に登録するとクリアされます。

注釈

Py_TPFLAGS_MAPPING と Py_TPFLAGS_SEQUENCE は排他的です。 両方を同時に有効にするとエラーになります。

継承:

このフラグは、Py_TPFLAGS_SEQUENCE がまだ設定されていない型に継承されます。

参考

PEP 634 -- 構造的パターンマッチ: 仕様

Added in version 3.10.

Py_TPFLAGS_SEQUENCE

このビットは、クラスのインスタンスが match ブロックの対象となる場合に、シーケンスパターンにマッチできることを示します。 collections.abc.Sequence に登録するか、そのサブクラスになると自動的に設定され、collections.abc.Mapping に登録するとクリアされます。

注釈

Py_TPFLAGS_MAPPING と Py_TPFLAGS_SEQUENCE は排他的です。 両方を同時に有効にするとエラーになります。

継承:

このフラグは、Py_TPFLAGS_MAPPING がまだ設定されていない型に継承されます。

参考

PEP 634 -- 構造的パターンマッチ: 仕様

Added in version 3.10.

Py_TPFLAGS_VALID_VERSION_TAG

内部使用専用です。 このフラグを設定したりクリアしたりしないでください。 クラスが変更されたことを示すには PyType_Modified() を呼び出してください。

警告

このフラグはヘッダーファイルに存在しますが、使われていません。 将来の CPython バージョンで削除される予定です。

Py_TPFLAGS_HAVE_VERSION_TAG

This is a soft deprecated macro that does nothing. Historically, this would indicate that the tp_version_tag field was available and initialized.

Py_TPFLAGS_INLINE_VALUES

This bit indicates that instances of this type will have an "inline values" array (containing the object's attributes) placed directly after the end of the object.

This requires that Py_TPFLAGS_HAVE_GC is set.

継承:

このフラグは継承されません。

Added in version 3.13.

Py_TPFLAGS_IS_ABSTRACT

This bit indicates that this is an abstract type and therefore cannot be instantiated.

継承:

このフラグは継承されません。

参考

abc

Py_TPFLAGS_HAVE_STACKLESS_EXTENSION

Internal. Do not set or unset this flag. Historically, this was a reserved flag for use in Stackless Python.

警告

This flag is present in header files, but is not be used. This may be removed in a future version of CPython.

const char *PyTypeObject.tp_doc

The corresponding slot ID Py_tp_doc is part of the Stable ABI.

この型オブジェクトのドキュメント文字列を表す、NUL 終端の C 文字列への省略可能なポインタです。 型とそのインスタンスの __doc__ 属性として公開されます。

継承:

サブタイプはこのフィールドを継承 しません 。

traverseproc PyTypeObject.tp_traverse

The corresponding slot ID Py_tp_traverse is part of the Stable ABI.

An optional pointer to a traversal function for the garbage collector. This is only used if the Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:

int tp_traverse(PyObject *self, visitproc visit, void *arg);

Pythonのガベージコレクションの仕組みについての詳細は、 循環参照ガベージコレクションをサポートする にあります。

The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical implementation of a tp_traverse function simply calls Py_VISIT() on each of the instance's members that are Python objects that the instance owns. For example, this is function local_traverse() from the _thread extension module:

static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
    Py_VISIT(self->args);
    Py_VISIT(self->kw);
    Py_VISIT(self->dict);
    return 0;
}

Py_VISIT() が循環参照になる恐れのあるメンバにだけ呼び出されていることに注目してください。 self->key メンバもありますが、それは NULL か Python文字列なので、循環参照の一部になることはありません。

一方、メンバーが循環参照の一部にならないと分かっていても、デバッグのために巡回しておくと、gc モジュールの get_referents() 関数の結果にそのメンバーを含められます。

Heap types (Py_TPFLAGS_HEAPTYPE) must visit their type with:

Py_VISIT(Py_TYPE(self));

It is only needed since Python 3.9. To support Python 3.8 and older, this line must be conditional:

#if PY_VERSION_HEX >= 0x03090000
    Py_VISIT(Py_TYPE(self));
#endif

tp_flags フィールドに Py_TPFLAGS_MANAGED_DICT ビットが設定されている場合、巡回関数は次のように PyObject_VisitManagedDict() を呼び出す必要があります。

PyObject_VisitManagedDict((PyObject*)self, visit, arg);

警告

When implementing tp_traverse, only the members that the instance owns (by having strong references to them) must be visited. For instance, if an object supports weak references via the tp_weaklist slot, the pointer supporting the linked list (what tp_weaklist points to) must not be visited as the instance does not directly own the weak references to itself (the weakreference list is there to support the weak reference machinery, but the instance has no strong reference to the elements inside it, as they are allowed to be removed even if the instance is still alive).

警告

The traversal function must not have any side effects. It must not modify the reference counts of any Python objects nor create or destroy any Python objects.

Note that Py_VISIT() requires the visit and arg parameters to local_traverse() to have these specific names; don't name them just anything.

Instances of heap-allocated types hold a reference to their type. Their traversal function must therefore either visit Py_TYPE(self), or delegate this responsibility by calling tp_traverse of another heap-allocated type (such as a heap-allocated superclass). If they do not, the type object may not be garbage-collected.

バージョン 3.9 で変更: ヒープに割り当てられた型は、tp_traverse で Py_TYPE(self) を巡回することが期待されます。 以前のバージョンの Python では、バグ 40217 によって、この処理がサブクラスのクラッシュを引き起こす場合があります。

継承:

グループ: Py_TPFLAGS_HAVE_GC、tp_traverse、tp_clear

このフィールドは、tp_clear および Py_TPFLAGS_HAVE_GC フラグビットとまとめてサブタイプに継承されます。 サブタイプでフラグビット、tp_traverse、tp_clear がすべてゼロの場合に、これらすべてを基底型から継承します。

inquiry PyTypeObject.tp_clear

The corresponding slot ID Py_tp_clear is part of the Stable ABI.

An optional pointer to a clear function for the garbage collector. This is only used if the Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:

int tp_clear(PyObject *);

The tp_clear member function is used to break reference cycles in cyclic garbage detected by the garbage collector. Taken together, all tp_clear functions in the system must combine to break all reference cycles. This is subtle, and if in any doubt supply a tp_clear function. For example, the tuple type does not implement a tp_clear function, because it's possible to prove that no reference cycle can be composed entirely of tuples. Therefore the tp_clear functions of other types must be sufficient to break any cycle containing a tuple. This isn't immediately obvious, and there's rarely a good reason to avoid implementing tp_clear.

次の例にあるように、 tp_clear の実装は、インスタンスから Python オブジェクトだと思われるメンバへの参照を外し、それらのメンバへのポインタに NULL をセットすべきです:

static int
local_clear(localobject *self)
{
    Py_CLEAR(self->key);
    Py_CLEAR(self->args);
    Py_CLEAR(self->kw);
    Py_CLEAR(self->dict);
    return 0;
}

参照のクリアは慎重に行う必要があるため、Py_CLEAR() マクロを使うべきです。 保持するオブジェクトへのポインタを NULL に設定するまでは、その参照を Py_DECREF() で解放してはいけません。 参照を解放すると、参照先が不要になって一連の回収処理が始まり、そのオブジェクトに関連するファイナライザや弱参照コールバックによって任意の Python コードが実行される可能性があるためです。 そのコードが再び self を参照する可能性があるなら、その時点で参照先へのポインタが NULL になっていることが重要です。 そうすることで self は、その参照先をもう使えないと判断できます。 Py_CLEAR() マクロは、安全な順序でこれらの操作を行います。

If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, the clear function must call PyObject_ClearManagedDict() like this:

PyObject_ClearManagedDict((PyObject*)self);

Note that tp_clear is not always called before an instance is deallocated. For example, when reference counting is enough to determine that an object is no longer used, the cyclic garbage collector is not involved and tp_dealloc is called directly.

Because the goal of tp_clear functions is to break reference cycles, it's not necessary to clear contained objects like Python strings or Python integers, which can't participate in reference cycles. On the other hand, it may be convenient to clear all contained Python objects, and write the type's tp_dealloc function to invoke tp_clear.

Pythonのガベージコレクションの仕組みについての詳細は、 循環参照ガベージコレクションをサポートする にあります。

継承:

グループ: Py_TPFLAGS_HAVE_GC、tp_traverse、tp_clear

このフィールドは、tp_traverse および Py_TPFLAGS_HAVE_GC フラグビットとまとめてサブタイプに継承されます。 サブタイプでフラグビット、tp_traverse、tp_clear がすべてゼロの場合に、これらすべてを基底型から継承します。

richcmpfunc PyTypeObject.tp_richcompare

The corresponding slot ID Py_tp_richcompare is part of the Stable ABI.

オプションのポインタで、拡張比較関数を指します。シグネチャは次の通りです:

PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);

第 1 引数は、その PyTypeObject が定義する型のインスタンスであることが保証されます。

この関数は、比較結果を返すべきです。(普通は Py_True か Py_False です。) 比較が未定義の場合は、Py_NotImplemented を、それ以外のエラーが発生した場合には例外状態をセットして NULL を返さなければなりません。

tp_richcompare および PyObject_RichCompare() 関数の第三引数に使うための定数としては以下が定義されています:

定数

比較

Py_LT

<

Py_LE

<=

Py_EQ

==

Py_NE

!=

Py_GT

>

Py_GE

>=

拡張比較関数(rich comparison functions)を簡単に記述するためのマクロが定義されています:

Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)

比較した結果に応じて Py_True か Py_False を返します。 VAL_A と VAL_B は C の比較演算によって順序付け可能でなければなりません(例えばこれらは C言語の整数か浮動小数点数になるでしょう)。三番目の引数には PyObject_RichCompare() と同様に要求された演算を指定します。

戻り値は新しい 強参照 です。

エラー時には例外を設定して、関数から NULL でリターンします。

Added in version 3.7.

継承:

グループ: tp_hash、tp_richcompare

このフィールドは tp_hash と共にサブタイプに継承されます: すなわち、サブタイプの tp_richcompare および tp_hash が両方とも NULL のとき、サブタイプは基底タイプから tp_richcompare と tp_hash を両方とも継承します。

デフォルト

PyBaseObject_Type provides a tp_richcompare implementation, which may be inherited. However, if only tp_hash is defined, not even the inherited function is used and instances of the type will not be able to participate in any comparisons.

Py_ssize_t PyTypeObject.tp_weaklistoffset

このフィールドは引き続きサポートされていますが、可能であれば代わりに Py_TPFLAGS_MANAGED_WEAKREF を使うべきです。

型のインスタンスが弱参照可能な場合、このフィールドはゼロよりも大きな数になり、インスタンス構造体における弱参照リストの先頭を示すオフセットが入ります (GC ヘッダがある場合には無視します); このオフセット値は PyObject_ClearWeakRefs() および PyWeakref_* 関数が利用します。インスタンス構造体には、 NULL に初期化された PyObject* 型のフィールドが入っていなければなりません。

このフィールドを tp_weaklist と混同しないようにしてください; これは型オブジェクト自身への弱参照からなるリストの先頭です。

Py_TPFLAGS_MANAGED_WEAKREF ビットと tp_weaklistoffset の両方を設定するとエラーになります。

継承:

このフィールドはサブタイプに継承されますが、以下の規則を読んでください。サブタイプはこのオフセット値をオーバライドすることがあります; 従って、サブタイプでは弱参照リストの先頭が基底タイプとは異なる場合があります。リストの先頭は常に tp_weaklistoffset で分かるはずなので、このことは問題にはならないはずです。

デフォルト

tp_flags フィールドに Py_TPFLAGS_MANAGED_WEAKREF ビットが設定されている場合、tp_weaklistoffset は負の値に設定され、このフィールドの使用が安全でないことを示します。

getiterfunc PyTypeObject.tp_iter

The corresponding slot ID Py_tp_iter is part of the Stable ABI.

オプションの変数で、そのオブジェクトの イテレータ を返す関数へのポインタです。この値が存在することは、通常この型のインスタンスが イテレート可能 であることを示しています (しかし、シーケンスはこの関数がなくてもイテレート可能です)。

この関数は PyObject_GetIter() と同じシグネチャを持っています:

PyObject *tp_iter(PyObject *self);

継承:

サブタイプはこのフィールドを継承します。

iternextfunc PyTypeObject.tp_iternext

The corresponding slot ID Py_tp_iternext is part of the Stable ABI.

オプションのポインタで、イテレーター の次の要素を返す関数を指します。シグネチャは次の通りです:

PyObject *tp_iternext(PyObject *self);

イテレータの要素がなくなると、この関数は NULL を返さなければなりません。 StopIteration 例外は設定してもしなくても良いです。その他のエラーが発生したときも、 NULL を返さなければなりません。このフィールドがあると、この型のインスタンスがイテレータであることを示します。

イテレータ型では、 tp_iter 関数も定義されていなければならず、その関数は (新たなイテレータインスタンスではなく) イテレータインスタンス自体を返さねばなりません。

この関数のシグネチャは PyIter_Next() と同じです。

継承:

サブタイプはこのフィールドを継承します。

struct PyMethodDef *PyTypeObject.tp_methods

The corresponding slot ID Py_tp_methods is part of the Stable ABI.

オプションのポインタで、この型の正規 (regular) のメソッドを宣言している PyMethodDef 構造体からなる、 NULL で終端された静的な配列を指します。

配列の各要素ごとに、メソッドデスクリプタの入った、要素が型の辞書 (下記の tp_dict 参照) に追加されます。

継承:

サブタイプはこのフィールドを継承しません (メソッドは別個のメカニズムで継承されています)。

struct PyMemberDef *PyTypeObject.tp_members

The corresponding slot ID Py_tp_members is part of the Stable ABI.

オプションのポインタで、型の正規 (regular) のデータメンバ (フィールドおよびスロット) を宣言している PyMemberDef 構造体からなる、 NULL で終端された静的な配列を指します。

配列の各要素ごとに、メンバデスクリプタの入った要素が型の辞書 (下記の tp_dict 参照) に追加されます。

継承:

サブタイプはこのフィールドを継承しません (メンバは別個のメカニズムで継承されています)。

struct PyGetSetDef *PyTypeObject.tp_getset

The corresponding slot ID Py_tp_getset is part of the Stable ABI.

オプションのポインタで、インスタンスの算出属性 (computed attribute) を宣言している PyGetSetDef 構造体からなる、 NULL で終端された静的な配列を指します。

配列の各要素ごとに、 getter/setter デスクリプタの入った、要素が型の辞書 (下記の tp_dict 参照) に追加されます。

継承:

サブタイプはこのフィールドを継承しません (算出属性は別個のメカニズムで継承されています)。

PyTypeObject *PyTypeObject.tp_base

The corresponding slot ID Py_tp_base is part of the Stable ABI.

オプションのポインタで、型に関するプロパティを継承する基底タイプを指します。このフィールドのレベルでは、単継承 (single inheritance) だけがサポートされています; 多重継承はメタタイプの呼び出しによる動的な型オブジェクトの生成を必要とします。

注釈

スロットの初期化には、グローバル変数の初期化の規則が適用されます。 C99 では、初期化子は「アドレス定数」である必要があります。 PyType_GenericNew() などの関数指示子は、暗黙にポインタへ変換され、有効な C99 のアドレス定数になります。

However, the unary '&' operator applied to a non-static variable like PyBaseObject_Type is not required to produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers are strictly standard conforming in this particular behavior.

したがって、tp_base は拡張モジュールの初期化関数内で設定するべきです。

継承:

(当たり前ですが) サブタイプはこのフィールドを継承しません。

デフォルト

このフィールドのデフォルト値は (Python プログラマは object 型として知っている) &PyBaseObject_Type になります。

PyObject *PyTypeObject.tp_dict

型の辞書は PyType_Ready() によってこのフィールドに収められます。

通常、このフィールドは PyType_Ready を呼び出す前に NULL に初期化するべきですが、型の初期属性を含む辞書で初期化することもできます。 PyType_Ready() が型を初期化した後は、__add__() のようなオーバーロードされる演算に対応しない属性だけを、この辞書に追加できます。 型の初期化が完了した後は、このフィールドを読み取り専用として扱うべきです。

このスロットに辞書を格納しない型もあります。 任意の型の辞書を取得するには PyType_GetDict() を使ってください。

バージョン 3.12 で変更: 実装詳細: 静的な組み込み型では常に NULL です。 代わりに、これらの型の辞書は PyInterpreterState に格納されます。 任意の型の辞書を取得するには PyType_GetDict() を使ってください。

継承:

サブタイプはこのフィールドを継承しません (が、この辞書内で定義されている属性は異なるメカニズムで継承されます)。

デフォルト

このフィールドが NULL の場合、PyType_Ready() が新しい辞書を割り当てます。

警告

tp_dict に PyDict_SetItem() を使ったり、辞書 C-API で編集するのは安全ではありません。

descrgetfunc PyTypeObject.tp_descr_get

The corresponding slot ID Py_tp_descr_get is part of the Stable ABI.

オプションのポインタで、デスクリプタの get 関数を指します。

関数のシグネチャは次のとおりです

PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);

継承:

サブタイプはこのフィールドを継承します。

descrsetfunc PyTypeObject.tp_descr_set

The corresponding slot ID Py_tp_descr_set is part of the Stable ABI.

オプションのポインタで、デスクリプタの値の設定と削除を行う関数を指します。

関数のシグネチャは次のとおりです

int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);

値を削除するには、value 引数に NULL を設定します。

継承:

サブタイプはこのフィールドを継承します。

Py_ssize_t PyTypeObject.tp_dictoffset

このフィールドは引き続きサポートされていますが、可能であれば代わりに Py_TPFLAGS_MANAGED_DICT を使うべきです。

型のインスタンスにインスタンス変数の入った辞書がある場合、このフィールドは非ゼロの値になり、型のインスタンスデータ構造体におけるインスタンス変数辞書へのオフセットが入ります; このオフセット値は PyObject_GenericGetAttr() が使います。

このフィールドを tp_dict と混同しないようにしてください; これは型オブジェクト自身の属性の辞書です。

この値は、インスタンス構造体の先頭からの辞書のオフセットを指定します。

tp_dictoffset は書き込み専用として扱うべきです。 辞書へのポインタを取得するには PyObject_GenericGetDict() を呼び出してください。 PyObject_GenericGetDict() は辞書用のメモリを割り当てる必要がある場合があるため、オブジェクトの属性にアクセスするなら PyObject_GetAttr() の方が効率的なことがあります。

Py_TPFLAGS_MANAGED_DICT ビットと tp_dictoffset の両方を設定するとエラーになります。

継承:

このフィールドはサブタイプに継承されます。 サブタイプでこのオフセットをオーバーライドするべきではありません。 C コードが以前のオフセットで辞書にアクセスすると、安全でない可能性があります。 継承を適切にサポートするには Py_TPFLAGS_MANAGED_DICT を使ってください。

デフォルト

このスロットにはデフォルト値がありません。 静的な型 でこのフィールドが NULL の場合、インスタンスに __dict__ は作成されません。

tp_flags フィールドに Py_TPFLAGS_MANAGED_DICT ビットが設定されている場合、tp_dictoffset は -1 に設定され、このフィールドの使用が安全でないことを示します。

initproc PyTypeObject.tp_init

The corresponding slot ID Py_tp_init is part of the Stable ABI.

オプションのポインタで、インスタンス初期化関数を指します。

この関数はクラスの __init__() メソッドに対応します。 __init__() と同様に、__init__() を呼び出さずにインスタンスを作成することも、__init__() メソッドを再び呼び出してインスタンスを再初期化することもできます。

関数のシグネチャは次のとおりです

int tp_init(PyObject *self, PyObject *args, PyObject *kwds);

self 引数は初期化するインスタンスです。 args と kwds は __init__() の呼び出しの位置引数とキーワード引数を表します。

tp_init 関数のフィールドが NULL でない場合、通常の型を呼び出す方法のインスタンス生成において、型の tp_new 関数がインスタンスを返した後に呼び出されます。 tp_new が元の型のサブタイプでない別の型を返す場合、 tp_init は全く呼び出されません; tp_new が元の型のサブタイプのインスタンスを返す場合、サブタイプの tp_init が呼び出されます。

成功のときには 0 を、エラー時には例外をセットして -1 を返します。

継承:

サブタイプはこのフィールドを継承します。

デフォルト

静的な型 では、このフィールドにデフォルト値はありません。

allocfunc PyTypeObject.tp_alloc

The corresponding slot ID Py_tp_alloc is part of the Stable ABI.

オプションのポインタで、インスタンスのメモリ確保関数を指します。

関数のシグネチャは次のとおりです

PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);

継承:

This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement).

デフォルト

For dynamic subtypes, this field is always set to PyType_GenericAlloc(), to force a standard heap allocation strategy.

For static subtypes, PyBaseObject_Type uses PyType_GenericAlloc(). That is the recommended value for all statically defined types.

newfunc PyTypeObject.tp_new

The corresponding slot ID Py_tp_new is part of the Stable ABI.

オプションのポインタで、インスタンス生成関数を指します。

関数のシグネチャは次のとおりです

PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);

subtype 引数は生成するオブジェクトの型です; args および kwds 引数は、型を呼び出すときの位置引数およびキーワード引数です。subtype は tp_new 関数を呼び出すときに使う型と同じである必要はないことに注意してください; その型の (無関係ではない) サブタイプのこともあります。

tp_new 関数は subtype->tp_alloc(subtype, nitems) を呼び出してオブジェクトのメモリ領域を確保し、初期化で絶対に必要とされる処理だけを行います。省略したり繰り返したりしても問題のない初期化処理は tp_init ハンドラ内に配置しなければなりません。だいたいの目安としては、変更不能な型では初期化は全て tp_new で行い、一方、変更可能な型ではほとんどの初期化を tp_init に回すべきです。

Python からこの型のインスタンスを作成することを禁止するには、Py_TPFLAGS_DISALLOW_INSTANTIATION フラグを設定してください。

継承:

サブタイプはこのフィールドを継承します。例外として、 tp_base が NULL か &PyBaseObject_Type になっている 静的な型 では継承しません。

デフォルト

静的な型 では、このフィールドにデフォルト値はありません。 スロットを NULL と定義すると、型を呼び出して新しいインスタンスを作成できなくなります。 その場合は、ファクトリ関数など別の方法でインスタンスを作成することになります。

freefunc PyTypeObject.tp_free

The corresponding slot ID Py_tp_free is part of the Stable ABI.

オプションのポインタで、インスタンスのメモリ解放関数を指します。シグネチャは以下の通りです:

void tp_free(void *self);

An initializer that is compatible with this signature is PyObject_Free().

継承:

This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement)

デフォルト

In dynamic subtypes, this field is set to a deallocator suitable to match PyType_GenericAlloc() and the value of the Py_TPFLAGS_HAVE_GC flag bit.

For static subtypes, PyBaseObject_Type uses PyObject_Del().

inquiry PyTypeObject.tp_is_gc

The corresponding slot ID Py_tp_is_gc is part of the Stable ABI.

オプションのポインタで、ガベージコレクタから呼び出される関数を指します。

ガベージコレクタは、個々のオブジェクトが回収可能かどうかを知る必要があります。 通常は、オブジェクトの型の tp_flags フィールドで Py_TPFLAGS_HAVE_GC フラグビットを確認すれば十分です。 ただし、静的に割り当てたインスタンスと動的に割り当てたインスタンスが混在する型もあり、静的なインスタンスは回収できません。 そうした型ではこの関数を定義し、回収可能なインスタンスなら 1、回収不能なら 0 を返すべきです。 シグネチャは次のとおりです。

int tp_is_gc(PyObject *self);

(上記のような型の例は、型オブジェクト自体です。メタタイプ PyType_Type は、型のメモリ確保が静的か 動的 かを区別するためにこの関数を定義しています。)

継承:

サブタイプはこのフィールドを継承します。

デフォルト

このスロットにはデフォルト値がありません。 NULL の場合は、代わりに Py_TPFLAGS_HAVE_GC が同等の役割を果たします。

PyObject *PyTypeObject.tp_bases

The corresponding slot ID Py_tp_bases is part of the Stable ABI.

基底型からなるタプルです。

このフィールドは NULL に設定し、読み取り専用として扱うべきです。 型が 初期化 されるときに、Python が設定します。

For dynamically created classes, the Py_tp_bases slot can be used instead of the bases argument of PyType_FromSpecWithBases(). The argument form is preferred.

警告

静的に定義された型では、多重継承はうまく動作しません。 tp_bases にタプルを設定しても Python はエラーを送出しませんが、一部のスロットは最初の基底クラスからしか継承されません。

継承:

このフィールドは継承されません。

PyObject *PyTypeObject.tp_mro

基底タイプ群を展開した集合が入っているタプルです。集合は該当する型自体からはじまり、 object で終わります。メソッド解決順序 (Method Resolution Order) に従って並んでいます。

このフィールドは NULL に設定し、読み取り専用として扱うべきです。 型が 初期化 されるときに、Python が設定します。

継承:

このフィールドは継承されません; フィールドの値は PyType_Ready() で毎回計算されます。

PyObject *PyTypeObject.tp_cache

未使用のフィールドです。内部でのみ利用されます。

継承:

このフィールドは継承されません。

void *PyTypeObject.tp_subclasses

サブクラスのコレクションです。 内部使用専用です。 無効なポインタの場合があります。

サブクラスのリストを取得するには、Python の __subclasses__() メソッドを呼び出してください。

バージョン 3.12 で変更: 一部の型では、このフィールドは有効な PyObject* を保持しません。 そのことを示すために、型が void* に変更されました。

継承:

このフィールドは継承されません。

PyObject *PyTypeObject.tp_weaklist

この型オブジェクトへの弱参照リストの先頭です。 継承されません。 内部使用専用です。

バージョン 3.12 で変更: 実装詳細: 静的な組み込み型では、弱参照が追加されていても常に NULL です。 代わりに、それぞれの弱参照は PyInterpreterState に格納されます。 この違いを意識せずに扱うには、公開 C API または内部マクロ _PyObject_GET_WEAKREFS_LISTPTR() を使ってください。

継承:

このフィールドは継承されません。

destructor PyTypeObject.tp_del

The corresponding slot ID Py_tp_del is part of the Stable ABI.

このフィールドは非推奨です。 代わりに tp_finalize を使ってください。

unsigned int PyTypeObject.tp_version_tag

メソッドキャッシュへのインデックスとして使われます。内部使用だけのための関数です。

継承:

このフィールドは継承されません。

destructor PyTypeObject.tp_finalize

The corresponding slot ID Py_tp_finalize is part of the Stable ABI (バージョン 3.5 より).

インスタンスのファイナライズ関数への省略可能なポインタです。 特殊メソッド __del__() の C 実装に相当します。 シグネチャは次のとおりです。

void tp_finalize(PyObject *self);

If tp_finalize is set, the interpreter calls it once when finalizing an instance. It is called either from the garbage collector (if the instance is part of an isolated reference cycle) or just before the object is deallocated. Either way, it is guaranteed to be called before attempting to break reference cycles, ensuring that it finds the object in a sane state.

tp_finalize should not mutate the current exception status; therefore, a recommended way to write a non-trivial finalizer is:

static void
local_finalize(PyObject *self)
{
    /* Save the current exception, if any. */
    PyObject *exc = PyErr_GetRaisedException();

    /* ... */

    /* Restore the saved exception. */
    PyErr_SetRaisedException(exc);
}

継承:

サブタイプはこのフィールドを継承します。

Added in version 3.4.

バージョン 3.8 で変更: バージョン 3.8 より前は、このフィールドを使うために Py_TPFLAGS_HAVE_FINALIZE フラグビットの設定が必要でした。 現在は不要です。

参考

"Safe object finalization" (PEP 442)

vectorcallfunc PyTypeObject.tp_vectorcall

Vectorcall function to use for calls of this type object. In other words, it is used to implement vectorcall for type.__call__. If tp_vectorcall is NULL, the default call implementation using __new__() and __init__() is used.

継承:

このフィールドは決して継承されません。

Added in version 3.9: (このフィールドは3.8から存在していますが、3.9以降でしか利用できません)

unsigned char PyTypeObject.tp_watched

内部使用専用です。 使わないでください。

Added in version 3.12.

静的な型

従来、C コードで定義する型は 静的 なものです。 つまり、静的な PyTypeObject 構造体をコード内に直接定義し、PyType_Ready() で初期化します。

この方法で作成される型には、Python で定義する型と比べて次の制約があります。

  • 静的な型の基底クラスは 1 つに限られ、多重継承は使えません。

  • 静的な型オブジェクトは変更不能です (そのインスタンスが変更不能とは限りません)。 Python から型オブジェクトの属性を追加したり変更したりすることはできません。

  • 静的な型オブジェクトは サブインタープリタ 間で共有されるため、サブインタープリタ固有の状態を含めるべきではありません。

また、PyTypeObject は不透明な構造体としてのみ Limited API に含まれるため、静的な型を使う拡張モジュールは、特定の Python マイナーバージョン向けにコンパイルしなければなりません。

ヒープ型

静的な型 の代わりに使えるのが、ヒープに割り当てられた型、略して ヒープ型 です。 Python の class 文で作成したクラスに近いものです。 ヒープ型には Py_TPFLAGS_HEAPTYPE フラグが設定されます。

PyType_Spec 構造体に値を設定し、PyType_FromSpec()、PyType_FromSpecWithBases()、PyType_FromModuleAndSpec()、PyType_FromMetaclass() のいずれかを呼び出して作成します。

数値オブジェクト構造体

type PyNumberMethods

この構造体は数値型プロトコルを実装するために使われる関数群へのポインタを保持しています。 以下のそれぞれの関数は 数値型プロトコル (number protocol) で解説されている似た名前の関数から利用されます。

以下は構造体の定義です:

typedef struct {
     binaryfunc nb_add;
     binaryfunc nb_subtract;
     binaryfunc nb_multiply;
     binaryfunc nb_remainder;
     binaryfunc nb_divmod;
     ternaryfunc nb_power;
     unaryfunc nb_negative;
     unaryfunc nb_positive;
     unaryfunc nb_absolute;
     inquiry nb_bool;
     unaryfunc nb_invert;
     binaryfunc nb_lshift;
     binaryfunc nb_rshift;
     binaryfunc nb_and;
     binaryfunc nb_xor;
     binaryfunc nb_or;
     unaryfunc nb_int;
     void *nb_reserved;
     unaryfunc nb_float;

     binaryfunc nb_inplace_add;
     binaryfunc nb_inplace_subtract;
     binaryfunc nb_inplace_multiply;
     binaryfunc nb_inplace_remainder;
     ternaryfunc nb_inplace_power;
     binaryfunc nb_inplace_lshift;
     binaryfunc nb_inplace_rshift;
     binaryfunc nb_inplace_and;
     binaryfunc nb_inplace_xor;
     binaryfunc nb_inplace_or;

     binaryfunc nb_floor_divide;
     binaryfunc nb_true_divide;
     binaryfunc nb_inplace_floor_divide;
     binaryfunc nb_inplace_true_divide;

     unaryfunc nb_index;

     binaryfunc nb_matrix_multiply;
     binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;

注釈

二項関数と三項関数は、すべてのオペランドの型をチェックしなければならず、必要な変換を実装しなければなりません (すくなくともオペランドの一つは定義している型のインスタンスです). もし与えられたオペランドに対して操作が定義されなければ、二項関数と三項関数は Py_NotImplemented を返さなければならず、他のエラーが起こった場合は、NULL を返して例外を設定しなければなりません。

注釈

nb_reserved フィールドは常に NULL にするべきです。 以前は nb_long という名前でしたが、Python 3.0.1 で改名されました。

binaryfunc PyNumberMethods.nb_add

The corresponding slot ID Py_nb_add is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_subtract

The corresponding slot ID Py_nb_subtract is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_multiply

The corresponding slot ID Py_nb_multiply is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_remainder

The corresponding slot ID Py_nb_remainder is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_divmod

The corresponding slot ID Py_nb_divmod is part of the Stable ABI.

ternaryfunc PyNumberMethods.nb_power

The corresponding slot ID Py_nb_power is part of the Stable ABI.

unaryfunc PyNumberMethods.nb_negative

The corresponding slot ID Py_nb_negative is part of the Stable ABI.

unaryfunc PyNumberMethods.nb_positive

The corresponding slot ID Py_nb_positive is part of the Stable ABI.

unaryfunc PyNumberMethods.nb_absolute

The corresponding slot ID Py_nb_absolute is part of the Stable ABI.

inquiry PyNumberMethods.nb_bool

The corresponding slot ID Py_nb_bool is part of the Stable ABI.

unaryfunc PyNumberMethods.nb_invert

The corresponding slot ID Py_nb_invert is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_lshift

The corresponding slot ID Py_nb_lshift is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_rshift

The corresponding slot ID Py_nb_rshift is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_and

The corresponding slot ID Py_nb_and is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_xor

The corresponding slot ID Py_nb_xor is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_or

The corresponding slot ID Py_nb_or is part of the Stable ABI.

unaryfunc PyNumberMethods.nb_int

The corresponding slot ID Py_nb_int is part of the Stable ABI.

void *PyNumberMethods.nb_reserved
unaryfunc PyNumberMethods.nb_float

The corresponding slot ID Py_nb_float is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_add

The corresponding slot ID Py_nb_inplace_add is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_subtract

The corresponding slot ID Py_nb_inplace_subtract is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_multiply

The corresponding slot ID Py_nb_inplace_multiply is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_remainder

The corresponding slot ID Py_nb_inplace_remainder is part of the Stable ABI.

ternaryfunc PyNumberMethods.nb_inplace_power

The corresponding slot ID Py_nb_inplace_power is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_lshift

The corresponding slot ID Py_nb_inplace_lshift is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_rshift

The corresponding slot ID Py_nb_inplace_rshift is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_and

The corresponding slot ID Py_nb_inplace_and is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_xor

The corresponding slot ID Py_nb_inplace_xor is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_or

The corresponding slot ID Py_nb_inplace_or is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_floor_divide

The corresponding slot ID Py_nb_floor_divide is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_true_divide

The corresponding slot ID Py_nb_true_divide is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_floor_divide

The corresponding slot ID Py_nb_inplace_floor_divide is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_inplace_true_divide

The corresponding slot ID Py_nb_inplace_true_divide is part of the Stable ABI.

unaryfunc PyNumberMethods.nb_index

The corresponding slot ID Py_nb_index is part of the Stable ABI.

binaryfunc PyNumberMethods.nb_matrix_multiply

The corresponding slot ID Py_nb_matrix_multiply is part of the Stable ABI (バージョン 3.5 より).

binaryfunc PyNumberMethods.nb_inplace_matrix_multiply

The corresponding slot ID Py_nb_inplace_matrix_multiply is part of the Stable ABI (バージョン 3.5 より).

マップオブジェクト構造体

type PyMappingMethods

この構造体はマップ型プロトコルを実装するために使われる関数群へのポインタを保持しています。 以下の3つのメンバを持っています:

lenfunc PyMappingMethods.mp_length

The corresponding slot ID Py_mp_length is part of the Stable ABI.

この関数は PyMapping_Size() や PyObject_Size() から利用され、それらと同じシグネチャを持っています。オブジェクトが定義された長さを持たない場合は、このスロットは NULL に設定されることがあります。

binaryfunc PyMappingMethods.mp_subscript

The corresponding slot ID Py_mp_subscript is part of the Stable ABI.

この関数は PyObject_GetItem() および PySequence_GetSlice() から利用され、PyObject_GetItem() と同じシグネチャを持っています。このスロットは PyMapping_Check() が 1 を返すためには必要で、そうでなければ NULL の場合があります。

objobjargproc PyMappingMethods.mp_ass_subscript

The corresponding slot ID Py_mp_ass_subscript is part of the Stable ABI.

この関数は PyObject_SetItem()、PyObject_DelItem()、PySequence_SetSlice()、PySequence_DelSlice() で使われます。 シグネチャは PyObject_SetItem() と同じですが、要素を削除するために v を NULL にすることもできます。 このスロットが NULL の場合、オブジェクトは要素の代入と削除をサポートしません。

シーケンスオブジェクト構造体

type PySequenceMethods

この構造体はシーケンス型プロトコルを実装するために使われる関数群へのポインタを保持しています。

lenfunc PySequenceMethods.sq_length

The corresponding slot ID Py_sq_length is part of the Stable ABI.

この関数は PySequence_Size() と PyObject_Size() で使われ、それらと同じシグネチャを持ちます。 sq_item スロットや sq_ass_item スロットを使う際の、負のインデックスの処理にも使われます。

binaryfunc PySequenceMethods.sq_concat

The corresponding slot ID Py_sq_concat is part of the Stable ABI.

この関数は PySequence_Concat() で利用され、同じシグネチャを持っています。また、 + 演算子でも、 nb_add スロットによる数値加算を試した後に利用されます。

ssizeargfunc PySequenceMethods.sq_repeat

The corresponding slot ID Py_sq_repeat is part of the Stable ABI.

この関数は PySequence_Repeat() で利用され、同じシグネチャを持っています。また、 * 演算でも、 nb_multiply スロットによる数値乗算を試したあとに利用されます。

ssizeargfunc PySequenceMethods.sq_item

The corresponding slot ID Py_sq_item is part of the Stable ABI.

この関数は PySequence_GetItem() で使われ、同じシグネチャを持ちます。 PyObject_GetItem() でも、mp_subscript スロットによる添字指定を試した後で使われます。 PySequence_Check() が 1 を返すにはこのスロットの設定が必要ですが、それ以外の場合は NULL にできます。

負のインデックスは次のように処理されます。 sq_length スロットが設定されていれば、それを呼び出してシーケンスの長さを取得し、正のインデックスを計算して sq_item に渡します。 sq_length が NULL の場合は、インデックスをそのまま関数に渡します。

ssizeobjargproc PySequenceMethods.sq_ass_item

The corresponding slot ID Py_sq_ass_item is part of the Stable ABI.

この関数は PySequence_SetItem() で使われ、同じシグネチャを持ちます。 PyObject_SetItem() と PyObject_DelItem() でも、mp_ass_subscript スロットによる要素の代入や削除を試した後で使われます。 オブジェクトが要素の代入と削除をサポートしない場合、このスロットは NULL のままにできます。

objobjproc PySequenceMethods.sq_contains

The corresponding slot ID Py_sq_contains is part of the Stable ABI.

この関数は PySequence_Contains() から利用され、同じシグネチャを持っています。このスロットは NULL の場合があり、その時 PySequence_Contains() はシンプルにマッチするオブジェクトを見つけるまでシーケンスを巡回します。

binaryfunc PySequenceMethods.sq_inplace_concat

The corresponding slot ID Py_sq_inplace_concat is part of the Stable ABI.

この関数は PySequence_InPlaceConcat() で使われ、同じシグネチャを持ちます。 第 1 オペランドを変更して返すべきです。 このスロットは NULL のままにできます。 その場合 PySequence_InPlaceConcat() は PySequence_Concat() にフォールバックします。 累算代入 += でも、nb_inplace_add スロットによる数値のインプレース加算を試した後で使われます。

ssizeargfunc PySequenceMethods.sq_inplace_repeat

The corresponding slot ID Py_sq_inplace_repeat is part of the Stable ABI.

この関数は PySequence_InPlaceRepeat() で使われ、同じシグネチャを持ちます。 第 1 オペランドを変更して返すべきです。 このスロットは NULL のままにできます。 その場合 PySequence_InPlaceRepeat() は PySequence_Repeat() にフォールバックします。 累算代入 *= でも、nb_inplace_multiply スロットによる数値のインプレース乗算を試した後で使われます。

バッファオブジェクト構造体 (buffer object structure)

type PyBufferProcs

この構造体は buffer プロトコル が要求する関数群へのポインタを保持しています。 そのプロトコルは、エクスポーターオブジェクトが如何にして、その内部データをコンシューマオブジェクトに渡すかを定義します。

getbufferproc PyBufferProcs.bf_getbuffer

The corresponding slot ID Py_bf_getbuffer is part of the Stable ABI (バージョン 3.11 より).

この関数のシグネチャは以下の通りです:

int (PyObject *exporter, Py_buffer *view, int flags);

flags で指定された方法で view を埋めてほしいという exporter に対する要求を処理します。ステップ(3) を除いて、この関数の実装では以下のステップを行わなければなりません:

  1. Check if the request can be met. If not, raise BufferError, set view->obj to NULL and return -1.

  2. 要求されたフィールドを埋めます。

  3. エクスポートした回数を保持する内部カウンタをインクリメントします。

  4. Set view->obj to exporter and increment view->obj.

  5. 0 を返します。

exporter がバッファプロバイダのチェインかツリーの一部であれば、2つの主要な方式が使用できます:

  • Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference to itself.

  • Redirect: The buffer request is redirected to the root object of the tree. Here, view->obj will be a new reference to the root object.

view の個別のフィールドは バッファ構造体 の節で説明されており、エクスポートが特定の要求に対しどう対応しなければならないかの規則は、 バッファ要求のタイプ の節にあります。

Py_buffer 構造体の中から参照している全てのメモリはエクスポータに属し、コンシューマがいなくなるまで有効でなくてはなりません。 format 、 shape 、 strides 、 suboffsets 、 internal はコンシューマからは読み出し専用です。

PyBuffer_FillInfo() は、全てのリクエストタイプを正しく扱う際に、単純なバイトバッファを公開する簡単な方法を提供します。

PyObject_GetBuffer() は、この関数をラップするコンシューマ向けのインターフェースです。

releasebufferproc PyBufferProcs.bf_releasebuffer

The corresponding slot ID Py_bf_releasebuffer is part of the Stable ABI (バージョン 3.11 より).

この関数のシグネチャは以下の通りです:

void (PyObject *exporter, Py_buffer *view);

バッファのリソースを開放する要求を処理します。もし開放する必要のあるリソースがない場合、 PyBufferProcs.bf_releasebuffer は NULL にしても構いません。そうでない場合は、この関数の標準的な実装は、以下の任意の処理手順 (optional step) を行います:

  1. エクスポートした回数を保持する内部カウンタをデクリメントします。

  2. カウンタが 0 の場合は、view に関連付けられた全てのメモリを解放します。

エクスポータは、バッファ固有のリソースを管理するために internal フィールドを使わなければなりません。 このフィールドの値は変わらないことが保証されますが、コンシューマは元のバッファのコピーを view 引数として渡しても構いません。

This function MUST NOT decrement view->obj, since that is done automatically in PyBuffer_Release() (this scheme is useful for breaking reference cycles).

PyBuffer_Release() は、この関数をラップするコンシューマ向けのインターフェースです。

async オブジェクト構造体

Added in version 3.5.

type PyAsyncMethods

この構造体は awaitable オブジェクトと asynchronous iterator オブジェクトを実装するのに必要な関数へのポインタを保持しています。

以下は構造体の定義です:

typedef struct {
    unaryfunc am_await;
    unaryfunc am_aiter;
    unaryfunc am_anext;
    sendfunc am_send;
} PyAsyncMethods;
unaryfunc PyAsyncMethods.am_await

The corresponding slot ID Py_am_await is part of the Stable ABI (バージョン 3.5 より).

この関数のシグネチャは以下の通りです:

PyObject *am_await(PyObject *self);

返されるオブジェクトは イテレータ でなければなりません。 つまりこのオブジェクトに対して PyIter_Check() が 1 を返さなければなりません。

オブジェクトが awaitable でない場合、このスロットを NULL に設定します。

unaryfunc PyAsyncMethods.am_aiter

The corresponding slot ID Py_am_aiter is part of the Stable ABI (バージョン 3.5 より).

この関数のシグネチャは以下の通りです:

PyObject *am_aiter(PyObject *self);

非同期イテレータ オブジェクトを返さなければなりません。 詳細は __anext__() を参照してください。

オブジェクトが非同期反復処理のプロトコルを実装していない場合、このスロットを NULL に設定します。

unaryfunc PyAsyncMethods.am_anext

The corresponding slot ID Py_am_anext is part of the Stable ABI (バージョン 3.5 より).

この関数のシグネチャは以下の通りです:

PyObject *am_anext(PyObject *self);

待機可能 オブジェクトを返さなければなりません。 詳細は __anext__() を参照してください。 このスロットは NULL にできます。

sendfunc PyAsyncMethods.am_send

The corresponding slot ID Py_am_send is part of the Stable ABI (バージョン 3.10 より).

この関数のシグネチャは以下の通りです:

PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);

詳細は PyIter_Send() を参照してください。 このスロットは NULL にできます。

Added in version 3.10.

Slot Type typedefs

typedef PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)
次に属します: Stable ABI.

この関数の目的は、メモリの割り当てと初期化を分離することです。 インスタンスに十分な長さを持ち、適切にアラインメントされ、ゼロで初期化されたメモリブロックへのポインタを返すべきです。 ただし、ob_refcnt は 1 に、ob_type は型引数に設定します。 型の tp_itemsize がゼロでなければ、オブジェクトの ob_size フィールドを nitems に初期化し、割り当てるメモリブロックの長さは tp_basicsize + nitems*tp_itemsize を sizeof(void*) の倍数に切り上げた値にするべきです。 それ以外の場合、nitems は使わず、ブロックの長さは tp_basicsize にするべきです。

この関数では他のいかなるインスタンス初期化も行ってはなりません。追加のメモリ割り当てすらも行ってはなりません。そのような処理は tp_new で行われるべきです。

typedef void (*destructor)(PyObject*)
次に属します: Stable ABI.
typedef void (*freefunc)(void*)

tp_free を参照してください。

typedef PyObject *(*newfunc)(PyTypeObject*, PyObject*, PyObject*)
次に属します: Stable ABI.

tp_new を参照してください。

typedef int (*initproc)(PyObject*, PyObject*, PyObject*)
次に属します: Stable ABI.

tp_init を参照してください。

typedef PyObject *(*reprfunc)(PyObject*)
次に属します: Stable ABI.

tp_repr を参照してください。

typedef PyObject *(*getattrfunc)(PyObject *self, char *attr)
次に属します: Stable ABI.

オブジェクトの属性の値を返します。

typedef int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
次に属します: Stable ABI.

オブジェクトの属性に値を設定します。属性を削除するには、 value (実) 引数に NULL を設定します。

typedef PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)
次に属します: Stable ABI.

オブジェクトの属性の値を返します。

tp_getattro を参照してください。

typedef int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)
次に属します: Stable ABI.

オブジェクトの属性に値を設定します。属性を削除するには、 value (実) 引数に NULL を設定します。

tp_setattro を参照してください。

typedef PyObject *(*descrgetfunc)(PyObject*, PyObject*, PyObject*)
次に属します: Stable ABI.

tp_descr_get を参照してください。

typedef int (*descrsetfunc)(PyObject*, PyObject*, PyObject*)
次に属します: Stable ABI.

tp_descr_set を参照してください。

typedef Py_hash_t (*hashfunc)(PyObject*)
次に属します: Stable ABI.

tp_hash を参照してください。

typedef PyObject *(*richcmpfunc)(PyObject*, PyObject*, int)
次に属します: Stable ABI.

tp_richcompare を参照してください。

typedef PyObject *(*getiterfunc)(PyObject*)
次に属します: Stable ABI.

tp_iter を参照してください。

typedef PyObject *(*iternextfunc)(PyObject*)
次に属します: Stable ABI.

tp_iternext を参照してください。

typedef Py_ssize_t (*lenfunc)(PyObject*)
次に属します: Stable ABI.
typedef int (*getbufferproc)(PyObject*, Py_buffer*, int)
次に属します: Stable ABI (バージョン 3.12 より).
typedef void (*releasebufferproc)(PyObject*, Py_buffer*)
次に属します: Stable ABI (バージョン 3.12 より).
typedef PyObject *(*unaryfunc)(PyObject*)
次に属します: Stable ABI.
typedef PyObject *(*binaryfunc)(PyObject*, PyObject*)
次に属します: Stable ABI.
typedef PySendResult (*sendfunc)(PyObject*, PyObject*, PyObject**)

am_send を参照してください。

typedef PyObject *(*ternaryfunc)(PyObject*, PyObject*, PyObject*)
次に属します: Stable ABI.
typedef PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)
次に属します: Stable ABI.
typedef int (*ssizeobjargproc)(PyObject*, Py_ssize_t, PyObject*)
次に属します: Stable ABI.
typedef int (*objobjproc)(PyObject*, PyObject*)
次に属します: Stable ABI.
typedef int (*objobjargproc)(PyObject*, PyObject*, PyObject*)
次に属します: Stable ABI.

使用例

ここでは Python の型定義の簡単な例をいくつか挙げます。これらの例にはあなたが遭遇する共通的な利用例を含んでいます。いくつかの例ではトリッキーなコーナーケースを実演しています。より多くの例や実践的な情報、チュートリアルが必要なら、拡張の型の定義: チュートリアル や 拡張の型の定義: 雑多なトピック を参照してください。

基本的な 静的な型。

typedef struct {
    PyObject_HEAD
    const char *data;
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My オブジェクト"),
    .tp_new = myobj_new,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
};

より冗長な初期化子を用いた古いコードを(特にCPythonのコードベース中で)見かけることがあるかもしれません:

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "mymod.MyObject",               /* tp_name */
    sizeof(MyObject),               /* tp_basicsize */
    0,                              /* tp_itemsize */
    (destructor)myobj_dealloc,      /* tp_dealloc */
    0,                              /* tp_vectorcall_offset */
    0,                              /* tp_getattr */
    0,                              /* tp_setattr */
    0,                              /* tp_as_async */
    (reprfunc)myobj_repr,           /* tp_repr */
    0,                              /* tp_as_number */
    0,                              /* tp_as_sequence */
    0,                              /* tp_as_mapping */
    0,                              /* tp_hash */
    0,                              /* tp_call */
    0,                              /* tp_str */
    0,                              /* tp_getattro */
    0,                              /* tp_setattro */
    0,                              /* tp_as_buffer */
    0,                              /* tp_flags */
    PyDoc_STR("My オブジェクト"),        /* tp_doc */
    0,                              /* tp_traverse */
    0,                              /* tp_clear */
    0,                              /* tp_richcompare */
    0,                              /* tp_weaklistoffset */
    0,                              /* tp_iter */
    0,                              /* tp_iternext */
    0,                              /* tp_methods */
    0,                              /* tp_members */
    0,                              /* tp_getset */
    0,                              /* tp_base */
    0,                              /* tp_dict */
    0,                              /* tp_descr_get */
    0,                              /* tp_descr_set */
    0,                              /* tp_dictoffset */
    0,                              /* tp_init */
    0,                              /* tp_alloc */
    myobj_new,                      /* tp_new */
};

弱参照やインスタンス辞書、ハッシュをサポートする型:

typedef struct {
    PyObject_HEAD
    const char *data;
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject),
    .tp_doc = PyDoc_STR("My objects"),
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
         Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MANAGED_DICT |
         Py_TPFLAGS_MANAGED_WEAKREF,
    .tp_new = myobj_new,
    .tp_traverse = (traverseproc)myobj_traverse,
    .tp_clear = (inquiry)myobj_clear,
    .tp_alloc = PyType_GenericNew,
    .tp_dealloc = (destructor)myobj_dealloc,
    .tp_repr = (reprfunc)myobj_repr,
    .tp_hash = (hashfunc)myobj_hash,
    .tp_richcompare = PyBaseObject_Type.tp_richcompare,
};

Py_TPFLAGS_DISALLOW_INSTANTIATION フラグを使い、サブクラス化も、呼び出しによるインスタンスの作成もできない str のサブクラスです (例えば別のファクトリ関数を使います)。

typedef struct {
    PyUnicodeObject raw;
    char *extra;
} MyStr;

static PyTypeObject MyStr_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyStr",
    .tp_basicsize = sizeof(MyStr),
    .tp_base = NULL,  // モジュール初期化時に &PyUnicode_Type を設定
    .tp_doc = PyDoc_STR("独自の str"),
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
    .tp_repr = (reprfunc)myobj_repr,
};

固定長のインスタンスを持つ、最も単純な 静的な型。

typedef struct {
    PyObject_HEAD
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
};

可変長のインスタンスを持つ、最も単純な 静的な型。

typedef struct {
    PyObject_VAR_HEAD
    const char *data[1];
} MyObject;

static PyTypeObject MyObject_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "mymod.MyObject",
    .tp_basicsize = sizeof(MyObject) - sizeof(char *),
    .tp_itemsize = sizeof(char *),
};