型オブジェクト

新スタイルの型を定義する構造体: 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 *

%

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()

bf_releasebuffer

releasebufferproc()

スロットの定義型 (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

See Slot Type typedefs below for more detail.

PyTypeObject 定義

PyTypeObject の構造体定義は Include/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 スロット

The type object structure extends the PyVarObject structure. The ob_size field is used for dynamic types (created by type_new(), usually called from a class statement). Note that PyType_Type (the metatype) initializes tp_itemsize, which means that its instances (i.e. type objects) must have the ob_size field.

Py_ssize_t PyObject.ob_refcnt
Part of the 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
Part of the Stable ABI.

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

Foo_Type.ob_type = &PyType_Type;

This should be done before any instances of the type are created. PyType_Ready() checks if ob_type is NULL, and if so, initializes it to the ob_type field of the base class. PyType_Ready() will not change this field if it is non-zero.

継承:

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

PyObject *PyObject._ob_next
PyObject *PyObject._ob_prev

These fields are only present when the macro Py_TRACE_REFS is defined (see the configure --with-trace-refs option).

Their initialization to NULL is taken care of by the PyObject_HEAD_INIT macro. For statically allocated objects, these fields always remain NULL. For dynamically allocated objects, these two fields are used to link the object into a doubly linked list of all live objects on the heap.

This could be used for various debugging purposes; currently the only uses are the sys.getobjects() function and to print the objects that are still alive at the end of a run when the environment variable PYTHONDUMPREFS is set.

継承:

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

PyVarObject スロット

Py_ssize_t PyVarObject.ob_size
Part of the Stable ABI.

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

継承:

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

PyTypeObject スロット

Each slot has a section describing inheritance. If PyType_Ready() may set a value when the field is set to NULL then there will also be a "Default" section. (Note that many fields set on PyBaseObject_Type and PyType_Type effectively act as defaults.)

const char *PyTypeObject.tp_name

Pointer to a NUL-terminated string containing the name of the type. For types that are accessible as module globals, the string should be the full module name, followed by a dot, followed by the type name; for built-in types, it should be just the type name. If the module is a submodule of a package, the full package name is part of the full module name. For example, a type named T defined in module M in subpackage Q in package P should have the tp_name initializer "P.Q.M.T".

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

静的にメモリ確保される型オブジェクト の場合、 tp_name フィールドにはドットが含まれているはずです。 最後のドットよりも前にある部分文字列全体は __module__ 属性として、またドットよりも後ろにある部分は __name__ 属性としてアクセスできます。

ドットが入っていない場合、 tp_name フィールドの内容全てが __name__ 属性になり、 __module__ 属性は (前述のように型の辞書内で明示的にセットしないかぎり) 未定義になります。 このため、その型は pickle 化できないことになります。 さらに、 pydoc が作成するモジュールドキュメントのリストにも載らなくなります。

This field must not be NULL. It is the only required field in PyTypeObject() (other than potentially tp_itemsize).

継承:

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

Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize

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

型には二つの種類があります: 固定長インスタンスの型は、 tp_itemsize フィールドがゼロで、可変長インスタンスの方は tp_itemsize フィールドが非ゼロの値になります。固定長インスタンスの型の場合、全てのインスタンスは等しく tp_basicsize で与えられたサイズになります。

For a type with variable-length instances, the instances must have an ob_size field, and the instance size is tp_basicsize plus N times tp_itemsize, where N is the "length" of the object. The value of N is typically stored in the instance's ob_size field. There are exceptions: for example, ints use a negative ob_size to indicate a negative number, and N is abs(ob_size) there. Also, the presence of an ob_size field in the instance layout doesn't mean that the instance structure is variable-length (for example, the structure for the list type has fixed-length instances, yet those instances have a meaningful ob_size field).

The basic size includes the fields in the instance declared by the macro PyObject_HEAD or PyObject_VAR_HEAD (whichever is used to declare the instance struct) and this in turn includes the _ob_prev and _ob_next fields if they are present. This means that the only correct way to get an initializer for the tp_basicsize is to use the sizeof operator on the struct used to declare the instance layout. The basic size does not include the GC header size.

アラインメントに関する注釈: 変数の各要素を配置する際に特定のアラインメントが必要となる場合、 tp_basicsize の値に気をつけなければなりません。例: ある型が double の配列を実装しているとします。 tp_itemsizesizeof(double) です。 tp_basicsizesizeof(double) (ここではこれを double のアラインメントが要求するサイズと仮定する) の個数分のサイズになるようにするのはプログラマの責任です。

For any type with variable-length instances, this field must not be NULL.

継承:

これらのフィールドはサブタイプに別々に継承されます。基底タイプが 0 でない tp_itemsize を持っていた場合、基底タイプの実装に依存しますが、一般的にはサブタイプで別の 0 で無い値を tp_itemsize に設定するのは安全ではありません。

destructor PyTypeObject.tp_dealloc

インスタンスのデストラクタ関数へのポインタです。この関数は (単量子 NoneEllipsis の場合のように) インスタンスが決してメモリ解放されない型でない限り必ず定義しなければなりません。シグネチャは次の通りです:

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);
}

継承:

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

Py_ssize_t PyTypeObject.tp_vectorcall_offset

An optional offset to a per-instance function that implements calling the object using the vectorcall protocol, a more efficient alternative of the simpler tp_call.

This field is only used if the flag Py_TPFLAGS_HAVE_VECTORCALL is set. If so, this must be a positive integer containing the offset in the instance of a vectorcallfunc pointer.

The vectorcallfunc pointer may be NULL, in which case the instance behaves as if Py_TPFLAGS_HAVE_VECTORCALL was not set: calling the instance falls back to tp_call.

Any class that sets Py_TPFLAGS_HAVE_VECTORCALL must also set tp_call and make sure its behaviour is consistent with the vectorcallfunc function. This can be done by setting tp_call to PyVectorcall_Call().

バージョン 3.8 で変更: Before version 3.8, this slot was named tp_print. In Python 2.x, it was used for printing to a file. In Python 3.0 to 3.7, it was unused.

バージョン 3.12 で変更: Before version 3.12, it was not recommended for mutable heap types to implement the vectorcall protocol. When a user sets __call__ in Python code, only tp_call is updated, likely making it inconsistent with the vectorcall function. Since 3.12, setting __call__ will disable vectorcall optimization by clearing the Py_TPFLAGS_HAVE_VECTORCALL flag.

継承:

This field is always inherited. However, the Py_TPFLAGS_HAVE_VECTORCALL flag is not always inherited. If it's not set, then the subclass won't use vectorcall, except when PyVectorcall_Call() is explicitly called.

getattrfunc PyTypeObject.tp_getattr

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

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

継承:

Group: tp_getattr, tp_getattro

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

setattrfunc PyTypeObject.tp_setattr

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

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

継承:

Group: tp_setattr, tp_setattro

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

PyAsyncMethods *PyTypeObject.tp_as_async

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

バージョン 3.5 で追加: 以前は tp_comparetp_reserved として知られていました。

継承:

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

reprfunc PyTypeObject.tp_repr

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

The signature is the same as for 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

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

The signature is the same as for PyObject_Hash():

Py_hash_t tp_hash(PyObject *);

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

When this field is not set (and tp_richcompare is not set), an attempt to take the hash of the object raises TypeError. This is the same as setting it to PyObject_HashNotImplemented().

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

継承:

Group: tp_hash, tp_richcompare

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

ternaryfunc PyTypeObject.tp_call

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

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

継承:

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

reprfunc PyTypeObject.tp_str

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

The signature is the same as for PyObject_Str():

PyObject *tp_str(PyObject *self);

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

継承:

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

デフォルト

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

getattrofunc PyTypeObject.tp_getattro

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

The signature is the same as for PyObject_GetAttr():

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

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

継承:

Group: tp_getattr, tp_getattro

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

デフォルト

PyBaseObject_Type uses PyObject_GenericGetAttr().

setattrofunc PyTypeObject.tp_setattro

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

The signature is the same as for PyObject_SetAttr():

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

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

継承:

Group: tp_setattr, tp_setattro

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

デフォルト

PyBaseObject_Type uses PyObject_GenericSetAttr().

PyBufferProcs *PyTypeObject.tp_as_buffer

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

継承:

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

unsigned long PyTypeObject.tp_flags

このフィールドは様々なフラグからなるビットマスクです。いくつかのフラグは、特定の状況において変則的なセマンティクスが適用されることを示します; その他のフラグは、型オブジェクト (あるいは tp_as_numbertp_as_sequencetp_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 uses Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE.

Bit Masks:

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

Py_TPFLAGS_HEAPTYPE

This bit is set when the type object itself is allocated on the heap, for example, types created dynamically using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference to the type, and the type object is INCREF'ed when a new instance is created, and DECREF'ed when an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the instance's ob_type gets INCREF'ed or DECREF'ed).

継承:

???

Py_TPFLAGS_BASETYPE

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

継承:

???

Py_TPFLAGS_READY

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

継承:

???

Py_TPFLAGS_READYING

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

継承:

???

Py_TPFLAGS_HAVE_GC

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.

継承:

Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear

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.

Py_TPFLAGS_DEFAULT

This is a bitmask of all the bits that pertain to the existence of certain fields in the type object and its extension structures. Currently, it includes the following bits: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION.

継承:

???

Py_TPFLAGS_METHOD_DESCRIPTOR

This bit indicates that objects behave like unbound methods.

If this flag is set for type(meth), then:

  • meth.__get__(obj, cls)(*args, **kwds) (with obj not None) must be equivalent to meth(obj, *args, **kwds).

  • meth.__get__(None, cls)(*args, **kwds) must be equivalent to meth(*args, **kwds).

This flag enables an optimization for typical method calls like obj.meth(): it avoids creating a temporary "bound method" object for obj.meth.

バージョン 3.8 で追加.

継承:

This flag is never inherited by types without the Py_TPFLAGS_IMMUTABLETYPE flag set. For extension types, it is inherited whenever tp_descr_get is inherited.

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.

If this flag is set, Py_TPFLAGS_HAVE_GC should also be set.

バージョン 3.12 で追加.

継承:

This flag is inherited unless the tp_dictoffset field is set in a superclass.

Py_TPFLAGS_MANAGED_WEAKREF

This bit indicates that instances of the class should be weakly referenceable.

バージョン 3.12 で追加.

継承:

This flag is inherited unless the tp_weaklistoffset field is set in a superclass.

Py_TPFLAGS_ITEMS_AT_END

Only usable with variable-size types, i.e. ones with non-zero tp_itemsize.

Indicates that the variable-sized portion of an instance of this type is at the end of the instance's memory area, at an offset of Py_TYPE(obj)->tp_basicsize (which may be different in each subclass).

When setting this flag, be sure that all superclasses either use this memory layout, or are not variable-sized. Python does not check this.

バージョン 3.12 で追加.

継承:

This flag is inherited.

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

これらのフラグは PyLong_Check() のような関数が、型がとある組み込み型のサブクラスかどうかを素早く判断するのに使われます; この専用のチェックは PyObject_IsInstance() のような汎用的なチェックよりも高速です。 組み込み型を継承した独自の型では tp_flags を適切に設定すべきで、そうしないとその型が関わるコードでは、どんなチェックの方法が使われるかによって振る舞いが異なってしまうでしょう。

Py_TPFLAGS_HAVE_FINALIZE

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

バージョン 3.4 で追加.

バージョン 3.8 で非推奨: This flag isn't necessary anymore, as the interpreter assumes the tp_finalize slot is always present in the type structure.

Py_TPFLAGS_HAVE_VECTORCALL

This bit is set when the class implements the vectorcall protocol. See tp_vectorcall_offset for details.

継承:

This bit is inherited if tp_call is also inherited.

バージョン 3.9 で追加.

バージョン 3.12 で変更: This flag is now removed from a class when the class's __call__() method is reassigned.

This flag can now be inherited by mutable classes.

Py_TPFLAGS_IMMUTABLETYPE

This bit is set for type objects that are immutable: type attributes cannot be set nor deleted.

PyType_Ready() automatically applies this flag to static types.

継承:

This flag is not inherited.

バージョン 3.10 で追加.

Py_TPFLAGS_DISALLOW_INSTANTIATION

Disallow creating instances of the type: set tp_new to NULL and don't create the __new__ key in the type dictionary.

The flag must be set before creating the type, not after. For example, it must be set before PyType_Ready() is called on the type.

The flag is set automatically on static types if tp_base is NULL or &PyBaseObject_Type and tp_new is NULL.

継承:

This flag is not inherited. However, subclasses will not be instantiable unless they provide a non-NULL tp_new (which is only possible via the C API).

注釈

To disallow instantiating a class directly but allow instantiating its subclasses (e.g. for an abstract base class), do not use this flag. Instead, make tp_new only succeed for subclasses.

バージョン 3.10 で追加.

Py_TPFLAGS_MAPPING

This bit indicates that instances of the class may match mapping patterns when used as the subject of a match block. It is automatically set when registering or subclassing collections.abc.Mapping, and unset when registering collections.abc.Sequence.

注釈

Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error to enable both flags simultaneously.

継承:

This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.

参考

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

バージョン 3.10 で追加.

Py_TPFLAGS_SEQUENCE

This bit indicates that instances of the class may match sequence patterns when used as the subject of a match block. It is automatically set when registering or subclassing collections.abc.Sequence, and unset when registering collections.abc.Mapping.

注釈

Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error to enable both flags simultaneously.

継承:

This flag is inherited by types that do not already set Py_TPFLAGS_MAPPING.

参考

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

バージョン 3.10 で追加.

Py_TPFLAGS_VALID_VERSION_TAG

Internal. Do not set or unset this flag. To indicate that a class has changed call PyType_Modified()

警告

This flag is present in header files, but is an internal feature and should not be used. It will be removed in a future version of CPython

const char *PyTypeObject.tp_doc

オプションのポインタで、この型オブジェクトの docstring を与える NUL 終端された C の文字列を指します。この値は型オブジェクトと型のインスタンスにおける __doc__ 属性として公開されます。

継承:

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

traverseproc PyTypeObject.tp_traverse

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() 関数は循環参照になり得ないメンバも返します。

警告

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).

Py_VISIT()local_traverse()visitarg という決まった名前の引数を持つことを要求します。

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 で変更: Heap-allocated types are expected to visit Py_TYPE(self) in tp_traverse. In earlier versions of Python, due to bug 40217, doing this may lead to crashes in subclasses.

継承:

Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear

This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.

inquiry PyTypeObject.tp_clear

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 *);

tp_clear メンバ関数は GC が検出した循環しているゴミの循環参照を壊すために用いられます。総合的な視点で考えると、システム内の全ての tp_clear 関数が連携して、全ての循環参照を破壊しなければなりません。 (訳注: ある型が tp_clear を実装しなくても全ての循環参照が破壊できるのであれば実装しなくても良い) これはとても繊細で、もし少しでも不確かな部分があるのであれば、 tp_clear 関数を提供するべきです。例えば、タプルは tp_clear を実装しません。なぜなら、タプルだけで構成された循環参照がみつかることは無いからです。従って、タプル以外の型の tp_clear 関数だけで、タプルを含むどんな循環参照も必ず破壊できることになります。これは簡単に判ることではなく、 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;
}

The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the contained object must not be released (via Py_DECREF()) until after the pointer to the contained object is set to NULL. This is because releasing the reference may cause the contained object to become trash, triggering a chain of reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks, associated with the contained object). If it's possible for such code to reference self again, it's important that the pointer to the contained object be NULL at that time, so that self knows the contained object can no longer be used. The Py_CLEAR() macro performs the operations in a safe order.

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.

tp_clear 関数の目的は参照カウントを破壊することなので、 Python 文字列や Python 整数のような、循環参照に含むことのできないオブジェクトをクリアする必要はありません。一方、所有する全ての Python オブジェクトをクリアするようにし、その型の tp_dealloc 関数が tp_clear 関数を実行するようにすると実装が楽になるでしょう。

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

継承:

Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear

This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit: the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.

richcmpfunc PyTypeObject.tp_richcompare

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

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

The first parameter is guaranteed to be an instance of the type that is defined by PyTypeObject.

この関数は、比較結果を返すべきです。(普通は Py_TruePy_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_TruePy_False を返します。 VAL_A と VAL_B は C の比較演算によって順序付け可能でなければなりません(例えばこれらは C言語の整数か浮動小数点数になるでしょう)。三番目の引数には PyObject_RichCompare() と同様に要求された演算を指定します。

The returned value is a new strong reference.

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

バージョン 3.7 で追加.

継承:

Group: tp_hash, tp_richcompare

このフィールドは tp_hash と共にサブタイプに継承されます: すなわち、サブタイプの tp_richcompare および tp_hash が両方とも NULL のとき、サブタイプは基底タイプから tp_richcomparetp_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

While this field is still supported, Py_TPFLAGS_MANAGED_WEAKREF should be used instead, if at all possible.

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

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

It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_weaklist.

継承:

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

デフォルト

If the Py_TPFLAGS_MANAGED_WEAKREF bit is set in the tp_dict field, then tp_weaklistoffset will be set to a negative value, to indicate that it is unsafe to use this field.

getiterfunc PyTypeObject.tp_iter

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

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

PyObject *tp_iter(PyObject *self);

継承:

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

iternextfunc PyTypeObject.tp_iternext

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

PyObject *tp_iternext(PyObject *self);

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

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

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

継承:

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

struct PyMethodDef *PyTypeObject.tp_methods

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

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

継承:

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

struct PyMemberDef *PyTypeObject.tp_members

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

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

継承:

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

struct PyGetSetDef *PyTypeObject.tp_getset

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

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

継承:

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

PyTypeObject *PyTypeObject.tp_base

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

注釈

Slot initialization is subject to the rules of initializing globals. C99 requires the initializers to be "address constants". Function designators like PyType_GenericNew(), with implicit conversion to a pointer, are valid C99 address constants.

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.

Consequently, tp_base should be set in the extension module's init function.

継承:

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

デフォルト

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

PyObject *PyTypeObject.tp_dict

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

This field should normally be initialized to NULL before PyType_Ready is called; it may also be initialized to a dictionary containing initial attributes for the type. Once PyType_Ready() has initialized the type, extra attributes for the type may be added to this dictionary only if they don't correspond to overloaded operations (like __add__()). Once initialization for the type has finished, this field should be treated as read-only.

Some types may not store their dictionary in this slot. Use PyType_GetDict() to retrieve the dictionary for an arbitrary type.

バージョン 3.12 で変更: Internals detail: For static builtin types, this is always NULL. Instead, the dict for such types is stored on PyInterpreterState. Use PyType_GetDict() to get the dict for an arbitrary type.

継承:

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

デフォルト

If this field is NULL, PyType_Ready() will assign a new dictionary to it.

警告

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

descrgetfunc PyTypeObject.tp_descr_get

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

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

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

継承:

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

descrsetfunc PyTypeObject.tp_descr_set

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

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

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

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

継承:

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

Py_ssize_t PyTypeObject.tp_dictoffset

While this field is still supported, Py_TPFLAGS_MANAGED_DICT should be used instead, if at all possible.

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

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

The value specifies the offset of the dictionary from the start of the instance structure.

The tp_dictoffset should be regarded as write-only. To get the pointer to the dictionary call PyObject_GenericGetDict(). Calling PyObject_GenericGetDict() may need to allocate memory for the dictionary, so it is may be more efficient to call PyObject_GetAttr() when accessing an attribute on the object.

It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_dictoffset.

継承:

This field is inherited by subtypes. A subtype should not override this offset; doing so could be unsafe, if C code tries to access the dictionary at the previous offset. To properly support inheritance, use Py_TPFLAGS_MANAGED_DICT.

デフォルト

This slot has no default. For static types, if the field is NULL then no __dict__ gets created for instances.

If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_dict field, then tp_dictoffset will be set to -1, to indicate that it is unsafe to use this field.

initproc PyTypeObject.tp_init

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

This function corresponds to the __init__() method of classes. Like __init__(), it is possible to create an instance without calling __init__(), and it is possible to reinitialize an instance by calling its __init__() method again.

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

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

The self argument is the instance to be initialized; the args and kwds arguments represent positional and keyword arguments of the call to __init__().

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

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

継承:

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

デフォルト

For static types this field does not have a default.

allocfunc PyTypeObject.tp_alloc

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

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

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

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

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

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

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

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

Set the Py_TPFLAGS_DISALLOW_INSTANTIATION flag to disallow creating instances of the type in Python.

継承:

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

デフォルト

For static types this field has no default. This means if the slot is defined as NULL, the type cannot be called to create new instances; presumably there is some other way to create instances, like a factory function.

freefunc PyTypeObject.tp_free

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

void tp_free(void *self);

このシグネチャと互換性のある初期化子は 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 garbage collector needs to know whether a particular object is collectible or not. Normally, it is sufficient to look at the object's type's tp_flags field, and check the Py_TPFLAGS_HAVE_GC flag bit. But some types have a mixture of statically and dynamically allocated instances, and the statically allocated instances are not collectible. Such types should define this function; it should return 1 for a collectible instance, and 0 for a non-collectible instance. The signature is:

int tp_is_gc(PyObject *self);

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

継承:

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

デフォルト

This slot has no default. If this field is NULL, Py_TPFLAGS_HAVE_GC is used as the functional equivalent.

PyObject *PyTypeObject.tp_bases

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

This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.

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.

警告

Multiple inheritance does not work well for statically defined types. If you set tp_bases to a tuple, Python will not raise an error, but some slots will only be inherited from the first base.

継承:

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

PyObject *PyTypeObject.tp_mro

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

This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.

継承:

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

PyObject *PyTypeObject.tp_cache

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

継承:

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

void *PyTypeObject.tp_subclasses

A collection of subclasses. Internal use only. May be an invalid pointer.

To get a list of subclasses, call the Python method __subclasses__().

バージョン 3.12 で変更: For some types, this field does not hold a valid PyObject*. The type was changed to void* to indicate this.

継承:

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

PyObject *PyTypeObject.tp_weaklist

この型オブジェクトに対する弱参照からなるリストの先頭です。

バージョン 3.12 で変更: Internals detail: For the static builtin types this is always NULL, even if weakrefs are added. Instead, the weakrefs for each are stored on PyInterpreterState. Use the public C-API or the internal _PyObject_GET_WEAKREFS_LISTPTR() macro to avoid the distinction.

継承:

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

destructor PyTypeObject.tp_del

このフィールドは廃止されました。tp_finalize を代わりに利用してください。

unsigned int PyTypeObject.tp_version_tag

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

継承:

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

destructor PyTypeObject.tp_finalize

オプションのポインタで、インスタンスの終了処理関数を指します。シグネチャは以下の通りです:

void tp_finalize(PyObject *self);

tp_finalize が設定されている場合、インスタンスをファイナライズするときに、インタプリタがこの関数を1回呼び出します。 ガベージコレクタ (このインスタンスが孤立した循環参照の一部だった場合) やオブジェクトが破棄される直前にもこの関数は呼び出されます。 どちらの場合でも、循環参照を破壊しようとする前に呼び出されることが保証されていて、確実にオブジェクトが正常な状態にあるようにします。

tp_finalize は現在の例外状態を変更すべきではありません; 従って、単純でないファイナライザを書くには次の方法が推奨されます:

static void
local_finalize(PyObject *self)
{
    PyObject *error_type, *error_value, *error_traceback;

    /* Save the current exception, if any. */
    PyErr_Fetch(&error_type, &error_value, &error_traceback);

    /* ... */

    /* Restore the saved exception. */
    PyErr_Restore(error_type, error_value, error_traceback);
}

また、 Python のガベージコレクションでは、 tp_dealloc を呼び出すのはオブジェクトを生成したスレッドだけではなく、任意の Python スレッドかもしれないという点にも注意して下さい。 (オブジェクトが循環参照の一部の場合、任意のスレッドのガベージコレクションによって解放されてしまうかもしれません)。Python API 側からみれば、 tp_dealloc を呼び出すスレッドはグローバルインタプリタロック (GIL: Global Interpreter Lock) を獲得するので、これは問題ではありません。しかしながら、削除されようとしているオブジェクトが何らかの C や C++ ライブラリ由来のオブジェクトを削除する場合、 tp_dealloc を呼び出すスレッドのオブジェクトを削除することで、ライブラリの仮定している何らかの規約に違反しないように気を付ける必要があります。

継承:

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

バージョン 3.4 で追加.

バージョン 3.8 で変更: Before version 3.8 it was necessary to set the Py_TPFLAGS_HAVE_FINALIZE flags bit in order for this field to be used. This is no longer required.

参考

"オブジェクトの安全な終了処理" (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.

継承:

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

バージョン 3.9 で追加: (このフィールドは3.8から存在していますが、3.9以降でしか利用できません)

unsigned char PyTypeObject.tp_watched

Internal. Do not use.

バージョン 3.12 で追加.

Static Types

Traditionally, types defined in C code are static, that is, a static PyTypeObject structure is defined directly in code and initialized using PyType_Ready().

This results in types that are limited relative to types defined in Python:

  • Static types are limited to one base, i.e. they cannot use multiple inheritance.

  • Static type objects (but not necessarily their instances) are immutable. It is not possible to add or modify the type object's attributes from Python.

  • Static type objects are shared across sub-interpreters, so they should not include any subinterpreter-specific state.

Also, since PyTypeObject is only part of the Limited API as an opaque struct, any extension modules using static types must be compiled for a specific Python minor version.

Heap Types

An alternative to static types is heap-allocated types, or heap types for short, which correspond closely to classes created by Python's class statement. Heap types have the Py_TPFLAGS_HEAPTYPE flag set.

This is done by filling a PyType_Spec structure and calling PyType_FromSpec(), PyType_FromSpecWithBases(), PyType_FromModuleAndSpec(), or 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 を返して例外を設定しなければなりません。

注釈

The nb_reserved field should always be NULL. It was previously called nb_long, and was renamed in Python 3.0.1.

binaryfunc PyNumberMethods.nb_add
binaryfunc PyNumberMethods.nb_subtract
binaryfunc PyNumberMethods.nb_multiply
binaryfunc PyNumberMethods.nb_remainder
binaryfunc PyNumberMethods.nb_divmod
ternaryfunc PyNumberMethods.nb_power
unaryfunc PyNumberMethods.nb_negative
unaryfunc PyNumberMethods.nb_positive
unaryfunc PyNumberMethods.nb_absolute
inquiry PyNumberMethods.nb_bool
unaryfunc PyNumberMethods.nb_invert
binaryfunc PyNumberMethods.nb_lshift
binaryfunc PyNumberMethods.nb_rshift
binaryfunc PyNumberMethods.nb_and
binaryfunc PyNumberMethods.nb_xor
binaryfunc PyNumberMethods.nb_or
unaryfunc PyNumberMethods.nb_int
void *PyNumberMethods.nb_reserved
unaryfunc PyNumberMethods.nb_float
binaryfunc PyNumberMethods.nb_inplace_add
binaryfunc PyNumberMethods.nb_inplace_subtract
binaryfunc PyNumberMethods.nb_inplace_multiply
binaryfunc PyNumberMethods.nb_inplace_remainder
ternaryfunc PyNumberMethods.nb_inplace_power
binaryfunc PyNumberMethods.nb_inplace_lshift
binaryfunc PyNumberMethods.nb_inplace_rshift
binaryfunc PyNumberMethods.nb_inplace_and
binaryfunc PyNumberMethods.nb_inplace_xor
binaryfunc PyNumberMethods.nb_inplace_or
binaryfunc PyNumberMethods.nb_floor_divide
binaryfunc PyNumberMethods.nb_true_divide
binaryfunc PyNumberMethods.nb_inplace_floor_divide
binaryfunc PyNumberMethods.nb_inplace_true_divide
unaryfunc PyNumberMethods.nb_index
binaryfunc PyNumberMethods.nb_matrix_multiply
binaryfunc PyNumberMethods.nb_inplace_matrix_multiply

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

type PyMappingMethods

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

lenfunc PyMappingMethods.mp_length

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

binaryfunc PyMappingMethods.mp_subscript

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

objobjargproc PyMappingMethods.mp_ass_subscript

This function is used by PyObject_SetItem(), PyObject_DelItem(), PySequence_SetSlice() and PySequence_DelSlice(). It has the same signature as PyObject_SetItem(), but v can also be set to NULL to delete an item. If this slot is NULL, the object does not support item assignment and deletion.

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

type PySequenceMethods

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

lenfunc PySequenceMethods.sq_length

This function is used by PySequence_Size() and PyObject_Size(), and has the same signature. It is also used for handling negative indices via the sq_item and the sq_ass_item slots.

binaryfunc PySequenceMethods.sq_concat

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

ssizeargfunc PySequenceMethods.sq_repeat

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

ssizeargfunc PySequenceMethods.sq_item

This function is used by PySequence_GetItem() and has the same signature. It is also used by PyObject_GetItem(), after trying the subscription via the mp_subscript slot. This slot must be filled for the PySequence_Check() function to return 1, it can be NULL otherwise.

Negative indexes are handled as follows: if the sq_length slot is filled, it is called and the sequence length is used to compute a positive index which is passed to sq_item. If sq_length is NULL, the index is passed as is to the function.

ssizeobjargproc PySequenceMethods.sq_ass_item

This function is used by PySequence_SetItem() and has the same signature. It is also used by PyObject_SetItem() and PyObject_DelItem(), after trying the item assignment and deletion via the mp_ass_subscript slot. This slot may be left to NULL if the object does not support item assignment and deletion.

objobjproc PySequenceMethods.sq_contains

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

binaryfunc PySequenceMethods.sq_inplace_concat

This function is used by PySequence_InPlaceConcat() and has the same signature. It should modify its first operand, and return it. This slot may be left to NULL, in this case PySequence_InPlaceConcat() will fall back to PySequence_Concat(). It is also used by the augmented assignment +=, after trying numeric in-place addition via the nb_inplace_add slot.

ssizeargfunc PySequenceMethods.sq_inplace_repeat

This function is used by PySequence_InPlaceRepeat() and has the same signature. It should modify its first operand, and return it. This slot may be left to NULL, in this case PySequence_InPlaceRepeat() will fall back to PySequence_Repeat(). It is also used by the augmented assignment *=, after trying numeric in-place multiplication via the nb_inplace_multiply slot.

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

type PyBufferProcs

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

getbufferproc PyBufferProcs.bf_getbuffer

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

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. view->objexporter を設定し、 view->obj をインクリメントします。

  5. 0 を返します。

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

  • 再エクスポート: ツリーの各要素がエクスポートされるオブジェクトとして振る舞い、自身への新しい参照を view->obj へセットします。

  • リダイレクト: バッファ要求がツリーのルートオブジェクトにリダイレクトされます。ここでは、 view->obj はルートオブジェクトへの新しい参照になります。

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

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

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

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

releasebufferproc PyBufferProcs.bf_releasebuffer

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

void (PyObject *exporter, Py_buffer *view);

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

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

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

エクスポータは、バッファ固有のリソースを監視し続けるために internal フィールドを使わなければなりません。このフィールドは、コンシューマが view 引数としてオリジナルのバッファのコピーを渡しているであろう間、変わらないことが保証されています。

この関数は、view->obj をデクリメントしてはいけません、なぜならそれは PyBuffer_Release() で自動的に行われるからです(この方式は参照の循環を防ぐのに有用です)。

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

async オブジェクト構造体

バージョン 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

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

PyObject *am_await(PyObject *self);

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

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

unaryfunc PyAsyncMethods.am_aiter

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

PyObject *am_aiter(PyObject *self);

Must return an asynchronous iterator object. See __anext__() for details.

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

unaryfunc PyAsyncMethods.am_anext

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

PyObject *am_anext(PyObject *self);

Must return an awaitable object. See __anext__() for details. This slot may be set to NULL.

sendfunc PyAsyncMethods.am_send

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

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

See PyIter_Send() for details. This slot may be set to NULL.

バージョン 3.10 で追加.

Slot Type typedefs

typedef PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)
Part of the Stable ABI.

The purpose of this function is to separate memory allocation from memory initialization. It should return a pointer to a block of memory of adequate length for the instance, suitably aligned, and initialized to zeros, but with ob_refcnt set to 1 and ob_type set to the type argument. If the type's tp_itemsize is non-zero, the object's ob_size field should be initialized to nitems and the length of the allocated memory block should be tp_basicsize + nitems*tp_itemsize, rounded up to a multiple of sizeof(void*); otherwise, nitems is not used and the length of the block should be tp_basicsize.

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

typedef void (*destructor)(PyObject*)
Part of the Stable ABI.
typedef void (*freefunc)(void*)

tp_free を参照してください。

typedef PyObject *(*newfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

tp_new を参照してください。

typedef int (*initproc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

tp_init を参照してください。

typedef PyObject *(*reprfunc)(PyObject*)
Part of the Stable ABI.

tp_repr を参照してください。

typedef PyObject *(*getattrfunc)(PyObject *self, char *attr)
Part of the Stable ABI.

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

typedef int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
Part of the Stable ABI.

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

typedef PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)
Part of the Stable ABI.

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

tp_getattro を参照してください。

typedef int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)
Part of the Stable ABI.

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

tp_setattro を参照してください。

typedef PyObject *(*descrgetfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

tp_descr_get を参照してください。

typedef int (*descrsetfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

tp_descr_set を参照してください。

typedef Py_hash_t (*hashfunc)(PyObject*)
Part of the Stable ABI.

tp_hash を参照してください。

typedef PyObject *(*richcmpfunc)(PyObject*, PyObject*, int)
Part of the Stable ABI.

tp_richcompare を参照してください。

typedef PyObject *(*getiterfunc)(PyObject*)
Part of the Stable ABI.

tp_iter を参照してください。

typedef PyObject *(*iternextfunc)(PyObject*)
Part of the Stable ABI.

tp_iternext を参照してください。

typedef Py_ssize_t (*lenfunc)(PyObject*)
Part of the Stable ABI.
typedef int (*getbufferproc)(PyObject*, Py_buffer*, int)
Part of the Stable ABI since version 3.12.
typedef void (*releasebufferproc)(PyObject*, Py_buffer*)
Part of the Stable ABI since version 3.12.
typedef PyObject *(*unaryfunc)(PyObject*)
Part of the Stable ABI.
typedef PyObject *(*binaryfunc)(PyObject*, PyObject*)
Part of the Stable ABI.
typedef PySendResult (*sendfunc)(PyObject*, PyObject*, PyObject**)

am_send を参照してください。

typedef PyObject *(*ternaryfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.
typedef PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)
Part of the Stable ABI.
typedef int (*ssizeobjargproc)(PyObject*, Py_ssize_t, PyObject*)
Part of the Stable ABI.
typedef int (*objobjproc)(PyObject*, PyObject*)
Part of the Stable ABI.
typedef int (*objobjargproc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

使用例

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

A basic static type:

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_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 objects"),        /* 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,
};

A str subclass that cannot be subclassed and cannot be called to create instances (e.g. uses a separate factory func) using Py_TPFLAGS_DISALLOW_INSTANTIATION flag:

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,  // set to &PyUnicode_Type in module init
    .tp_doc = PyDoc_STR("my custom str"),
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
    .tp_repr = (reprfunc)myobj_repr,
};

The simplest static type with fixed-length instances:

typedef struct {
    PyObject_HEAD
} MyObject;

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

The simplest static type with variable-length instances:

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 *),
};