Об’єктний протокол

PyObject *Py_NotImplemented

Синглтон NotImplemented, який використовується для сигналу про те, що операція не реалізована для даної комбінації типів.

Py_RETURN_NOTIMPLEMENTED

Properly handle returning Py_NotImplemented from within a C function (that is, create a new strong reference to NotImplemented and return it).

Py_PRINT_RAW

Flag to be used with multiple functions that print the object (like PyObject_Print() and PyFile_WriteObject()). If passed, these function would use the str() of the object instead of the repr().

int PyObject_Print(PyObject *o, FILE *fp, int flags)

Print an object o, on file fp. Returns -1 on error. The flags argument is used to enable certain printing options. The only option currently supported is Py_PRINT_RAW; if given, the str() of the object is written instead of the repr().

int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
Part of the Stable ABI.

Повертає 1, якщо o має атрибут attr_name, і 0 інакше. Це еквівалентно виразу Python hasattr(o, attr_name). Ця функція завжди успішна.

Примітка

Exceptions that occur when this calls __getattr__() and __getattribute__() methods are silently ignored. For proper error handling, use PyObject_GetAttr() instead.

int PyObject_HasAttrString(PyObject *o, const char *attr_name)
Part of the Stable ABI.

This is the same as PyObject_HasAttr(), but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.

Примітка

Exceptions that occur when this calls __getattr__() and __getattribute__() methods or while creating the temporary str object are silently ignored. For proper error handling, use PyObject_GetAttrString() instead.

PyObject *PyObject_GetAttr(PyObject *o, PyObject *attr_name)
Return value: New reference. Part of the Stable ABI.

Отримати атрибут з назвою attr_name з об’єкта o. Повертає значення атрибута в разі успіху або NULL у разі невдачі. Це еквівалент виразу Python o.attr_name.

PyObject *PyObject_GetAttrString(PyObject *o, const char *attr_name)
Return value: New reference. Part of the Stable ABI.

This is the same as PyObject_GetAttr(), but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.

PyObject *PyObject_GenericGetAttr(PyObject *o, PyObject *name)
Return value: New reference. Part of the Stable ABI.

Загальна функція отримання атрибутів, яка призначена для розміщення в слоті tp_getattro об’єкта типу. Він шукає дескриптор у словнику класів у MRO об’єкта, а також атрибут у __dict__ об’єкта (якщо є). Як зазначено в Реалізація дескрипторів, дескриптори даних мають перевагу над атрибутами екземплярів, тоді як дескриптори, що не є даними, ні. В іншому випадку виникає помилка AttributeError.

int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)
Part of the Stable ABI.

Установіть значення атрибута attr_name для об’єкта o на значення v. Викликати виняток і повертати -1 у разі помилки; повернути 0 в разі успіху. Це еквівалент оператора Python o.attr_name = v.

Якщо v має значення NULL, атрибут видаляється. Ця поведінка застаріла на користь використання PyObject_DelAttr(), але наразі немає планів її видалення.

int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)
Part of the Stable ABI.

This is the same as PyObject_SetAttr(), but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.

Якщо v має значення NULL, атрибут видаляється, але ця функція застаріла на користь використання PyObject_DelAttrString().

int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)
Part of the Stable ABI.

Загальна функція встановлення та видалення атрибутів, яка призначена для розміщення в слоті tp_setattro об’єкта типу. Він шукає дескриптор даних у словнику класів у MRO об’єкта, і якщо його знайдено, він надає перевагу над налаштуванням або видаленням атрибута в словнику екземпляра. В іншому випадку атрибут встановлюється або видаляється в об’єкті __dict__ (якщо є). У разі успіху повертається 0, інакше виникає AttributeError і повертається -1.

int PyObject_DelAttr(PyObject *o, PyObject *attr_name)

Видалити атрибут з назвою attr_name для об’єкта o. Повертає -1 у разі помилки. Це еквівалент оператора Python del o.attr_name.

int PyObject_DelAttrString(PyObject *o, const char *attr_name)

This is the same as PyObject_DelAttr(), but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.

PyObject *PyObject_GenericGetDict(PyObject *o, void *context)
Return value: New reference. Part of the Stable ABI since version 3.10.

Загальна реалізація засобу отримання дескриптора __dict__. Він створює словник, якщо це необхідно.

This function may also be called to get the __dict__ of the object o. Pass NULL for context when calling it. Since this function may need to allocate memory for the dictionary, it may be more efficient to call PyObject_GetAttr() when accessing an attribute on the object.

On failure, returns NULL with an exception set.

Added in version 3.3.

int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
Part of the Stable ABI since version 3.7.

Загальна реалізація засобу налаштування дескриптора __dict__. Ця реалізація не дозволяє видаляти словник.

Added in version 3.3.

PyObject **_PyObject_GetDictPtr(PyObject *obj)

Return a pointer to __dict__ of the object obj. If there is no __dict__, return NULL without setting an exception.

This function may need to allocate memory for the dictionary, so it may be more efficient to call PyObject_GetAttr() when accessing an attribute on the object.

PyObject *PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)
Return value: New reference. Part of the Stable ABI.

Compare the values of o1 and o2 using the operation specified by opid, which must be one of Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, or Py_GE, corresponding to <, <=, ==, !=, >, or >= respectively. This is the equivalent of the Python expression o1 op o2, where op is the operator corresponding to opid. Returns the value of the comparison on success, or NULL on failure.

int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)
Part of the Stable ABI.

Compare the values of o1 and o2 using the operation specified by opid, like PyObject_RichCompare(), but returns -1 on error, 0 if the result is false, 1 otherwise.

Примітка

If o1 and o2 are the same object, PyObject_RichCompareBool() will always return 1 for Py_EQ and 0 for Py_NE.

PyObject *PyObject_Format(PyObject *obj, PyObject *format_spec)
Part of the Stable ABI.

Format obj using format_spec. This is equivalent to the Python expression format(obj, format_spec).

format_spec may be NULL. In this case the call is equivalent to format(obj). Returns the formatted string on success, NULL on failure.

PyObject *PyObject_Repr(PyObject *o)
Return value: New reference. Part of the Stable ABI.

Обчислити рядкове представлення об’єкта o. Повертає рядкове представлення в разі успіху, NULL у разі невдачі. Це еквівалент виразу Python repr(o). Викликається вбудованою функцією repr().

Змінено в версії 3.4: Ця функція тепер включає твердження налагодження, щоб гарантувати, що вона не відкидає мовчки активний виняток.

PyObject *PyObject_ASCII(PyObject *o)
Return value: New reference. Part of the Stable ABI.

Як PyObject_Repr(), обчислити рядкове представлення об’єкта o, але екранувати символи, відмінні від ASCII, у рядку, який повертає PyObject_Repr(), за допомогою \x, \u або \U екранується. Це створює рядок, подібний до того, який повертає PyObject_Repr() у Python 2. Викликається вбудованою функцією ascii().

PyObject *PyObject_Str(PyObject *o)
Return value: New reference. Part of the Stable ABI.

Обчислити рядкове представлення об’єкта o. Повертає рядкове представлення в разі успіху, NULL у разі невдачі. Це еквівалент виразу Python str(o). Викликається вбудованою функцією str() і, отже, функцією print().

Змінено в версії 3.4: Ця функція тепер включає твердження налагодження, щоб гарантувати, що вона не відкидає мовчки активний виняток.

PyObject *PyObject_Bytes(PyObject *o)
Return value: New reference. Part of the Stable ABI.

Обчисліть байтове представлення об’єкта o. У разі помилки повертається NULL, а в разі успіху — об’єкт bytes. Це еквівалентно виразу Python bytes(o), коли o не є цілим числом. На відміну від bytes(o), помилка TypeError виникає, коли o є цілим числом замість об’єкта bytes, ініціалізованого нулем.

int PyObject_IsSubclass(PyObject *derived, PyObject *cls)
Part of the Stable ABI.

Повертає 1, якщо клас derived ідентичний або походить від класу cls, інакше повертає 0. У разі помилки поверніть -1.

Якщо cls є кортежем, перевірятиметься кожен запис у cls. Результатом буде 1, якщо хоча б одна з перевірок повертає 1, інакше він буде 0.

Якщо cls має метод __subclasscheck__(), його буде викликано для визначення статусу підкласу, як описано в PEP 3119. В іншому випадку derived є підкласом cls, якщо він є прямим або непрямим підкласом, тобто міститься в cls.__mro__.

Normally only class objects, i.e. instances of type or a derived class, are considered classes. However, objects can override this by having a __bases__ attribute (which must be a tuple of base classes).

int PyObject_IsInstance(PyObject *inst, PyObject *cls)
Part of the Stable ABI.

Повертає 1, якщо inst є екземпляром класу cls або підкласом cls, або 0, якщо ні. У разі помилки повертає -1 і встановлює виняток.

Якщо cls є кортежем, перевірятиметься кожен запис у cls. Результатом буде 1, якщо хоча б одна з перевірок повертає 1, інакше він буде 0.

Якщо cls має метод __instancecheck__(), його буде викликано для визначення статусу підкласу, як описано в PEP 3119. В іншому випадку inst є екземпляром cls, якщо його клас є підкласом cls.

An instance inst can override what is considered its class by having a __class__ attribute.

An object cls can override if it is considered a class, and what its base classes are, by having a __bases__ attribute (which must be a tuple of base classes).

Py_hash_t PyObject_Hash(PyObject *o)
Part of the Stable ABI.

Обчислити та повернути хеш-значення об’єкта o. У разі помилки поверніть -1. Це еквівалент виразу Python hash(o).

Змінено в версії 3.2: Тип повернення тепер Py_hash_t. Це ціле число зі знаком такого ж розміру, як Py_ssize_t.

Py_hash_t PyObject_HashNotImplemented(PyObject *o)
Part of the Stable ABI.

Set a TypeError indicating that type(o) is not hashable and return -1. This function receives special treatment when stored in a tp_hash slot, allowing a type to explicitly indicate to the interpreter that it is not hashable.

int PyObject_IsTrue(PyObject *o)
Part of the Stable ABI.

Повертає 1, якщо об’єкт o вважається істинним, і 0 в іншому випадку. Це еквівалентно виразу Python not not o. У разі помилки поверніть -1.

int PyObject_Not(PyObject *o)
Part of the Stable ABI.

Повертає 0, якщо об’єкт o вважається істинним, і 1 інакше. Це еквівалентно виразу Python not o. У разі помилки поверніть -1.

PyObject *PyObject_Type(PyObject *o)
Return value: New reference. Part of the Stable ABI.

When o is non-NULL, returns a type object corresponding to the object type of object o. On failure, raises SystemError and returns NULL. This is equivalent to the Python expression type(o). This function creates a new strong reference to the return value. There’s really no reason to use this function instead of the Py_TYPE() function, which returns a pointer of type PyTypeObject*, except when a new strong reference is needed.

int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)

Повертає відмінне від нуля значення, якщо об’єкт o має тип type або підтип type, і 0 інакше. Обидва параметри не мають бути NULL.

Py_ssize_t PyObject_Size(PyObject *o)
Py_ssize_t PyObject_Length(PyObject *o)
Part of the Stable ABI.

Повертає довжину об’єкта o. Якщо об’єкт o надає протоколи послідовності та відображення, повертається довжина послідовності. У разі помилки повертається -1. Це еквівалент виразу Python len(o).

Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)

Повертає приблизну довжину об’єкта o. Спочатку спробуйте повернути його фактичну довжину, потім оцінку за допомогою __length_hint__() і, нарешті, поверніть значення за замовчуванням. У разі помилки повертає -1. Це еквівалент виразу Python operator.length_hint(o, defaultvalue).

Added in version 3.4.

PyObject *PyObject_GetItem(PyObject *o, PyObject *key)
Return value: New reference. Part of the Stable ABI.

Повертає елемент o, що відповідає об’єкту key або NULL у разі помилки. Це еквівалент виразу Python o[key].

int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)
Part of the Stable ABI.

Зіставте об’єкт key на значення v. Викликати виняток і повертати -1 у разі помилки; повернути 0 в разі успіху. Це еквівалент оператора Python o[key] = v. Ця функція не викрадає посилання на v.

int PyObject_DelItem(PyObject *o, PyObject *key)
Part of the Stable ABI.

Видаліть зіставлення для об’єкта key з об’єкта o. Повернути -1 у разі помилки. Це еквівалентно оператору Python del o[key].

PyObject *PyObject_Dir(PyObject *o)
Return value: New reference. Part of the Stable ABI.

Це еквівалентно виразу Python dir(o), який повертає (можливо, порожній) список рядків, відповідних для аргументу об’єкта, або NULL, якщо була помилка. Якщо аргумент NULL, це схоже на dir() Python, що повертає імена поточних локальних систем; у цьому випадку, якщо жоден кадр виконання не активний, повертається NULL, але PyErr_Occurred() повертатиме false.

PyObject *PyObject_GetIter(PyObject *o)
Return value: New reference. Part of the Stable ABI.

Це еквівалентно виразу Python iter(o). Він повертає новий ітератор для аргументу об’єкта або сам об’єкт, якщо об’єкт уже є ітератором. Викликає TypeError і повертає NULL, якщо об’єкт не можна повторити.

PyObject *PyObject_GetAIter(PyObject *o)
Return value: New reference. Part of the Stable ABI since version 3.10.

Це еквівалент виразу Python aiter(o). Бере об’єкт AsyncIterable і повертає для нього AsyncIterator. Зазвичай це новий ітератор, але якщо аргументом є AsyncIterator, він повертає сам себе. Викликає TypeError і повертає NULL, якщо об’єкт не можна повторити.

Added in version 3.10.

void *PyObject_GetTypeData(PyObject *o, PyTypeObject *cls)
Part of the Stable ABI since version 3.12.

Get a pointer to subclass-specific data reserved for cls.

The object o must be an instance of cls, and cls must have been created using negative PyType_Spec.basicsize. Python does not check this.

On error, set an exception and return NULL.

Added in version 3.12.

Py_ssize_t PyType_GetTypeDataSize(PyTypeObject *cls)
Part of the Stable ABI since version 3.12.

Return the size of the instance memory space reserved for cls, i.e. the size of the memory PyObject_GetTypeData() returns.

This may be larger than requested using -PyType_Spec.basicsize; it is safe to use this larger size (e.g. with memset()).

The type cls must have been created using negative PyType_Spec.basicsize. Python does not check this.

On error, set an exception and return a negative value.

Added in version 3.12.

void *PyObject_GetItemData(PyObject *o)

Get a pointer to per-item data for a class with Py_TPFLAGS_ITEMS_AT_END.

On error, set an exception and return NULL. TypeError is raised if o does not have Py_TPFLAGS_ITEMS_AT_END set.

Added in version 3.12.