型オブジェクト¶
新スタイルの型を定義する構造体: 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__ |
~ |
|||
[ |
|
|||||
|
__subclasses__ |
|||||
|
||||||
( |
||||||
unsigned int |
||||||
__del__ |
X |
|||||
- 1
(): A slot name in parentheses indicates it is (effectively) deprecated.
<>: Names in angle brackets should be initially set to
NULLand treated as read-only.[]: Names in square brackets are for internal use only.
<R> (as a prefix) means the field is required (must be non-
NULL).- 2
列:
"O": set on
PyBaseObject_Type"T": set on
PyType_Type"D": default (if slot is set to
NULL)X - PyType_Ready sets this value if it is NULL ~ - PyType_Ready always sets this value (it should be NULL) ? - PyType_Ready may set this value depending on other slots Also see the inheritance column ("I")."I": inheritance
X - type slot is inherited via *PyType_Ready* if defined with a *NULL* value % - the slots of the sub-struct are inherited individually G - inherited, but only in combination with other slots; see the slot's description ? - it's complicated; see the slot's description
Note that some slots are effectively inherited through the normal attribute lookup chain.
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__ |
||
スロットの定義型 (typedef)¶
定義型 (typedef) |
引数型 |
返り値型 |
|---|---|---|
|
||
void * |
void |
|
void * |
void |
|
int |
||
|
||
int |
||
|
|
|
PyObject *const char *
|
|
|
int |
||
|
||
int |
||
|
||
int |
||
|
Py_hash_t |
|
|
||
|
|
|
|
|
|
|
||
int |
||
void |
||
void * |
int |
|
PyObject * |
|
|
|
||
|
||
|
||
int |
||
int |
||
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;
} PyTypeObject;
PyObject スロット¶
型オブジェクト構造体は PyVarObject 構造体を拡張したものです。 ob_size フィールドは、(通常 class 文が呼び出す type_new() で生成される) 動的な型に使います。 PyType_Type (メタタイプ) は tp_itemsize を初期化するので注意してください。すなわち、 インスタンス (つまり型オブジェクト) には ob_size フィールドが存在しなければ なりません 。
-
Py_ssize_t
PyObject.ob_refcnt¶ - Part of the Stable ABI.
型オブジェクトの参照カウントで、
PyObject_HEAD_INITはこの値を1に初期化します。静的にメモリ確保された型オブジェクト では、型のインスタンス (ob_typeが該当する型を指しているオブジェクト) は参照をカウントする対象には なりません 。動的にメモリ確保される型オブジェクト の場合、インスタンスは参照カウントの対象に なります 。継承:
サブタイプはこのフィールドを継承しません。
-
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;
上の操作は、該当する型のいかなるインスタンス生成よりも前にしておかなければなりません。
PyType_Ready()はob_typeがNULLかどうか調べ、NULLの場合には基底クラスのob_typeフィールドで初期化します。 ob_type フィールドがゼロでない場合、PyType_Ready()はこのフィールドを変更しません。継承:
サブタイプはこのフィールドを継承します。
-
PyObject *
PyObject._ob_next¶ -
PyObject *
PyObject._ob_prev¶ These fields are only present when the macro
Py_TRACE_REFSis defined (see theconfigure --with-trace-refs option).Their initialization to
NULLis taken care of by thePyObject_HEAD_INITmacro. For statically allocated objects, these fields always remainNULL. 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 variablePYTHONDUMPREFSis 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¶ 型の名前が入っている NUL 終端された文字列へのポインタです。モジュールのグローバル変数としてアクセスできる型の場合、この文字列は完全なモジュール名、ドット、そして型の名前と続く文字列になります; 組み込み型の場合、ただの型の名前です。モジュールがあるパッケージのサブモジュールの場合、完全なパッケージ名が完全なモジュール名の一部になっています。例えば、パッケージ
P内のサブモジュールQに入っているモジュールM内で定義されているTは、tp_nameを"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 inPyTypeObject()(other than potentiallytp_itemsize).継承:
サブタイプはこのフィールドを継承しません。
-
Py_ssize_t
PyTypeObject.tp_basicsize¶ -
Py_ssize_t
PyTypeObject.tp_itemsize¶ これらのフィールドは、型インスタンスのバイトサイズを計算できるようにします。
型には二つの種類があります: 固定長インスタンスの型は、
tp_itemsizeフィールドがゼロで、可変長インスタンスの方はtp_itemsizeフィールドが非ゼロの値になります。固定長インスタンスの型の場合、全てのインスタンスは等しくtp_basicsizeで与えられたサイズになります。可変長インスタンスの型の場合、インスタンスには
ob_sizeフィールドがなくてはならず、インスタンスのサイズは N をオブジェクトの "長さ" として、tp_basicsizeとtp_itemsizeの N 倍を足したものになります。 N の値は通常、インスタンスのob_sizeフィールドに記憶されます。ただし例外がいくつかあります: 例えば、整数では負の値をob_sizeに使って、インスタンスの表す値が負であることを示し、 N 自体はabs(ob_size)になります。また、ob_sizeフィールドがあるからといって、必ずしもインスタンスが可変長であることを意味しません (例えば、 リスト型の構造体は固定長のインスタンスになるにもかかわらず、インスタンスにはちゃんと意味を持ったob_sizeフィールドがあります)。基本サイズには、
PyObject_HEADマクロまたはPyObject_VAR_HEADマクロ (インスタンス構造体を宣言するのに使ったどちらかのマクロ) で宣言されているフィールドが入っています。さらに、_ob_prevおよび_ob_nextフィールドがある場合、これらのフィールドもサイズに加算されます。従って、tp_basicsizeの正しい初期化値を得るには、インスタンスデータのレイアウトを宣言するのに使う構造体に対してsizeof演算子を使うしかありません。基本サイズには、GC ヘッダサイズは入っていません。アラインメントに関する注釈: 変数の各要素を配置する際に特定のアラインメントが必要となる場合、
tp_basicsizeの値に気をつけなければなりません。例: ある型がdoubleの配列を実装しているとします。tp_itemsizeはsizeof(double)です。tp_basicsizeがsizeof(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¶ インスタンスのデストラクタ関数へのポインタです。この関数は (単量子
NoneやEllipsisの場合のように) インスタンスが決してメモリ解放されない型でない限り必ず定義しなければなりません。シグネチャは次の通りです:void tp_dealloc(PyObject *self);
デストラクタ関数は、参照カウントが新たにゼロになった際に
Py_DECREF()やPy_XDECREF()マクロから呼び出されます。呼び出された時点では、インスタンスはまだ存在しますが、インスタンスに対する参照は全くない状態です。デストラクタ関数はインスタンスが保持している全ての参照を解放し、インスタンスが確保している全てのメモリバッファを (バッファの確保時に使った関数に対応するメモリ解放関数を使って) 解放し、その型のtp_free関数を呼び出します。ある型がサブタイプを作成できない (Py_TPFLAGS_BASETYPEフラグがセットされていない) 場合、tp_freeの代わりにオブジェクトのメモリ解放関数 (deallocator) を直接呼び出してもかまいません。オブジェクトのメモリ解放関数は、インスタンスのメモリ確保を行う際に使った関数に対応したものでなければなりません; インスタンスをPyObject_New()やPyObject_VarNew()でメモリ 確保した場合には、通常PyObject_Del()を使い、PyObject_GC_New()やPyObject_GC_NewVar()で確保した場合にはPyObject_GC_Del()を使います。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); }
継承:
サブタイプはこのフィールドを継承します。
-
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_VECTORCALLis set. If so, this must be a positive integer containing the offset in the instance of avectorcallfuncpointer.The vectorcallfunc pointer may be
NULL, in which case the instance behaves as ifPy_TPFLAGS_HAVE_VECTORCALLwas not set: calling the instance falls back totp_call.Any class that sets
Py_TPFLAGS_HAVE_VECTORCALLmust also settp_calland make sure its behaviour is consistent with the vectorcallfunc function. This can be done by setting tp_call toPyVectorcall_Call().警告
It is not recommended for 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.バージョン 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.継承:
This field is always inherited. However, the
Py_TPFLAGS_HAVE_VECTORCALLflag is not always inherited. If it's not, then the subclass won't use vectorcall, except whenPyVectorcall_Call()is explicitly called. This is in particular the case for heap types (including subclasses defined in Python).
-
getattrfunc
PyTypeObject.tp_getattr¶ オプションのポインタで、get-attribute-string を行う関数を指します。
このフィールドは非推奨です。 このフィールドを定義するときは、
tp_getattro関数と同じように動作し、属性名は Python 文字列 オブジェクトではなく C 文字列で指定するような関数を指すようにしなければなりません。継承:
Group:
tp_getattr,tp_getattroこのフィールドは
tp_getattroと共にサブタイプに継承されます: すなわち、サブタイプのtp_getattrおよびtp_getattroが共にNULLの場合、サブタイプは基底タイプからtp_getattrとtp_getattroを両方とも継承します。
-
setattrfunc
PyTypeObject.tp_setattr¶ オプションのポインタで、属性の設定と削除を行う関数を指します。
このフィールドは非推奨です。 このフィールドを定義するときは、
tp_setattro関数と同じように動作し、属性名は Python 文字列 オブジェクトではなく C 文字列で指定するような関数を指すようにしなければなりません。継承:
Group:
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 オブジェクト構造体 を参照してください。
バージョン 3.5 で追加: 以前は
tp_compareやtp_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_richcompareis not set), an attempt to take the hash of the object raisesTypeError. This is the same as setting it toPyObject_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_richcompareとtp_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_getattrとtp_getattroを両方とも継承します。デフォルト
PyBaseObject_TypeusesPyObject_GenericGetAttr().
-
setattrofunc
PyTypeObject.tp_setattro¶ オプションのポインタで、属性の設定と削除を行う関数を指します。
The signature is the same as for
PyObject_SetAttr():int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);
さらに、value に
NULLを指定して属性を削除できるようにしなければなりません。 通常のオブジェクト属性設定を実装しているPyObject_GenericSetAttr()をこのフィールドに設定しておくとたいていの場合は便利です。継承:
Group:
tp_setattr,tp_setattroこのフィールドは
tp_setattrと共にサブタイプに継承されます: すなわち、サブタイプのtp_setattrおよびtp_setattroが共にNULLの場合、サブタイプは基底タイプからtp_setattrとtp_setattroを両方とも継承します。デフォルト
PyBaseObject_TypeusesPyObject_GenericSetAttr().
-
PyBufferProcs *
PyTypeObject.tp_as_buffer¶ バッファインターフェースを実装しているオブジェクトにのみ関連する、一連のフィールド群が入った別の構造体を指すポインタです。構造体内の各フィールドは バッファオブジェクト構造体 (buffer object structure) で説明します。
継承:
tp_as_bufferフィールド自体は継承されませんが、これに含まれるフィールドは個別に継承されます。
-
unsigned long
PyTypeObject.tp_flags¶ このフィールドは様々なフラグからなるビットマスクです。いくつかのフラグは、特定の状況において変則的なセマンティクスが適用されることを示します; その他のフラグは、型オブジェクト (あるいは
tp_as_number、tp_as_sequence、tp_as_mapping、 およびtp_as_bufferが参照している拡張機能構造体) の特定のフィールドのうち、過去から現在までずっと存在していたわけではないものが有効になっていることを示すために使われます; フラグビットがクリアされていれば、フラグが保護しているフィールドにはアクセスしない代わりに、その値はゼロかNULLになっているとみなさなければなりません。継承:
このフィールドの継承は込み入っています。ほとんどのフラグは個別に継承されます。すなわち、基底タイプのフラグビットが設定されていたら、サブタイプのフラグビットもそれを引き継ぎます。拡張機能構造体が継承される場合は、拡張機能構造体に関係するフラグビットは厳密に継承されます。すなわち、基底タイプのフラグビットの値は、拡張機能構造体へのポインタと共に、サブタイプにコピーされます。
Py_TPFLAGS_HAVE_GCフラグビットはtp_traverseフィールドとtp_clearフィールドと共に継承されます。すなわち、サブタイプにおいて、Py_TPFLAGS_HAVE_GCフラグビットがクリアされていて、tp_traverseフィールドとtp_clearフィールドが存在しNULLになっている場合に継承されます。デフォルト
PyBaseObject_TypeusesPy_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, theob_typefield 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¶ オブジェクトがガベージコレクション (GC) をサポートする場合にセットされるビットです。このビットがセットされている場合、インスタンスは
PyObject_GC_New()を使って生成し、PyObject_GC_Del()を使って破棄しなければなりません。詳しい情報は 循環参照ガベージコレクションをサポートする にあります。このビットは、GC に関連するフィールドtp_traverseおよびtp_clearが型オブジェクト内に存在することも示しています。継承:
Group:
Py_TPFLAGS_HAVE_GC,tp_traverse,tp_clearThe
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.
-
Py_TPFLAGS_DEFAULT¶ 型オブジェクトおよび拡張機能構造体の特定のフィールドの存在の有無に関連する全てのビットからなるビットマスクです。現状では、このビットマスクには以下のビット:
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)(withobjnot None) must be equivalent tometh(obj, *args, **kwds).meth.__get__(None, cls)(*args, **kwds)must be equivalent tometh(*args, **kwds).
This flag enables an optimization for typical method calls like
obj.meth(): it avoids creating a temporary "bound method" object forobj.meth.バージョン 3.8 で追加.
継承:
This flag is never inherited by heap types. For extension types, it is inherited whenever
tp_descr_getis 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_finalizeslot 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_offsetfor details.継承:
This bit is inherited for static subtypes if
tp_callis also inherited. Heap types do not inheritPy_TPFLAGS_HAVE_VECTORCALL.バージョン 3.9 で追加.
-
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_newto 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_baseis NULL or&PyBaseObject_Typeandtp_newis 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_newonly 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
matchblock. It is automatically set when registering or subclassingcollections.abc.Mapping, and unset when registeringcollections.abc.Sequence.注釈
Py_TPFLAGS_MAPPINGandPy_TPFLAGS_SEQUENCEare 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
matchblock. It is automatically set when registering or subclassingcollections.abc.Sequence, and unset when registeringcollections.abc.Mapping.注釈
Py_TPFLAGS_MAPPINGandPy_TPFLAGS_SEQUENCEare 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 で追加.
-
-
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_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()関数は循環参照になり得ないメンバも返します。警告
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).Py_VISIT()はlocal_traverse()が visit と arg という決まった名前の引数を持つことを要求します。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 で変更: Heap-allocated types are expected to visit
Py_TYPE(self)intp_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このフィールドは
tp_clearおよびPy_TPFLAGS_HAVE_GCフラグビットと共にサブタイプに継承されます: すなわち、サブタイプのtp_traverseおよびtp_clearが両方ともゼロの場合、サブタイプは基底タイプからtp_traverseとtp_clearを両方とも継承します。
-
inquiry
PyTypeObject.tp_clear¶ オプションのポインタで、ガベージコレクタにおける消去関数 (clear function) を指します。
Py_TPFLAGS_HAVE_GCがセットされている場合にのみ使われます。シグネチャは次の通りです: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 (viaPy_DECREF()) until after the pointer to the contained object is set toNULL. 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 beNULLat that time, so that self knows the contained object can no longer be used. ThePy_CLEAR()macro performs the operations in a safe order.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.tp_clear関数の目的は参照カウントを破壊することなので、 Python 文字列や Python 整数のような、循環参照に含むことのできないオブジェクトをクリアする必要はありません。一方、所有する全ての Python オブジェクトをクリアするようにし、その型のtp_dealloc関数がtp_clear関数を実行するようにすると実装が楽になるでしょう。Pythonのガベージコレクションの仕組みについての詳細は、 循環参照ガベージコレクションをサポートする にあります。
継承:
Group:
Py_TPFLAGS_HAVE_GC,tp_traverse,tp_clearこのフィールドは
tp_traverseおよびPy_TPFLAGS_HAVE_GCフラグビットと共にサブタイプに継承されます: すなわち、サブタイプのtp_traverseおよびtp_clearが両方ともゼロの場合、サブタイプは基底タイプからtp_traverseとtp_clearを両方とも継承します。
-
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_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()と同様に要求された演算を指定します。The returned value is a new strong reference.
エラー時には例外を設定して、関数から
NULLでリターンします。バージョン 3.7 で追加.
継承:
Group:
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_ssize_t
PyTypeObject.tp_weaklistoffset¶ 型のインスタンスが弱参照可能な場合、このフィールドはゼロよりも大きな数になり、インスタンス構造体における弱参照リストの先頭を示すオフセットが入ります (GC ヘッダがある場合には無視します); このオフセット値は
PyObject_ClearWeakRefs()およびPyWeakref_*関数が利用します。インスタンス構造体には、NULLに初期化されたPyObject*型のフィールドが入っていなければなりません。このフィールドを
tp_weaklistと混同しないようにしてください; これは型オブジェクト自身への弱参照からなるリストの先頭です。継承:
このフィールドはサブタイプに継承されますが、以下の規則を読んでください。サブタイプはこのオフセット値をオーバライドすることがあります; 従って、サブタイプでは弱参照リストの先頭が基底タイプとは異なる場合があります。リストの先頭は常に
tp_weaklistoffsetで分かるはずなので、このことは問題にはならないはずです。class文で定義された型に__slots__宣言が全くなく、かつ基底タイプが弱参照可能でない場合、その型を弱参照可能にするには弱参照リストの先頭を表すスロットをインスタンスデータレイアウト構造体に追加し、スロットのオフセットをtp_weaklistoffsetに設定します。型の
__slots__の宣言に__weakref__という名前のスロットが含まれているとき、スロットはその型のインスタンスにおける弱参照リストの先頭を表すスロットになり、スロットのオフセットが型のtp_weaklistoffsetに入ります。型の
__slots__宣言が__weakref__という名前のスロットを含んでいないとき、その型は基底タイプからtp_weaklistoffsetを継承します。
-
getiterfunc
PyTypeObject.tp_iter¶ オプションの変数で、そのオブジェクトの イテレータ を返す関数へのポインタです。この値が存在することは、通常この型のインスタンスが イテレート可能 であることを示しています (しかし、シーケンスはこの関数がなくてもイテレート可能です)。
この関数は
PyObject_GetIter()と同じシグネチャを持っています:PyObject *tp_iter(PyObject *self);
継承:
サブタイプはこのフィールドを継承します。
-
iternextfunc
PyTypeObject.tp_iternext¶ オプションのポインタで、イテレーター の次の要素を返す関数を指します。シグネチャは次の通りです:
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_baseshould be set in the extension module's init function.継承:
(当たり前ですが) サブタイプはこのフィールドを継承しません。
デフォルト
このフィールドのデフォルト値は (Python プログラマは
object型として知っている)&PyBaseObject_Typeになります。
-
PyObject *
PyTypeObject.tp_dict¶ 型の辞書は
PyType_Ready()によってこのフィールドに収められます。このフィールドは通常、
PyType_Ready()を呼び出す前にNULLに初期化しておかなければなりません; あるいは、型の初期属性の入った辞書で初期化しておいてもかまいません。PyType_Ready()が型をひとたび初期化すると、型の新たな属性をこの辞書に追加できるのは、属性が (__add__()のような) オーバロード用演算でないときだけです。継承:
サブタイプはこのフィールドを継承しません (が、この辞書内で定義されている属性は異なるメカニズムで継承されます)。
デフォルト
If this field is
NULL,PyType_Ready()will assign a new dictionary to it.警告
tp_dictにPyDict_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¶ 型のインスタンスにインスタンス変数の入った辞書がある場合、このフィールドは非ゼロの値になり、型のインスタンスデータ構造体におけるインスタンス変数辞書へのオフセットが入ります; このオフセット値は
PyObject_GenericGetAttr()が使います。このフィールドを
tp_dictと混同しないようにしてください; これは型オブジェクト自身の属性の辞書です。このフィールドの値がゼロより大きければ、値はインスタンス構造体の先頭からの オフセットを表します。値がゼロより小さければ、インスタンス構造体の 末尾 からのオフセットを表します。負のオフセットを使うコストは比較的高くつくので、 インスタンス構造体に可変長部分があるときのみ使うべきです。例えば、
strやtupleのサブタイプにインスタンス変数の辞書を追加する場合には、負のオフセットを使います。この場合、たとえ辞書が基本のオブジェクトレイアウトに含まれていなくても、tp_basicsizeフィールドは追加された辞書を考慮にいれなければならないことに注意してください。ポインタサイズが 4 バイトのシステムでは、 構造体の最後尾に辞書が宣言されていることを示す場合、tp_dictoffsetを-4にしなければなりません。負の
tp_dictoffsetから、インスタンスでの実際のオフセットを計算するには以下のようにします:dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset if dictoffset is not aligned on sizeof(void*): round up to sizeof(void*)
ここで、
tp_basicsize、tp_itemsizeおよびtp_dictoffsetは型オブジェクトから取り出され、ob_sizeはインスタンスから取り出されます。 絶対値を取っているのは、整数は符号を記憶するのにob_sizeの符号を使うためです。 (この計算を自分で行う必要はまったくありません; 計算は_PyObject_GetDictPtr()がやってくれます。)継承:
このフィールドはサブタイプに継承されますが、以下の規則を読んでください。サブタイプはこのオフセット値をオーバライドすることがあります; 従って、サブタイプでは辞書のオフセットが基底タイプとは異なる場合があります。辞書のオフセットは常に
tp_dictoffsetで分かるはずなので、このことは問題にはならないはずです。class文で定義された型に__slots__宣言がなく、かつ基底タイプの全てにインスタンス変数辞書がない場合、辞書のスロットをインスタンスデータレイアウト構造体に追加し、スロットのオフセットをtp_dictoffsetに設定します。class文で定義された型に__slots__宣言がある場合、この型は基底タイプからtp_dictoffsetを継承します。(
__dict__という名前のスロットを__slots__宣言に追加しても、期待どおりの効果は得られず、単に混乱を招くだけになります。とはいえ、これは将来__weakref__のように追加されるはずです。)デフォルト
This slot has no default. For static types, if the field is
NULLthen no__dict__gets created for instances.
-
initproc
PyTypeObject.tp_init¶ オプションのポインタで、インスタンス初期化関数を指します。
この関数はクラスにおける
__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を返します。継承:
サブタイプはこのフィールドを継承します。
デフォルト
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_TypeusesPyType_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 引数は、型を呼び出すときの位置引数およびキーワード引数です。subtype は
tp_new関数を呼び出すときに使う型と同じである必要はないことに注意してください; その型の (無関係ではない) サブタイプのこともあります。tp_new関数はsubtype->tp_alloc(subtype, nitems)を呼び出してオブジェクトのメモリ領域を確保し、初期化で絶対に必要とされる処理だけを行います。省略したり繰り返したりしても問題のない初期化処理はtp_initハンドラ内に配置しなければなりません。だいたいの目安としては、変更不能な型では初期化は全てtp_newで行い、一方、変更可能な型ではほとんどの初期化をtp_initに回すべきです。Set the
Py_TPFLAGS_DISALLOW_INSTANTIATIONflag to disallow creating instances of the type in Python.継承:
サブタイプはこのフィールドを継承します。例外として、
tp_baseがNULLか&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 thePy_TPFLAGS_HAVE_GCflag bit.For static subtypes,
PyBaseObject_Typeuses PyObject_Del.
-
inquiry
PyTypeObject.tp_is_gc¶ オプションのポインタで、ガベージコレクタから呼び出される関数を指します。
ガベージコレクタは、オブジェクトを回収して良いかどうかを知る必要があります。通常は、オブジェクトの型の
tp_flagsフィールドを見て、Py_TPFLAGS_HAVE_GCフラグビットを調べるだけで十分です。しかし、ある型では静的にメモリ確保されたインスタンスと動的にメモリ確保されたインスタンスが混じっていて、静的にメモリ確保されたインスタンスは回収できません。こうした型では、関数を定義しなければなりません; 関数はインスタンスが回収可能の場合には1を、回収不能の場合には0を返さねばなりません。シグネチャは:int tp_is_gc(PyObject *self);
(上記のような型の例は、型オブジェクト自体です。メタタイプ
PyType_Typeは、型のメモリ確保が静的か 動的 かを区別するためにこの関数を定義しています。)継承:
サブタイプはこのフィールドを継承します。
デフォルト
This slot has no default. If this field is
NULL,Py_TPFLAGS_HAVE_GCis used as the functional equivalent.
-
PyObject *
PyTypeObject.tp_bases¶ 基底型からなるタプルです。
This field should be set to
NULLand treated as read-only. Python will fill it in when the type isinitialized.For dynamically created classes, the
Py_tp_basesslotcan be used instead of the bases argument ofPyType_FromSpecWithBases(). The argument form is preferred.警告
Multiple inheritance does not work well for statically defined types. If you set
tp_basesto 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
NULLand treated as read-only. Python will fill it in when the type isinitialized.継承:
このフィールドは継承されません; フィールドの値は
PyType_Ready()で毎回計算されます。
-
PyObject *
PyTypeObject.tp_cache¶ 未使用のフィールドです。内部でのみ利用されます。
継承:
このフィールドは継承されません。
-
PyObject *
PyTypeObject.tp_subclasses¶ サブクラスへの弱参照からなるリストです。内部で使用するためだけのものです。
継承:
このフィールドは継承されません。
-
PyObject *
PyTypeObject.tp_weaklist¶ この型オブジェクトに対する弱参照からなるリストの先頭です。
継承:
このフィールドは継承されません。
-
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_FINALIZEflags 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__. Iftp_vectorcallisNULL, the default call implementation using__new__and__init__is used.継承:
このフィールドは決して継承されません。
バージョン 3.9 で追加: (このフィールドは3.8から存在していますが、3.9以降でしか利用できません)
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(),
or PyType_FromModuleAndSpec().
数値オブジェクト構造体¶
-
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¶
-
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()から利用され、PyObject_GetItem()と同じシグネチャを持っています。このスロットはPyMapping_Check()が1を返すためには必要で、そうでなければNULLの場合があります。
-
objobjargproc
PyMappingMethods.mp_ass_subscript¶ この関数は
PyObject_SetItem()、PyObject_DelItem()、PyObject_SetSlice()およびPyObject_DelSlice()から利用されます。PyObject_SetItem()と同じシグネチャを持ちますが、 v にNULLを設定して要素の削除もできます。このスロットがNULLの場合は、このオブジェクトはアイテムの代入と削除をサポートしません。
シーケンスオブジェクト構造体¶
-
type
PySequenceMethods¶ この構造体はシーケンス型プロトコルを実装するために使われる関数群へのポインタを保持しています。
-
lenfunc
PySequenceMethods.sq_length¶ This function is used by
PySequence_Size()andPyObject_Size(), and has the same signature. It is also used for handling negative indices via thesq_itemand thesq_ass_itemslots.
-
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 byPyObject_GetItem(), after trying the subscription via themp_subscriptslot. This slot must be filled for thePySequence_Check()function to return1, it can beNULLotherwise.負のインデックスは次のように処理されます:
sq_lengthスロットが埋められていれば、それを呼び出してシーケンスの長さから正のインデックスを計算し、sq_itemに渡します。sq_lengthがNULLの場合は、インデックスはそのままこの関数に渡されます。
-
ssizeobjargproc
PySequenceMethods.sq_ass_item¶ This function is used by
PySequence_SetItem()and has the same signature. It is also used byPyObject_SetItem()andPyObject_DelItem(), after trying the item assignment and deletion via themp_ass_subscriptslot. This slot may be left toNULLif 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 toNULL, in this casePySequence_InPlaceConcat()will fall back toPySequence_Concat(). It is also used by the augmented assignment+=, after trying numeric in-place addition via thenb_inplace_addslot.
-
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 toNULL, in this casePySequence_InPlaceRepeat()will fall back toPySequence_Repeat(). It is also used by the augmented assignment*=, after trying numeric in-place multiplication via thenb_inplace_multiplyslot.
バッファオブジェクト構造体 (buffer object structure)¶
-
type
PyBufferProcs¶ この構造体は buffer プロトコル が要求する関数群へのポインタを保持しています。 そのプロトコルは、エクスポーターオブジェクトが如何にして、その内部データをコンシューマオブジェクトに渡すかを定義します。
-
getbufferproc
PyBufferProcs.bf_getbuffer¶ この関数のシグネチャは以下の通りです:
int (PyObject *exporter, Py_buffer *view, int flags);
flags で指定された方法で view を埋めてほしいという exporter に対する要求を処理します。ステップ(3) を除いて、この関数の実装では以下のステップを行わなければなりません:
リクエストが合致するか確認します。 合致しない場合は、
PyExc_BufferErrorを送出し、view->objにNULLを設定し-1を返します。要求されたフィールドを埋めます。
エクスポートした回数を保持する内部カウンタをインクリメントします。
view->objに exporter を設定し、view->objをインクリメントします。0を返します。
exporter がバッファプロバイダのチェインかツリーの一部であれば、2つの主要な方式が使用できます:
再エクスポート: ツリーの各要素がエクスポートされるオブジェクトとして振る舞い、自身への新しい参照を
view->objへセットします。リダイレクト: バッファ要求がツリーのルートオブジェクトにリダイレクトされます。ここでは、
view->objはルートオブジェクトへの新しい参照になります。
view の個別のフィールドは バッファ構造体 の節で説明されており、エクスポートが特定の要求に対しどう対応しなければならないかの規則は、 バッファ要求のタイプ の節にあります。
Py_buffer構造体の中から参照している全てのメモリはエクスポータに属し、コンシューマがいなくなるまで有効でなくてはなりません。format、shape、strides、suboffsets、internalはコンシューマからは読み出し専用です。PyBuffer_FillInfo()は、全てのリクエストタイプを正しく扱う際に、単純なバイトバッファを公開する簡単な方法を提供します。PyObject_GetBuffer()は、この関数をラップするコンシューマ向けのインターフェースです。
-
releasebufferproc
PyBufferProcs.bf_releasebuffer¶ この関数のシグネチャは以下の通りです:
void (PyObject *exporter, Py_buffer *view);
バッファのリソースを開放する要求を処理します。もし開放する必要のあるリソースがない場合、
PyBufferProcs.bf_releasebufferはNULLにしても構いません。そうでない場合は、この関数の標準的な実装は、以下の任意の処理手順 (optional step) を行います:エクスポートした回数を保持する内部カウンタをデクリメントします。
カウンタが
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);
asynchronous iterator オブジェクトを返さなければなりません。 詳しいことは
__anext__()を参照してください。オブジェクトが非同期反復処理のプロトコルを実装していない場合、このスロットを
NULLに設定します。
-
unaryfunc
PyAsyncMethods.am_anext¶ この関数のシグネチャは以下の通りです:
PyObject *am_anext(PyObject *self);
awaitable オブジェクトを返さなければなりません。 詳しいことは
__anext__()を参照してください。 このスロットはNULLに設定されていることもあります。
-
sendfunc
PyAsyncMethods.am_send¶ この関数のシグネチャは以下の通りです:
PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);
See
PyIter_Send()for details. This slot may be set toNULL.バージョン 3.10 で追加.
Slot Type typedefs¶
-
typedef PyObject *(*
allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)¶ - Part of the Stable ABI.
この関数の目的は、メモリ確保をメモリ初期化から分離することにあります。この関数は、インスタンス用の的確なサイズ、適切なアラインメント、ゼロによる初期化がなされ、
ob_refcntを1に、ob_typeを型引数 (type argument) にセットしたメモリブロックへのポインタを返さねばなりません。型のtp_itemsizeがゼロでない場合、オブジェクトのob_sizeフィールドは nitems に初期化され、確保されるメモリブロックの長さはtp_basicsize + nitems*tp_itemsizeをsizeof(void*)の倍数に切り上げた値になるはずです; それ以外の場合、 nitems の値は使われず、メモリブロックの長さはtp_basicsizeになるはずです。この関数では他のいかなるインスタンス初期化も行ってはなりません。追加のメモリ割り当てすらも行ってはなりません。そのような処理は
tp_newで行われるべきです。
-
typedef void (*
destructor)(PyObject*)¶ - Part of the Stable ABI.
-
typedef PyObject *(*
newfunc)(PyObject*, PyObject*, PyObject*)¶ - Part of the Stable ABI.
tp_newを参照してください。
-
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 PyObject *(*
unaryfunc)(PyObject*)¶ - Part of the Stable ABI.
-
typedef PyObject *(*
binaryfunc)(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 の型定義の簡単な例をいくつか挙げます。これらの例にはあなたが遭遇する共通的な利用例を含んでいます。いくつかの例ではトリッキーなコーナーケースを実演しています。より多くの例や実践的な情報、チュートリアルが必要なら、拡張の型の定義: チュートリアル や 拡張の型の定義: 雑多なトピック を参照してください。
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;
PyObject *inst_dict;
PyObject *weakreflist;
} 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_weaklistoffset = offsetof(MyObject, weakreflist),
.tp_dictoffset = offsetof(MyObject, inst_dict),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
.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 *),
};