# Type Object Structures

新スタイルの型を定義する構造体: `PyTypeObject` 構造体は、おそらく Python オブジェクトシステムの中で最も重要な構造体の1つでしょう。型オブジェクトは `PyObject_*` 系や `PyType_*` 系の関数で扱えますが、ほとんどの Python アプリケーションにとって、さして面白みのある機能を提供しません。型オブジェクトはオブジェクトがどのように振舞うかを決める基盤ですから、インタプリタ自体や新たな型を定義する拡張モジュールでは非常に重要な存在です。

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

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

## クイックリファレンス

### tp スロット

PyTypeObject スロット [1] | 型 | 特殊メソッド/特殊属性 | Info [2]
--- | --- | --- | ---
O | T | D | I
<R> `tp_name` | const char * | __name__ | X | X |  |
`tp_basicsize` | `Py_ssize_t` |  | X | X |  | X
`tp_itemsize` | `Py_ssize_t` |  |  | X |  | X
`tp_dealloc` | `destructor` |  | X | X |  | X
`tp_vectorcall_offset` | `Py_ssize_t` |  |  | X |  | X
(`tp_getattr`) | `getattrfunc` | __getattribute__, __getattr__ |  |  |  | G
(`tp_setattr`) | `setattrfunc` | __setattr__, __delattr__ |  |  |  | G
`tp_as_async` | `PyAsyncMethods` * | sub-slots |  |  |  | %
`tp_repr` | `reprfunc` | __repr__ | X | X |  | X
`tp_as_number` | `PyNumberMethods` * | sub-slots |  |  |  | %
`tp_as_sequence` | `PySequenceMethods` * | sub-slots |  |  |  | %
`tp_as_mapping` | `PyMappingMethods` * | sub-slots |  |  |  | %
`tp_hash` | `hashfunc` | __hash__ | X |  |  | G
`tp_call` | `ternaryfunc` | __call__ |  | X |  | X
`tp_str` | `reprfunc` | __str__ | X |  |  | X
`tp_getattro` | `getattrofunc` | __getattribute__, __getattr__ | X | X |  | G
`tp_setattro` | `setattrofunc` | __setattr__, __delattr__ | X | X |  | G
`tp_as_buffer` | `PyBufferProcs` * | sub-slots |  |  |  | %
`tp_flags` | unsigned long |  | X | X |  | ?
`tp_doc` | const char * | __doc__ | X | X |  |
`tp_traverse` | `traverseproc` |  |  | X |  | G
`tp_clear` | `inquiry` |  |  | X |  | G
`tp_richcompare` | `richcmpfunc` | __lt__, __le__, __eq__, __ne__, __gt__, __ge__ | X |  |  | G
(`tp_weaklistoffset`) | `Py_ssize_t` |  |  | X |  | ?
`tp_iter` | `getiterfunc` | __iter__ |  |  |  | X
`tp_iternext` | `iternextfunc` | __next__ |  |  |  | X
`tp_methods` | `PyMethodDef` [] |  | X | X |  |
`tp_members` | `PyMemberDef` [] |  |  | X |  |
`tp_getset` | `PyGetSetDef` [] |  | X | X |  |
`tp_base` | `PyTypeObject` * | __base__ |  |  | X |
`tp_dict` | `PyObject` * | __dict__ |  |  | ? |
`tp_descr_get` | `descrgetfunc` | __get__ |  |  |  | X
`tp_descr_set` | `descrsetfunc` | __set__, __delete__ |  |  |  | X
(`tp_dictoffset`) | `Py_ssize_t` |  |  | X |  | ?
`tp_init` | `initproc` | __init__ | X | X |  | X
`tp_alloc` | `allocfunc` |  | X |  | ? | ?
`tp_new` | `newfunc` | __new__ | X | X | ? | ?
`tp_free` | `freefunc` |  | X | X | ? | ?
`tp_is_gc` | `inquiry` |  |  | X |  | X
<`tp_bases`> | `PyObject` * | __bases__ |  |  | ~ |
<`tp_mro`> | `PyObject` * | __mro__ |  |  | ~ |
[`tp_cache`] | `PyObject` * |  |  |  |
[`tp_subclasses`] | void * | __subclasses__ |  |  |
[`tp_weaklist`] | `PyObject` * |  |  |  |
(`tp_del`) | `destructor` |  |  |  |  |
[`tp_version_tag`] | unsigned int |  |  |  |
`tp_finalize` | `destructor` | __del__ |  |  |  | X
`tp_vectorcall` | `vectorcallfunc` |  |  |  |  |
[`tp_watched`] | unsigned char |  |  |  |  |

[1]

(): A slot name in parentheses indicates it is (effectively) deprecated.

<>: Names in angle brackets should be initially set to `NULL` and 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 | 型 | 特殊メソッド
--- | --- | ---
`am_await` | `unaryfunc` | __await__
`am_aiter` | `unaryfunc` | __aiter__
`am_anext` | `unaryfunc` | __anext__
`am_send` | `sendfunc` |
`nb_add` | `binaryfunc` | __add__ __radd__
`nb_inplace_add` | `binaryfunc` | __iadd__
`nb_subtract` | `binaryfunc` | __sub__ __rsub__
`nb_inplace_subtract` | `binaryfunc` | __isub__
`nb_multiply` | `binaryfunc` | __mul__ __rmul__
`nb_inplace_multiply` | `binaryfunc` | __imul__
`nb_remainder` | `binaryfunc` | __mod__ __rmod__
`nb_inplace_remainder` | `binaryfunc` | __imod__
`nb_divmod` | `binaryfunc` | __divmod__ __rdivmod__
`nb_power` | `ternaryfunc` | __pow__ __rpow__
`nb_inplace_power` | `ternaryfunc` | __ipow__
`nb_negative` | `unaryfunc` | __neg__
`nb_positive` | `unaryfunc` | __pos__
`nb_absolute` | `unaryfunc` | __abs__
`nb_bool` | `inquiry` | __bool__
`nb_invert` | `unaryfunc` | __invert__
`nb_lshift` | `binaryfunc` | __lshift__ __rlshift__
`nb_inplace_lshift` | `binaryfunc` | __ilshift__
`nb_rshift` | `binaryfunc` | __rshift__ __rrshift__
`nb_inplace_rshift` | `binaryfunc` | __irshift__
`nb_and` | `binaryfunc` | __and__ __rand__
`nb_inplace_and` | `binaryfunc` | __iand__
`nb_xor` | `binaryfunc` | __xor__ __rxor__
`nb_inplace_xor` | `binaryfunc` | __ixor__
`nb_or` | `binaryfunc` | __or__ __ror__
`nb_inplace_or` | `binaryfunc` | __ior__
`nb_int` | `unaryfunc` | __int__
`nb_reserved` | void * |
`nb_float` | `unaryfunc` | __float__
`nb_floor_divide` | `binaryfunc` | __floordiv__
`nb_inplace_floor_divide` | `binaryfunc` | __ifloordiv__
`nb_true_divide` | `binaryfunc` | __truediv__
`nb_inplace_true_divide` | `binaryfunc` | __itruediv__
`nb_index` | `unaryfunc` | __index__
`nb_matrix_multiply` | `binaryfunc` | __matmul__ __rmatmul__
`nb_inplace_matrix_multiply` | `binaryfunc` | __imatmul__
`mp_length` | `lenfunc` | __len__
`mp_subscript` | `binaryfunc` | __getitem__
`mp_ass_subscript` | `objobjargproc` | __setitem__, __delitem__
`sq_length` | `lenfunc` | __len__
`sq_concat` | `binaryfunc` | __add__
`sq_repeat` | `ssizeargfunc` | __mul__
`sq_item` | `ssizeargfunc` | __getitem__
`sq_ass_item` | `ssizeobjargproc` | __setitem__ __delitem__
`sq_contains` | `objobjproc` | __contains__
`sq_inplace_concat` | `binaryfunc` | __iadd__
`sq_inplace_repeat` | `ssizeargfunc` | __imul__
`bf_getbuffer` | `getbufferproc()` | __buffer__
`bf_releasebuffer` | `releasebufferproc()` | __release_buffer__

### スロットの定義型 (typedef)

定義型 (typedef) | 引数型 | 返り値型
--- | --- | ---
`allocfunc` | `PyTypeObject` * `Py_ssize_t` | `PyObject` *
`destructor` | `PyObject` * | void
`freefunc` | void * | void
`traverseproc` | `PyObject` * `visitproc` void * | int
`newfunc` | `PyTypeObject` * `PyObject` * `PyObject` * | `PyObject` *
`initproc` | `PyObject` * `PyObject` * `PyObject` * | int
`reprfunc` | `PyObject` * | `PyObject` *
`getattrfunc` | `PyObject` * const char * | `PyObject` *
`setattrfunc` | `PyObject` * const char * `PyObject` * | int
`getattrofunc` | `PyObject` * `PyObject` * | `PyObject` *
`setattrofunc` | `PyObject` * `PyObject` * `PyObject` * | int
`descrgetfunc` | `PyObject` * `PyObject` * `PyObject` * | `PyObject` *
`descrsetfunc` | `PyObject` * `PyObject` * `PyObject` * | int
`hashfunc` | `PyObject` * | Py_hash_t
`richcmpfunc` | `PyObject` * `PyObject` * int | `PyObject` *
`getiterfunc` | `PyObject` * | `PyObject` *
`iternextfunc` | `PyObject` * | `PyObject` *
`lenfunc` | `PyObject` * | `Py_ssize_t`
`getbufferproc` | `PyObject` * `Py_buffer` * int | int
`releasebufferproc` | `PyObject` * `Py_buffer` * | void
`inquiry` | `PyObject` * | int
`unaryfunc` | `PyObject` * | `PyObject` *
`binaryfunc` | `PyObject` * `PyObject` * | `PyObject` *
`ternaryfunc` | `PyObject` * `PyObject` * `PyObject` * | `PyObject` *
`ssizeargfunc` | `PyObject` * `Py_ssize_t` | `PyObject` *
`ssizeobjargproc` | `PyObject` * `Py_ssize_t` `PyObject` * | int
`objobjproc` | `PyObject` * `PyObject` * | int
`objobjargproc` | `PyObject` * `PyObject` * `PyObject` * | int

See Slot Type typedefs below for more detail.

## PyTypeObject 定義

The structure definition for `PyTypeObject` can be found in `Include/cpython/object.h`. For convenience of reference, this repeats the definition found there:

    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 */
        PyMethodDef *tp_methods;
        PyMemberDef *tp_members;
        PyGetSetDef *tp_getset;
        // Strong reference on a heap type, borrowed reference on a static type
        PyTypeObject *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; /* no longer used */
        void *tp_subclasses;  /* for static builtin types this is an index */
        PyObject *tp_weaklist; /* not used for static builtin types */
        destructor tp_del;

        /* Type attribute cache version tag. Added in version 2.6.
         * If zero, the cache is invalid and must be initialized.
         */
        unsigned int tp_version_tag;

        destructor tp_finalize;
        vectorcallfunc tp_vectorcall;

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

        /* Number of tp_version_tag values used.
         * Set to _Py_ATTR_CACHE_UNUSED if the attribute cache is
         * disabled for this type (e.g. due to custom MRO entries).
         * Otherwise, limited to MAX_VERSIONS_PER_CLASS (defined elsewhere).
         */
        uint16_t tp_versions_used;
    } PyTypeObject;

## PyObject スロット

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

`PyObject.ob_refcnt`

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

> 継承:

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

`PyObject.ob_type`

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

>     Foo_Type.ob_type = &PyType_Type;

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

> 継承:

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

## PyVarObject スロット

`PyVarObject.ob_size`

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

> This field should be accessed using the `Py_SIZE()` macro.

> 継承:

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

## PyTypeObject スロット

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

const char *PyTypeObject.tp_name

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

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

  For statically allocated type objects, the tp_name field should contain a dot. Everything before the last dot is made accessible as the `__module__` attribute, and everything after the last dot is made accessible as the `__name__` attribute.

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

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

  継承:

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

Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize

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

  There are two kinds of types: types with fixed-length instances have a zero `tp_itemsize` field, types with variable-length instances have a non-zero `tp_itemsize` field. For a type with fixed-length instances, all instances have the same size, given in `tp_basicsize`. (Exceptions to this rule can be made using `PyUnstable_Object_GC_NewWithExtraData()`.)

  For a type with variable-length instances, the instances must have an `ob_size` field, and the instance size is `tp_basicsize` plus N times `tp_itemsize`, where N is the "length" of the object.

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

  注釈

  The `ob_size` field should be accessed using the `Py_SIZE()` and `Py_SET_SIZE()` macros.

  Also, the presence of an `ob_size` field in the instance layout doesn't mean that the instance structure is variable-length. For example, the `list` type has fixed-length instances, yet those instances have a `ob_size` field. (As with `int`, avoid reading lists' `ob_size` directly. Call `PyList_Size()` instead.)

  The `tp_basicsize` includes size needed for data of the type's `tp_base`, plus any extra data needed by each instance.

  The correct way to set `tp_basicsize` is to use the `sizeof` operator on the struct used to declare the instance layout. This struct must include the struct used to declare the base type. In other words, `tp_basicsize` must be greater than or equal to the base's `tp_basicsize`.

  Since every type is a subtype of `object`, this struct must include `PyObject` or `PyVarObject` (depending on whether `ob_size` should be included). These are usually defined by the macro `PyObject_HEAD` or `PyObject_VAR_HEAD`, respectively.

  The basic size does not include the GC header size, as that header is not part of `PyObject_HEAD`.

  For cases where struct used to declare the base type is unknown, see `PyType_Spec.basicsize` and `PyType_FromMetaclass()`.

  Notes about alignment:

  - `tp_basicsize` must be a multiple of `_Alignof(PyObject)`. When using `sizeof` on a `struct` that includes `PyObject_HEAD`, as recommended, the compiler ensures this. When not using a C `struct`, or when using compiler extensions like `__attribute__((packed))`, it is up to you.

  - If the variable items require a particular alignment, `tp_basicsize` and `tp_itemsize` must each be a multiple of that alignment. For example, if a type's variable part stores a `double`, it is your responsibility that both fields are a multiple of `_Alignof(double)`.

  継承:

  These fields are inherited separately by subtypes. (That is, if the field is set to zero, `PyType_Ready()` will copy the value from the base type, indicating that the instances do not need additional storage.)

  If the base type has a non-zero `tp_itemsize`, it is generally not safe to set `tp_itemsize` to a different non-zero value in a subtype (though this depends on the implementation of the base type).

destructor PyTypeObject.tp_dealloc

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

  A pointer to the instance destructor function. The function signature is:

      void tp_dealloc(PyObject *self);

  The destructor function should remove all references which the instance owns (e.g., call `Py_CLEAR()`), free all memory buffers owned by the instance, and call the type's `tp_free` function to free the object itself.

  If you may call functions that may set the error indicator, you must use `PyErr_GetRaisedException()` and `PyErr_SetRaisedException()` to ensure you don't clobber a preexisting error indicator (the deallocation could have occurred while processing a different error):

      static void
      foo_dealloc(foo_object *self)
      {
          PyObject *et, *ev, *etb;
          PyObject *exc = PyErr_GetRaisedException();
          ...
          PyErr_SetRaisedException(exc);
      }

  The dealloc handler itself must not raise an exception; if it hits an error case it should call `PyErr_FormatUnraisable()` to log (and clear) an unraisable exception.

  No guarantees are made about when an object is destroyed, except:

  - Python will destroy an object immediately or some time after the final reference to the object is deleted, unless its finalizer (`tp_finalize`) subsequently resurrects the object.

  - An object will not be destroyed while it is being automatically finalized (`tp_finalize`) or automatically cleared (`tp_clear`).

  CPython currently destroys an object immediately from `Py_DECREF()` when the new reference count is zero, but this may change in a future version.

  It is recommended to call `PyObject_CallFinalizerFromDealloc()` at the beginning of `tp_dealloc` to guarantee that the object is always finalized before destruction.

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

  It is permissible to call `tp_clear` from `tp_dealloc` to reduce code duplication and to guarantee that the object is always cleared before destruction. Beware that `tp_clear` might have already been called.

  If the type is heap allocated (`Py_TPFLAGS_HEAPTYPE`), the deallocator should release the owned reference to its type object (via `Py_DECREF()`) after calling the type deallocator. See the example code below.:

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

  `tp_dealloc` must leave the exception status unchanged. If it needs to call something that might raise an exception, the exception state must be backed up first and restored later (after logging any exceptions with `PyErr_WriteUnraisable()`).

  以下はプログラム例です:

      static void
      foo_dealloc(PyObject *self)
      {
          PyObject *exc = PyErr_GetRaisedException();

          if (PyObject_CallFinalizerFromDealloc(self) < 0) {
              // self was resurrected.
              goto done;
          }

          PyTypeObject *tp = Py_TYPE(self);

          if (tp->tp_flags & Py_TPFLAGS_HAVE_GC) {
              PyObject_GC_UnTrack(self);
          }

          // Optional, but convenient to avoid code duplication.
          if (tp->tp_clear && tp->tp_clear(self) < 0) {
              PyErr_WriteUnraisable(self);
          }

          // Any additional destruction goes here.

          tp->tp_free(self);
          self = NULL;  // In case PyErr_WriteUnraisable() is called below.

          if (tp->tp_flags & Py_TPFLAGS_HEAPTYPE) {
              Py_CLEAR(tp);
          }

      done:
          // Optional, if something was called that might have raised an
          // exception.
          if (PyErr_Occurred()) {
              PyErr_WriteUnraisable(self);
          }
          PyErr_SetRaisedException(exc);
      }

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

  継承:

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

  参考

  Object Life Cycle for details about how this slot relates to other slots.

Py_ssize_t PyTypeObject.tp_vectorcall_offset

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

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

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

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

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

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

  継承:

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

getattrfunc PyTypeObject.tp_getattr

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

  オプションのポインタで、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

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

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

  このフィールドは非推奨です。 このフィールドを定義するときは、 `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 オブジェクト構造体 を参照してください。

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

  継承:

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

reprfunc PyTypeObject.tp_repr

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

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

  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

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

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

  The signature is the same as for `PyObject_Hash()`:

      Py_hash_t tp_hash(PyObject *);

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

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

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

  継承:

  Group: `tp_hash`, `tp_richcompare`

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

  デフォルト

  `PyBaseObject_Type` uses `PyObject_GenericHash()`.

ternaryfunc PyTypeObject.tp_call

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

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

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

  継承:

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

reprfunc PyTypeObject.tp_str

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

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

  The signature is the same as for `PyObject_Str()`:

      PyObject *tp_str(PyObject *self);

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

  継承:

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

  デフォルト

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

getattrofunc PyTypeObject.tp_getattro

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

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

  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_Type` uses `PyObject_GenericGetAttr()`.

setattrofunc PyTypeObject.tp_setattro

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

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

  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_Type` uses `PyObject_GenericSetAttr()`.

PyBufferProcs *PyTypeObject.tp_as_buffer

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

  継承:

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

unsigned long PyTypeObject.tp_flags

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

  継承:

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

  デフォルト

  `PyBaseObject_Type` uses `Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE`.

  Bit Masks:

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

  Py_TPFLAGS_HEAPTYPE

    This bit is set when the type object itself is allocated on the heap, for example, types created dynamically using `PyType_FromSpec()`. In this case, the `ob_type` field of its instances is considered a reference to the type, and the type object is INCREF'ed when a new instance is created, and DECREF'ed when an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the instance's ob_type gets INCREF'ed or DECREF'ed). Heap types should also support garbage collection as they can form a reference cycle with their own module object.

    継承:

    ???

  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, memory for new instances (see `tp_alloc`) must be allocated using `PyObject_GC_New` or `PyType_GenericAlloc()` and deallocated (see `tp_free`) using `PyObject_GC_Del()`. More information in section 循環参照ガベージコレクションをサポートする.

    継承:

    Group: `Py_TPFLAGS_HAVE_GC`, `tp_traverse`, `tp_clear`

    The `Py_TPFLAGS_HAVE_GC` flag bit is inherited together with the `tp_traverse` and `tp_clear` fields, i.e. if the `Py_TPFLAGS_HAVE_GC` flag bit is clear in the subtype and the `tp_traverse` and `tp_clear` fields in the subtype exist and have `NULL` values.

  Py_TPFLAGS_DEFAULT
    次に属します: Stable ABI.

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

    継承:

    ???

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

    This bit indicates that objects behave like unbound methods.

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

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

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

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

    Added in version 3.8.

    継承:

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

  Py_TPFLAGS_MANAGED_DICT

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

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

    The type traverse function must call `PyObject_VisitManagedDict()` and its clear function must call `PyObject_ClearManagedDict()`.

    Added in version 3.12.

    継承:

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

  Py_TPFLAGS_MANAGED_WEAKREF

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

    Added in version 3.12.

    継承:

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

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

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

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

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

    Added in version 3.12.

    継承:

    This flag is inherited.

  Py_TPFLAGS_LONG_SUBCLASS
  Py_TPFLAGS_LIST_SUBCLASS
  Py_TPFLAGS_TUPLE_SUBCLASS
  Py_TPFLAGS_BYTES_SUBCLASS
  Py_TPFLAGS_UNICODE_SUBCLASS
  Py_TPFLAGS_DICT_SUBCLASS
  Py_TPFLAGS_BASE_EXC_SUBCLASS
  Py_TPFLAGS_TYPE_SUBCLASS

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

  Py_TPFLAGS_HAVE_FINALIZE

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

    Added in version 3.4.

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

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

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

    継承:

    This bit is inherited if `tp_call` is also inherited.

    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 で変更: This flag is now removed from a class when the class's `__call__()` method is reassigned.

    This flag can now be inherited by mutable classes.

  Py_TPFLAGS_IMMUTABLETYPE

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

    `PyType_Ready()` automatically applies this flag to static types.

    継承:

    This flag is not inherited.

    Added in version 3.10.

  Py_TPFLAGS_DISALLOW_INSTANTIATION

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

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

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

    継承:

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

    注釈

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

    Added in version 3.10.

  Py_TPFLAGS_MAPPING

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

    注釈

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

    継承:

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

    参考

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

    Added in version 3.10.

  Py_TPFLAGS_SEQUENCE

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

    注釈

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

    継承:

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

    参考

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

    Added in version 3.10.

  Py_TPFLAGS_VALID_VERSION_TAG

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

    警告

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

  Py_TPFLAGS_HAVE_VERSION_TAG

    This macro does nothing. Historically, this would indicate that the `tp_version_tag` field was available and initialized.

    Soft deprecated since version 3.13.

  Py_TPFLAGS_INLINE_VALUES

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

    This requires that `Py_TPFLAGS_HAVE_GC` is set.

    継承:

    This flag is not inherited.

    Added in version 3.13.

  Py_TPFLAGS_IS_ABSTRACT

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

    継承:

    This flag is not inherited.

    参考

    `abc`

  Py_TPFLAGS_HAVE_STACKLESS_EXTENSION

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

    警告

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

const char *PyTypeObject.tp_doc

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

  An optional pointer to a NUL-terminated C string giving the docstring for this type object. This is exposed as the `__doc__` attribute on the type and instances of the type.

  継承:

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

traverseproc PyTypeObject.tp_traverse

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

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

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

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

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

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

  Note that `Py_VISIT()` is called only on those members that can participate in reference cycles. Although there is also a `self->key` member, it can only be `NULL` or a Python string and therefore cannot be part of a reference cycle.

  On the other hand, even if you know a member can never be part of a cycle, as a debugging aid you may want to visit it anyway just so the `gc` module's `get_referents()` function will include it.

  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

  If the `Py_TPFLAGS_MANAGED_DICT` bit is set in the `tp_flags` field, the traverse function must call `PyObject_VisitManagedDict()` like this:

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

  警告

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

  警告

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

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

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

  注釈

  The `tp_traverse` function can be called from any thread.

  バージョン 3.9 で変更: Heap-allocated types are expected to visit `Py_TYPE(self)` in `tp_traverse`. In earlier versions of Python, due to bug 40217, doing this may lead to crashes in subclasses.

  継承:

  Group: `Py_TPFLAGS_HAVE_GC`, `tp_traverse`, `tp_clear`

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

inquiry PyTypeObject.tp_clear

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

  An optional pointer to a clear function. The signature is:

      int tp_clear(PyObject *);

  The purpose of this function is to break reference cycles that are causing a cyclic isolate so that the objects can be safely destroyed. A cleared object is a partially destroyed object; the object is not obligated to satisfy design invariants held during normal use.

  `tp_clear` does not need to delete references to objects that can't participate in reference cycles, such as Python strings or Python integers. However, it may be convenient to clear all references, and write the type's `tp_dealloc` function to invoke `tp_clear` to avoid code duplication. (Beware that `tp_clear` might have already been called. Prefer calling idempotent functions like `Py_CLEAR()`.)

  Any non-trivial cleanup should be performed in `tp_finalize` instead of `tp_clear`.

  注釈

  If `tp_clear` fails to break a reference cycle then the objects in the cyclic isolate may remain indefinitely uncollectable ("leak"). See `gc.garbage`.

  注釈

  Referents (direct and indirect) might have already been cleared; they are not guaranteed to be in a consistent state.

  注釈

  The `tp_clear` function can be called from any thread.

  注釈

  An object is not guaranteed to be automatically cleared before its destructor (`tp_dealloc`) is called.

  This function differs from the destructor (`tp_dealloc`) in the following ways:

  - The purpose of clearing an object is to remove references to other objects that might participate in a reference cycle. The purpose of the destructor, on the other hand, is a superset: it must release all resources it owns, including references to objects that cannot participate in a reference cycle (e.g., integers) as well as the object's own memory (by calling `tp_free`).

  - When `tp_clear` is called, other objects might still hold references to the object being cleared. Because of this, `tp_clear` must not deallocate the object's own memory (`tp_free`). The destructor, on the other hand, is only called when no (strong) references exist, and as such, must safely destroy the object itself by deallocating it.

  - `tp_clear` might never be automatically called. An object's destructor, on the other hand, will be automatically called some time after the object becomes unreachable (i.e., either there are no references to the object or the object is a member of a cyclic isolate).

  No guarantees are made about when, if, or how often Python automatically clears an object, except:

  - Python will not automatically clear an object if it is reachable, i.e., there is a reference to it and it is not a member of a cyclic isolate.

  - Python will not automatically clear an object if it has not been automatically finalized (see `tp_finalize`). (If the finalizer resurrected the object, the object may or may not be automatically finalized again before it is cleared.)

  - If an object is a member of a cyclic isolate, Python will not automatically clear it if any member of the cyclic isolate has not yet been automatically finalized (`tp_finalize`).

  - Python will not destroy an object until after any automatic calls to its `tp_clear` function have returned. This ensures that the act of breaking a reference cycle does not invalidate the `self` pointer while `tp_clear` is still executing.

  - Python will not automatically call `tp_clear` multiple times concurrently.

  CPython currently only automatically clears objects as needed to break reference cycles in a cyclic isolate, but future versions might clear objects regularly before their destruction.

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

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

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

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

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

      PyObject_ClearManagedDict((PyObject*)self);

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

  継承:

  Group: `Py_TPFLAGS_HAVE_GC`, `tp_traverse`, `tp_clear`

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

  参考

  Object Life Cycle for details about how this slot relates to other slots.

richcmpfunc PyTypeObject.tp_richcompare

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

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

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

  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` でリターンします。

    Added in version 3.7.

  継承:

  Group: `tp_hash`, `tp_richcompare`

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

  デフォルト

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

Py_ssize_t PyTypeObject.tp_weaklistoffset

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

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

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

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

  継承:

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

  デフォルト

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

getiterfunc PyTypeObject.tp_iter

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

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

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

      PyObject *tp_iter(PyObject *self);

  継承:

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

iternextfunc PyTypeObject.tp_iternext

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

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

      PyObject *tp_iternext(PyObject *self);

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

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

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

  継承:

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

struct PyMethodDef *PyTypeObject.tp_methods

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

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

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

  継承:

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

struct PyMemberDef *PyTypeObject.tp_members

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

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

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

  継承:

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

struct PyGetSetDef *PyTypeObject.tp_getset

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

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

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

  継承:

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

PyTypeObject *PyTypeObject.tp_base

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

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

  注釈

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

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

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

  継承:

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

  デフォルト

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

PyObject *PyTypeObject.tp_dict

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

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

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

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

  継承:

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

  デフォルト

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

  警告

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

descrgetfunc PyTypeObject.tp_descr_get

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

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

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

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

  継承:

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

descrsetfunc PyTypeObject.tp_descr_set

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

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

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

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

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

  継承:

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

Py_ssize_t PyTypeObject.tp_dictoffset

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

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

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

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

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

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

  継承:

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

  デフォルト

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

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

initproc PyTypeObject.tp_init

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

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

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

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

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

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

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

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

  継承:

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

  デフォルト

  For static types this field does not have a default.

allocfunc PyTypeObject.tp_alloc

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

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

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

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

  継承:

  Static subtypes inherit this slot, which will be `PyType_GenericAlloc()` if inherited from `object`.

  Heap subtypes do not inherit this slot.

  デフォルト

  For heap subtypes, this field is always set to `PyType_GenericAlloc()`.

  For static subtypes, this slot is inherited (see above).

newfunc PyTypeObject.tp_new

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

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

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

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

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

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

  Set the `Py_TPFLAGS_DISALLOW_INSTANTIATION` flag 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

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

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

      void tp_free(void *self);

  This function must free the memory allocated by `tp_alloc`.

  継承:

  Static subtypes inherit this slot, which will be `PyObject_Free()` if inherited from `object`. Exception: If the type supports garbage collection (i.e., the `Py_TPFLAGS_HAVE_GC` flag is set in `tp_flags`) and it would inherit `PyObject_Free()`, then this slot is not inherited but instead defaults to `PyObject_GC_Del()`.

  Heap subtypes do not inherit this slot.

  デフォルト

  For heap subtypes, this slot defaults to a deallocator suitable to match `PyType_GenericAlloc()` and the value of the `Py_TPFLAGS_HAVE_GC` flag.

  For static subtypes, this slot is inherited (see above).

inquiry PyTypeObject.tp_is_gc

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

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

  The garbage collector needs to know whether a particular object is collectible or not. Normally, it is sufficient to look at the object's type's `tp_flags` field, and check the `Py_TPFLAGS_HAVE_GC` flag bit. But some types have a mixture of statically and dynamically allocated instances, and the statically allocated instances are not collectible. Such types should define this function; it should return `1` for a collectible instance, and `0` for a non-collectible instance. The signature is:

      int tp_is_gc(PyObject *self);

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

  継承:

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

  デフォルト

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

PyObject *PyTypeObject.tp_bases

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

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

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

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

  警告

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

  継承:

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

PyObject *PyTypeObject.tp_mro

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

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

  継承:

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

PyObject *PyTypeObject.tp_cache

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

  継承:

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

void *PyTypeObject.tp_subclasses

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

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

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

  継承:

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

PyObject *PyTypeObject.tp_weaklist

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

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

  継承:

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

destructor PyTypeObject.tp_del

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

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

unsigned int PyTypeObject.tp_version_tag

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

  継承:

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

destructor PyTypeObject.tp_finalize

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

  An optional pointer to an instance finalization function. This is the C implementation of the `__del__()` special method. Its signature is:

      void tp_finalize(PyObject *self);

  The primary purpose of finalization is to perform any non-trivial cleanup that must be performed before the object is destroyed, while the object and any other objects it directly or indirectly references are still in a consistent state. The finalizer is allowed to execute arbitrary Python code.

  Before Python automatically finalizes an object, some of the object's direct or indirect referents might have themselves been automatically finalized. However, none of the referents will have been automatically cleared (`tp_clear`) yet.

  Other non-finalized objects might still be using a finalized object, so the finalizer must leave the object in a sane state (e.g., invariants are still met).

  注釈

  After Python automatically finalizes an object, Python might start automatically clearing (`tp_clear`) the object and its referents (direct and indirect). Cleared objects are not guaranteed to be in a consistent state; a finalized object must be able to tolerate cleared referents.

  注釈

  An object is not guaranteed to be automatically finalized before its destructor (`tp_dealloc`) is called. It is recommended to call `PyObject_CallFinalizerFromDealloc()` at the beginning of `tp_dealloc` to guarantee that the object is always finalized before destruction.

  注釈

  The `tp_finalize` function can be called from any thread, although the GIL will be held.

  注釈

  The `tp_finalize` function can be called during shutdown, after some global variables have been deleted. See the documentation of the `__del__()` method for details.

  When Python finalizes an object, it behaves like the following algorithm:

  1. Python might mark the object as finalized. Currently, Python always marks objects whose type supports garbage collection (i.e., the `Py_TPFLAGS_HAVE_GC` flag is set in `tp_flags`) and never marks other types of objects; this might change in a future version.

  2. If the object is not marked as finalized and its `tp_finalize` finalizer function is non-`NULL`, the finalizer function is called.

  3. If the finalizer function was called and the finalizer made the object reachable (i.e., there is a reference to the object and it is not a member of a cyclic isolate), then the finalizer is said to have resurrected the object. It is unspecified whether the finalizer can also resurrect the object by adding a new reference to the object that does not make it reachable, i.e., the object is (still) a member of a cyclic isolate.

  4. If the finalizer resurrected the object, the object's pending destruction is canceled and the object's finalized mark might be removed if present. Currently, Python never removes the finalized mark; this might change in a future version.

  Automatic finalization refers to any finalization performed by Python except via calls to `PyObject_CallFinalizer()` or `PyObject_CallFinalizerFromDealloc()`. No guarantees are made about when, if, or how often an object is automatically finalized, except:

  - Python will not automatically finalize an object if it is reachable, i.e., there is a reference to it and it is not a member of a cyclic isolate.

  - Python will not automatically finalize an object if finalizing it would not mark the object as finalized. Currently, this applies to objects whose type does not support garbage collection, i.e., the `Py_TPFLAGS_HAVE_GC` flag is not set. Such objects can still be manually finalized by calling `PyObject_CallFinalizer()` or `PyObject_CallFinalizerFromDealloc()`.

  - Python will not automatically finalize any two members of a cyclic isolate concurrently.

  - Python will not automatically finalize an object after it has automatically cleared (`tp_clear`) the object.

  - If an object is a member of a cyclic isolate, Python will not automatically finalize it after automatically clearing (see `tp_clear`) any other member.

  - Python will automatically finalize every member of a cyclic isolate before it automatically clears (see `tp_clear`) any of them.

  - If Python is going to automatically clear an object (`tp_clear`), it will automatically finalize the object first.

  Python currently only automatically finalizes objects that are members of a cyclic isolate, but future versions might finalize objects regularly before their destruction.

  To manually finalize an object, do not call this function directly; call `PyObject_CallFinalizer()` or `PyObject_CallFinalizerFromDealloc()` instead.

  `tp_finalize` should leave the current exception status unchanged. The recommended way to write a non-trivial finalizer is to back up the exception at the beginning by calling `PyErr_GetRaisedException()` and restore the exception at the end by calling `PyErr_SetRaisedException()`. If an exception is encountered in the middle of the finalizer, log and clear it with `PyErr_WriteUnraisable()` or `PyErr_FormatUnraisable()`. For example:

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

          // ...

          if (do_something_that_might_raise() != success_indicator) {
              PyErr_WriteUnraisable(self);
              goto done;
          }

      done:
          // Restore the saved exception.  This silently discards any exception
          // raised above, so be sure to call PyErr_WriteUnraisable first if
          // necessary.
          PyErr_SetRaisedException(exc);
      }

  継承:

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

  Added in version 3.4.

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

  参考

  - PEP 442: "Safe object finalization"

  - Object Life Cycle for details about how this slot relates to other slots.

  - `PyObject_CallFinalizer()`

  - `PyObject_CallFinalizerFromDealloc()`

vectorcallfunc PyTypeObject.tp_vectorcall

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

  A vectorcall function to use for calls of this type object (rather than instances). In other words, `tp_vectorcall` can be used to optimize `type.__call__`, which typically returns a new instance of type.

  As with any vectorcall function, if `tp_vectorcall` is `NULL`, the tp_call protocol (`Py_TYPE(type)->tp_call`) is used instead.

  注釈

  The vectorcall protocol requires that the vectorcall function has the same behavior as the corresponding `tp_call`. This means that `type->tp_vectorcall` must match the behavior of `Py_TYPE(type)->tp_call`.

  Specifically, if type uses the default metaclass, `type->tp_vectorcall` must behave the same as PyType_Type->tp_call, which:

  - calls `type->tp_new`,

  - if the result is a subclass of type, calls `type->tp_init` on the result of `tp_new`, and

  - returns the result of `tp_new`.

  Typically, `tp_vectorcall` is overridden to optimize this process for specific `tp_new` and `tp_init`. When doing this for user-subclassable types, note that both can be overridden (using `__new__()` and `__init__()`, respectively).

  継承:

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

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

unsigned char PyTypeObject.tp_watched

  Internal. Do not use.

  Added in version 3.12.

## Static Types

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

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

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

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

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

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

## Heap Types

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

This is done by filling a `PyType_Spec` structure and calling `PyType_FromSpec()`, `PyType_FromSpecWithBases()`, `PyType_FromModuleAndSpec()`, or `PyType_FromMetaclass()`.

## 数値オブジェクト構造体

type PyNumberMethods

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

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

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

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

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

           unaryfunc nb_index;

           binaryfunc nb_matrix_multiply;
           binaryfunc nb_inplace_matrix_multiply;
      } PyNumberMethods;

  注釈

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

  注釈

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

binaryfunc PyNumberMethods.nb_add

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

binaryfunc PyNumberMethods.nb_subtract

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

binaryfunc PyNumberMethods.nb_multiply

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

binaryfunc PyNumberMethods.nb_remainder

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

binaryfunc PyNumberMethods.nb_divmod

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

ternaryfunc PyNumberMethods.nb_power

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

unaryfunc PyNumberMethods.nb_negative

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

unaryfunc PyNumberMethods.nb_positive

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

unaryfunc PyNumberMethods.nb_absolute

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

inquiry PyNumberMethods.nb_bool

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

unaryfunc PyNumberMethods.nb_invert

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

binaryfunc PyNumberMethods.nb_lshift

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

binaryfunc PyNumberMethods.nb_rshift

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

binaryfunc PyNumberMethods.nb_and

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

binaryfunc PyNumberMethods.nb_xor

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

binaryfunc PyNumberMethods.nb_or

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

unaryfunc PyNumberMethods.nb_int

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

void *PyNumberMethods.nb_reserved

unaryfunc PyNumberMethods.nb_float

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

binaryfunc PyNumberMethods.nb_inplace_add

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

binaryfunc PyNumberMethods.nb_inplace_subtract

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

binaryfunc PyNumberMethods.nb_inplace_multiply

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

binaryfunc PyNumberMethods.nb_inplace_remainder

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

ternaryfunc PyNumberMethods.nb_inplace_power

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

binaryfunc PyNumberMethods.nb_inplace_lshift

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

binaryfunc PyNumberMethods.nb_inplace_rshift

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

binaryfunc PyNumberMethods.nb_inplace_and

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

binaryfunc PyNumberMethods.nb_inplace_xor

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

binaryfunc PyNumberMethods.nb_inplace_or

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

binaryfunc PyNumberMethods.nb_floor_divide

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

binaryfunc PyNumberMethods.nb_true_divide

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

binaryfunc PyNumberMethods.nb_inplace_floor_divide

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

binaryfunc PyNumberMethods.nb_inplace_true_divide

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

unaryfunc PyNumberMethods.nb_index

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

binaryfunc PyNumberMethods.nb_matrix_multiply

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

binaryfunc PyNumberMethods.nb_inplace_matrix_multiply

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

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

type PyMappingMethods

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

lenfunc PyMappingMethods.mp_length

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

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

binaryfunc PyMappingMethods.mp_subscript

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

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

objobjargproc PyMappingMethods.mp_ass_subscript

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

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

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

type PySequenceMethods

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

lenfunc PySequenceMethods.sq_length

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

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

binaryfunc PySequenceMethods.sq_concat

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

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

ssizeargfunc PySequenceMethods.sq_repeat

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

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

ssizeargfunc PySequenceMethods.sq_item

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

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

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

ssizeobjargproc PySequenceMethods.sq_ass_item

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

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

objobjproc PySequenceMethods.sq_contains

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

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

binaryfunc PySequenceMethods.sq_inplace_concat

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

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

ssizeargfunc PySequenceMethods.sq_inplace_repeat

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

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

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

type PyBufferProcs

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

getbufferproc PyBufferProcs.bf_getbuffer

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

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

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

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

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

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

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

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

  5. `0` を返します。

  Thread safety:

  In the free-threaded build, implementations must ensure:

  - The export counter increment in step (3) is atomic.

  - The underlying buffer data remains valid and at a stable memory location for the lifetime of all exports.

  - For objects that support resizing or reallocation (such as `bytearray`), the export counter is checked atomically before such operations, and `BufferError` is raised if exports exist.

  - The function is safe to call concurrently from multiple threads.

  See also Thread safety for memoryview objects for the Python-level thread safety guarantees of `memoryview` objects.

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

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

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

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

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

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

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

releasebufferproc PyBufferProcs.bf_releasebuffer

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

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

      void (PyObject *exporter, Py_buffer *view);

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

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

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

  Thread safety:

  In the free-threaded build:

  - The export counter decrement in step (1) must be atomic.

  - Resource cleanup when the counter reaches zero must be done atomically, as the final release may race with concurrent releases from other threads and deallocation must only happen once.

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

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

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

## async オブジェクト構造体

Added in version 3.5.

type PyAsyncMethods

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

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

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

unaryfunc PyAsyncMethods.am_await

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

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

      PyObject *am_await(PyObject *self);

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

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

unaryfunc PyAsyncMethods.am_aiter

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

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

      PyObject *am_aiter(PyObject *self);

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

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

unaryfunc PyAsyncMethods.am_anext

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

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

      PyObject *am_anext(PyObject *self);

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

sendfunc PyAsyncMethods.am_send

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

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

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

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

  Added in version 3.10.

## Slot Type typedefs

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

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

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

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

typedef void (*freefunc)(void*)

  `tp_free` を参照してください。

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

  `tp_new` を参照してください。

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

  `tp_init` を参照してください。

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

  `tp_repr` を参照してください。

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

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

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

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

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

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

  `tp_getattro` を参照してください。

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

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

  `tp_setattro` を参照してください。

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

  `tp_descr_get` を参照してください。

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

  `tp_descr_set` を参照してください。

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

  `tp_hash` を参照してください。

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

  `tp_richcompare` を参照してください。

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

  `tp_iter` を参照してください。

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

  `tp_iternext` を参照してください。

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

typedef int (*getbufferproc)(PyObject*, Py_buffer*, int)
  次に属します: Stable ABI (バージョン 3.12 より).

typedef void (*releasebufferproc)(PyObject*, Py_buffer*)
  次に属します: Stable ABI (バージョン 3.12 より).

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

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

typedef PySendResult (*sendfunc)(PyObject*, PyObject*, PyObject**)

  `am_send` を参照してください。

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

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

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

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

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

## 使用例

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

A basic static type:

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

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

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

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

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

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

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

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

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

    static PyTypeObject MyStr_Type = {
        PyVarObject_HEAD_INIT(NULL, 0)
        .tp_name = "mymod.MyStr",
        .tp_basicsize = sizeof(MyStr),
        .tp_base = NULL,  // set to &PyUnicode_Type in module init
        .tp_doc = PyDoc_STR("my custom str"),
        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
        .tp_repr = (reprfunc)myobj_repr,
    };

The simplest static type with fixed-length instances:

    typedef struct {
        PyObject_HEAD
    } MyObject;

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

The simplest static type with variable-length instances:

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

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