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

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. Thread safety: Atomic.

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

PyObject *PyTuple_FromArray(PyObject *const *array, Py_ssize_t size)
Thread safety: Atomic.

Create a tuple of size items and copy references from array to the new tuple.

array can be NULL if size is 0.

On success, return a new reference. On error, set an exception and return NULL.

Added in version 3.15.

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

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. Thread safety: Atomic.

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

Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
Thread safety: Atomic.

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. Thread safety: Safe to call from multiple threads with external synchronization only.

Повертає об’єкт у позицію 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. Thread safety: Safe to call from multiple threads with external synchronization only.

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

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

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. Thread safety: Safe to call from multiple threads with external synchronization only.

Insert a reference to object o at position pos of the tuple pointed to by p. Return 0 on success. If pos is out of bounds, return -1 and set an IndexError exception. This function should only be used to fill in brand new tuples; using it on an existing tuple is thread-unsafe.

Примітка

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

void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)
Thread safety: Safe to call from multiple threads with external synchronization only.

Like PyTuple_SetItem(), but does no error checking, and should only be used to fill in brand new tuples, using it on an existing tuple is thread-unsafe.

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)
Thread safety: Safe to call from multiple threads with external synchronization only.

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

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

A struct sequence object is a named tuple, that is, a sequence whose items can also be accessed through attributes. It is similar to collections.namedtuple(), but provides a slightly different interface.

To create a struct sequence, you first have to create a specific struct sequence type.

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

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

Return NULL with an exception set on failure.

void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)
Thread safety: Safe to call without external synchronization on distinct objects.

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

int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc)
Thread safety: Safe to call without external synchronization on distinct objects.

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. Thread safety: Atomic.

Створює екземпляр 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. Thread safety: Safe to call from multiple threads with external synchronization only.

Return the object at position pos in the struct sequence pointed to by p. The returned reference is borrowed from the struct sequence p (that is: it is only valid as long as you hold a reference to 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. Thread safety: Safe to call from multiple threads with external synchronization only.

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. Thread safety: Safe to call from multiple threads with external synchronization only.

Встановлює поле за індексом 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)
Thread safety: Safe to call from multiple threads with external synchronization only.

Alias to PyStructSequence_SetItem().

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