Кортежні об’єкти

type PyTupleObject

Цей підтип PyObject представляє об’єкт кортежу Python.

PyTypeObject PyTuple_Type
Part of the Stable ABI.

Цей екземпляр PyTypeObject представляє тип кортежу Python; це той самий об’єкт, що й tuple на рівні Python.

int PyTuple_Check(PyObject *p)

Повертає true, якщо p є об’єктом кортежу або екземпляром підтипу типу кортежу. Ця функція завжди успішна.

int PyTuple_CheckExact(PyObject *p)

Повертає true, якщо p є об’єктом кортежу, але не екземпляром підтипу типу кортежу. Ця функція завжди успішна.

PyObject *PyTuple_New(Py_ssize_t len)
Return value: New reference. Part of the Stable ABI.

Return a new tuple object of size len, or NULL with an exception set on failure.

PyObject *PyTuple_Pack(Py_ssize_t n, ...)
Return value: New reference. Part of the Stable ABI.

Return a new tuple object of size n, or NULL with an exception set on failure. The tuple values are initialized to the subsequent n C arguments pointing to Python objects. PyTuple_Pack(2, a, b) is equivalent to Py_BuildValue("(OO)", a, b).

Py_ssize_t PyTuple_Size(PyObject *p)
Part of the Stable ABI.

Take a pointer to a tuple object, and return the size of that tuple. On error, return -1 and with an exception set.

Py_ssize_t PyTuple_GET_SIZE(PyObject *p)

Like PyTuple_Size(), but without error checking.

PyObject *PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Part of the Stable ABI.

Повертає об’єкт у позицію pos у кортежі, на який вказує p. Якщо pos є негативним або виходить за межі, поверніть NULL і встановіть виняток IndexError.

The returned reference is borrowed from the tuple p (that is: it is only valid as long as you hold a reference to p). To get a strong reference, use Py_NewRef(PyTuple_GetItem(...)) or PySequence_GetItem().

PyObject *PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference.

Як PyTuple_GetItem(), але не перевіряє його аргументи.

PyObject *PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)
Return value: New reference. Part of the Stable ABI.

Return the slice of the tuple pointed to by p between low and high, or NULL with an exception set on failure.

This is the equivalent of the Python expression p[low:high]. Indexing from the end of the tuple is not supported.

int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Part of the Stable ABI.

Вставте посилання на об’єкт o у позиції pos кортежу, на який вказує p. У разі успіху повертає 0. Якщо pos виходить за межі, поверніть -1 і встановіть виняток IndexError.

Примітка

Ця функція «викрадає» посилання на o та відкидає посилання на елемент, який уже міститься в кортежі в ураженій позиції.

void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)

Подібно до PyTuple_SetItem(), але не перевіряє помилки, і його слід використовувати лише для заповнення абсолютно нових кортежів.

Bounds checking is performed as an assertion if Python is built in debug mode or with assertions.

Примітка

This function «steals» a reference to o, and, unlike PyTuple_SetItem(), does not discard a reference to any item that is being replaced; any reference in the tuple at position pos will be leaked.

Попередження

This macro should only be used on tuples that are newly created. Using this macro on a tuple that is already in use (or in other words, has a refcount > 1) could lead to undefined behavior.

int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)

Можна використовувати для зміни розміру кортежу. newsize буде новою довжиною кортежу. Оскільки кортежі вважаються незмінними, це слід використовувати, лише якщо є лише одне посилання на об’єкт. Не використовуйте це, якщо кортеж може бути вже відомий іншій частині коду. Кортеж завжди зростатиме або зменшуватиметься в кінці. Думайте про це як про знищення старого кортежу та створення нового, але більш ефективного. У разі успіху повертає 0. Клієнтський код ніколи не повинен вважати, що результуюче значення *p буде таким самим, як і до виклику цієї функції. Якщо об’єкт, на який посилається *p, замінюється, оригінальний *p знищується. У разі помилки повертає -1 і встановлює *p значення NULL і викликає MemoryError або SystemError.

Структуруйте об’єкти послідовності

Об’єкти послідовності структур є еквівалентом C об’єктів namedtuple(), тобто послідовності, до елементів якої також можна отримати доступ через атрибути. Щоб створити послідовність структур, спочатку потрібно створити певний тип послідовності структур.

PyTypeObject *PyStructSequence_NewType(PyStructSequence_Desc *desc)
Return value: New reference. Part of the Stable ABI.

Створіть новий тип послідовності структур із даних у desc, як описано нижче. Екземпляри отриманого типу можна створити за допомогою PyStructSequence_New().

Return NULL with an exception set on failure.

void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)

Ініціалізує структурну послідовність типу type з desc на місці.

int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc)

Like PyStructSequence_InitType(), but returns 0 on success and -1 with an exception set on failure.

Added in version 3.4.

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

Містить метаінформацію типу послідовності структур, яку потрібно створити.

const char *name

Fully qualified name of the type; null-terminated UTF-8 encoded. The name must contain the module name.

const char *doc

Pointer to docstring for the type or NULL to omit.

PyStructSequence_Field *fields

Pointer to NULL-terminated array with field names of the new type.

int n_in_sequence

Number of fields visible to the Python side (if used as tuple).

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

Describes a field of a struct sequence. As a struct sequence is modeled as a tuple, all fields are typed as PyObject*. The index in the fields array of the PyStructSequence_Desc determines which field of the struct sequence is described.

const char *name

Name for the field or NULL to end the list of named fields, set to PyStructSequence_UnnamedField to leave unnamed.

const char *doc

Field docstring or NULL to omit.

const char *const PyStructSequence_UnnamedField
Part of the Stable ABI since version 3.11.

Спеціальне значення для імені поля, щоб залишити його без імені.

Змінено в версії 3.9: Тип змінено з char *.

PyObject *PyStructSequence_New(PyTypeObject *type)
Return value: New reference. Part of the Stable ABI.

Створює екземпляр type, який має бути створено за допомогою PyStructSequence_NewType().

Return NULL with an exception set on failure.

PyObject *PyStructSequence_GetItem(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Part of the Stable ABI.

Return the object at position pos in the struct sequence pointed to by p.

Bounds checking is performed as an assertion if Python is built in debug mode or with assertions.

PyObject *PyStructSequence_GET_ITEM(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference.

Alias to PyStructSequence_GetItem().

Змінено в версії 3.13: Now implemented as an alias to PyStructSequence_GetItem().

void PyStructSequence_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Part of the Stable ABI.

Встановлює поле за індексом pos послідовності структур p на значення o. Як і PyTuple_SET_ITEM(), це слід використовувати лише для заповнення абсолютно нових екземплярів.

Bounds checking is performed as an assertion if Python is built in debug mode or with assertions.

Примітка

Ця функція «краде» посилання на o.

void PyStructSequence_SET_ITEM(PyObject *p, Py_ssize_t *pos, PyObject *o)

Alias to PyStructSequence_SetItem().

Змінено в версії 3.13: Now implemented as an alias to PyStructSequence_SetItem().