# 형 객체

type PyTypeObject
  Part of the Limited API (as an opaque struct).

  내장형을 기술하는 데 사용되는 객체의 C 구조체.

PyTypeObject PyType_Type
  Part of the Stable ABI.

  이것은 형 객체의 형 객체입니다; 파이썬 계층의 `type`과 같은 객체입니다.

int PyType_Check(PyObject *o)

  객체 o가 표준형 객체에서 파생된 형의 인스턴스를 포함하여 형 객체면 0이 아닌 값을 반환합니다. 다른 모든 경우 0을 반환합니다. 이 함수는 항상 성공합니다.

int PyType_CheckExact(PyObject *o)

  객체 o가 형 객체이지만, 표준형 객체의 서브 형이 아니면 0이 아닌 값을 반환합니다. 다른 모든 경우 0을 반환합니다. 이 함수는 항상 성공합니다.

unsigned int PyType_ClearCache()
  Part of the Stable ABI.

  내부 조회 캐시를 지웁니다. 현재의 버전 태그를 반환합니다.

unsigned long PyType_GetFlags(PyTypeObject *type)
  Part of the Stable ABI.

  Return the `tp_flags` member of type. This function is primarily meant for use with `Py_LIMITED_API`; the individual flag bits are guaranteed to be stable across Python releases, but access to `tp_flags` itself is not part of the limited API.

  Added in version 3.2.

  버전 3.4에서 변경: 반환형은 이제 `long`이 아니라 `unsigned long`입니다.

PyObject *PyType_GetDict(PyTypeObject *type)

  Return the type object’s internal namespace, which is otherwise only exposed via a read-only proxy (`cls.__dict__`). This is a replacement for accessing `tp_dict` directly. The returned dictionary must be treated as read-only.

  This function is meant for specific embedding and language-binding cases, where direct access to the dict is necessary and indirect access (e.g. via the proxy or `PyObject_GetAttr()`) isn’t adequate.

  Extension modules should continue to use `tp_dict`, directly or indirectly, when setting up their own types.

  Added in version 3.12.

void PyType_Modified(PyTypeObject *type)
  Part of the Stable ABI.

  형과 그것의 모든 서브 형에 대한 내부 검색 캐시를 무효로 합니다. 형의 어트리뷰트나 베이스 클래스를 수동으로 수정한 후에는 이 함수를 호출해야 합니다.

int PyType_AddWatcher(PyType_WatchCallback callback)

  Register callback as a type watcher. Return a non-negative integer ID which must be passed to future calls to `PyType_Watch()`. In case of error (e.g. no more watcher IDs available), return `-1` and set an exception.

  Added in version 3.12.

int PyType_ClearWatcher(int watcher_id)

  Clear watcher identified by watcher_id (previously returned from `PyType_AddWatcher()`). Return `0` on success, `-1` on error (e.g. if watcher_id was never registered.)

  An extension should never call `PyType_ClearWatcher` with a watcher_id that was not returned to it by a previous call to `PyType_AddWatcher()`.

  Added in version 3.12.

int PyType_Watch(int watcher_id, PyObject *type)

  Mark type as watched. The callback granted watcher_id by `PyType_AddWatcher()` will be called whenever `PyType_Modified()` reports a change to type. (The callback may be called only once for a series of consecutive modifications to type, if `_PyType_Lookup()` is not called on type between the modifications; this is an implementation detail and subject to change.)

  An extension should never call `PyType_Watch` with a watcher_id that was not returned to it by a previous call to `PyType_AddWatcher()`.

  Added in version 3.12.

typedef int (*PyType_WatchCallback)(PyObject *type)

  Type of a type-watcher callback function.

  The callback must not modify type or cause `PyType_Modified()` to be called on type or any type in its MRO; violating this rule could cause infinite recursion.

  Added in version 3.12.

int PyType_HasFeature(PyTypeObject *o, int feature)

  형 객체 o가 기능 feature를 설정하면 0이 아닌 값을 반환합니다. 형 기능은 단일 비트 플래그로 표시됩니다.

int PyType_IS_GC(PyTypeObject *o)

  Return true if the type object includes support for the cycle detector; this tests the type flag `Py_TPFLAGS_HAVE_GC`.

int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
  Part of the Stable ABI.

  a가 b의 서브 형이면 참을 반환합니다.

  This function only checks for actual subtypes, which means that `__subclasscheck__()` is not called on b. Call `PyObject_IsSubclass()` to do the same check that `issubclass()` would do.

PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
  Return value: New reference. Part of the Stable ABI.

  형 객체의 `tp_alloc` 슬롯을 위한 일반 처리기. 파이썬의 기본 메모리 할당 메커니즘을 사용하여 새 인스턴스를 할당하고 모든 내용을 `NULL`로 초기화합니다.

PyObject *PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
  Return value: New reference. Part of the Stable ABI.

  형 객체의 `tp_new` 슬롯을 위한 일반 처리기. 형의 `tp_alloc` 슬롯을 사용하여 새 인스턴스를 만듭니다.

int PyType_Ready(PyTypeObject *type)
  Part of the Stable ABI.

  형 개체를 마무리합니다. 초기화를 완료하려면 모든 형 객체에 대해 이 메서드를 호출해야 합니다. 이 함수는 형의 베이스 클래스에서 상속된 슬롯을 추가합니다. 성공 시 `0`을 반환하고, 오류 시 `-1`을 반환하고 예외를 설정합니다.

  참고

  If some of the base classes implements the GC protocol and the provided type does not include the `Py_TPFLAGS_HAVE_GC` in its flags, then the GC protocol will be automatically implemented from its parents. On the contrary, if the type being created does include `Py_TPFLAGS_HAVE_GC` in its flags then it must implement the GC protocol itself by at least implementing the `tp_traverse` handle.

PyObject *PyType_GetName(PyTypeObject *type)
  Return value: New reference. Part of the Stable ABI since version 3.11.

  Return the type’s name. Equivalent to getting the type’s `__name__` attribute.

  Added in version 3.11.

PyObject *PyType_GetQualName(PyTypeObject *type)
  Return value: New reference. Part of the Stable ABI since version 3.11.

  Return the type’s qualified name. Equivalent to getting the type’s `__qualname__` attribute.

  Added in version 3.11.

void *PyType_GetSlot(PyTypeObject *type, int slot)
  Part of the Stable ABI since version 3.4.

  지정된 슬롯에 저장된 함수 포인터를 반환합니다. 결과가 `NULL`이면, 슬롯이 `NULL`이거나 함수가 유효하지 않은 매개 변수로 호출되었음을 나타냅니다. 호출자는 일반적으로 결과 포인터를 적절한 함수 형으로 캐스팅합니다.

  slot 인자의 가능한 값은 `PyType_Slot.slot`을 참조하십시오.

  Added in version 3.4.

  버전 3.10에서 변경: `PyType_GetSlot()` can now accept all types. Previously, it was limited to heap types.

PyObject *PyType_GetModule(PyTypeObject *type)
  Part of the Stable ABI since version 3.10.

  `PyType_FromModuleAndSpec()`를 사용하여 형을 만들 때 지정된 형과 관련된 모듈 객체를 반환합니다.

  주어진 형과 연관된 모듈이 없으면, `TypeError`를 설정하고 `NULL`을 반환합니다.

  This function is usually used to get the module in which a method is defined. Note that in such a method, `PyType_GetModule(Py_TYPE(self))` may not return the intended result. `Py_TYPE(self)` may be a subclass of the intended class, and subclasses are not necessarily defined in the same module as their superclass. See `PyCMethod` to get the class that defines the method. See `PyType_GetModuleByDef()` for cases when `PyCMethod` cannot be used.

  Added in version 3.9.

void *PyType_GetModuleState(PyTypeObject *type)
  Part of the Stable ABI since version 3.10.

  주어진 형과 관련된 모듈 객체의 상태를 반환합니다. `PyType_GetModule()` 결과에 `PyModule_GetState()`를 호출하는 바로 가기입니다.

  주어진 형과 연관된 모듈이 없으면, `TypeError`를 설정하고 `NULL`을 반환합니다.

  type에 연관된 모듈이 있지만, 상태가 `NULL`이면, 예외를 설정하지 않고 `NULL`을 반환합니다.

  Added in version 3.9.

PyObject *PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)

  Find the first superclass whose module was created from the given `PyModuleDef` def, and return that module.

  If no module is found, raises a `TypeError` and returns `NULL`.

  This function is intended to be used together with `PyModule_GetState()` to get module state from slot methods (such as `tp_init` or `nb_add`) and other places where a method’s defining class cannot be passed using the `PyCMethod` calling convention.

  Added in version 3.11.

int PyUnstable_Type_AssignVersionTag(PyTypeObject *type)
  This is Unstable API. It may change without warning in minor releases.

  Attempt to assign a version tag to the given type.

  Returns 1 if the type already had a valid version tag or a new one was assigned, or 0 if a new tag could not be assigned.

  Added in version 3.12.

## 힙에 할당된 형 만들기

다음 함수와 구조체는 힙 형을 만드는 데 사용됩니다.

PyObject *PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject *bases)
  Part of the Stable ABI since version 3.12.

  Create and return a heap type from the spec (see `Py_TPFLAGS_HEAPTYPE`).

  The metaclass metaclass is used to construct the resulting type object. When metaclass is `NULL`, the metaclass is derived from bases (or Py_tp_base[s] slots if bases is `NULL`, see below).

  Metaclasses that override `tp_new` are not supported, except if `tp_new` is `NULL`. (For backwards compatibility, other `PyType_From*` functions allow such metaclasses. They ignore `tp_new`, which may result in incomplete initialization. This is deprecated and in Python 3.14+ such metaclasses will not be supported.)

  The bases argument can be used to specify base classes; it can either be only one class or a tuple of classes. If bases is `NULL`, the Py_tp_bases slot is used instead. If that also is `NULL`, the Py_tp_base slot is used instead. If that also is `NULL`, the new type derives from `object`.

  The module argument can be used to record the module in which the new class is defined. It must be a module object or `NULL`. If not `NULL`, the module is associated with the new type and can later be retrieved with `PyType_GetModule()`. The associated module is not inherited by subclasses; it must be specified for each class individually.

  이 함수는 새로운 형에 `PyType_Ready()`를 호출합니다.

  Note that this function does not fully match the behavior of calling `type()` or using the `class` statement. With user-provided base types or metaclasses, prefer calling `type` (or the metaclass) over `PyType_From*` functions. Specifically:

  - `__new__()` is not called on the new class (and it must be set to `type.__new__`).

  - `__init__()` is not called on the new class.

  - `__init_subclass__()` is not called on any bases.

  - `__set_name__()` is not called on new descriptors.

  Added in version 3.12.

PyObject *PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
  Return value: New reference. Part of the Stable ABI since version 3.10.

  Equivalent to `PyType_FromMetaclass(NULL, module, spec, bases)`.

  Added in version 3.9.

  버전 3.10에서 변경: The function now accepts a single class as the bases argument and `NULL` as the `tp_doc` slot.

  버전 3.12에서 변경: The function now finds and uses a metaclass corresponding to the provided base classes. Previously, only `type` instances were returned.

  The `tp_new` of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose metaclass overrides `tp_new` is deprecated and in Python 3.14+ it will be no longer allowed.

PyObject *PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
  Return value: New reference. Part of the Stable ABI since version 3.3.

  Equivalent to `PyType_FromMetaclass(NULL, NULL, spec, bases)`.

  Added in version 3.3.

  버전 3.12에서 변경: The function now finds and uses a metaclass corresponding to the provided base classes. Previously, only `type` instances were returned.

  The `tp_new` of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose metaclass overrides `tp_new` is deprecated and in Python 3.14+ it will be no longer allowed.

PyObject *PyType_FromSpec(PyType_Spec *spec)
  Return value: New reference. Part of the Stable ABI.

  Equivalent to `PyType_FromMetaclass(NULL, NULL, spec, NULL)`.

  버전 3.12에서 변경: The function now finds and uses a metaclass corresponding to the base classes provided in Py_tp_base[s] slots. Previously, only `type` instances were returned.

  The `tp_new` of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose metaclass overrides `tp_new` is deprecated and in Python 3.14+ it will be no longer allowed.

type PyType_Spec
  Part of the Stable ABI (including all members).

  형의 행동을 정의하는 구조체.

  const char *name

    형의 이름, `PyTypeObject.tp_name`을 설정하는 데 사용됩니다.

  int basicsize

    If positive, specifies the size of the instance in bytes. It is used to set `PyTypeObject.tp_basicsize`.

    If zero, specifies that `tp_basicsize` should be inherited.

    If negative, the absolute value specifies how much space instances of the class need in addition to the superclass. Use `PyObject_GetTypeData()` to get a pointer to subclass-specific memory reserved this way. For negative `basicsize`, Python will insert padding when needed to meet `tp_basicsize`’s alignment requirements.

    버전 3.12에서 변경: Previously, this field could not be negative.

  int itemsize

    Size of one element of a variable-size type, in bytes. Used to set `PyTypeObject.tp_itemsize`. See `tp_itemsize` documentation for caveats.

    If zero, `tp_itemsize` is inherited. Extending arbitrary variable-sized classes is dangerous, since some types use a fixed offset for variable-sized memory, which can then overlap fixed-sized memory used by a subclass. To help prevent mistakes, inheriting `itemsize` is only possible in the following situations:

    - The base is not variable-sized (its `tp_itemsize`).

    - The requested `PyType_Spec.basicsize` is positive, suggesting that the memory layout of the base class is known.

    - The requested `PyType_Spec.basicsize` is zero, suggesting that the subclass does not access the instance’s memory directly.

    - With the `Py_TPFLAGS_ITEMS_AT_END` flag.

  unsigned int flags

    형 플래그, `PyTypeObject.tp_flags`를 설정하는 데 사용됩니다.

    `Py_TPFLAGS_HEAPTYPE` 플래그가 설정되어 있지 않으면, `PyType_FromSpecWithBases()` 가 자동으로 플래그를 설정합니다.

  PyType_Slot *slots

    `PyType_Slot` 구조체의 배열. 특수 슬롯값 `{0, NULL}`에 의해 종료됩니다.

    Each slot ID should be specified at most once.

type PyType_Slot
  Part of the Stable ABI (including all members).

  형의 선택적 기능을 정의하는 구조체, 슬롯 ID와 값 포인터를 포함합니다.

  int slot

    슬롯 ID.

    슬롯 ID는 구조체 `PyTypeObject`, `PyNumberMethods`, `PySequenceMethods`, `PyMappingMethods` 및 `PyAsyncMethods` 의 필드 이름에 `Py_` 접두사를 붙인 이름을 사용합니다. 예를 들어, :

    - `PyTypeObject.tp_dealloc`을 설정하는 `Py_tp_dealloc`

    - `PyNumberMethods.nb_add`를 설정하는 `Py_nb_add`

    - `PySequenceMethods.sq_length`를 설정하는 `Py_sq_length`

    The following “offset” fields cannot be set using `PyType_Slot`:

    - `tp_weaklistoffset` (use `Py_TPFLAGS_MANAGED_WEAKREF` instead if possible)

    - `tp_dictoffset` (use `Py_TPFLAGS_MANAGED_DICT` instead if possible)

    - `tp_vectorcall_offset` (use `"__vectorcalloffset__"` in PyMemberDef)

    If it is not possible to switch to a `MANAGED` flag (for example, for vectorcall or to support Python older than 3.12), specify the offset in `Py_tp_members`. See PyMemberDef documentation for details.

    The following fields cannot be set at all when creating a heap type:

    - `tp_vectorcall` (use `tp_new` and/or `tp_init`)

    - Internal fields: `tp_dict`, `tp_mro`, `tp_cache`, `tp_subclasses`, and `tp_weaklist`.

    Setting `Py_tp_bases` or `Py_tp_base` may be problematic on some platforms. To avoid issues, use the bases argument of `PyType_FromSpecWithBases()` instead.

    버전 3.9에서 변경: Slots in `PyBufferProcs` may be set in the unlimited API.

    버전 3.11에서 변경: `bf_getbuffer` and `bf_releasebuffer` are now available under the limited API.

  void *pfunc

    슬롯의 원하는 값입니다. 대부분 이것은 함수에 대한 포인터입니다.

    Slots other than `Py_tp_doc` may not be `NULL`.