型オブジェクトの構造体¶
新しい型を定義する PyTypeObject 構造体は、Python のオブジェクトシステムで特に重要な構造体の 1 つです。
型オブジェクトは PyObject_* 関数や PyType_* 関数で扱えますが、ほとんどの Python アプリケーションにとって関心のある機能はあまり提供しません。
これらのオブジェクトはオブジェクトの動作を決める基盤なので、インタープリタ自体や新しい型を実装する拡張モジュールにとっては非常に重要です。
型オブジェクトは標準の型 (standard type) に比べるとかなり大きな構造体です。各型オブジェクトは多くの値を保持しており、そのほとんどは C 関数へのポインタで、それぞれの関数はその型の機能の小さい部分を実装しています。この節では、型オブジェクトの各フィールドについて詳細を説明します。各フィールドは、構造体内で出現する順番に説明されています。
以下のクイックリファレンスに加えて、 使用例 節では PyTypeObject の意味と使い方を一目で理解できる例を載せています。
クイックリファレンス¶
tp スロット¶
PyTypeObject スロット [1] |
特殊メソッド/特殊属性 |
Info [2] |
||||
|---|---|---|---|---|---|---|
O |
T |
D |
I |
|||
<R> |
const char * |
__name__ |
X |
X |
||
X |
X |
X |
||||
X |
X |
|||||
X |
X |
X |
||||
X |
X |
|||||
__getattribute__, __getattr__ |
G |
|||||
__setattr__, __delattr__ |
G |
|||||
% |
||||||
__repr__ |
X |
X |
X |
|||
% |
||||||
% |
||||||
% |
||||||
__hash__ |
X |
G |
||||
__call__ |
X |
X |
||||
__str__ |
X |
X |
||||
__getattribute__, __getattr__ |
X |
X |
G |
|||
__setattr__, __delattr__ |
X |
X |
G |
|||
% |
||||||
unsigned long |
X |
X |
? |
|||
const char * |
__doc__ |
X |
X |
|||
X |
G |
|||||
X |
G |
|||||
__lt__, __le__, __eq__, __ne__, __gt__, __ge__ |
X |
G |
||||
X |
? |
|||||
__iter__ |
X |
|||||
__next__ |
X |
|||||
|
X |
X |
||||
|
X |
|||||
|
X |
X |
||||
__base__ |
X |
|||||
|
__dict__ |
? |
||||
__get__ |
X |
|||||
__set__, __delete__ |
X |
|||||
X |
? |
|||||
__init__ |
X |
X |
X |
|||
X |
? |
? |
||||
__new__ |
X |
X |
? |
? |
||
X |
X |
? |
? |
|||
X |
X |
|||||
< |
|
__bases__ |
~ |
|||
< |
|
__mro__ |
~ |
|||
[ |
|
|||||
void * |
__subclasses__ |
|||||
|
||||||
( |
||||||
unsigned int |
||||||
__del__ |
X |
|||||
unsigned char |
||||||
sub-slots¶
Slot |
特殊メソッド |
|
|---|---|---|
__await__ |
||
__aiter__ |
||
__anext__ |
||
__add__ __radd__ |
||
__iadd__ |
||
__sub__ __rsub__ |
||
__isub__ |
||
__mul__ __rmul__ |
||
__imul__ |
||
__mod__ __rmod__ |
||
__imod__ |
||
__divmod__ __rdivmod__ |
||
__pow__ __rpow__ |
||
__ipow__ |
||
__neg__ |
||
__pos__ |
||
__abs__ |
||
__bool__ |
||
__invert__ |
||
__lshift__ __rlshift__ |
||
__ilshift__ |
||
__rshift__ __rrshift__ |
||
__irshift__ |
||
__and__ __rand__ |
||
__iand__ |
||
__xor__ __rxor__ |
||
__ixor__ |
||
__or__ __ror__ |
||
__ior__ |
||
__int__ |
||
void * |
||
__float__ |
||
__floordiv__ |
||
__ifloordiv__ |
||
__truediv__ |
||
__itruediv__ |
||
__index__ |
||
__matmul__ __rmatmul__ |
||
__imatmul__ |
||
__len__ |
||
__getitem__ |
||
__setitem__, __delitem__ |
||
__len__ |
||
__add__ |
||
__mul__ |
||
__getitem__ |
||
__setitem__ __delitem__ |
||
__contains__ |
||
__iadd__ |
||
__imul__ |
||
__buffer__ |
||
__release_buffer__ |
||
スロットの定義型 (typedef)¶
定義型 (typedef) |
引数型 |
返り値型 |
|---|---|---|
|
||
|
void |
|
void * |
void |
|
int |
||
|
||
int |
||
|
|
|
PyObject *const char *
|
|
|
int |
||
|
||
int |
||
|
||
int |
||
|
Py_hash_t |
|
|
||
|
|
|
|
|
|
|
||
int |
||
void |
||
|
int |
|
PyObject * |
|
|
|
||
|
||
|
||
int |
||
int |
||
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
1by thePyObject_HEAD_INITmacro. Note that for statically allocated type objects, the type's instances (objects whoseob_typepoints 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()andPy_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_namefield 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'sob_sizefield. Note that theob_sizefield may later be used for other purposes. For example,intinstances use the bits ofob_sizein 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_deallocis 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
NoneandEllipsis). The function signature is:void tp_dealloc(PyObject *self);
The destructor function is called by the
Py_DECREF()andPy_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'stp_freefunction. If the type is not subtypable (doesn't have thePy_TPFLAGS_BASETYPEflag bit set), it is permissible to call the object deallocator directly instead of viatp_free. The object deallocator should be the one used to allocate the instance; this is normallyPyObject_Del()if the instance was allocated usingPyObject_NeworPyObject_NewVar, orPyObject_GC_Del()if the instance was allocated usingPyObject_GC_NeworPyObject_GC_NewVar.If the type supports garbage collection (has the
Py_TPFLAGS_HAVE_GCflag bit set), the destructor should callPyObject_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 (viaPy_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_deallocmay 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 whichtp_deallocis 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 calledtp_deallocwill 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_getattris 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_setattris 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_repris 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_hashis 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_callis 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_stris 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_getattrois 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を両方とも継承します。デフォルト
-
setattrofunc PyTypeObject.tp_setattro¶
The corresponding slot ID
Py_tp_setattrois 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を両方とも継承します。デフォルト
-
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_GCflag bit is inherited together with thetp_traverseandtp_clearfields, i.e. if thePy_TPFLAGS_HAVE_GCflag bit is clear in the subtype and thetp_traverseandtp_clearfields in the subtype exist and haveNULLvalues. .. 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_Newand destroyed usingPyObject_GC_Del(). More information in section 循環参照ガベージコレクションをサポートする. This bit also implies that the GC-related fieldstp_traverseandtp_clearare present in the type object.継承:
グループ:
Py_TPFLAGS_HAVE_GC、tp_traverse、tp_clearPy_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 callPyType_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, likePyObject_IsInstance(). Custom types that inherit from built-ins should have theirtp_flagsset 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_tagfield 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_GCis set.継承:
このフラグは継承されません。
Added in version 3.13.
-
Py_TPFLAGS_IS_ABSTRACT¶
This bit indicates that this is an abstract type and therefore cannot be instantiated.
継承:
このフラグは継承されません。
参考
-
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.
-
Py_TPFLAGS_HEAPTYPE¶
-
const char *PyTypeObject.tp_doc¶
The corresponding slot ID
Py_tp_docis part of the Stable ABI.この型オブジェクトのドキュメント文字列を表す、NUL 終端の C 文字列への省略可能なポインタです。 型とそのインスタンスの
__doc__属性として公開されます。継承:
サブタイプはこのフィールドを継承 しません 。
-
traverseproc PyTypeObject.tp_traverse¶
The corresponding slot ID
Py_tp_traverseis 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_GCflag bit is set. The signature is:int tp_traverse(PyObject *self, visitproc visit, void *arg);
Pythonのガベージコレクションの仕組みについての詳細は、 循環参照ガベージコレクションをサポートする にあります。
The
tp_traversepointer is used by the garbage collector to detect reference cycles. A typical implementation of atp_traversefunction simply callsPy_VISIT()on each of the instance's members that are Python objects that the instance owns. For example, this is functionlocal_traverse()from the_threadextension 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 thetp_weaklistslot, 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 tolocal_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 callingtp_traverseof 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_clearis 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_GCflag bit is set. The signature is:int tp_clear(PyObject *);
The
tp_clearmember function is used to break reference cycles in cyclic garbage detected by the garbage collector. Taken together, alltp_clearfunctions in the system must combine to break all reference cycles. This is subtle, and if in any doubt supply atp_clearfunction. For example, the tuple type does not implement atp_clearfunction, because it's possible to prove that no reference cycle can be composed entirely of tuples. Therefore thetp_clearfunctions 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 implementingtp_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_DICTbit is set in thetp_flagsfield, the clear function must callPyObject_ClearManagedDict()like this:PyObject_ClearManagedDict((PyObject*)self);
Note that
tp_clearis 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 andtp_deallocis called directly.Because the goal of
tp_clearfunctions 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'stp_deallocfunction to invoketp_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_richcompareis 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_Typeprovides atp_richcompareimplementation, which may be inherited. However, if onlytp_hashis defined, not even the inherited function is used and instances of the type will not be able to participate in any comparisons.-
Py_LT¶
-
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_iteris part of the Stable ABI.オプションの変数で、そのオブジェクトの イテレータ を返す関数へのポインタです。この値が存在することは、通常この型のインスタンスが イテレート可能 であることを示しています (しかし、シーケンスはこの関数がなくてもイテレート可能です)。
この関数は
PyObject_GetIter()と同じシグネチャを持っています:PyObject *tp_iter(PyObject *self);
継承:
サブタイプはこのフィールドを継承します。
-
iternextfunc PyTypeObject.tp_iternext¶
The corresponding slot ID
Py_tp_iternextis 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_methodsis part of the Stable ABI.オプションのポインタで、この型の正規 (regular) のメソッドを宣言している
PyMethodDef構造体からなる、NULLで終端された静的な配列を指します。配列の各要素ごとに、メソッドデスクリプタの入った、要素が型の辞書 (下記の
tp_dict参照) に追加されます。継承:
サブタイプはこのフィールドを継承しません (メソッドは別個のメカニズムで継承されています)。
-
struct PyMemberDef *PyTypeObject.tp_members¶
The corresponding slot ID
Py_tp_membersis part of the Stable ABI.オプションのポインタで、型の正規 (regular) のデータメンバ (フィールドおよびスロット) を宣言している
PyMemberDef構造体からなる、NULLで終端された静的な配列を指します。配列の各要素ごとに、メンバデスクリプタの入った要素が型の辞書 (下記の
tp_dict参照) に追加されます。継承:
サブタイプはこのフィールドを継承しません (メンバは別個のメカニズムで継承されています)。
-
struct PyGetSetDef *PyTypeObject.tp_getset¶
The corresponding slot ID
Py_tp_getsetis part of the Stable ABI.オプションのポインタで、インスタンスの算出属性 (computed attribute) を宣言している
PyGetSetDef構造体からなる、NULLで終端された静的な配列を指します。配列の各要素ごとに、 getter/setter デスクリプタの入った、要素が型の辞書 (下記の
tp_dict参照) に追加されます。継承:
サブタイプはこのフィールドを継承しません (算出属性は別個のメカニズムで継承されています)。
-
PyTypeObject *PyTypeObject.tp_base¶
The corresponding slot ID
Py_tp_baseis part of the Stable ABI.オプションのポインタで、型に関するプロパティを継承する基底タイプを指します。このフィールドのレベルでは、単継承 (single inheritance) だけがサポートされています; 多重継承はメタタイプの呼び出しによる動的な型オブジェクトの生成を必要とします。
注釈
スロットの初期化には、グローバル変数の初期化の規則が適用されます。 C99 では、初期化子は「アドレス定数」である必要があります。
PyType_GenericNew()などの関数指示子は、暗黙にポインタへ変換され、有効な C99 のアドレス定数になります。However, the unary '&' operator applied to a non-static variable like
PyBaseObject_Typeis 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_getis 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_setis 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_initis 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_allocis 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_TypeusesPyType_GenericAlloc(). That is the recommended value for all statically defined types.
-
newfunc PyTypeObject.tp_new¶
The corresponding slot ID
Py_tp_newis 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_freeis 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 thePy_TPFLAGS_HAVE_GCflag bit.For static subtypes,
PyBaseObject_TypeusesPyObject_Del().
-
inquiry PyTypeObject.tp_is_gc¶
The corresponding slot ID
Py_tp_is_gcis 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_basesis part of the Stable ABI.基底型からなるタプルです。
このフィールドは
NULLに設定し、読み取り専用として扱うべきです。 型が初期化されるときに、Python が設定します。For dynamically created classes, the
Py_tp_basesslotcan be used instead of the bases argument ofPyType_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_delis part of the Stable ABI.このフィールドは非推奨です。 代わりに
tp_finalizeを使ってください。
-
unsigned int PyTypeObject.tp_version_tag¶
メソッドキャッシュへのインデックスとして使われます。内部使用だけのための関数です。
継承:
このフィールドは継承されません。
-
destructor PyTypeObject.tp_finalize¶
The corresponding slot ID
Py_tp_finalizeis part of the Stable ABI (バージョン 3.5 より).インスタンスのファイナライズ関数への省略可能なポインタです。 特殊メソッド
__del__()の C 実装に相当します。 シグネチャは次のとおりです。void tp_finalize(PyObject *self);
If
tp_finalizeis 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_finalizeshould 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__. Iftp_vectorcallisNULL, 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_addis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_subtract¶
The corresponding slot ID
Py_nb_subtractis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_multiply¶
The corresponding slot ID
Py_nb_multiplyis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_remainder¶
The corresponding slot ID
Py_nb_remainderis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_divmod¶
The corresponding slot ID
Py_nb_divmodis part of the Stable ABI.
-
ternaryfunc PyNumberMethods.nb_power¶
The corresponding slot ID
Py_nb_poweris part of the Stable ABI.
-
unaryfunc PyNumberMethods.nb_negative¶
The corresponding slot ID
Py_nb_negativeis part of the Stable ABI.
-
unaryfunc PyNumberMethods.nb_positive¶
The corresponding slot ID
Py_nb_positiveis part of the Stable ABI.
-
unaryfunc PyNumberMethods.nb_absolute¶
The corresponding slot ID
Py_nb_absoluteis part of the Stable ABI.
-
inquiry PyNumberMethods.nb_bool¶
The corresponding slot ID
Py_nb_boolis part of the Stable ABI.
-
unaryfunc PyNumberMethods.nb_invert¶
The corresponding slot ID
Py_nb_invertis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_lshift¶
The corresponding slot ID
Py_nb_lshiftis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_rshift¶
The corresponding slot ID
Py_nb_rshiftis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_and¶
The corresponding slot ID
Py_nb_andis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_xor¶
The corresponding slot ID
Py_nb_xoris part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_or¶
The corresponding slot ID
Py_nb_oris part of the Stable ABI.
-
unaryfunc PyNumberMethods.nb_int¶
The corresponding slot ID
Py_nb_intis part of the Stable ABI.
-
void *PyNumberMethods.nb_reserved¶
-
unaryfunc PyNumberMethods.nb_float¶
The corresponding slot ID
Py_nb_floatis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_add¶
The corresponding slot ID
Py_nb_inplace_addis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_subtract¶
The corresponding slot ID
Py_nb_inplace_subtractis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_multiply¶
The corresponding slot ID
Py_nb_inplace_multiplyis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_remainder¶
The corresponding slot ID
Py_nb_inplace_remainderis part of the Stable ABI.
-
ternaryfunc PyNumberMethods.nb_inplace_power¶
The corresponding slot ID
Py_nb_inplace_poweris part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_lshift¶
The corresponding slot ID
Py_nb_inplace_lshiftis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_rshift¶
The corresponding slot ID
Py_nb_inplace_rshiftis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_and¶
The corresponding slot ID
Py_nb_inplace_andis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_xor¶
The corresponding slot ID
Py_nb_inplace_xoris part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_or¶
The corresponding slot ID
Py_nb_inplace_oris part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_floor_divide¶
The corresponding slot ID
Py_nb_floor_divideis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_true_divide¶
The corresponding slot ID
Py_nb_true_divideis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_floor_divide¶
The corresponding slot ID
Py_nb_inplace_floor_divideis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_inplace_true_divide¶
The corresponding slot ID
Py_nb_inplace_true_divideis part of the Stable ABI.
-
unaryfunc PyNumberMethods.nb_index¶
The corresponding slot ID
Py_nb_indexis part of the Stable ABI.
-
binaryfunc PyNumberMethods.nb_matrix_multiply¶
The corresponding slot ID
Py_nb_matrix_multiplyis part of the Stable ABI (バージョン 3.5 より).
-
binaryfunc PyNumberMethods.nb_inplace_matrix_multiply¶
The corresponding slot ID
Py_nb_inplace_matrix_multiplyis part of the Stable ABI (バージョン 3.5 より).
マップオブジェクト構造体¶
-
type PyMappingMethods¶
この構造体はマップ型プロトコルを実装するために使われる関数群へのポインタを保持しています。 以下の3つのメンバを持っています:
-
lenfunc PyMappingMethods.mp_length¶
The corresponding slot ID
Py_mp_lengthis part of the Stable ABI.この関数は
PyMapping_Size()やPyObject_Size()から利用され、それらと同じシグネチャを持っています。オブジェクトが定義された長さを持たない場合は、このスロットはNULLに設定されることがあります。
-
binaryfunc PyMappingMethods.mp_subscript¶
The corresponding slot ID
Py_mp_subscriptis 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_subscriptis 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_lengthis part of the Stable ABI.この関数は
PySequence_Size()とPyObject_Size()で使われ、それらと同じシグネチャを持ちます。sq_itemスロットやsq_ass_itemスロットを使う際の、負のインデックスの処理にも使われます。
-
binaryfunc PySequenceMethods.sq_concat¶
The corresponding slot ID
Py_sq_concatis part of the Stable ABI.この関数は
PySequence_Concat()で利用され、同じシグネチャを持っています。また、+演算子でも、nb_addスロットによる数値加算を試した後に利用されます。
-
ssizeargfunc PySequenceMethods.sq_repeat¶
The corresponding slot ID
Py_sq_repeatis part of the Stable ABI.この関数は
PySequence_Repeat()で利用され、同じシグネチャを持っています。また、*演算でも、nb_multiplyスロットによる数値乗算を試したあとに利用されます。
-
ssizeargfunc PySequenceMethods.sq_item¶
The corresponding slot ID
Py_sq_itemis 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_itemis 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_containsis part of the Stable ABI.この関数は
PySequence_Contains()から利用され、同じシグネチャを持っています。このスロットはNULLの場合があり、その時PySequence_Contains()はシンプルにマッチするオブジェクトを見つけるまでシーケンスを巡回します。
-
binaryfunc PySequenceMethods.sq_inplace_concat¶
The corresponding slot ID
Py_sq_inplace_concatis 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_repeatis 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_getbufferis part of the Stable ABI (バージョン 3.11 より).この関数のシグネチャは以下の通りです:
int (PyObject *exporter, Py_buffer *view, int flags);
flags で指定された方法で view を埋めてほしいという exporter に対する要求を処理します。ステップ(3) を除いて、この関数の実装では以下のステップを行わなければなりません:
Check if the request can be met. If not, raise
BufferError, setview->objtoNULLand return-1.要求されたフィールドを埋めます。
エクスポートした回数を保持する内部カウンタをインクリメントします。
Set
view->objto exporter and incrementview->obj.0を返します。
exporter がバッファプロバイダのチェインかツリーの一部であれば、2つの主要な方式が使用できます:
Re-export: Each member of the tree acts as the exporting object and sets
view->objto a new reference to itself.Redirect: The buffer request is redirected to the root object of the tree. Here,
view->objwill 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_releasebufferis part of the Stable ABI (バージョン 3.11 より).この関数のシグネチャは以下の通りです:
void (PyObject *exporter, Py_buffer *view);
バッファのリソースを開放する要求を処理します。もし開放する必要のあるリソースがない場合、
PyBufferProcs.bf_releasebufferはNULLにしても構いません。そうでない場合は、この関数の標準的な実装は、以下の任意の処理手順 (optional step) を行います:エクスポートした回数を保持する内部カウンタをデクリメントします。
カウンタが
0の場合は、view に関連付けられた全てのメモリを解放します。
エクスポータは、バッファ固有のリソースを管理するために
internalフィールドを使わなければなりません。 このフィールドの値は変わらないことが保証されますが、コンシューマは元のバッファのコピーを view 引数として渡しても構いません。This function MUST NOT decrement
view->obj, since that is done automatically inPyBuffer_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_awaitis 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_aiteris part of the Stable ABI (バージョン 3.5 より).この関数のシグネチャは以下の通りです:
PyObject *am_aiter(PyObject *self);
非同期イテレータ オブジェクトを返さなければなりません。 詳細は
__anext__()を参照してください。オブジェクトが非同期反復処理のプロトコルを実装していない場合、このスロットを
NULLに設定します。
-
unaryfunc PyAsyncMethods.am_anext¶
The corresponding slot ID
Py_am_anextis part of the Stable ABI (バージョン 3.5 より).この関数のシグネチャは以下の通りです:
PyObject *am_anext(PyObject *self);
待機可能 オブジェクトを返さなければなりません。 詳細は
__anext__()を参照してください。 このスロットはNULLにできます。
-
sendfunc PyAsyncMethods.am_send¶
The corresponding slot ID
Py_am_sendis 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 PyObject *(*newfunc)(PyTypeObject*, PyObject*, PyObject*)¶
- 次に属します: Stable ABI.
tp_newを参照してください。
-
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 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 *),
};