The Python C - API
The Python C - API
Versión 3.12.4
1 Introducción 3
1.1 Estándares de codificación . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Archivos de cabecera (Include) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Macros útiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Objetos, tipos y conteos de referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.1 Conteo de Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.2 Tipos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5 Excepciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.6 Integración de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.7 Depuración de compilaciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Estabilidad de la API en C 15
2.1 Unstable C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Interfaz binaria de aplicación estable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.1 Limited C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.2 Stable ABI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.3 Alcance y rendimiento de la API limitada . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.4 Advertencias de la API limitada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3 Consideraciones de la plataforma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4 Contenido de la API limitada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4 Conteo de referencias 47
5 Manejo de excepciones 51
5.1 Impresión y limpieza . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 Lanzando excepciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3 Emitir advertencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.4 Consultando el indicador de error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.5 Manejo de señal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.6 Clases de excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.7 Objetos excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.8 Objetos unicode de excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.9 Control de recursión . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.10 Excepciones estándar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.11 Categorías de advertencia estándar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
6 Utilidades 65
6.1 Utilidades del sistema operativo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.2 Funciones del Sistema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
i
6.3 Control de procesos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.4 Importando módulos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.5 Soporte de empaquetado (marshalling) de datos . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.6 Analizando argumentos y construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.6.1 Analizando argumentos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.6.2 Construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.7 Conversión y formato de cadenas de caracteres . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
6.8 PyHash API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.9 Reflexión . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.10 Registro de códec y funciones de soporte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.10.1 API de búsqueda de códec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.10.2 API de registro para controladores de errores de codificación Unicode . . . . . . . . . . . 87
6.11 Support for Perf Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
ii
8.6 Otros objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
8.6.1 Objetos archivo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
8.6.2 Objetos módulo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
8.6.3 Objetos iteradores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.6.4 Objetos descriptores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.6.5 Objetos rebanada (slice) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
8.6.6 Objetos de vista de memoria (MemoryView) . . . . . . . . . . . . . . . . . . . . . . . . 179
8.6.7 Objetos de referencia débil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.6.8 Cápsulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
8.6.9 Objetos frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
8.6.10 Objetos generadores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.11 Objetos corrutina . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.12 Objetos de variables de contexto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.13 Objetos DateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
8.6.14 Objetos para indicaciones de tipado . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
iii
11.7 Personalizar asignadores de memoria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
11.8 Configurar enlaces para detectar errores en las funciones del asignador de memoria de Python . . . 248
11.9 El asignador pymalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
11.9.1 Personalizar asignador de arena de pymalloc . . . . . . . . . . . . . . . . . . . . . . . . 249
11.10 tracemalloc C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
11.11 Ejemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
A Glosario 305
iv
C.3.11 strtod y dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
C.3.18 Conjunto de pruebas W3C C14N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
C.3.19 Audioop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
C.3.20 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Índice 345
v
vi
The Python/C API, Versión 3.12.4
Este manual documenta la API utilizada por los programadores de C y C ++ que desean escribir módulos de extensión
o incorporar Python. Es un complemento de extending-index, que describe los principios generales de la escritura de
extensión pero no documenta las funciones API en detalle.
Índice general 1
The Python/C API, Versión 3.12.4
2 Índice general
CAPÍTULO 1
Introducción
La interfaz del programador de aplicaciones (API) con Python brinda a los programadores de C y C++ acceso al
intérprete de Python en una variedad de niveles. La API es igualmente utilizable desde C++, pero por brevedad
generalmente se conoce como la API Python/C. Hay dos razones fundamentalmente diferentes para usar la API
Python/C. La primera razón es escribir módulos de extensión para propósitos específicos; Estos son módulos C que
extienden el intérprete de Python. Este es probablemente el uso más común. La segunda razón es usar Python co-
mo componente en una aplicación más grande; Esta técnica se conoce generalmente como integración (embedding)
Python en una aplicación.
Escribir un módulo de extensión es un proceso relativamente bien entendido, donde un enfoque de «libro de cocina»
(cookbook) funciona bien. Hay varias herramientas que automatizan el proceso hasta cierto punto. Si bien las personas
han integrado Python en otras aplicaciones desde su existencia temprana, el proceso de integrar Python es menos
sencillo que escribir una extensión.
Muchas funciones API son útiles independientemente de si está integrando o extendiendo Python; Además, la mayoría
de las aplicaciones que integran Python también necesitarán proporcionar una extensión personalizada, por lo que
probablemente sea una buena idea familiarizarse con la escritura de una extensión antes de intentar integrar Python
en una aplicación real.
Si está escribiendo código C para su inclusión en CPython, debe seguir las pautas y estándares definidos en PEP
7. Estas pautas se aplican independientemente de la versión de Python a la que esté contribuyendo. Seguir estas
convenciones no es necesario para sus propios módulos de extensión de terceros, a menos que eventualmente espere
contribuir con ellos a Python.
3
The Python/C API, Versión 3.12.4
Todas las definiciones de función, tipo y macro necesarias para usar la API Python/C se incluyen en su código
mediante la siguiente línea:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
Esto implica la inclusión de los siguientes archivos de encabezado estándar: <stdio.h>, <string.h>, <errno.
h>, <limits.h>, <assert.h> y <stdlib.h> (si está disponible).
Nota: Dado que Python puede definir algunas definiciones de preprocesador que afectan los encabezados estándar
en algunos sistemas, debe incluir Python.h antes de incluir encabezados estándar.
Se recomienda definir siempre PY_SSIZE_T_CLEAN antes de incluir Python.h. Consulte Analizando argumen-
tos y construyendo valores para obtener una descripción de este macro.
Todos los nombres visibles del usuario definidos por Python.h (excepto los definidos por los encabezados estándar
incluidos) tienen uno de los prefijos Py o _Py. Los nombres que comienzan con _Py son para uso interno de la
implementación de Python y no deben ser utilizados por escritores de extensiones. Los nombres de miembros de
estructura no tienen un prefijo reservado.
Nota: El código de usuario nunca debe definir nombres que comiencen con Py o _Py. Esto confunde al lector y
pone en peligro la portabilidad del código de usuario para futuras versiones de Python, que pueden definir nombres
adicionales que comienzan con uno de estos prefijos.
The header files are typically installed with Python. On Unix, these are located in the directories prefix/
include/pythonversion/ and exec_prefix/include/pythonversion/, where prefix and
exec_prefix are defined by the corresponding parameters to Python’s configure script and version is '%d.
%d' % sys.version_info[:2]. On Windows, the headers are installed in prefix/include, where
prefix is the installation directory specified to the installer.
To include the headers, place both directories (if different) on your compiler’s search path for includes. Do not place
the parent directories on the search path and then use #include <pythonX.Y/Python.h>; this will break on
multi-platform builds since the platform independent headers under prefix include the platform specific headers
from exec_prefix.
Los usuarios de C++ deben tener en cuenta que aunque la API se define completamente usando C, los archivos de
encabezado declaran correctamente que los puntos de entrada son extern "C". Como resultado, no es necesario
hacer nada especial para usar la API desde C++.
Varias macros útiles se definen en los archivos de encabezado de Python. Muchos se definen más cerca de donde son
útiles (por ejemplo Py_RETURN_NONE). Otros de una utilidad más general se definen aquí. Esto no es necesaria-
mente una lista completa.
PyMODINIT_FUNC
Declare an extension module PyInit initialization function. The function return type is PyObject*. The
macro declares any special linkage declarations required by the platform, and for C++ declares the function as
extern "C".
The initialization function must be named PyInit_name, where name is the name of the module, and should
be the only non-static item defined in the module file. Example:
4 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModule_Create(&spam_module);
}
Py_ABS(x)
Retorna el valor absoluto de x.
Added in version 3.3.
Py_ALWAYS_INLINE
Ordena al compilador a siempre usar inline en una función estática inline. El compilador puede ignorarlo y
decidir no usar inline en la función.
Puede ser usado para usar inline en funciones estáticas inline de rendimiento crítico cuando se corre Python en
modo de depuración con inline de funciones deshabilitado. Por ejemplo, MSC deshabilita el inline de funciones
cuando se configura en modo de depuración.
Marcar ciegamente una función estática inline con Py_ALWAYS_INLINE puede resultar en peor rendimientos
(debido a un aumento del tamaño del código, por ejemplo). El compilador es generalmente más inteligente que
el desarrollador para el análisis costo/beneficio.
If Python is built in debug mode (if the Py_DEBUG macro is defined), the Py_ALWAYS_INLINE macro
does nothing.
Debe ser especificado antes del tipo de retorno de la función. Uso:
Py_MIN(x, y)
Retorna el valor mínimo entre x e y.
Added in version 3.3.
Py_NO_INLINE
Deshabilita el uso de inline en una función. Por ejemplo, reduce el consumo de la pila C: útil en compilaciones
LTO+PGO que usan mucho inline (ver bpo-33720).
Uso:
PyDoc_STR(str)
Crea un docstring para la cadena de caracteres de entrada dada o una cadena vacía si los docstrings están
deshabilitados.
6 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
Utilice PyDoc_STR al especificar docstrings para admitir la construcción de Python sin docstrings, como se
especifica en PEP 7.
Ejemplo:
Most Python/C API functions have one or more arguments as well as a return value of type PyObject*. This type
is a pointer to an opaque data type representing an arbitrary Python object. Since all Python object types are treated
the same way by the Python language in most situations (e.g., assignments, scope rules, and argument passing), it
is only fitting that they should be represented by a single C type. Almost all Python objects live on the heap: you
never declare an automatic or static variable of type PyObject, only pointer variables of type PyObject* can
be declared. The sole exception are the type objects; since these must never be deallocated, they are typically static
PyTypeObject objects.
Todos los objetos de Python (incluso los enteros de Python) tienen un tipo (type) y un conteo de referencia (reference
count). El tipo de un objeto determina qué tipo de objeto es (por ejemplo, un número entero, una lista o una función
definida por el usuario; hay muchos más como se explica en types). Para cada uno de los tipos conocidos hay un
macro para verificar si un objeto es de ese tipo; por ejemplo, PyList_Check(a) es verdadero si (y solo si) el
objeto al que apunta a es una lista de Python.
The reference count is important because today’s computers have a finite (and often severely limited) memory size;
it counts how many different places there are that have a strong reference to an object. Such a place could be another
object, or a global (or static) C variable, or a local variable in some C function. When the last strong reference to an
object is released (i.e. its reference count becomes zero), the object is deallocated. If it contains references to other
objects, those references are released. Those other objects may be deallocated in turn, if there are no more references
to them, and so on. (There’s an obvious problem with objects that reference each other here; for now, the solution is
«don’t do that.»)
Reference counts are always manipulated explicitly. The normal way is to use the macro Py_INCREF() to take a
new reference to an object (i.e. increment its reference count by one), and Py_DECREF() to release that reference
(i.e. decrement the reference count by one). The Py_DECREF() macro is considerably more complex than the
incref one, since it must check whether the reference count becomes zero and then cause the object’s deallocator to
be called. The deallocator is a function pointer contained in the object’s type structure. The type-specific deallocator
takes care of releasing references for other objects contained in the object if this is a compound object type, such as
a list, as well as performing any additional finalization that’s needed. There’s no chance that the reference count can
overflow; at least as many bits are used to hold the reference count as there are distinct memory locations in virtual
memory (assuming sizeof(Py_ssize_t) >= sizeof(void*)). Thus, the reference count increment is a
simple operation.
It is not necessary to hold a strong reference (i.e. increment the reference count) for every local variable that contains
a pointer to an object. In theory, the object’s reference count goes up by one when the variable is made to point to
it and it goes down by one when the variable goes out of scope. However, these two cancel each other out, so at the
end the reference count hasn’t changed. The only real reason to use the reference count is to prevent the object from
being deallocated as long as our variable is pointing to it. If we know that there is at least one other reference to the
object that lives at least as long as our variable, there is no need to take a new strong reference (i.e. increment the
reference count) temporarily. An important situation where this arises is in objects that are passed as arguments to C
functions in an extension module that are called from Python; the call mechanism guarantees to hold a reference to
every argument for the duration of the call.
However, a common pitfall is to extract an object from a list and hold on to it for a while without taking a new
reference. Some other operation might conceivably remove the object from the list, releasing that reference, and
possibly deallocating it. The real danger is that innocent-looking operations may invoke arbitrary Python code which
could do this; there is a code path which allows control to flow back to the user from a Py_DECREF(), so almost
any operation is potentially dangerous.
A safe approach is to always use the generic operations (functions whose name begins with PyObject_,
PyNumber_, PySequence_ or PyMapping_). These operations always create a new strong reference (i.e.
increment the reference count) of the object they return. This leaves the caller with the responsibility to call
Py_DECREF() when they are done with the result; this soon becomes second nature.
The reference count behavior of functions in the Python/C API is best explained in terms of ownership of references.
Ownership pertains to references, never to objects (objects are not owned: they are always shared). «Owning a re-
ference» means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership
can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for
eventually releasing it by calling Py_DECREF() or Py_XDECREF() when it’s no longer needed—or passing on
this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is
said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing
needs to be done for a borrowed reference.
Por el contrario, cuando una función de llamada pasa una referencia a un objeto, hay dos posibilidades: la función roba
una referencia al objeto, o no lo hace. Robar una referencia significa que cuando pasa una referencia a una función,
esa función asume que ahora posee esa referencia, y usted ya no es responsable de ella.
Pocas funciones roban referencias; las dos excepciones notables son PyList_SetItem() y
PyTuple_SetItem(), que roban una referencia al elemento (¡pero no a la tupla o lista en la que se colo-
ca el elemento!). Estas funciones fueron diseñadas para robar una referencia debido a un idioma común para
poblar una tupla o lista con objetos recién creados; por ejemplo, el código para crear la tupla (1, 2, "tres")
podría verse así (olvidando el manejo de errores por el momento; una mejor manera de codificar esto se muestra a
continuación):
PyObject *t;
t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));
Aquí PyLong_FromLong() retorna una nueva referencia que es inmediatamente robada por
PyTuple_SetItem(). Cuando quiera seguir usando un objeto aunque se le robe la referencia, use
Py_INCREF() para tomar otra referencia antes de llamar a la función de robo de referencias.
Por cierto, PyTuple_SetItem() es la única forma de establecer elementos de tupla;
PySequence_SetItem() y PyObject_SetItem() se niegan a hacer esto ya que las tuplas son un
tipo de datos inmutable. Solo debe usar PyTuple_SetItem() para las tuplas que está creando usted mismo.
El código equivalente para llenar una lista se puede escribir usando PyList_New() y PyList_SetItem().
Sin embargo, en la práctica, rara vez utilizará estas formas de crear y completar una tupla o lista. Hay una función
genérica, Py_BuildValue(), que puede crear los objetos más comunes a partir de valores C, dirigidos por un
una cadena de caracteres de formato (format string). Por ejemplo, los dos bloques de código anteriores podrían
reemplazarse por lo siguiente (que también se ocupa de la comprobación de errores):
PyObject *tuple, *list;
It is much more common to use PyObject_SetItem() and friends with items whose references you are only
borrowing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding
8 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
references is much saner, since you don’t have to take a new reference just so you can give that reference away («have
it be stolen»). For example, this function sets all items of a list (actually, any mutable sequence) to a given item:
int
set_all(PyObject *target, PyObject *item)
{
Py_ssize_t i, n;
n = PyObject_Length(target);
if (n < 0)
return -1;
for (i = 0; i < n; i++) {
PyObject *index = PyLong_FromSsize_t(i);
if (!index)
return -1;
if (PyObject_SetItem(target, index, item) < 0) {
Py_DECREF(index);
return -1;
}
Py_DECREF(index);
}
return 0;
}
La situación es ligeramente diferente para los valores de retorno de la función. Si bien pasar una referencia a la mayo-
ría de las funciones no cambia sus responsabilidades de propiedad para esa referencia, muchas funciones que retornan
una referencia a un objeto le otorgan la propiedad de la referencia. La razón es simple: en muchos casos, el objeto
retornado se crea sobre la marcha, y la referencia que obtiene es la única referencia al objeto. Por lo tanto, las funcio-
nes genéricas que retornan referencias de objeto, como PyObject_GetItem() y PySequence_GetItem(),
siempre retornan una nueva referencia (la entidad que llama se convierte en el propietario de la referencia).
Es importante darse cuenta de que si posee una referencia retornada por una función depende de a qué función llame
únicamente — el plumaje (el tipo del objeto pasado como argumento a la función) no entra en él! Por lo tanto, si
extrae un elemento de una lista usando PyList_GetItem(), no posee la referencia — pero si obtiene el mismo
elemento de la misma lista usando PySequence_GetItem() (que toma exactamente los mismos argumentos),
usted posee una referencia al objeto retornado.
Aquí hay un ejemplo de cómo podría escribir una función que calcule la suma de los elementos en una lista de enteros;
una vez usando PyList_GetItem(), y una vez usando PySequence_GetItem().
long
sum_list(PyObject *list)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
n = PyList_Size(list);
if (n < 0)
return -1; /* Not a list */
for (i = 0; i < n; i++) {
item = PyList_GetItem(list, i); /* Can't fail */
if (!PyLong_Check(item)) continue; /* Skip non-integers */
value = PyLong_AsLong(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
return total;
}
long
sum_sequence(PyObject *sequence)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
n = PySequence_Length(sequence);
if (n < 0)
return -1; /* Has no length */
for (i = 0; i < n; i++) {
item = PySequence_GetItem(sequence, i);
if (item == NULL)
return -1; /* Not a sequence, or other failure */
if (PyLong_Check(item)) {
value = PyLong_AsLong(item);
Py_DECREF(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
else {
Py_DECREF(item); /* Discard reference ownership */
}
}
return total;
}
1.4.2 Tipos
There are few other data types that play a significant role in the Python/C API; most are simple C types such as
int, long, double and char*. A few structure types are used to describe static tables used to list the functions
exported by a module or the data attributes of a new object type, and another is used to describe the value of a
complex number. These will be discussed together with the functions that use them.
type Py_ssize_t
Part of the Stable ABI. Un tipo integral con signo tal que sizeof(Py_ssize_t) ==
sizeof(size_t). C99 no define directamente tal cosa (size_t es un tipo integral sin signo). Vea
PEP 353 para más detalles. PY_SSIZE_T_MAX es el valor positivo más grande del tipo Py_ssize_t.
1.5 Excepciones
El programador de Python solo necesita lidiar con excepciones si se requiere un manejo específico de errores; las
excepciones no manejadas se propagan automáticamente a la persona que llama, luego a la persona que llama, y
así sucesivamente, hasta que llegan al intérprete de nivel superior, donde se informan al usuario acompañado de un
seguimiento de pila (stack traceback).
Para los programadores de C, sin embargo, la comprobación de errores siempre tiene que ser explícita. Todas las
funciones en la API Python/C pueden generar excepciones, a menos que se señale explícitamente en la documentación
de una función. En general, cuando una función encuentra un error, establece una excepción, descarta cualquier
referencia de objeto que posea y retorna un indicador de error. Si no se documenta lo contrario, este indicador
es NULL o -1, dependiendo del tipo de retorno de la función. Algunas funciones retornan un resultado booleano
verdadero/falso, con falso que indica un error. Muy pocas funciones no retornan ningún indicador de error explícito
o tienen un valor de retorno ambiguo, y requieren pruebas explícitas de errores con PyErr_Occurred(). Estas
excepciones siempre se documentan explícitamente.
El estado de excepción se mantiene en el almacenamiento por subproceso (esto es equivalente a usar el almacena-
miento global en una aplicación sin subprocesos). Un subproceso puede estar en uno de dos estados: se ha producido
10 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
una excepción o no. La función PyErr_Occurred() puede usarse para verificar esto: retorna una referencia
prestada al objeto de tipo de excepción cuando se produce una excepción, y NULL de lo contrario. Hay una serie de
funciones para establecer el estado de excepción: PyErr_SetString() es la función más común (aunque no la
más general) para establecer el estado de excepción, y PyErr_Clear() borra la excepción estado.
El estado de excepción completo consta de tres objetos (todos los cuales pueden ser NULL): el tipo de excepción, el
valor de excepción correspondiente y el rastreo. Estos tienen los mismos significados que el resultado de Python de
sys.exc_info(); sin embargo, no son lo mismo: los objetos Python representan la última excepción manejada
por una declaración de Python try … except, mientras que el estado de excepción de nivel C solo existe mientras
se está pasando una excepción entre las funciones de C hasta que llega al bucle principal del intérprete de código de
bytes (bytecode) de Python, que se encarga de transferirlo a sys.exc_info() y amigos.
Tenga en cuenta que a partir de Python 1.5, la forma preferida y segura de subprocesos para acceder al estado de
excepción desde el código de Python es llamar a la función sys.exc_info(), que retorna el estado de excepción
por subproceso para el código de Python. Además, la semántica de ambas formas de acceder al estado de excepción
ha cambiado de modo que una función que detecta una excepción guardará y restaurará el estado de excepción de
su hilo para preservar el estado de excepción de su llamador. Esto evita errores comunes en el código de manejo
de excepciones causado por una función de aspecto inocente que sobrescribe la excepción que se maneja; También
reduce la extensión de vida útil a menudo no deseada para los objetos a los que hacen referencia los marcos de pila
en el rastreo.
Como principio general, una función que llama a otra función para realizar alguna tarea debe verificar si la función
llamada generó una excepción y, de ser así, pasar el estado de excepción a quien la llama (caller). Debe descartar
cualquier referencia de objeto que posea y retornar un indicador de error, pero no debe establecer otra excepción —
que sobrescribirá la excepción que se acaba de generar y perderá información importante sobre la causa exacta del
error.
A simple example of detecting exceptions and passing them on is shown in the sum_sequence() example above.
It so happens that this example doesn’t need to clean up any owned references when it detects an error. The following
example function shows some error cleanup. First, to remind you why you like Python, we show the equivalent Python
code:
int
incr_item(PyObject *dict, PyObject *key)
{
/* Objects all initialized to NULL for Py_XDECREF */
PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
int rv = -1; /* Return value initialized to -1 (failure) */
1.5. Excepciones 11
The Python/C API, Versión 3.12.4
error:
/* Cleanup code, shared by success and failure path */
La única tarea importante de la que solo tienen que preocuparse los integradores (a diferencia de los escritores de
extensión) del intérprete de Python es la inicialización, y posiblemente la finalización, del intérprete de Python. La
mayor parte de la funcionalidad del intérprete solo se puede usar después de que el intérprete se haya inicializado.
La función básica de inicialización es Py_Initialize(). Esto inicializa la tabla de módulos cargados y crea
los módulos fundamentales builtins, __main__, y sys. También inicializa la ruta de búsqueda del módulo
(sys.path).
Py_Initialize() no establece la «lista de argumentos de script» (sys.argv). Si esta variable es necesaria por
el código Python que se ejecutará más tarde, debe establecerse PyConfig.argv y PyConfig.parse_argv:
consulte Python Initialization Configuration.
En la mayoría de los sistemas (en particular, en Unix y Windows, aunque los detalles son ligeramente diferentes),
Py_Initialize() calcula la ruta de búsqueda del módulo basándose en su mejor estimación de la ubicación del
ejecutable del intérprete de Python estándar, suponiendo que la biblioteca de Python se encuentra en una ubicación fija
en relación con el ejecutable del intérprete de Python. En particular, busca un directorio llamado lib/pythonX.Y
relativo al directorio padre donde se encuentra el ejecutable llamado python en la ruta de búsqueda del comando
shell (la variable de entorno PATH).
Por ejemplo, si el ejecutable de Python se encuentra en /usr/local/bin/python, se supondrá que las biblio-
tecas están en /usr/local/lib/pythonX.Y. (De hecho, esta ruta particular también es la ubicación «alterna-
tiva», utilizada cuando no se encuentra un archivo ejecutable llamado python junto con PATH.) El usuario puede
anular este comportamiento configurando la variable de entorno PYTHONHOME, o inserte directorios adicionales
delante de la ruta estándar estableciendo PYTHONPATH.
La aplicación de integración puede dirigir la búsqueda llamando a Py_SetProgramName(file) antes llamando
Py_Initialize(). Tenga en cuenta que PYTHONHOME todavía anula esto y PYTHONPATH todavía se inserta
12 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
frente a la ruta estándar. Una aplicación que requiere un control total debe proporcionar su propia implementación de
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), y Py_GetProgramFullPath() (todo
definido en Modules/getpath.c).
A veces, es deseable «no inicializar» Python. Por ejemplo, la aplicación puede querer comenzar de nuevo (hacer otra
llamada a Py_Initialize()) o la aplicación simplemente se hace con el uso de Python y quiere liberar memoria
asignada por Python. Esto se puede lograr llamando a Py_FinalizeEx(). La función Py_IsInitialized()
retorna verdadero si Python se encuentra actualmente en el estado inicializado. Se proporciona más información
sobre estas funciones en un capítulo posterior. Tenga en cuenta que Py_FinalizeEx() no libera toda la memoria
asignada por el intérprete de Python, por ejemplo, la memoria asignada por los módulos de extensión actualmente no
se puede liberar.
Python se puede construir con varios macros para permitir verificaciones adicionales del intérprete y los módulos de
extensión. Estas comprobaciones tienden a agregar una gran cantidad de sobrecarga al tiempo de ejecución, por lo
que no están habilitadas de forma predeterminada.
A full list of the various types of debugging builds is in the file Misc/SpecialBuilds.txt in the Python source
distribution. Builds are available that support tracing of reference counts, debugging the memory allocator, or low-
level profiling of the main interpreter loop. Only the most frequently used builds will be described in the remainder
of this section.
Py_DEBUG
Compiling the interpreter with the Py_DEBUG macro defined produces what is generally meant by a debug build of
Python. Py_DEBUG is enabled in the Unix build by adding --with-pydebug to the ./configure command.
It is also implied by the presence of the not-Python-specific _DEBUG macro. When Py_DEBUG is enabled in the
Unix build, compiler optimization is disabled.
Además de la depuración del recuento de referencia que se describe a continuación, se realizan verificaciones adi-
cionales, véase compilaciones de depuración.
Definiendo Py_TRACE_REFS habilita el rastreo de referencias (véase la opción configure
--with-trace-refs). Cuando se define, se mantiene una lista circular doblemente vinculada de objetos
activos al agregar dos campos adicionales a cada PyObject. También se realiza un seguimiento de las asignaciones
totales. Al salir, se imprimen todas las referencias existentes. (En modo interactivo, esto sucede después de cada
declaración ejecutada por el intérprete).
Consulte Misc/SpecialBuilds.txt en la distribución fuente de Python para obtener información más deta-
llada.
14 Capítulo 1. Introducción
CAPÍTULO 2
Estabilidad de la API en C
Unless documented otherwise, Python’s C API is covered by the Backwards Compatibility Policy, PEP 387. Most
changes to it are source-compatible (typically by only adding new API). Changing existing API or removing API is
only done after a deprecation period or to fix serious issues.
CPython’s Application Binary Interface (ABI) is forward- and backwards-compatible across a minor release (if these
are compiled the same way; see Consideraciones de la plataforma below). So, code compiled for Python 3.10.0 will
work on 3.10.8 and vice versa, but will need to be compiled separately for 3.9.x and 3.11.x.
There are two tiers of C API with different stability expectations:
• Unstable API, may change in minor versions without a deprecation period. It is marked by the PyUnstable
prefix in names.
• Limited API, is compatible across several minor releases. When Py_LIMITED_API is defined, only this
subset is exposed from Python.h.
These are discussed in more detail below.
Names prefixed by an underscore, such as _Py_InternalState, are private API that can change without notice
even in patch releases. If you need to use this API, consider reaching out to CPython developers to discuss adding
public API for your use case.
Any API named with the PyUnstable prefix exposes CPython implementation details, and may change in every
minor release (e.g. from 3.9 to 3.10) without any deprecation warnings. However, it will not change in a bugfix release
(e.g. from 3.10.0 to 3.10.1).
It is generally intended for specialized, low-level tools like debuggers.
Projects that use this API are expected to follow CPython development and spend extra effort adjusting to changes.
15
The Python/C API, Versión 3.12.4
For simplicity, this document talks about extensions, but the Limited API and Stable ABI work the same way for all
uses of the API – for example, embedding Python.
Python 3.2 introduced the Limited API, a subset of Python’s C API. Extensions that only use the Limited API can be
compiled once and work with multiple versions of Python. Contents of the Limited API are listed below.
Py_LIMITED_API
Se define esta macro antes de incluir Python.h para optar por usar sólo la API limitada y para seleccionar
la versión de la API limitada.
Define Py_LIMITED_API to the value of PY_VERSION_HEX corresponding to the lowest Python version
your extension supports. The extension will work without recompilation with all Python 3 releases from the
specified one onward, and can use Limited API introduced up to that version.
En lugar de utilizar directamente la macro PY_VERSION_HEX, se codifica una versión menor mínima (por
ejemplo, 0x030A0000 para Python 3.10) para tener estabilidad cuando se compila con futuras versiones de
Python.
También se puede definir Py_LIMITED_API con 3. Esto funciona igual que 0x03020000 (Python 3.2, la
función que introdujo la API limitada).
To enable this, Python provides a Stable ABI: a set of symbols that will remain compatible across Python 3.x versions.
The Stable ABI contains symbols exposed in the Limited API, but also other ones – for example, functions necessary
to support older versions of the Limited API.
En Windows, las extensiones que usan la ABI estable deben estar vinculadas con python3.dll en lugar de una
biblioteca específica de la versión como python39.dll.
En algunas plataformas, Python buscará y cargará archivos de bibliotecas compartidas con el nombre de la etiqueta
abi3 (por ejemplo, mymodule.abi3.so). No comprueba si tales extensiones se ajustan a una ABI estable. El
usuario (o sus herramientas de empaquetado) necesitan asegurarse que, por ejemplo, las extensiones que se crean con
la API limitada 3.10+ no estén instaladas para versiones inferiores de Python.
Todas las funciones de la ABI estable se presentan como funciones en la biblioteca compartida de Python, no sólo
como macros. Esto las hace utilizables desde lenguajes que no usan el preprocesador de C.
El objetivo de la API limitada es permitir todo lo que es posible con la API completa en C, pero posiblemente con
una penalización de rendimiento.
Por ejemplo, mientras PyList_GetItem() está disponible, su variante macro “insegura”
PyList_GET_ITEM() no lo está. La macro puede ser más rápida porque puede confiar en los detalles de
implementación específicos de la versión del objeto de lista.
Sin definirse Py_LIMITED_API, algunas funciones de la API en C están integradas o reemplazadas por macros.
Definir Py_LIMITED_API desactiva esta integración, permitiendo estabilidad mientras que se mejoren las estruc-
turas de datos de Python, pero posiblemente reduzca el rendimiento.
Al dejar fuera la definición de Py_LIMITED_API, es posible compilar una extensión de la API limitada con una ABI
específica de la versión. Esto puede mejorar el rendimiento para esa versión de Python, pero limitará la compatibilidad.
Compilar con Py_LIMITED_API producirá una extensión que se puede distribuir donde una versión específica no
esté disponible - por ejemplo, para los prelanzamientos de una versión próxima de Python.
Note that compiling with Py_LIMITED_API is not a complete guarantee that code conforms to the Limited API or
the Stable ABI. Py_LIMITED_API only covers definitions, but an API also includes other issues, such as expected
semantics.
Un problema contra el que Py_LIMITED_API no protege es llamar una función con argumentos que son inválidos
en una versión inferior de Python. Por ejemplo, se considera una función que empieza a aceptar NULL como un
argumento. Ahora en Python 3.9, NULL selecciona un comportamiento predeterminado, pero en Python 3.8, el
argumento se usará directamente, causando una desreferencia NULL y se detendrá. Un argumento similar funciona
para campos de estructuras.
Otro problema es que algunos campos de estructura no se ocultan actualmente cuando se define Py_LIMITED_API,
aunque son parte de la API limitada.
Por estas razones, recomendamos probar una extensión con todas las versiones menores de Python que soporte, y
preferiblemente compilar con la versión más baja.
También recomendamos revisar la documentación de todas las API usadas para verificar si es parte explícitamente
de la API limitada. Aunque se defina Py_LIMITED_API, algunas declaraciones privadas se exponen por razones
técnicas (o incluso involuntariamente, como errores).
También tome en cuenta que la API limitada no necesariamente es estable: compilar con Py_LIMITED_API con
Python 3.8 significa que la extensión se ejecutará con Python 3.12, pero no necesariamente compilará con Python
3.12. En particular, las partes de la API limitada se pueden quedar obsoletas y eliminarse, siempre que la ABI estable
permanezca estable.
ABI stability depends not only on Python, but also on the compiler used, lower-level libraries and compiler options.
For the purposes of the Stable ABI, these details define a “platform”. They usually depend on the OS type and processor
architecture
Es la responsabilidad de cada distribuidor particular de Python de asegurarse de que todas las versiones de Python
en una plataforma particular se compilen de una forma que no rompa la ABI estable. Este es el caso de las versiones
de Windows y macOS de python.org y muchos distribuidores de terceros.
• PY_VECTORCALL_ARGUMENTS_OFFSET
• PyAIter_Check()
• PyArg_Parse()
• PyArg_ParseTuple()
• PyArg_ParseTupleAndKeywords()
• PyArg_UnpackTuple()
• PyArg_VaParse()
• PyArg_VaParseTupleAndKeywords()
• PyArg_ValidateKeywordArguments()
• PyBaseObject_Type
• PyBool_FromLong()
• PyBool_Type
• PyBuffer_FillContiguousStrides()
• PyBuffer_FillInfo()
• PyBuffer_FromContiguous()
• PyBuffer_GetPointer()
• PyBuffer_IsContiguous()
• PyBuffer_Release()
• PyBuffer_SizeFromFormat()
• PyBuffer_ToContiguous()
• PyByteArrayIter_Type
• PyByteArray_AsString()
• PyByteArray_Concat()
• PyByteArray_FromObject()
• PyByteArray_FromStringAndSize()
• PyByteArray_Resize()
• PyByteArray_Size()
• PyByteArray_Type
• PyBytesIter_Type
• PyBytes_AsString()
• PyBytes_AsStringAndSize()
• PyBytes_Concat()
• PyBytes_ConcatAndDel()
• PyBytes_DecodeEscape()
• PyBytes_FromFormat()
• PyBytes_FromFormatV()
• PyBytes_FromObject()
• PyBytes_FromString()
• PyBytes_FromStringAndSize()
• PyBytes_Repr()
• PyBytes_Size()
• PyBytes_Type
• PyCFunction
• PyCFunctionWithKeywords
• PyCFunction_Call()
• PyCFunction_GetFlags()
• PyCFunction_GetFunction()
• PyCFunction_GetSelf()
• PyCFunction_New()
• PyCFunction_NewEx()
• PyCFunction_Type
• PyCMethod_New()
• PyCallIter_New()
• PyCallIter_Type
• PyCallable_Check()
• PyCapsule_Destructor
• PyCapsule_GetContext()
• PyCapsule_GetDestructor()
• PyCapsule_GetName()
• PyCapsule_GetPointer()
• PyCapsule_Import()
• PyCapsule_IsValid()
• PyCapsule_New()
• PyCapsule_SetContext()
• PyCapsule_SetDestructor()
• PyCapsule_SetName()
• PyCapsule_SetPointer()
• PyCapsule_Type
• PyClassMethodDescr_Type
• PyCodec_BackslashReplaceErrors()
• PyCodec_Decode()
• PyCodec_Decoder()
• PyCodec_Encode()
• PyCodec_Encoder()
• PyCodec_IgnoreErrors()
• PyCodec_IncrementalDecoder()
• PyCodec_IncrementalEncoder()
• PyCodec_KnownEncoding()
• PyCodec_LookupError()
• PyCodec_NameReplaceErrors()
• PyCodec_Register()
• PyCodec_RegisterError()
• PyCodec_ReplaceErrors()
• PyCodec_StreamReader()
• PyCodec_StreamWriter()
• PyCodec_StrictErrors()
• PyCodec_Unregister()
• PyCodec_XMLCharRefReplaceErrors()
• PyComplex_FromDoubles()
• PyComplex_ImagAsDouble()
• PyComplex_RealAsDouble()
• PyComplex_Type
• PyDescr_NewClassMethod()
• PyDescr_NewGetSet()
• PyDescr_NewMember()
• PyDescr_NewMethod()
• PyDictItems_Type
• PyDictIterItem_Type
• PyDictIterKey_Type
• PyDictIterValue_Type
• PyDictKeys_Type
• PyDictProxy_New()
• PyDictProxy_Type
• PyDictRevIterItem_Type
• PyDictRevIterKey_Type
• PyDictRevIterValue_Type
• PyDictValues_Type
• PyDict_Clear()
• PyDict_Contains()
• PyDict_Copy()
• PyDict_DelItem()
• PyDict_DelItemString()
• PyDict_GetItem()
• PyDict_GetItemString()
• PyDict_GetItemWithError()
• PyDict_Items()
• PyDict_Keys()
• PyDict_Merge()
• PyDict_MergeFromSeq2()
• PyDict_New()
• PyDict_Next()
• PyDict_SetItem()
• PyDict_SetItemString()
• PyDict_Size()
• PyDict_Type
• PyDict_Update()
• PyDict_Values()
• PyEllipsis_Type
• PyEnum_Type
• PyErr_BadArgument()
• PyErr_BadInternalCall()
• PyErr_CheckSignals()
• PyErr_Clear()
• PyErr_Display()
• PyErr_DisplayException()
• PyErr_ExceptionMatches()
• PyErr_Fetch()
• PyErr_Format()
• PyErr_FormatV()
• PyErr_GetExcInfo()
• PyErr_GetHandledException()
• PyErr_GetRaisedException()
• PyErr_GivenExceptionMatches()
• PyErr_NewException()
• PyErr_NewExceptionWithDoc()
• PyErr_NoMemory()
• PyErr_NormalizeException()
• PyErr_Occurred()
• PyErr_Print()
• PyErr_PrintEx()
• PyErr_ProgramText()
• PyErr_ResourceWarning()
• PyErr_Restore()
• PyErr_SetExcFromWindowsErr()
• PyErr_SetExcFromWindowsErrWithFilename()
• PyErr_SetExcFromWindowsErrWithFilenameObject()
• PyErr_SetExcFromWindowsErrWithFilenameObjects()
• PyErr_SetExcInfo()
• PyErr_SetFromErrno()
• PyErr_SetFromErrnoWithFilename()
• PyErr_SetFromErrnoWithFilenameObject()
• PyErr_SetFromErrnoWithFilenameObjects()
• PyErr_SetFromWindowsErr()
• PyErr_SetFromWindowsErrWithFilename()
• PyErr_SetHandledException()
• PyErr_SetImportError()
• PyErr_SetImportErrorSubclass()
• PyErr_SetInterrupt()
• PyErr_SetInterruptEx()
• PyErr_SetNone()
• PyErr_SetObject()
• PyErr_SetRaisedException()
• PyErr_SetString()
• PyErr_SyntaxLocation()
• PyErr_SyntaxLocationEx()
• PyErr_WarnEx()
• PyErr_WarnExplicit()
• PyErr_WarnFormat()
• PyErr_WriteUnraisable()
• PyEval_AcquireLock()
• PyEval_AcquireThread()
• PyEval_CallFunction()
• PyEval_CallMethod()
• PyEval_CallObjectWithKeywords()
• PyEval_EvalCode()
• PyEval_EvalCodeEx()
• PyEval_EvalFrame()
• PyEval_EvalFrameEx()
• PyEval_GetBuiltins()
• PyEval_GetFrame()
• PyEval_GetFuncDesc()
• PyEval_GetFuncName()
• PyEval_GetGlobals()
• PyEval_GetLocals()
• PyEval_InitThreads()
• PyEval_ReleaseLock()
• PyEval_ReleaseThread()
• PyEval_RestoreThread()
• PyEval_SaveThread()
• PyEval_ThreadsInitialized()
• PyExc_ArithmeticError
• PyExc_AssertionError
• PyExc_AttributeError
• PyExc_BaseException
• PyExc_BaseExceptionGroup
• PyExc_BlockingIOError
• PyExc_BrokenPipeError
• PyExc_BufferError
• PyExc_BytesWarning
• PyExc_ChildProcessError
• PyExc_ConnectionAbortedError
• PyExc_ConnectionError
• PyExc_ConnectionRefusedError
• PyExc_ConnectionResetError
• PyExc_DeprecationWarning
• PyExc_EOFError
• PyExc_EncodingWarning
• PyExc_EnvironmentError
• PyExc_Exception
• PyExc_FileExistsError
• PyExc_FileNotFoundError
• PyExc_FloatingPointError
• PyExc_FutureWarning
• PyExc_GeneratorExit
• PyExc_IOError
• PyExc_ImportError
• PyExc_ImportWarning
• PyExc_IndentationError
• PyExc_IndexError
• PyExc_InterruptedError
• PyExc_IsADirectoryError
• PyExc_KeyError
• PyExc_KeyboardInterrupt
• PyExc_LookupError
• PyExc_MemoryError
• PyExc_ModuleNotFoundError
• PyExc_NameError
• PyExc_NotADirectoryError
• PyExc_NotImplementedError
• PyExc_OSError
• PyExc_OverflowError
• PyExc_PendingDeprecationWarning
• PyExc_PermissionError
• PyExc_ProcessLookupError
• PyExc_RecursionError
• PyExc_ReferenceError
• PyExc_ResourceWarning
• PyExc_RuntimeError
• PyExc_RuntimeWarning
• PyExc_StopAsyncIteration
• PyExc_StopIteration
• PyExc_SyntaxError
• PyExc_SyntaxWarning
• PyExc_SystemError
• PyExc_SystemExit
• PyExc_TabError
• PyExc_TimeoutError
• PyExc_TypeError
• PyExc_UnboundLocalError
• PyExc_UnicodeDecodeError
• PyExc_UnicodeEncodeError
• PyExc_UnicodeError
• PyExc_UnicodeTranslateError
• PyExc_UnicodeWarning
• PyExc_UserWarning
• PyExc_ValueError
• PyExc_Warning
• PyExc_WindowsError
• PyExc_ZeroDivisionError
• PyExceptionClass_Name()
• PyException_GetArgs()
• PyException_GetCause()
• PyException_GetContext()
• PyException_GetTraceback()
• PyException_SetArgs()
• PyException_SetCause()
• PyException_SetContext()
• PyException_SetTraceback()
• PyFile_FromFd()
• PyFile_GetLine()
• PyFile_WriteObject()
• PyFile_WriteString()
• PyFilter_Type
• PyFloat_AsDouble()
• PyFloat_FromDouble()
• PyFloat_FromString()
• PyFloat_GetInfo()
• PyFloat_GetMax()
• PyFloat_GetMin()
• PyFloat_Type
• PyFrameObject
• PyFrame_GetCode()
• PyFrame_GetLineNumber()
• PyFrozenSet_New()
• PyFrozenSet_Type
• PyGC_Collect()
• PyGC_Disable()
• PyGC_Enable()
• PyGC_IsEnabled()
• PyGILState_Ensure()
• PyGILState_GetThisThreadState()
• PyGILState_Release()
• PyGILState_STATE
• PyGetSetDef
• PyGetSetDescr_Type
• PyImport_AddModule()
• PyImport_AddModuleObject()
• PyImport_AppendInittab()
• PyImport_ExecCodeModule()
• PyImport_ExecCodeModuleEx()
• PyImport_ExecCodeModuleObject()
• PyImport_ExecCodeModuleWithPathnames()
• PyImport_GetImporter()
• PyImport_GetMagicNumber()
• PyImport_GetMagicTag()
• PyImport_GetModule()
• PyImport_GetModuleDict()
• PyImport_Import()
• PyImport_ImportFrozenModule()
• PyImport_ImportFrozenModuleObject()
• PyImport_ImportModule()
• PyImport_ImportModuleLevel()
• PyImport_ImportModuleLevelObject()
• PyImport_ImportModuleNoBlock()
• PyImport_ReloadModule()
• PyIndex_Check()
• PyInterpreterState
• PyInterpreterState_Clear()
• PyInterpreterState_Delete()
• PyInterpreterState_Get()
• PyInterpreterState_GetDict()
• PyInterpreterState_GetID()
• PyInterpreterState_New()
• PyIter_Check()
• PyIter_Next()
• PyIter_Send()
• PyListIter_Type
• PyListRevIter_Type
• PyList_Append()
• PyList_AsTuple()
• PyList_GetItem()
• PyList_GetSlice()
• PyList_Insert()
• PyList_New()
• PyList_Reverse()
• PyList_SetItem()
• PyList_SetSlice()
• PyList_Size()
• PyList_Sort()
• PyList_Type
• PyLongObject
• PyLongRangeIter_Type
• PyLong_AsDouble()
• PyLong_AsLong()
• PyLong_AsLongAndOverflow()
• PyLong_AsLongLong()
• PyLong_AsLongLongAndOverflow()
• PyLong_AsSize_t()
• PyLong_AsSsize_t()
• PyLong_AsUnsignedLong()
• PyLong_AsUnsignedLongLong()
• PyLong_AsUnsignedLongLongMask()
• PyLong_AsUnsignedLongMask()
• PyLong_AsVoidPtr()
• PyLong_FromDouble()
• PyLong_FromLong()
• PyLong_FromLongLong()
• PyLong_FromSize_t()
• PyLong_FromSsize_t()
• PyLong_FromString()
• PyLong_FromUnsignedLong()
• PyLong_FromUnsignedLongLong()
• PyLong_FromVoidPtr()
• PyLong_GetInfo()
• PyLong_Type
• PyMap_Type
• PyMapping_Check()
• PyMapping_GetItemString()
• PyMapping_HasKey()
• PyMapping_HasKeyString()
• PyMapping_Items()
• PyMapping_Keys()
• PyMapping_Length()
• PyMapping_SetItemString()
• PyMapping_Size()
• PyMapping_Values()
• PyMem_Calloc()
• PyMem_Free()
• PyMem_Malloc()
• PyMem_Realloc()
• PyMemberDef
• PyMemberDescr_Type
• PyMember_GetOne()
• PyMember_SetOne()
• PyMemoryView_FromBuffer()
• PyMemoryView_FromMemory()
• PyMemoryView_FromObject()
• PyMemoryView_GetContiguous()
• PyMemoryView_Type
• PyMethodDef
• PyMethodDescr_Type
• PyModuleDef
• PyModuleDef_Base
• PyModuleDef_Init()
• PyModuleDef_Type
• PyModule_AddFunctions()
• PyModule_AddIntConstant()
• PyModule_AddObject()
• PyModule_AddObjectRef()
• PyModule_AddStringConstant()
• PyModule_AddType()
• PyModule_Create2()
• PyModule_ExecDef()
• PyModule_FromDefAndSpec2()
• PyModule_GetDef()
• PyModule_GetDict()
• PyModule_GetFilename()
• PyModule_GetFilenameObject()
• PyModule_GetName()
• PyModule_GetNameObject()
• PyModule_GetState()
• PyModule_New()
• PyModule_NewObject()
• PyModule_SetDocString()
• PyModule_Type
• PyNumber_Absolute()
• PyNumber_Add()
• PyNumber_And()
• PyNumber_AsSsize_t()
• PyNumber_Check()
• PyNumber_Divmod()
• PyNumber_Float()
• PyNumber_FloorDivide()
• PyNumber_InPlaceAdd()
• PyNumber_InPlaceAnd()
• PyNumber_InPlaceFloorDivide()
• PyNumber_InPlaceLshift()
• PyNumber_InPlaceMatrixMultiply()
• PyNumber_InPlaceMultiply()
• PyNumber_InPlaceOr()
• PyNumber_InPlacePower()
• PyNumber_InPlaceRemainder()
• PyNumber_InPlaceRshift()
• PyNumber_InPlaceSubtract()
• PyNumber_InPlaceTrueDivide()
• PyNumber_InPlaceXor()
• PyNumber_Index()
• PyNumber_Invert()
• PyNumber_Long()
• PyNumber_Lshift()
• PyNumber_MatrixMultiply()
• PyNumber_Multiply()
• PyNumber_Negative()
• PyNumber_Or()
• PyNumber_Positive()
• PyNumber_Power()
• PyNumber_Remainder()
• PyNumber_Rshift()
• PyNumber_Subtract()
• PyNumber_ToBase()
• PyNumber_TrueDivide()
• PyNumber_Xor()
• PyOS_AfterFork()
• PyOS_AfterFork_Child()
• PyOS_AfterFork_Parent()
• PyOS_BeforeFork()
• PyOS_CheckStack()
• PyOS_FSPath()
• PyOS_InputHook
• PyOS_InterruptOccurred()
• PyOS_double_to_string()
• PyOS_getsig()
• PyOS_mystricmp()
• PyOS_mystrnicmp()
• PyOS_setsig()
• PyOS_sighandler_t
• PyOS_snprintf()
• PyOS_string_to_double()
• PyOS_strtol()
• PyOS_strtoul()
• PyOS_vsnprintf()
• PyObject
• PyObject.ob_refcnt
• PyObject.ob_type
• PyObject_ASCII()
• PyObject_AsCharBuffer()
• PyObject_AsFileDescriptor()
• PyObject_AsReadBuffer()
• PyObject_AsWriteBuffer()
• PyObject_Bytes()
• PyObject_Call()
• PyObject_CallFunction()
• PyObject_CallFunctionObjArgs()
• PyObject_CallMethod()
• PyObject_CallMethodObjArgs()
• PyObject_CallNoArgs()
• PyObject_CallObject()
• PyObject_Calloc()
• PyObject_CheckBuffer()
• PyObject_CheckReadBuffer()
• PyObject_ClearWeakRefs()
• PyObject_CopyData()
• PyObject_DelItem()
• PyObject_DelItemString()
• PyObject_Dir()
• PyObject_Format()
• PyObject_Free()
• PyObject_GC_Del()
• PyObject_GC_IsFinalized()
• PyObject_GC_IsTracked()
• PyObject_GC_Track()
• PyObject_GC_UnTrack()
• PyObject_GenericGetAttr()
• PyObject_GenericGetDict()
• PyObject_GenericSetAttr()
• PyObject_GenericSetDict()
• PyObject_GetAIter()
• PyObject_GetAttr()
• PyObject_GetAttrString()
• PyObject_GetBuffer()
• PyObject_GetItem()
• PyObject_GetIter()
• PyObject_GetTypeData()
• PyObject_HasAttr()
• PyObject_HasAttrString()
• PyObject_Hash()
• PyObject_HashNotImplemented()
• PyObject_Init()
• PyObject_InitVar()
• PyObject_IsInstance()
• PyObject_IsSubclass()
• PyObject_IsTrue()
• PyObject_Length()
• PyObject_Malloc()
• PyObject_Not()
• PyObject_Realloc()
• PyObject_Repr()
• PyObject_RichCompare()
• PyObject_RichCompareBool()
• PyObject_SelfIter()
• PyObject_SetAttr()
• PyObject_SetAttrString()
• PyObject_SetItem()
• PyObject_Size()
• PyObject_Str()
• PyObject_Type()
• PyObject_Vectorcall()
• PyObject_VectorcallMethod()
• PyProperty_Type
• PyRangeIter_Type
• PyRange_Type
• PyReversed_Type
• PySeqIter_New()
• PySeqIter_Type
• PySequence_Check()
• PySequence_Concat()
• PySequence_Contains()
• PySequence_Count()
• PySequence_DelItem()
• PySequence_DelSlice()
• PySequence_Fast()
• PySequence_GetItem()
• PySequence_GetSlice()
• PySequence_In()
• PySequence_InPlaceConcat()
• PySequence_InPlaceRepeat()
• PySequence_Index()
• PySequence_Length()
• PySequence_List()
• PySequence_Repeat()
• PySequence_SetItem()
• PySequence_SetSlice()
• PySequence_Size()
• PySequence_Tuple()
• PySetIter_Type
• PySet_Add()
• PySet_Clear()
• PySet_Contains()
• PySet_Discard()
• PySet_New()
• PySet_Pop()
• PySet_Size()
• PySet_Type
• PySlice_AdjustIndices()
• PySlice_GetIndices()
• PySlice_GetIndicesEx()
• PySlice_New()
• PySlice_Type
• PySlice_Unpack()
• PyState_AddModule()
• PyState_FindModule()
• PyState_RemoveModule()
• PyStructSequence_Desc
• PyStructSequence_Field
• PyStructSequence_GetItem()
• PyStructSequence_New()
• PyStructSequence_NewType()
• PyStructSequence_SetItem()
• PyStructSequence_UnnamedField
• PySuper_Type
• PySys_AddWarnOption()
• PySys_AddWarnOptionUnicode()
• PySys_AddXOption()
• PySys_FormatStderr()
• PySys_FormatStdout()
• PySys_GetObject()
• PySys_GetXOptions()
• PySys_HasWarnOptions()
• PySys_ResetWarnOptions()
• PySys_SetArgv()
• PySys_SetArgvEx()
• PySys_SetObject()
• PySys_SetPath()
• PySys_WriteStderr()
• PySys_WriteStdout()
• PyThreadState
• PyThreadState_Clear()
• PyThreadState_Delete()
• PyThreadState_Get()
• PyThreadState_GetDict()
• PyThreadState_GetFrame()
• PyThreadState_GetID()
• PyThreadState_GetInterpreter()
• PyThreadState_New()
• PyThreadState_SetAsyncExc()
• PyThreadState_Swap()
• PyThread_GetInfo()
• PyThread_ReInitTLS()
• PyThread_acquire_lock()
• PyThread_acquire_lock_timed()
• PyThread_allocate_lock()
• PyThread_create_key()
• PyThread_delete_key()
• PyThread_delete_key_value()
• PyThread_exit_thread()
• PyThread_free_lock()
• PyThread_get_key_value()
• PyThread_get_stacksize()
• PyThread_get_thread_ident()
• PyThread_get_thread_native_id()
• PyThread_init_thread()
• PyThread_release_lock()
• PyThread_set_key_value()
• PyThread_set_stacksize()
• PyThread_start_new_thread()
• PyThread_tss_alloc()
• PyThread_tss_create()
• PyThread_tss_delete()
• PyThread_tss_free()
• PyThread_tss_get()
• PyThread_tss_is_created()
• PyThread_tss_set()
• PyTraceBack_Here()
• PyTraceBack_Print()
• PyTraceBack_Type
• PyTupleIter_Type
• PyTuple_GetItem()
• PyTuple_GetSlice()
• PyTuple_New()
• PyTuple_Pack()
• PyTuple_SetItem()
• PyTuple_Size()
• PyTuple_Type
• PyTypeObject
• PyType_ClearCache()
• PyType_FromMetaclass()
• PyType_FromModuleAndSpec()
• PyType_FromSpec()
• PyType_FromSpecWithBases()
• PyType_GenericAlloc()
• PyType_GenericNew()
• PyType_GetFlags()
• PyType_GetModule()
• PyType_GetModuleState()
• PyType_GetName()
• PyType_GetQualName()
• PyType_GetSlot()
• PyType_GetTypeDataSize()
• PyType_IsSubtype()
• PyType_Modified()
• PyType_Ready()
• PyType_Slot
• PyType_Spec
• PyType_Type
• PyUnicodeDecodeError_Create()
• PyUnicodeDecodeError_GetEncoding()
• PyUnicodeDecodeError_GetEnd()
• PyUnicodeDecodeError_GetObject()
• PyUnicodeDecodeError_GetReason()
• PyUnicodeDecodeError_GetStart()
• PyUnicodeDecodeError_SetEnd()
• PyUnicodeDecodeError_SetReason()
• PyUnicodeDecodeError_SetStart()
• PyUnicodeEncodeError_GetEncoding()
• PyUnicodeEncodeError_GetEnd()
• PyUnicodeEncodeError_GetObject()
• PyUnicodeEncodeError_GetReason()
• PyUnicodeEncodeError_GetStart()
• PyUnicodeEncodeError_SetEnd()
• PyUnicodeEncodeError_SetReason()
• PyUnicodeEncodeError_SetStart()
• PyUnicodeIter_Type
• PyUnicodeTranslateError_GetEnd()
• PyUnicodeTranslateError_GetObject()
• PyUnicodeTranslateError_GetReason()
• PyUnicodeTranslateError_GetStart()
• PyUnicodeTranslateError_SetEnd()
• PyUnicodeTranslateError_SetReason()
• PyUnicodeTranslateError_SetStart()
• PyUnicode_Append()
• PyUnicode_AppendAndDel()
• PyUnicode_AsASCIIString()
• PyUnicode_AsCharmapString()
• PyUnicode_AsDecodedObject()
• PyUnicode_AsDecodedUnicode()
• PyUnicode_AsEncodedObject()
• PyUnicode_AsEncodedString()
• PyUnicode_AsEncodedUnicode()
• PyUnicode_AsLatin1String()
• PyUnicode_AsMBCSString()
• PyUnicode_AsRawUnicodeEscapeString()
• PyUnicode_AsUCS4()
• PyUnicode_AsUCS4Copy()
• PyUnicode_AsUTF16String()
• PyUnicode_AsUTF32String()
• PyUnicode_AsUTF8AndSize()
• PyUnicode_AsUTF8String()
• PyUnicode_AsUnicodeEscapeString()
• PyUnicode_AsWideChar()
• PyUnicode_AsWideCharString()
• PyUnicode_BuildEncodingMap()
• PyUnicode_Compare()
• PyUnicode_CompareWithASCIIString()
• PyUnicode_Concat()
• PyUnicode_Contains()
• PyUnicode_Count()
• PyUnicode_Decode()
• PyUnicode_DecodeASCII()
• PyUnicode_DecodeCharmap()
• PyUnicode_DecodeCodePageStateful()
• PyUnicode_DecodeFSDefault()
• PyUnicode_DecodeFSDefaultAndSize()
• PyUnicode_DecodeLatin1()
• PyUnicode_DecodeLocale()
• PyUnicode_DecodeLocaleAndSize()
• PyUnicode_DecodeMBCS()
• PyUnicode_DecodeMBCSStateful()
• PyUnicode_DecodeRawUnicodeEscape()
• PyUnicode_DecodeUTF16()
• PyUnicode_DecodeUTF16Stateful()
• PyUnicode_DecodeUTF32()
• PyUnicode_DecodeUTF32Stateful()
• PyUnicode_DecodeUTF7()
• PyUnicode_DecodeUTF7Stateful()
• PyUnicode_DecodeUTF8()
• PyUnicode_DecodeUTF8Stateful()
• PyUnicode_DecodeUnicodeEscape()
• PyUnicode_EncodeCodePage()
• PyUnicode_EncodeFSDefault()
• PyUnicode_EncodeLocale()
• PyUnicode_FSConverter()
• PyUnicode_FSDecoder()
• PyUnicode_Find()
• PyUnicode_FindChar()
• PyUnicode_Format()
• PyUnicode_FromEncodedObject()
• PyUnicode_FromFormat()
• PyUnicode_FromFormatV()
• PyUnicode_FromObject()
• PyUnicode_FromOrdinal()
• PyUnicode_FromString()
• PyUnicode_FromStringAndSize()
• PyUnicode_FromWideChar()
• PyUnicode_GetDefaultEncoding()
• PyUnicode_GetLength()
• PyUnicode_InternFromString()
• PyUnicode_InternInPlace()
• PyUnicode_IsIdentifier()
• PyUnicode_Join()
• PyUnicode_Partition()
• PyUnicode_RPartition()
• PyUnicode_RSplit()
• PyUnicode_ReadChar()
• PyUnicode_Replace()
• PyUnicode_Resize()
• PyUnicode_RichCompare()
• PyUnicode_Split()
• PyUnicode_Splitlines()
• PyUnicode_Substring()
• PyUnicode_Tailmatch()
• PyUnicode_Translate()
• PyUnicode_Type
• PyUnicode_WriteChar()
• PyVarObject
• PyVarObject.ob_base
• PyVarObject.ob_size
• PyVectorcall_Call()
• PyVectorcall_NARGS()
• PyWeakReference
• PyWeakref_GetObject()
• PyWeakref_NewProxy()
• PyWeakref_NewRef()
• PyWrapperDescr_Type
• PyWrapper_New()
• PyZip_Type
• Py_AddPendingCall()
• Py_AtExit()
• Py_BEGIN_ALLOW_THREADS
• Py_BLOCK_THREADS
• Py_BuildValue()
• Py_BytesMain()
• Py_CompileString()
• Py_DecRef()
• Py_DecodeLocale()
• Py_END_ALLOW_THREADS
• Py_EncodeLocale()
• Py_EndInterpreter()
• Py_EnterRecursiveCall()
• Py_Exit()
• Py_FatalError()
• Py_FileSystemDefaultEncodeErrors
• Py_FileSystemDefaultEncoding
• Py_Finalize()
• Py_FinalizeEx()
• Py_GenericAlias()
• Py_GenericAliasType
• Py_GetBuildInfo()
• Py_GetCompiler()
• Py_GetCopyright()
• Py_GetExecPrefix()
• Py_GetPath()
• Py_GetPlatform()
• Py_GetPrefix()
• Py_GetProgramFullPath()
• Py_GetProgramName()
• Py_GetPythonHome()
• Py_GetRecursionLimit()
• Py_GetVersion()
• Py_HasFileSystemDefaultEncoding
• Py_IncRef()
• Py_Initialize()
• Py_InitializeEx()
• Py_Is()
• Py_IsFalse()
• Py_IsInitialized()
• Py_IsNone()
• Py_IsTrue()
• Py_LeaveRecursiveCall()
• Py_Main()
• Py_MakePendingCalls()
• Py_NewInterpreter()
• Py_NewRef()
• Py_ReprEnter()
• Py_ReprLeave()
• Py_SetPath()
• Py_SetProgramName()
• Py_SetPythonHome()
• Py_SetRecursionLimit()
• Py_UCS4
• Py_UNBLOCK_THREADS
• Py_UTF8Mode
• Py_VaBuildValue()
• Py_Version
• Py_XNewRef()
• Py_buffer
• Py_intptr_t
• Py_ssize_t
• Py_uintptr_t
• allocfunc
• binaryfunc
• descrgetfunc
• descrsetfunc
• destructor
• getattrfunc
• getattrofunc
• getbufferproc
• getiterfunc
• getter
• hashfunc
• initproc
• inquiry
• iternextfunc
• lenfunc
• newfunc
• objobjargproc
• objobjproc
• releasebufferproc
• reprfunc
• richcmpfunc
• setattrfunc
• setattrofunc
• setter
• ssizeargfunc
• ssizeobjargproc
• ssizessizeargfunc
• ssizessizeobjargproc
• symtable
• ternaryfunc
• traverseproc
• unaryfunc
• vectorcallfunc
• visitproc
Las funciones en este capítulo te permitirán ejecutar código fuente de Python desde un archivo o un búfer, pero no
te permitirán interactuar de una manera detallada con el intérprete.
Several of these functions accept a start symbol from the grammar as a parameter. The available start symbols are
Py_eval_input, Py_file_input, and Py_single_input. These are described following the functions
which accept them as parameters.
Note also that several of these functions take FILE* parameters. One particular issue which needs to be handled
carefully is that the FILE structure for different C libraries can be different and incompatible. Under Windows (at
least), it is possible for dynamically linked extensions to actually use different libraries, so care should be taken that
FILE* parameters are only passed to these functions if it is certain that they were created by the same library that
the Python runtime is using.
int Py_Main(int argc, wchar_t **argv)
Part of the Stable ABI. El programa principal para el intérprete estándar. Está disponible para programas que
incorporan Python. Los parámetros argc y argv deben prepararse exactamente como los que se pasan a la
función main() de un programa en C (convertido a wchar_t de acuerdo con la configuración regional del
usuario). Es importante tener en cuenta que la lista de argumentos puede ser modificada (pero el contenido
de las cadenas de caracteres señaladas por la lista de argumentos no lo es). El valor de retorno será 0 si el
intérprete acaba normalmente (es decir, sin excepción), 1 si el intérprete acaba debido a una excepción, o 2 si
la lista de parámetros no representa una línea de comando Python válida.
Note that if an otherwise unhandled SystemExit is raised, this function will not return 1, but exit the
process, as long as PyConfig.inspect is zero.
int Py_BytesMain(int argc, char **argv)
Part of the Stable ABI since version 3.8. Similar a Py_Main() pero argv es un arreglo de cadenas de caracteres
de bytes.
Added in version 3.8.
int PyRun_AnyFile(FILE *fp, const char *filename)
Esta es una interfaz simplificada para PyRun_AnyFileExFlags() más abajo, dejando closeit establecido
a 0 y flags establecido a NULL.
int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Esta es una interfaz simplificada para PyRun_AnyFileExFlags() más abajo, dejando closeit establecido
a 0.
41
The Python/C API, Versión 3.12.4
Nota: En Windows, fp debe abrirse en modo binario (por ejemplo, fopen(filename, "rb"). De lo
contrario, Python puede no manejar correctamente el archivo de script con la terminación de línea LF.
int (*PyOS_InputHook)(void)
Part of the Stable ABI. Se puede configurar para que apunte a una función con el prototipo int
func(void). Se llamará a la función cuando el indicador del intérprete de Python esté a punto de estar
inactivo y espere la entrada del usuario desde el terminal. El valor de retorno es ignorado. Sobrescribiendo este
enlace se puede utilizar para integrar la solicitud del intérprete con otros bucles de eventos, como se hace en
Modules/_tkinter.c en el código fuente de Python.
Distinto en la versión 3.12: This function is only called from the main interpreter.
char *(*PyOS_ReadlineFunctionPointer)(FILE*, FILE*, const char*)
Se puede configurar para que apunte a una función con el prototipo char *func (FILE *stdin,
FILE *stdout, char *prompt), sobrescribiendo la función predeterminada utilizada para leer una
sola línea de entrada desde el intérprete. Se espera que la función genere la cadena de caracteres prompt si
no es NULL, y luego lea una línea de entrada del archivo de entrada estándar proporcionado, retornando la
cadena de caracteres resultante. Por ejemplo, el módulo readline establece este enlace para proporcionar
funciones de edición de línea y finalización de tabulación.
El resultado debe ser una cadena de caracteres alocado por PyMem_RawMalloc() o
PyMem_RawRealloc(), o NULL si ocurre un error.
Distinto en la versión 3.4: El resultado debe ser alocado por PyMem_RawMalloc() o
PyMem_RawRealloc(), en vez de ser alocado por PyMem_Malloc() o PyMem_Realloc().
Distinto en la versión 3.12: This function is only called from the main interpreter.
PyObject *PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Return value: New reference. Esta es una interfaz simplificada para PyRun_StringFlags() más abajo,
dejando flags establecido a NULL.
PyObject *PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
Return value: New reference. Ejecuta el código fuente de Python desde str en el contexto especificado por los
objetos globals y locals con los indicadores del compilador especificados por flags. globals debe ser un diccio-
nario; locals puede ser cualquier objeto que implemente el protocolo de mapeo. El parámetro start especifica
el token de inicio que se debe usar para analizar el código fuente.
Retorna el resultado de ejecutar el código como un objeto Python, o NULL” si se produjo una excepción.
PyObject *PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)
Return value: New reference. Esta es una interfaz simplificada para PyRun_FileExFlags() más abajo,
dejando closeit establecido a 0 y flags establecido a NULL.
PyObject *PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int
closeit)
Return value: New reference. Esta es una interfaz simplificada para PyRun_FileExFlags() más abajo,
dejando flags establecido a NULL.
PyObject *PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
Return value: New reference. Esta es una interfaz simplificada para PyRun_FileExFlags() más abajo,
dejando closeit establecido a 0.
PyObject *PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
int closeit, PyCompilerFlags *flags)
Return value: New reference. Similar a PyRun_StringFlags(), pero el código fuente de Python se lee
de fp en lugar de una cadena de caracteres en memoria. filename debe ser el nombre del fichero, es decodifi-
cado desde el filesystem encoding and error handler. Si closeit es verdadero, el fichero se cierra antes de que
PyRun_FileExFlags() retorne.
PyObject *Py_CompileString(const char *str, const char *filename, int start)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz simplificada para
Py_CompileStringFlags() más abajo, dejando flags establecido a NULL.
43
The Python/C API, Versión 3.12.4
PyObject *Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)
Return value: New reference. Esta es una interfaz simplificada para Py_CompileStringExFlags() más
abajo, con optimize establecido a -1.
PyObject *Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags,
int optimize)
Return value: New reference. Parse and compile the Python source code in str, returning the resulting code
object. The start token is given by start; this can be used to constrain the code which can be compiled and should
be Py_eval_input, Py_file_input, or Py_single_input. The filename specified by filename is
used to construct the code object and may appear in tracebacks or SyntaxError exception messages. This
returns NULL if the code cannot be parsed or compiled.
El número entero optimize especifica el nivel de optimización del compilador; un valor de -1 selecciona el nivel
de optimización del intérprete como se indica en las opciones -O. Los niveles explícitos son 0 (sin optimización;
__debug__ es verdadero), 1 (los asserts se eliminan, __debug__ es falso) o 2 (los docstrings también se
eliminan) )
Added in version 3.4.
PyObject *Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags
*flags, int optimize)
Return value: New reference. Como Py_CompileStringObject(), pero filename es una cadena de bytes
decodificada a partir del manejador de codificación y errores del sistema de archivos.
Added in version 3.2.
PyObject *PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz simplificada para
PyEval_EvalCodeEx(), con solo el objeto de código y las variables globales y locales. Los otros ar-
gumentos están establecidos en NULL.
PyObject *PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int
argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int
defcount, PyObject *kwdefs, PyObject *closure)
Return value: New reference. Part of the Stable ABI. Evaluar un objeto de código precompilado, dado un
entorno particular para su evaluación. Este entorno consta de un diccionario de variables globales, un objeto de
mapeo de variables locales, arreglos de argumentos, palabras clave y valores predeterminados, un diccionario
de valores predeterminados para argumentos keyword-only y una tupla de cierre de células.
PyObject *PyEval_EvalFrame(PyFrameObject *f)
Return value: New reference. Part of the Stable ABI. Evaluar un marco de ejecución. Esta es una interfaz
simplificada para PyEval_EvalFrameEx(), para compatibilidad con versiones anteriores.
PyObject *PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Return value: New reference. Part of the Stable ABI. Esta es la función principal sin barnizar de la interpretación
de Python. El objeto de código asociado con el marco de ejecución del marco f se ejecuta, interpretando el
código de bytes y ejecutando llamadas según sea necesario. El parámetro adicional throwflag se puede ignorar
por lo general; si es verdadero, entonces se lanza una excepción de inmediato; esto se usa para los métodos
throw() de objetos generadores.
Distinto en la versión 3.4: Esta función ahora incluye una afirmación de depuración para ayudar a garantizar
que no descarte silenciosamente una excepción activa.
int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Esta función cambia los flags del marco de evaluación actual, y retorna verdad (true) en caso de éxito, falso
(false) en caso de fallo.
int Py_eval_input
El símbolo de inicio de la gramática de Python para expresiones aisladas; para usar con
Py_CompileString().
int Py_file_input
El símbolo de inicio de la gramática de Python para secuencias de declaración leídos desde un archivo u otra
fuente; para usar con Py_CompileString(). Este es el símbolo usado cuando se compile un código fuente
en Python arbitrariamente largo.
int Py_single_input
El símbolo de inicio de la gramática de Python para una declaración única; para usar con
Py_CompileString(). Este es el símbolo usado para el bucle interactivo del intérprete.
struct PyCompilerFlags
Esta es la estructura usada para contener los flags del compilador. En casos donde el código es sólo compilado,
es pasado como int flags, y en casos donde el código es ejecutado, es pasado como PyCompilerFlags
*flags. En este caso, from __future__ import puede modificar los flags.
Whenever PyCompilerFlags *flags is NULL, cf_flags is treated as equal to 0, and any modifica-
tion due to from __future__ import is discarded.
int cf_flags
Flags del compilador.
int cf_feature_version
cf_feature_version es la versión menor de Python. Debe ser inicializado a PY_MINOR_VERSION.
The field is ignored by default, it is used if and only if PyCF_ONLY_AST flag is set in cf_flags.
Distinto en la versión 3.8: Agregado el campo cf_feature_version.
int CO_FUTURE_DIVISION
Este bit puede ser configurado en flags para causar que un operador de división / sea interpretado como una
«división real» de acuerdo a PEP 238.
45
The Python/C API, Versión 3.12.4
Conteo de referencias
The functions and macros in this section are used for managing reference counts of Python objects.
Py_ssize_t Py_REFCNT(PyObject *o)
Get the reference count of the Python object o.
Note that the returned value may not actually reflect how many references to the object are actually held. For
example, some objects are «immortal» and have a very high refcount that does not reflect the actual number of
references. Consequently, do not rely on the returned value to be accurate, other than a value of 0 or 1.
Use the Py_SET_REFCNT() function to set an object reference count.
Distinto en la versión 3.10: Py_REFCNT() is changed to the inline static function.
Distinto en la versión 3.11: The parameter type is no longer const PyObject*.
void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)
Set the object o reference counter to refcnt.
Note that this function has no effect on immortal objects.
Added in version 3.9.
Distinto en la versión 3.12: Immortal objects are not modified.
void Py_INCREF(PyObject *o)
Indicate taking a new strong reference to object o, indicating it is in use and should not be destroyed.
Esta función se usa generalmente para convertir un borrowed reference en un strong reference en su lugar. La
función Py_NewRef() se puede utilizar para crear un nuevo strong reference.
When done using the object, release it by calling Py_DECREF().
El objeto no debe ser NULL; si no está seguro de que no sea NULL, use Py_XINCREF().
Do not expect this function to actually modify o in any way. For at least some objects, this function has no
effect.
Distinto en la versión 3.12: Immortal objects are not modified.
void Py_XINCREF(PyObject *o)
Similar to Py_INCREF(), but the object o can be NULL, in which case this has no effect.
Ver también Py_XNewRef().
47
The Python/C API, Versión 3.12.4
Advertencia: The deallocation function can cause arbitrary Python code to be invoked (e.g. when a class
instance with a __del__() method is deallocated). While exceptions in such code are not propagated,
the executed code has free access to all Python global variables. This means that any object that is reachable
from a global variable should be in a consistent state before Py_DECREF() is invoked. For example, code
to delete an object from a list should copy a reference to the deleted object in a temporary variable, update
the list data structure, and then call Py_DECREF() for the temporary variable.
Py_DECREF(dst);
dst = src;
Py_SETREF(dst, src);
That arranges to set dst to src _before_ releasing the reference to the old value of dst, so that any code triggered
as a side-effect of dst getting torn down no longer believes dst points to a valid object.
Added in version 3.6.
Distinto en la versión 3.12: The macro arguments are now only evaluated once. If an argument has side effects,
these are no longer duplicated.
Py_XSETREF(dst, src)
Variant of Py_SETREF macro that uses Py_XDECREF() instead of Py_DECREF().
Added in version 3.6.
Distinto en la versión 3.12: The macro arguments are now only evaluated once. If an argument has side effects,
these are no longer duplicated.
49
The Python/C API, Versión 3.12.4
Manejo de excepciones
Las funciones descritas en este capítulo le permitirán manejar y lanzar excepciones de Python. Es importante com-
prender algunos de los conceptos básicos del manejo de excepciones de Python. Funciona de manera similar a la
variable POSIX errno: hay un indicador global (por hilo) del último error que ocurrió. La mayoría de las funciones
de C API no borran esto en caso de éxito, pero lo configurarán para indicar la causa del error en caso de falla. La
mayoría de las funciones de C API también retornan un indicador de error, generalmente NULL si se supone que
retornan un puntero, o -1 si retornan un número entero (excepción: las funciones PyArg_* retornan 1 para el éxito
y 0 para el fracaso).
Concretamente, el indicador de error consta de tres punteros de objeto: el tipo de excepción, el valor de la excep-
ción y el objeto de rastreo. Cualquiera de esos punteros puede ser NULL si no está configurado (aunque algunas
combinaciones están prohibidas, por ejemplo, no puede tener un rastreo no NULL si el tipo de excepción es NULL).
Cuando una función debe fallar porque alguna función que llamó falló, generalmente no establece el indicador de
error; la función que llamó ya lo configuró. Es responsable de manejar el error y borrar la excepción o regresar
después de limpiar cualquier recurso que tenga (como referencias de objetos o asignaciones de memoria); debería
no continuar normalmente si no está preparado para manejar el error. Si regresa debido a un error, es importante
indicarle a la persona que llama que se ha establecido un error. Si el error no se maneja o se propaga cuidadosamente,
es posible que las llamadas adicionales a la API de Python/C no se comporten como se espera y pueden fallar de
manera misteriosa.
void PyErr_Clear()
Part of the Stable ABI. Borra el indicador de error. Si el indicador de error no está configurado, no hay efecto.
void PyErr_PrintEx(int set_sys_last_vars)
Part of the Stable ABI. Imprime un rastreo estándar en sys.stderr y borra el indicador de error. A menos
que el error sea un Salida del sistema, en ese caso no se imprime ningún rastreo y el proceso de
Python se cerrará con el código de error especificado por la instancia de Salida del sistema.
51
The Python/C API, Versión 3.12.4
Llame a esta función solo cuando el indicador de error está configurado. De lo contrario, provocará un error
fatal!
If set_sys_last_vars is nonzero, the variable sys.last_exc is set to the printed exception. For
backwards compatibility, the deprecated variables sys.last_type, sys.last_value and sys.
last_traceback are also set to the type, value and traceback of this exception, respectively.
Distinto en la versión 3.12: The setting of sys.last_exc was added.
void PyErr_Print()
Part of the Stable ABI. Alias para PyErr_PrintEx(1).
void PyErr_WriteUnraisable(PyObject *obj)
Part of the Stable ABI. Llama sys.unraisablehook() utilizando la excepción actual y el argumento
obj.
This utility function prints a warning message to sys.stderr when an exception has been set but it is
impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs
in an __del__() method.
The function is called with a single argument obj that identifies the context in which the unraisable exception
occurred. If possible, the repr of obj will be printed in the warning message. If obj is NULL, only the traceback
is printed.
Se debe establecer una excepción al llamar a esta función.
Distinto en la versión 3.4: Print a traceback. Print only traceback if obj is NULL.
Distinto en la versión 3.8: Use sys.unraisablehook().
void PyErr_DisplayException(PyObject *exc)
Part of the Stable ABI since version 3.12. Print the standard traceback display of exc to sys.stderr,
including chained exceptions and notes.
Added in version 3.12.
Estas funciones lo ayudan a configurar el indicador de error del hilo actual. Por conveniencia, algunas de estas fun-
ciones siempre retornarán un puntero NULL para usar en una declaración return.
void PyErr_SetString(PyObject *type, const char *message)
Part of the Stable ABI. This is the most common way to set the error indicator. The first argument specifies the
exception type; it is normally one of the standard exceptions, e.g. PyExc_RuntimeError. You need not
create a new strong reference to it (e.g. with Py_INCREF()). The second argument is an error message; it is
decoded from 'utf-8'.
void PyErr_SetObject(PyObject *type, PyObject *value)
Part of the Stable ABI. Esta función es similar a PyErr_SetString() pero le permite especificar un objeto
Python arbitrario para el «valor» de la excepción.
PyObject *PyErr_Format(PyObject *exception, const char *format, ...)
Return value: Always NULL. Part of the Stable ABI. Esta función establece el indicador de error y retorna
NULL. exception debe ser una clase de excepción Python. El format y los parámetros posteriores ayudan a
formatear el mensaje de error; tienen el mismo significado y valores que en PyUnicode_FromFormat().
format es una cadena de caracteres codificada en ASCII.
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Return value: Always NULL. Part of the Stable ABI since version 3.5. Igual que PyErr_Format(), pero
tomando un argumento va_list en lugar de un número variable de argumentos.
Added in version 3.5.
PyErr_SetFromWindowsErr(), with the additional behavior that if filename is not NULL, it is deco-
ded from the filesystem encoding (os.fsdecode()) and passed to the constructor of OSError as a third
parameter to be used to define the filename attribute of the exception instance.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject
*filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar to
PyErr_SetExcFromWindowsErr(), with the additional behavior that if filename is not NULL, it is
passed to the constructor of OSError as a third parameter to be used to define the filename attribute of
the exception instance.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject
*filename, PyObject *filename2)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a
PyErr_SetExcFromWindowsErrWithFilenameObject(), pero acepta un segundo objeto de
nombre de archivo.
Disponibilidad: Windows.
Added in version 3.4.
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char
*filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a
PyErr_SetFromWindowsErrWithFilename(), con un parámetro adicional que especifica el tipo
de excepción que se lanzará.
Disponibilidad: Windows.
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.7. Esta es una función conveniente para subir
ImportError. msg se establecerá como la cadena de mensaje de la excepción. name y path, que pueden ser
NULL, se establecerán como atributos respectivos name y path de ImportError.
Added in version 3.3.
PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name,
PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.6. Al igual que
PyErr_SetImportError() pero esta función permite especificar una subclase de ImportError para
aumentar.
Added in version 3.6.
void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Establece información de archivo, línea y desplazamiento para la excepción actual. Si la excepción actual no es
un SyntaxError, establece atributos adicionales, lo que hace que el sub sistema de impresión de excepciones
piense que la excepción es SyntaxError.
Added in version 3.4.
void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Part of the Stable ABI since version 3.7. Como PyErr_SyntaxLocationObject(), pero filename es
una cadena de bytes decodificada a partir de filesystem encoding and error handler.
Added in version 3.2.
void PyErr_SyntaxLocation(const char *filename, int lineno)
Part of the Stable ABI. Como PyErr_SyntaxLocationEx(), pero se omite el parámetro col_offset.
void PyErr_BadInternalCall()
Part of the Stable ABI. Esta es una abreviatura de PyErr_SetString(PyExc_SystemError,
message), donde message indica que se invocó una operación interna (por ejemplo, una función de Pyt-
hon/C API) con un argumento ilegal. Es principalmente para uso interno.
Use estas funciones para emitir advertencias desde el código C. Reflejan funciones similares exportadas por el módulo
Python warnings. Normalmente imprimen un mensaje de advertencia a sys.stderr; sin embargo, también es posible
que el usuario haya especificado que las advertencias se conviertan en errores, y en ese caso lanzarán una excepción.
También es posible que las funciones generen una excepción debido a un problema con la maquinaria de advertencia.
El valor de retorno es 0 si no se lanza una excepción, o -1 si se lanza una excepción. (No es posible determinar
si realmente se imprime un mensaje de advertencia, ni cuál es el motivo de la excepción; esto es intencional). Si se
produce una excepción, la persona que llama debe hacer su manejo normal de excepciones (por ejemplo, referencias
propiedad de Py_DECREF() y retornan un valor de error).
int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Part of the Stable ABI. Emite un mensaje de advertencia. El argumento category es una categoría de advertencia
(ver más abajo) o NULL; el argumento message es una cadena de caracteres codificada en UTF-8. stack_level
es un número positivo que proporciona una cantidad de marcos de pila; la advertencia se emitirá desde la línea
de código que se está ejecutando actualmente en ese marco de pila. Un stack_level de 1 es la función que llama
PyErr_WarnEx(), 2 es la función por encima de eso, y así sucesivamente.
Las categorías de advertencia deben ser subclases de PyExc_Warning; PyExc_Warning es una subcla-
se de PyExc_Exception; la categoría de advertencia predeterminada es PyExc_RuntimeWarning.
Las categorías de advertencia estándar de Python están disponibles como variables globales cuyos nombres se
enumeran en Categorías de advertencia estándar.
Para obtener información sobre el control de advertencia, consulte la documentación del módulo warnings
y la opción -W en la documentación de la línea de comandos. No hay API de C para el control de advertencia.
int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno,
PyObject *module, PyObject *registry)
Emite un mensaje de advertencia con control explícito sobre todos los atributos de advertencia. Este es un
contenedor sencillo alrededor de la función Python warnings.warn_explicit(); consulte allí para
obtener más información. Los argumentos module y registry pueden establecerse en NULL para obtener el
efecto predeterminado que se describe allí.
Added in version 3.4.
int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const
char *module, PyObject *registry)
Part of the Stable ABI. Similar a PyErr_WarnExplicitObject() excepto que message y module son
cadenas codificadas UTF-8, y filename se decodifica de filesystem encoding and error handler.
int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI. Función similar a PyErr_WarnEx(), pero usa PyUnicode_FromFormat()
para formatear el mensaje de advertencia. format es una cadena de caracteres codificada en ASCII.
Added in version 3.2.
int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI since version 3.6. Function similar to PyErr_WarnFormat(), but category is
ResourceWarning and it passes source to warnings.WarningMessage.
Added in version 3.6.
PyObject *PyErr_Occurred()
Return value: Borrowed reference. Part of the Stable ABI. Prueba si el indicador de error está configurado.
Si se establece, retorna la excepción type (el primer argumento de la última llamada a una de las funciones
PyErr_Set* o PyErr_Restore()). Si no está configurado, retorna NULL. No posee una referencia al
valor de retorno, por lo que no necesita usar Py_DECREF().
La persona que llama debe retener el GIL.
Nota: No compare el valor de retorno con una excepción específica; use PyErr_ExceptionMatches()
en su lugar, como se muestra a continuación. (La comparación podría fallar fácilmente ya que la excepción
puede ser una instancia en lugar de una clase, en el caso de una excepción de clase, o puede ser una subclase
de la excepción esperada).
{
PyObject *exc = PyErr_GetRaisedException();
PyErr_SetRaisedException(exc);
}
Ver también:
PyErr_GetHandledException(), to save the exception currently being handled.
Added in version 3.12.
void PyErr_SetRaisedException(PyObject *exc)
Part of the Stable ABI since version 3.12. Set exc as the exception currently being raised, clearing the existing
exception if one is set.
Advertencia: This call steals a reference to exc, which must be a valid exception.
Nota: This function is normally only used by legacy code that needs to catch exceptions or save and restore
the error indicator temporarily.
For example:
{
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
Nota: This function is normally only used by legacy code that needs to save and restore the error indicator
temporarily. Use PyErr_Fetch() to save the current error indicator.
Nota: This function does not implicitly set the __traceback__ attribute on the exception value. If setting
the traceback appropriately is desired, the following additional snippet is needed:
if (tb != NULL) {
PyException_SetTraceback(val, tb);
}
PyObject *PyErr_GetHandledException(void)
Part of the Stable ABI since version 3.11. Recupera la instancia de excepción activa, como la que devolvería
sys.exception(). Esto se refiere a una excepción que ya fue capturada, no a una excepción recién lan-
zada. Retorna una nueva referencia a la excepción o NULL. No modifica el estado de excepción del intérprete.
Nota: Esta función normalmente no es utilizada por el código que quiere manejar excepciones. En cam-
bio, se puede usar cuando el código necesita guardar y restaurar el estado de excepción temporalmente. Use
PyErr_SetHandledException() para restaurar o borrar el estado de excepción.
Nota: Esta función normalmente no es utilizada por el código que quiere manejar excepciones. En cam-
bio, se puede usar cuando el código necesita guardar y restaurar el estado de excepción temporalmente. Use
PyErr_GetHandledException() para leer el estado de excepción.
Nota: Esta función normalmente no es utilizada por el código que quiere manejar excepciones. En cam-
bio, se puede usar cuando el código necesita guardar y restaurar el estado de excepción temporalmente. Use
PyErr_SetExcInfo() para restaurar o borrar el estado de excepción.
Nota: Esta función normalmente no es utilizada por el código que quiere manejar excepciones. En cam-
bio, se puede usar cuando el código necesita guardar y restaurar el estado de excepción temporalmente. Use
PyErr_GetExcInfo() para leer el estado de excepción.
int PyErr_CheckSignals()
Part of the Stable ABI. Esta función interactúa con el manejo de señales de Python.
Si la función se llama desde el hilo principal y bajo el intérprete principal de Python, verifica si se ha enviado
una señal a los procesos y, de ser así, invoca el manejador de señales correspondiente. Si el módulo signal
es compatible, esto puede invocar un manejador de señales escrito en Python.
La función intenta manejar todas las señales pendientes y luego devuelve 0. Sin embargo, si un manejador de
señales de Python lanza una excepción, el indicador de error se establece y la función devuelve -1 inmedia-
tamente (de modo que es posible que otras señales pendientes no se hayan manejado todavía: estarán en la
siguiente invocación de PyErr_CheckSignals()).
Si la función se llama desde un hilo no principal, o bajo un intérprete de Python no principal, no hace nada y
devuelve 0.
Esta función se puede llamar mediante un código C de ejecución prolongada que quiere ser interrumpible por
las peticiones del usuario (como presionar Ctrl-C).
Nota: The default Python signal handler for SIGINT raises the KeyboardInterrupt exception.
void PyErr_SetInterrupt()
Part of the Stable ABI. Simulate the effect of a SIGINT signal arriving. This is equivalent to
PyErr_SetInterruptEx(SIGINT).
Nota: Esta función es segura para señales asíncronas. Se puede llamar sin el GIL y desde un manejador de
señales de C.
Nota: Esta función es segura para señales asíncronas. Se puede llamar sin el GIL y desde un manejador de
señales de C.
Implement part of the interpreter’s implementation of except*. orig is the original exception that was caught,
and excs is the list of the exceptions that need to be raised. This list contains the unhandled part of orig, if any,
as well as the exceptions that were raised from the except* clauses (so they have a different traceback from
orig) and those that were reraised (and have the same traceback as orig). Return the ExceptionGroup that
needs to be reraised in the end, or None if there is nothing to reraise.
Added in version 3.12.
Estas dos funciones proporcionan una forma de realizar llamadas recursivas seguras en el nivel C, tanto en el núcleo
como en los módulos de extensión. Son necesarios si el código recursivo no invoca necesariamente el código Python
(que rastrea su profundidad de recursión automáticamente). Tampoco son necesarios para las implementaciones de
tp_call porque call protocol se encarga del manejo de la recursividad.
int Py_EnterRecursiveCall(const char *where)
Part of the Stable ABI since version 3.9. Marca un punto donde una llamada recursiva de nivel C está a punto
de realizarse.
If USE_STACKCHECK is defined, this function checks if the OS stack overflowed using
PyOS_CheckStack(). If this is the case, it sets a MemoryError and returns a nonzero value.
La función verifica si se alcanza el límite de recursión. Si este es el caso, se establece a RecursionError
y se retorna un valor distinto de cero. De lo contrario, se retorna cero.
where debería ser una cadena de caracteres codificada en UTF-8 como "en la comprobación de
instancia" para concatenarse con el mensaje RecursionError causado por el límite de profundidad
de recursión.
Distinto en la versión 3.9: This function is now also available in the limited API.
void Py_LeaveRecursiveCall(void)
Part of the Stable ABI since version 3.9. Termina una Py_EnterRecursiveCall(). Se debe llamar una
vez por cada invocación exitosa de Py_EnterRecursiveCall().
Distinto en la versión 3.9: This function is now also available in the limited API.
La implementación adecuada de tp_repr para los tipos de contenedor requiere un manejo de recursión especial.
Además de proteger la pila, tp_repr también necesita rastrear objetos para evitar ciclos. Las siguientes dos funcio-
nes facilitan esta funcionalidad. Efectivamente, estos son los C equivalentes a reprlib.recursive_repr().
Todas las excepciones estándar de Python están disponibles como variables globales cuyos nombres son PyExc_
seguidos del nombre de excepción de Python. Estos tienen el tipo PyObject*; todos son objetos de clase. Para
completar, aquí están todas las variables:
Nombre en C Notas
PyExc_EnvironmentError
PyExc_IOError
2
PyExc_WindowsError
Distinto en la versión 3.3: Estos alias solían ser tipos de excepción separados.
Notas:
Todas las categorías de advertencia estándar de Python están disponibles como variables globales cuyos nombres son
PyExc_ seguidos del nombre de excepción de Python. Estos tienen el tipo PyObject*; todos son objetos de clase.
Para completar, aquí están todas las variables:
Utilidades
Las funciones de este capítulo realizan varias tareas de utilidad, que van desde ayudar a que el código C sea más portátil
en todas las plataformas, usar módulos Python desde C y analizar argumentos de funciones y construir valores Python
a partir de valores C.
Advertencia: La llamada C fork() solo debe hacerse desde hilo «principal» (del intérprete «principal»).
Lo mismo es cierto para PyOS_BeforeFork().
65
The Python/C API, Versión 3.12.4
o cualquier función similar que clone el proceso actual, independientemente de si la clonación del proceso fue
exitosa. Solo disponible en sistemas donde fork() está definido.
Advertencia: La llamada C fork() solo debe hacerse desde hilo «principal» (del intérprete «principal»).
Lo mismo es cierto para PyOS_AfterFork_Parent().
Advertencia: La llamada C fork() solo debe hacerse desde hilo «principal» (del intérprete «principal»).
Lo mismo es cierto para PyOS_AfterFork_Child().
Advertencia: Esta función no debe llamarse directamente: utilice la API PyConfig con la función
PyConfig_SetBytesString() que asegura que Python está preinicializado.
Esta función no debe llamarse antes de que Python esté preinicializado y para que la configuración local
LC_CTYPE esté correctamente configurada: véase la función Py_PreInitialize().
66 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
Decodifica una cadena de bytes a partir del manejador de codificación y errores del sistema de archivos. Si el
controlador de error es el controlador de error surrogateescape, los bytes no codificables se decodifican como
caracteres en el rango U+DC80..U+DCFF; y si una secuencia de bytes se puede decodificar como un carácter
sustituto, escape los bytes usando el controlador de error surrogateescape en lugar de decodificarlos.
Retorna un puntero a una cadena de caracteres anchos recientemente asignada, use PyMem_RawFree() para
liberar la memoria. Si el tamaño no es NULL, escribe el número de caracteres anchos excluyendo el carácter
nulo en *size
Retorna NULL en caso de error de decodificación o error de asignación de memoria. Si size no es NULL,
*size se establece en (size_t) -1 en caso de error de memoria o en (size_t) -2 en caso de error
de decodificación.
El filesystem encoding and error handler son seleccionados por PyConfig_Read(): ver
filesystem_encoding y filesystem_errors que pertenecen a PyConfig.
Los errores de decodificación nunca deberían ocurrir, a menos que haya un error en la biblioteca C.
Utilice la función Py_EncodeLocale() para codificar la cadena de caracteres en una cadena de bytes.
Ver también:
Las funciones PyUnicode_DecodeFSDefaultAndSize() y PyUnicode_DecodeLocaleAndSize().
Added in version 3.5.
Distinto en la versión 3.7: La función ahora utiliza la codificación UTF-8 en el Modo Python UTF-8.
Distinto en la versión 3.8: The function now uses the UTF-8 encoding on Windows if PyPreConfig.
legacy_windows_fs_encoding is zero;
char *Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
Part of the Stable ABI since version 3.7. Codifica una cadena de caracteres amplios según el término filesystem
encoding and error handler. Si el gestor de errores es surrogateescape error handler, los caracteres sustituidos
en el rango U+DC80..U+DCFF se convierten en bytes 0x80..0xFF.
Retorna un puntero a una cadena de bytes recién asignada, usa PyMem_Free() para liberar la memoria.
Retorna NULL si se genera un error de codificación o error de asignación de memoria.
Si error_pos no es NULL, *error_pos se establece en (size_t)-1 en caso de éxito, o se establece en el
índice del carácter no válido en el error de codificación.
El filesystem encoding and error handler son seleccionados por PyConfig_Read(): ver
filesystem_encoding y filesystem_errors que pertenecen a PyConfig.
Use la función Py_DecodeLocale() para decodificar la cadena de bytes en una cadena de caracteres
anchos.
Advertencia: Esta función no debe llamarse antes de que Python esté preinicializado y para que la confi-
guración local LC_CTYPE esté correctamente configurada: véase la función Py_PreInitialize().
Ver también:
Las funciones PyUnicode_EncodeFSDefault() y PyUnicode_EncodeLocale().
Added in version 3.5.
Distinto en la versión 3.7: La función ahora utiliza la codificación UTF-8 en el Modo Python UTF-8.
Distinto en la versión 3.8: The function now uses the UTF-8 encoding on Windows if PyPreConfig.
legacy_windows_fs_encoding is zero.
Estas son funciones de utilidad que hacen que la funcionalidad del módulo sys sea accesible para el código C. Todos
funcionan con el diccionario del módulo sys del subproceso actual del intérprete, que está contenido en la estructura
interna del estado del subproceso.
PyObject *PySys_GetObject(const char *name)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto name del módulo sys o NULL si
no existe, sin establecer una excepción.
int PySys_SetObject(const char *name, PyObject *v)
Part of the Stable ABI. Establece name en el módulo sys en v a menos que v sea NULL, en cuyo caso name
se elimina del módulo sys. Retorna 0 en caso de éxito, -1 en caso de error.
void PySys_ResetWarnOptions()
Part of the Stable ABI. Restablece sys.warnoptions a una lista vacía. Esta función puede llamarse antes
de Py_Initialize().
void PySys_AddWarnOption(const wchar_t *s)
Part of the Stable ABI. Esta API se mantiene para conservar compatibilidad con versiones anteriores, en su
lugar se debe usar: PyConfig.warnoptions, ver Configuración de inicialización de Python.
Agrega s a sys.warnoptions. Esta función debe llamarse antes de Py_Initialize() para afectar la
lista de filtros de advertencias.
Obsoleto desde la versión 3.11.
void PySys_AddWarnOptionUnicode(PyObject *unicode)
Part of the Stable ABI. Esta API se mantiene para conservar compatibilidad con versiones anteriores, en su
lugar se debe usar: PyConfig.warnoptions, ver Configuración de inicialización de Python.
Agrega unicode a sys.warnoptions.
Nota: esta función no se puede utilizar actualmente desde fuera de la implementación de CPython, ya que debe
llamarse antes de la importación implícita de warnings en Py_Initialize() para que sea efectiva,
pero no se puede llamar hasta que se haya inicializado suficiente tiempo de ejecución para permitir la creación
de objetos Unicode.
Obsoleto desde la versión 3.11.
void PySys_SetPath(const wchar_t *path)
Part of the Stable ABI. Esta API se mantiene para conservar compatibilidad con versiones anteriores, en su lugar
se debe usar: PyConfig.module_search_paths y PyConfig.module_search_paths_set,
ver Python Initialization Configuration.
Establece sys.path en un objeto lista de rutas que se encuentra en path, que debería ser una lista de rutas
separadas con el delimitador de ruta de búsqueda de la plataforma (: en Unix, ; en Windows )
Obsoleto desde la versión 3.11.
void PySys_WriteStdout(const char *format, ...)
Part of the Stable ABI. Escribe la cadena de caracteres de salida descrita por format en sys.stdout. No se
lanzan excepciones, incluso si se produce el truncamiento (ver más abajo).
format debe limitar el tamaño total de la cadena de caracteres de salida formateada a 1000 bytes o menos;
después de 1000 bytes, la cadena de caracteres de salida se trunca. En particular, esto significa que no deben
existir formatos «%s» sin restricciones; estos deben limitarse usando «%.<N>s» donde <N> es un número
decimal calculado de modo que <N> más el tamaño máximo de otro texto formateado no exceda los 1000
bytes. También tenga cuidado con «%f», que puede imprimir cientos de dígitos para números muy grandes.
Si ocurre un problema, o sys.stdout no está configurado, el mensaje formateado se escribe en el real (nivel
C) stdout.
68 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
Ver PEP 578 para una descripción detallada de la auditoría. Las funciones en el tiempo de ejecución y la
biblioteca estándar que generan eventos se enumeran en table de eventos de auditoria. Los detalles se encuentran
en la documentación de cada función.
Lanza un evento de auditoria sys.addaudithook sin argumentos.
typedef int (*Py_AuditHookFunction)(const char *event, PyObject *args, void *userData)
The type of the hook function. event is the C string event argument passed to PySys_Audit(). args
is guaranteed to be a PyTupleObject. userData is the argument passed to PySys_AddAuditHook().
Added in version 3.8.
70 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
El valor de retorno es una nueva referencia al módulo importado o paquete de nivel superior, o NULL con una
excepción establecida en caso de error. Al igual que para __import__(), el valor de retorno cuando se
solicitó un submódulo de un paquete normalmente es el paquete de nivel superior, a menos que se proporcione
un fromlist no vacío.
Las importaciones que fallan eliminan objetos de módulo incompletos, como con
PyImport_ImportModule().
PyObject *PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI since version 3.7. Importa un módulo. Esto se descri-
be mejor haciendo referencia a la función Python incorporada __import__(), ya que la función estándar
__import__() llama a esta función directamente.
El valor de retorno es una nueva referencia al módulo importado o paquete de nivel superior, o NULL con una
excepción establecida en caso de error. Al igual que para __import__(), el valor de retorno cuando se
solicitó un submódulo de un paquete normalmente es el paquete de nivel superior, a menos que se proporcione
un fromlist no vacío.
Added in version 3.3.
PyObject *PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI. Similar a PyImport_ImportModuleLevelObject(),
pero el nombre es una cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
Distinto en la versión 3.3: Los valores negativos para level ya no se aceptan.
PyObject *PyImport_Import(PyObject *name)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz de nivel superior que llama a la
«función de enlace de importación» actual (con un nivel explícito de 0, que significa importación absoluta).
Invoca la función __import__() de las __builtins__ de los globales (globals) actuales. Esto significa
que la importación se realiza utilizando los ganchos de importación instalados en el entorno actual.
Esta función siempre usa importaciones absolutas.
PyObject *PyImport_ReloadModule(PyObject *m)
Return value: New reference. Part of the Stable ABI. Recarga un módulo. Retorna una nueva referencia al
módulo recargado, o NULL con una excepción establecida en caso de error (el módulo todavía existe en este
caso).
PyObject *PyImport_AddModuleObject(PyObject *name)
Return value: Borrowed reference. Part of the Stable ABI since version 3.7. Retorna el objeto módulo corres-
pondiente a un nombre de módulo. El argumento name puede tener la forma package.module. Primero
revise el diccionario de módulos si hay uno allí, y si no, crea uno nuevo y lo agrega al diccionario de módulos.
Retorna NULL con una excepción establecida en caso de error.
Nota: Esta función no carga ni importa el módulo; si el módulo no estaba cargado, obtendrá un objeto de
módulo vacío. Utilice PyImport_ImportModule() o una de sus variantes para importar un módulo. Las
estructuras de paquete implicadas por un nombre punteado para name no se crean si aún no están presentes.
set if an error occurred. name is removed from sys.modules in error cases, even if name was already in
sys.modules on entry to PyImport_ExecCodeModule(). Leaving incompletely initialized modules
in sys.modules is dangerous, as imports of such modules have no way to know that the module object is
an unknown (and probably damaged with respect to the module author’s intents) state.
The module’s __spec__ and __loader__ will be set, if not set already, with the appropriate values. The
spec’s loader will be set to the module’s __loader__ (if set) and to an instance of SourceFileLoader
otherwise.
The module’s __file__ attribute will be set to the code object’s co_filename. If applicable,
__cached__ will also be set.
Esta función volverá a cargar el módulo si ya se importó. Consulte PyImport_ReloadModule() para
conocer la forma prevista de volver a cargar un módulo.
Si name apunta a un nombre punteado de la forma package.module, cualquier estructura de paquete que
no se haya creado aún no se creará.
Ver también PyImport_ExecCodeModuleEx() y PyImport_ExecCodeModuleWithPathnames().
Distinto en la versión 3.12: The setting of __cached__ and __loader__ is deprecated. See
ModuleSpec for alternatives.
PyObject *PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Return value: New reference. Part of the Stable ABI. Como PyImport_ExecCodeModule(), pero el
atributo __file__ del objeto del módulo se establece en pathname si no es NULL.
Ver también PyImport_ExecCodeModuleWithPathnames().
PyObject *PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
PyObject *cpathname)
Return value: New reference. Part of the Stable ABI since version 3.7. Como
PyImport_ExecCodeModuleEx(), pero el atributo __cached__ del objeto módulo se establece en
cpathname si no es NULL. De las tres funciones, esta es la recomendada para usar.
Added in version 3.3.
Distinto en la versión 3.12: Setting __cached__ is deprecated. See ModuleSpec for alternatives.
PyObject *PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char
*pathname, const char *cpathname)
Return value: New reference. Part of the Stable ABI. Como PyImport_ExecCodeModuleObject(),
pero name, pathname y cpathname son cadenas de caracteres codificadas UTF-8. También se intenta averiguar
cuál debe ser el valor de pathname de cpathname si el primero se establece en NULL.
Added in version 3.2.
Distinto en la versión 3.3: Uses imp.source_from_cache() in calculating the source path if only the
bytecode path is provided.
Distinto en la versión 3.12: No longer uses the removed imp module.
long PyImport_GetMagicNumber()
Part of the Stable ABI. Retorna el número mágico para los archivos de bytecode de Python (también conocido
como archivos .pyc). El número mágico debe estar presente en los primeros cuatro bytes del archivo de código
de bytes, en orden de bytes little-endian. Retorna -1 en caso de error.
Distinto en la versión 3.3: Retorna un valor de -1 en caso de error.
const char *PyImport_GetMagicTag()
Part of the Stable ABI. Retorna la cadena de caracteres de etiqueta mágica para nombres de archivo de có-
digo de bytes Python en formato PEP 3147. Tenga en cuenta que el valor en sys.implementation.
cache_tag es autoritario y debe usarse en lugar de esta función.
Added in version 3.2.
72 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
PyObject *PyImport_GetModuleDict()
Return value: Borrowed reference. Part of the Stable ABI. Retorna el diccionario utilizado para la administración
del módulo (también conocido como sys.modules). Tenga en cuenta que esta es una variable por intérprete.
PyObject *PyImport_GetModule(PyObject *name)
Return value: New reference. Part of the Stable ABI since version 3.8. Retorna el módulo ya importado con el
nombre dado. Si el módulo aún no se ha importado, retorna NULL pero no establece un error. Retorna NULL
y establece un error si falla la búsqueda.
Added in version 3.7.
PyObject *PyImport_GetImporter(PyObject *path)
Return value: New reference. Part of the Stable ABI. Return a finder object for a sys.path/pkg.__path__
item path, possibly by fetching it from the sys.path_importer_cache dict. If it wasn’t yet cached,
traverse sys.path_hooks until a hook is found that can handle the path item. Return None if no hook
could; this tells our caller that the path based finder could not find a finder for this path item. Cache the result
in sys.path_importer_cache. Return a new reference to the finder object.
int PyImport_ImportFrozenModuleObject(PyObject *name)
Part of the Stable ABI since version 3.7. Carga un módulo congelado llamado name. Retorna 1 para el éxito,
0 si no se encuentra el módulo y -1 con una excepción establecida si falla la inicialización. Para acceder al
módulo importado con una carga exitosa, use PyImport_ImportModule(). (Tenga en cuenta el nombre
inapropiado — esta función volvería a cargar el módulo si ya se importó).
Added in version 3.3.
Distinto en la versión 3.4: El atributo __file__ ya no está establecido en el módulo.
int PyImport_ImportFrozenModule(const char *name)
Part of the Stable ABI. Similar a PyImport_ImportFrozenModuleObject(), pero el nombre es una
cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
struct _frozen
Esta es la definición del tipo de estructura para los descriptores de módulos congelados, según lo generado con
la herramienta freeze (ver Tools/freeze en la distribución de código fuente de Python). Su definición,
que se encuentra en Include/import.h, es:
struct _frozen {
const char *name;
const unsigned char *code;
int size;
bool is_package;
};
Distinto en la versión 3.11: El nuevo campo is_package indica si el módulo es un paquete o no. Esto
sustituye a la configuración del campo size con un valor negativo.
const struct _frozen *PyImport_FrozenModules
Este puntero se inicializa para apuntar a un arreglo de registros _frozen, terminado por uno cuyos registros
son todos NULL o cero. Cuando se importa un módulo congelado, se busca en esta tabla. El código de terceros
podría jugar con esto para proporcionar una colección de módulos congelados creada dinámicamente.
int PyImport_AppendInittab(const char *name, PyObject *(*initfunc)(void))
Part of the Stable ABI. Agrega un solo módulo a la tabla existente de módulos incorporados. Este es un con-
tenedor conveniente PyImport_ExtendInittab(), que retorna -1 si la tabla no se puede extender. El
nuevo módulo se puede importar con el nombre name, y utiliza la función initfunc como la función de inicia-
lización llamada en el primer intento de importación. Esto debería llamarse antes de Py_Initialize().
struct _inittab
Structure describing a single entry in the list of built-in modules. Programs which embed Python may use an
array of these structures in conjunction with PyImport_ExtendInittab() to provide additional built-in
modules. The structure consists of two members:
Estas rutinas permiten que el código C funcione con objetos serializados utilizando el mismo formato de datos que
el módulo marshal. Hay funciones para escribir datos en el formato de serialización y funciones adicionales que
se pueden usar para volver a leer los datos. Los archivos utilizados para almacenar datos ordenados deben abrirse en
modo binario.
Los valores numéricos se almacenan con el byte menos significativo primero.
El módulo admite dos versiones del formato de datos: la versión 0 es la versión histórica, la versión 1 comparte
cadenas de caracteres internas en el archivo y al desempaquetar (unmarshalling). La versión 2 usa un formato binario
para números de punto flotante. Py_MARSHAL_VERSION indica el formato de archivo actual (actualmente 2).
void PyMarshal_WriteLongToFile(long value, FILE *file, int version)
Empaqueta (marshal) un entero value long a un archivo file. Esto solo escribirá los 32 bits menos significativos
de value; sin importar el tamaño del tipo long nativo. version indica el formato del archivo.
This function can fail, in which case it sets the error indicator. Use PyErr_Occurred() to check for that.
void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)
Empaqueta (marshal) un objeto Python, value, a un archivo file. version indica el formato del archivo.
This function can fail, in which case it sets the error indicator. Use PyErr_Occurred() to check for that.
PyObject *PyMarshal_WriteObjectToString(PyObject *value, int version)
Return value: New reference. Retorna un objeto de bytes que contiene la representación empaquetada (mars-
halled) de value. version indica el formato del archivo.
Las siguientes funciones permiten volver a leer los valores empaquetados (marshalled).
long PyMarshal_ReadLongFromFile(FILE *file)
Retorna un entero long de C desde el flujo de datos FILE* abierto para lectura. Solo se puede leer un valor
de 32 bits con esta función, independientemente del tamaño nativo del tipo long.
En caso de error, establece la excepción apropiada (EOFError) y retorna -1.
int PyMarshal_ReadShortFromFile(FILE *file)
Retorna un entero short de C desde el flujo de datos FILE* abierto para lectura. Solo se puede leer un valor
de 16 bits con esta función, independientemente del tamaño nativo del tipo short.
En caso de error, establece la excepción apropiada (EOFError) y retorna -1.
PyObject *PyMarshal_ReadObjectFromFile(FILE *file)
Return value: New reference. Retorna un objeto Python del flujo de datos FILE* abierto para lectura.
En caso de error, establece la excepción apropiada (EOFError, ValueError o TypeError) y retorna
NULL.
74 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
Estas funciones son útiles al crear sus propias funciones y métodos de extensiones. Información y ejemplos adicionales
están disponibles en extending-index.
Las tres primeras de estas funciones descritas, PyArg_ParseTuple(),
PyArg_ParseTupleAndKeywords(), y PyArg_Parse(), todas usan cadenas de caracteres de for-
mato que se utilizan para contarle a la función sobre los argumentos esperados. Las cadenas de caracteres de formato
utilizan la misma sintaxis para cada una de estas funciones.
Una cadena de formato consta de cero o más «unidades de formato.» Una unidad de formato describe un objeto
Python; por lo general es un solo carácter o una secuencia de unidades formato entre paréntesis. Con unas pocas
excepciones, una unidad de formato que no es una secuencia entre paréntesis normalmente corresponde a un único
argumento de dirección de estas funciones. En la siguiente descripción, la forma citada es la unidad de formato; la
entrada en paréntesis (redondos) es el tipo de objeto Python que coincida con la unidad de formato; y la entrada entre
corchetes [cuadrados] es el tipo de la variable(s) C cuya dirección debe ser pasada.
Estos formatos permiten acceder a un objeto como un bloque contiguo de memoria. Usted no tiene que proporcionar
almacenamiento en bruto para el Unicode o área de bytes retornada.
A menos que se indique lo contrario, los búferes no son terminados en NULL (NUL-terminated).
There are three ways strings and buffers can be converted to C:
• Formats such as y* and s* fill a Py_buffer structure. This locks the underlying buffer so that the caller can
subsequently use the buffer even inside a Py_BEGIN_ALLOW_THREADS block without the risk of mutable
data being resized or destroyed. As a result, you have to call PyBuffer_Release() after you have finished
processing the data (or in any early abort case).
• The es, es#, et and et# formats allocate the result buffer. You have to call PyMem_Free() after you
have finished processing the data (or in any early abort case).
• Other formats take a str or a read-only bytes-like object, such as bytes, and provide a const char *
pointer to its buffer. In this case the buffer is «borrowed»: it is managed by the corresponding Python object,
and shares the lifetime of this object. You won’t have to release any memory yourself.
To ensure that the underlying buffer may be safely borrowed, the object’s PyBufferProcs.
bf_releasebuffer field must be NULL. This disallows common mutable objects such as bytearray,
but also some read-only objects such as memoryview of bytes.
Besides this bf_releasebuffer requirement, there is no check to verify whether the input object is im-
mutable (e.g. whether it would honor a request for a writable buffer, or whether another thread can mutate the
data).
Nota: Para todas las variantes de formatos # (s#, y#, etc.), la macro PY_SSIZE_T_CLEAN tiene que estar definida
antes de incluir Python.h. En Python 3.9 y versiones anteriores, el tipo del argumento length es Py_ssize_t si
la macro PY_SSIZE_T_CLEAN está definida, o int si no lo está.
Nota: Este formato no acepta objetos de tipo bytes. Si desea aceptar los caminos del sistema
de archivos y convertirlos en cadenas de caracteres C, es preferible utilizar el formato O& con
PyUnicode_FSConverter() como convertidor.
Distinto en la versión 3.5: Anteriormente, TypeError se lanzó cuando se encontraron puntos de código nulos
incrustados en la cadena de caracteres de Python.
s* (str o bytes-like object) [Py_buffer]
Este formato acepta objetos Unicode, así como objetos de tipo bytes. Llena una estructura Py_buffer pro-
porcionada por la persona que llama. En este caso la cadena de caracteres de C resultante puede contener
bytes NUL embebidos. Los objetos Unicode se convierten en cadenas de caracteres C utilizando codificación
'utf-8'.
s# (str, bytes-like object de sólo lectura) [const char *, Py_ssize_t]
Like s*, except that it provides a borrowed buffer. The result is stored into two C variables, the first one a
pointer to a C string, the second one its length. The string may contain embedded null bytes. Unicode objects
are converted to C strings using 'utf-8' encoding.
z (str o None) [const char *]
Como s, pero el objeto Python también puede ser None, en cuyo caso el puntero C se establece en NULL.
z* (str, bytes-like object o None) [Py_buffer]
Como s*, pero el objeto Python también puede ser None, en cuyo caso el miembro de buf de la estructura
Py_buffer se establece en NULL.
z# (str, bytes-like object de sólo lectura o None) [const char *, Py_ssize_t]
Como s#, pero el objeto Python también puede ser None, en cuyo caso el puntero C se establece en NULL.
y (bytes-like object de sólo lectura) [const char *]
This format converts a bytes-like object to a C pointer to a borrowed character string; it does not accept Unicode
objects. The bytes buffer must not contain embedded null bytes; if it does, a ValueError exception is raised.
Distinto en la versión 3.5: Anteriormente, TypeError se lanzó cuando bytes nulos incrustados se encontraron
en el buffer de bytes.
y* (bytes-like object) [Py_buffer]
Esta variante de s* no acepta objetos Unicode, solamente los objetos de tipo bytes. Esta es la forma reco-
mendada para aceptar datos binarios.
y# (bytes-like object de sólo lectura) [const char *, Py_ssize_t]
Esta variante en s# no acepta objetos Unicode, solo objetos similares a bytes.
76 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
S (bytes) [PyBytesObject *]
Requires that the Python object is a bytes object, without attempting any conversion. Raises TypeError
if the object is not a bytes object. The C variable may also be declared as PyObject*.
Y (bytearray) [PyByteArrayObject *]
Requires that the Python object is a bytearray object, without attempting any conversion. Raises
TypeError if the object is not a bytearray object. The C variable may also be declared as PyObject*.
U (str) [PyObject *]
Requires that the Python object is a Unicode object, without attempting any conversion. Raises TypeError
if the object is not a Unicode object. The C variable may also be declared as PyObject*.
w* (bytes-like object de lectura y escritura) [Py_buffer]
Este formato acepta cualquier objeto que implemente la interfaz del búfer de lectura-escritura. Llena la es-
tructura Py_buffer proporcionada por quien llama. El búfer puede contener bytes nulos incrustados. Quien
llama tiene que llamar PyBuffer_Release() cuando termina con el búfer.
es (str) [const char *encoding, char **buffer]
Esta variante en s se usa para codificar Unicode en un búfer de caracteres. Solo funciona para datos codificados
sin bytes NUL integrados.
This format requires two arguments. The first is only used as input, and must be a const char* which
points to the name of an encoding as a NUL-terminated string, or NULL, in which case 'utf-8' encoding
is used. An exception is raised if the named encoding is not known to Python. The second argument must be
a char**; the value of the pointer it references will be set to a buffer with the contents of the argument text.
The text will be encoded in the encoding specified by the first argument.
PyArg_ParseTuple() asignará un búfer del tamaño necesitado, copiará los datos codificados en este búfer
y ajustará *buffer para referenciar el nuevo almacenamiento asignado. Quien llama es responsable para llamar
PyMem_Free() para liberar el búfer asignado después de su uso.
et (str, bytes o bytearray) [const char *encoding, char **buffer]
Igual que es, excepto que los objetos de cadena de caracteres de bytes se pasan sin recodificarlos. En cambio,
la implementación supone que el objeto de cadena de caracteres de bytes utiliza la codificación que se pasa
como parámetro.
es# (str) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
Esta variante en s# se usa para codificar Unicode en un búfer de caracteres. A diferencia del formato es, esta
variante permite datos de entrada que contienen caracteres NUL.
It requires three arguments. The first is only used as input, and must be a const char* which points to the
name of an encoding as a NUL-terminated string, or NULL, in which case 'utf-8' encoding is used. An
exception is raised if the named encoding is not known to Python. The second argument must be a char**;
the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will
be encoded in the encoding specified by the first argument. The third argument must be a pointer to an integer;
the referenced integer will be set to the number of bytes in the output buffer.
Hay dos modos de operación:
Si *buffer señala un puntero NULL, la función asignará un búfer del tamaño necesario, copiará los datos co-
dificados en este búfer y configurará *buffer para hacer referencia al almacenamiento recién asignado. Quien
llama es responsable de llamar a PyMem_Free() para liberar el búfer asignado después del uso.
Si *buffer apunta a un puntero no NULL (un búfer ya asignado), PyArg_ParseTuple() usará esta ubica-
ción como el búfer e interpretará el valor inicial de *buffer_length como el tamaño del búfer. Luego copiará los
datos codificados en el búfer y los terminará en NUL. Si el búfer no es lo suficientemente grande, se establecerá
a ValueError.
En ambos casos, *buffer_length se establece a la longitud de los datos codificados sin el byte NUL final.
et# (str, bytes o bytearray) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
Igual que es#, excepto que los objetos de cadena de caracteres de bytes se pasan sin recodificarlos. En cambio,
la implementación supone que el objeto de cadena de caracteres de bytes utiliza la codificación que se pasa
como parámetro.
Distinto en la versión 3.12: u, u#, Z, and Z# are removed because they used a legacy Py_UNICODE* representation.
Números
Otros objetos
O (object) [PyObject *]
Store a Python object (without any conversion) in a C object pointer. The C program thus receives the ac-
tual object that was passed. A new strong reference to the object is not created (i.e. its reference count is not
increased). The pointer stored is not NULL.
O! (object) [typeobject, PyObject *]
Store a Python object in a C object pointer. This is similar to O, but takes two C arguments: the first is the
address of a Python type object, the second is the address of the C variable (of type PyObject*) into which
the object pointer is stored. If the Python object does not have the required type, TypeError is raised.
78 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
where object is the Python object to be converted and address is the void* argument that was passed to the
PyArg_Parse* function. The returned status should be 1 for a successful conversion and 0 if the conversion
has failed. When the conversion fails, the converter function should raise an exception and leave the content of
address unmodified.
Si el converter retorna Py_CLEANUP_SUPPORTED, se puede llamar por segunda vez si el análisis del argu-
mento finalmente falla, dando al convertidor la oportunidad de liberar cualquier memoria que ya haya asignado.
En esta segunda llamada, el parámetro object será NULL; address tendrá el mismo valor que en la llamada ori-
ginal.
Distinto en la versión 3.1: Py_CLEANUP_SUPPORTED fue agregada.
p (bool) [int]
Prueba el valor pasado por verdad (un booleano predicado p) y convierte el resultado a su valor entero C
verdadero/falso entero equivalente. Establece int en 1 si la expresión era verdadera y 0 si era falsa. Esto acepta
cualquier valor válido de Python. Consulte truth para obtener más información sobre cómo Python prueba los
valores por verdad.
Added in version 3.3.
(items) (tuple) [matching-items]
El objeto debe ser una secuencia de Python cuya longitud es el número de unidades de formato en items. Los
argumentos C deben corresponder a las unidades de formato individuales en items. Las unidades de formato
para secuencias pueden estar anidadas.
It is possible to pass «long» integers (integers whose value exceeds the platform’s LONG_MAX) however no proper
range checking is done — the most significant bits are silently truncated when the receiving field is too small to receive
the value (actually, the semantics are inherited from downcasts in C — your mileage may vary).
Algunos otros caracteres tienen un significado en una cadena de formato. Esto puede no ocurrir dentro de paréntesis
anidados. Son:
|
Indica que los argumentos restantes en la lista de argumentos de Python son opcionales. Las variables C corres-
pondientes a argumentos opcionales deben inicializarse a su valor predeterminado — cuando no se especifica
un argumento opcional, PyArg_ParseTuple() no toca el contenido de las variables C correspondientes.
$
PyArg_ParseTupleAndKeywords() solamente: indica que los argumentos restantes en la lista de ar-
gumentos de Python son solo palabras clave. Actualmente, todos los argumentos de solo palabras clave también
deben ser argumentos opcionales, por lo que | siempre debe especificarse antes de $ en la cadena de formato.
Added in version 3.3.
:
La lista de unidades de formato termina aquí; la cadena después de los dos puntos se usa como el nombre de la
función en los mensajes de error (el «valor asociado» de la excepción que PyArg_ParseTuple() lanza).
;
La lista de unidades de formato termina aquí; la cadena después del punto y coma se usa como mensaje de
error en lugar de del mensaje de error predeterminado. : y ; se excluyen mutuamente.
Note that any Python object references which are provided to the caller are borrowed references; do not release them
(i.e. do not decrement their reference count)!
Los argumentos adicionales pasados a estas funciones deben ser direcciones de variables cuyo tipo está determinado
por la cadena de formato; Estos se utilizan para almacenar valores de la tupla de entrada. Hay algunos casos, como
se describe en la lista de unidades de formato anterior, donde estos parámetros se utilizan como valores de entrada;
deben coincidir con lo especificado para la unidad de formato correspondiente en ese caso.
For the conversion to succeed, the arg object must match the format and the format must be exhausted. On success,
the PyArg_Parse* functions return true, otherwise they return false and raise an appropriate exception. When the
PyArg_Parse* functions fail due to conversion failure in one of the format units, the variables at the addresses
corresponding to that and the following format units are left untouched.
Funciones API
80 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
PyObject *result = NULL;
82 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
call producing the argument found an error and set an exception. Therefore, Py_BuildValue() will
return NULL but won’t raise an exception. If no exception has been raised yet, SystemError is set.
S (object) [PyObject *]
Igual que O.
N (object) [PyObject *]
Same as O, except it doesn’t create a new strong reference. Useful when the object is created by a call to
an object constructor in the argument list.
O& (object) [converter, anything]
Convert anything to a Python object through a converter function. The function is called with anything
(which should be compatible with void*) as its argument and should return a «new» Python object, or
NULL if an error occurred.
(items) (tuple) [matching-items]
Convierta una secuencia de valores C en una tupla de Python con el mismo número de elementos.
[items] (list) [matching-items]
Convierte una secuencia de valores C en una lista de Python con el mismo número de elementos.
{items} (dict) [matching-items]
Convierte una secuencia de valores C en un diccionario Python. Cada par de valores C consecutivos
agrega un elemento al diccionario, que sirve como clave y valor, respectivamente.
Si hay un error en la cadena de formato, se establece la excepción SystemError y se retorna NULL.
PyObject *Py_VaBuildValue(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Idéntico a Py_BuildValue(), excepto que acepta una
va_list en lugar de un número variable de argumentos.
Las siguientes funciones proporcionan cadenas de caracteres independientes de la configuración regional para numerar
las conversiones.
unsigned long PyOS_strtoul(const char *str, char **ptr, int base)
Part of the Stable ABI. Convert the initial part of the string in str to an unsigned long value according
to the given base, which must be between 2 and 36 inclusive, or be the special value 0.
Leading white space and case of characters are ignored. If base is zero it looks for a leading 0b, 0o or 0x to
tell which base. If these are absent it defaults to 10. Base must be 0 or between 2 and 36 (inclusive). If ptr is
non-NULL it will contain a pointer to the end of the scan.
If the converted value falls out of range of corresponding return type, range error occurs (errno is set to
ERANGE) and ULONG_MAX is returned. If no conversion can be performed, 0 is returned.
See also the Unix man page strtoul(3).
Added in version 3.2.
long PyOS_strtol(const char *str, char **ptr, int base)
Part of the Stable ABI. Convert the initial part of the string in str to an long value according to the given
base, which must be between 2 and 36 inclusive, or be the special value 0.
Same as PyOS_strtoul(), but return a long value instead and LONG_MAX on overflows.
See also the Unix man page strtol(3).
Added in version 3.2.
double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)
Part of the Stable ABI. Convert a string s to a double, raising a Python exception on failure. The set of
accepted strings corresponds to the set of strings accepted by Python’s float() constructor, except that s
must not have leading or trailing whitespace. The conversion is independent of the current locale.
Si endptr es NULL, convierte toda la cadena de caracteres. Lanza ValueError y retorna -1.0 si la cadena
de caracteres no es una representación válida de un número de punto flotante.
Si endptr no es NULL, convierte la mayor cantidad posible de la cadena de caracteres y configura *endptr
para que apunte al primer carácter no convertido. Si ningún segmento inicial de la cadena de caracteres es la
representación válida de un número de punto flotante, configura *endptr para que apunte al comienzo de la
cadena de caracteres, lanza ValueError y retorna -1.0.
Si s representa un valor que es demasiado grande para almacenar en un flotante (por ejemplo, "1e500"
es una cadena de caracteres de este tipo en muchas plataformas), entonces si overflow_exception es
NULL retorna Py_HUGE_VAL (con un signo apropiado) y no establece ninguna excepción. De lo contrario,
overflow_exception debe apuntar a un objeto excepción de Python; lanza esa excepción y retorna -1.
0. En ambos casos, configura *endptr para que apunte al primer carácter después del valor convertido.
Si se produce algún otro error durante la conversión (por ejemplo, un error de falta de memoria), establece la
excepción Python adecuada y retorna -1.0.
Added in version 3.1.
char *PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)
Part of the Stable ABI. Convert a double val to a string using supplied format_code, precision, and flags.
format_code debe ser uno de 'e', 'E', 'f', 'F', 'g', 'G' or 'r'. Para 'r', la precision suministrada
debe ser 0 y se ignora. El código de formato 'r' especifica el formato estándar repr().
flags puede ser cero o más de los valores Py_DTSF_SIGN, Py_DTSF_ADD_DOT_0, o Py_DTSF_ALT,
unidos por or (or-ed) juntos:
• Py_DTSF_SIGN significa preceder siempre a la cadena de caracteres retornada con un carácter de signo,
incluso si val no es negativo.
• Py_DTSF_ADD_DOT_0 significa asegurarse de que la cadena de caracteres retornada no se verá como
un número entero.
84 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
• Py_DTSF_ALT significa aplicar reglas de formato «alternativas». Consulte la documentación del espe-
cificador PyOS_snprintf() '#' para obtener más detalles.
Si ptype no es NULL, el valor al que apunta se establecerá en uno de Py_DTST_FINITE,
Py_DTST_INFINITE o Py_DTST_NAN, lo que significa que val es un número finito, un número infinito
o no es un número, respectivamente.
El valor de retorno es un puntero a buffer con la cadena de caracteres convertida o NULL si la conversión falla.
La persona que llama es responsable de liberar la cadena de caracteres retornada llamando a PyMem_Free().
Added in version 3.1.
int PyOS_stricmp(const char *s1, const char *s2)
Case insensitive comparison of strings. The function works almost identically to strcmp() except that it
ignores the case.
int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size)
Case insensitive comparison of strings. The function works almost identically to strncmp() except that it
ignores the case.
6.9 Reflexión
PyObject *PyEval_GetBuiltins(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las construcciones en el
marco de ejecución actual, o el intérprete del estado del hilo si no se está ejecutando ningún marco actualmente.
PyObject *PyEval_GetLocals(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las variables locales en el
marco de ejecución actual, o NULL si actualmente no se está ejecutando ningún marco.
PyObject *PyEval_GetGlobals(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las variables globales en
el marco de ejecución actual, o NULL si actualmente no se está ejecutando ningún marco.
PyFrameObject *PyEval_GetFrame(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el marco del estado del hilo actual, que es
NULL si actualmente no se está ejecutando ningún marco.
Vea también PyThreadState_GetFrame().
const char *PyEval_GetFuncName(PyObject *func)
Part of the Stable ABI. Retorna el nombre de func si es una función, clase u objeto de instancia; de lo contrario,
el nombre del tipo funcs.
const char *PyEval_GetFuncDesc(PyObject *func)
Part of the Stable ABI. Retorna una cadena de caracteres de descripción, según el tipo de func. Los valores
de retorno incluyen «()» para funciones y métodos, «constructor», «instancia» y «objeto». Concatenado con el
resultado de PyEval_GetFuncName(), el resultado será una descripción de func.
86 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
object se pasa a través de la función de decodificador encontrada por el encoding dado usando el método de
manejo de errores definido por errors. errors puede ser NULL para usar el método predeterminado definido
para el códec. Lanza un LookupError si no se puede encontrar el codificador.
En las siguientes funciones, la cadena de caracteres encoding se busca convertida a todos los caracteres en minúscula,
lo que hace que las codificaciones se busquen a través de este mecanismo sin distinción entre mayúsculas y minúsculas.
Si no se encuentra ningún códec, se establece un KeyError y se retorna NULL.
PyObject *PyCodec_Encoder(const char *encoding)
Return value: New reference. Part of the Stable ABI. Obtiene una función de codificador para el encoding dado.
PyObject *PyCodec_Decoder(const char *encoding)
Return value: New reference. Part of the Stable ABI. Obtiene una función de decodificador para el encoding
dado.
PyObject *PyCodec_IncrementalEncoder(const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtiene un objeto IncrementalEncoder para el
encoding dada.
PyObject *PyCodec_IncrementalDecoder(const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtiene un objeto IncrementalDecoder para el
encoding dado.
PyObject *PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtiene una función de fábrica StreamReader para el
encoding dado.
PyObject *PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtiene una función de fábrica StreamWriter por el
encoding dado.
On supported platforms (as of this writing, only Linux), the runtime can take advantage of perf map files to make
Python functions visible to an external profiling tool (such as perf). A running process may create a file in the /tmp
directory, which contains entries that can map a section of executable code to a name. This interface is described in
the documentation of the Linux Perf tool.
In Python, these helper APIs can be used by libraries and features that rely on generating machine code on the fly.
Note that holding the Global Interpreter Lock (GIL) is not required for these APIs.
int PyUnstable_PerfMapState_Init(void)
Open the /tmp/perf-$pid.map file, unless it’s already opened, and create a lock to ensure thread-safe
writes to the file (provided the writes are done through PyUnstable_WritePerfMapEntry()). Nor-
mally, there’s no need to call this explicitly; just use PyUnstable_WritePerfMapEntry() and it will
initialize the state on first call.
Returns 0 on success, -1 on failure to create/open the perf map file, or -2 on failure to create a lock. Check
errno for more information about the cause of a failure.
int PyUnstable_WritePerfMapEntry(const void *code_addr, unsigned int code_size, const char
*entry_name)
Write one single entry to the /tmp/perf-$pid.map file. This function is thread safe. Here is what an
example entry looks like:
# address size name
7f3529fcf759 b py::bar:/run/t.py
Will call PyUnstable_PerfMapState_Init() before writing the entry, if the perf map file is not
already opened. Returns 0 on success, or the same error codes as PyUnstable_PerfMapState_Init()
on failure.
88 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
void PyUnstable_PerfMapState_Fini(void)
Close the perf map file opened by PyUnstable_PerfMapState_Init(). This is called by the runtime
itself during interpreter shut-down. In general, there shouldn’t be a reason to explicitly call this, except to handle
specific scenarios such as forking.
90 Capítulo 6. Utilidades
CAPÍTULO 7
Las funciones de este capítulo interactúan con los objetos de Python independientemente de su tipo, o con amplias
clases de tipos de objetos (por ejemplo, todos los tipos numéricos o todos los tipos de secuencia). Cuando se usan en
tipos de objetos para los que no se aplican, lanzarán una excepción de Python.
No es posible utilizar estas funciones en objetos que no se inicializan correctamente, como un objeto de lista que ha
sido creado por PyList_New(), pero cuyos elementos no se han establecido en algunos valores no-NULL aún.
PyObject *Py_NotImplemented
El singleton NotImplemented, se usa para indicar que una operación no está implementada para la com-
binación de tipos dada.
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. Retorna 1 si o tiene el atributo attr_name, y 0 en caso contrario. Esto es equivalente a
la expresión de Python hasattr(o, attr_name). Esta función siempre finaliza exitosamente.
Nota: Exceptions that occur when this calls __getattr__() and __getattribute__() methods are
silently ignored. For proper error handling, use PyObject_GetAttr() instead.
91
The Python/C API, Versión 3.12.4
Nota: Exceptions that occur when this calls __getattr__() and __getattribute__() met-
hods or while creating the temporary str object are silently ignored. For proper error handling, use
PyObject_GetAttrString() instead.
Esta función también puede ser llamada para obtener el __dict__ del objeto o. Se pasa context igual a NULL
cuando se lo llama. Dado que esta función puede necesitar asignar memoria para el diccionario, puede ser más
eficiente llamar a PyObject_GetAttr() para acceder a un atributo del objeto.
En caso de fallo, retorna NULL con una excepción establecida.
Added in version 3.3.
int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
Part of the Stable ABI since version 3.7. Una implementación genérica para el creador de un descriptor
__dict__. Esta implementación no permite que se elimine el diccionario.
Added in version 3.3.
PyObject **_PyObject_GetDictPtr(PyObject *obj)
Retorna un puntero al __dict__ del objeto obj. Si no hay __dict__, retorna NULL sin establecer una
excepción.
Esta función puede necesitar asignar memoria para el diccionario, por lo que puede ser más eficiente llamar a
PyObject_GetAttr() para acceder a un atributo del objeto.
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.
Nota: If o1 and o2 are the same object, PyObject_RichCompareBool() will always return 1 for Py_EQ and
0 for Py_NE.
Las instancias de clases que establecen tp_call son invocables. La firma del slot es:
Se realiza una llamada usando una tupla para los argumentos posicionales y un dict para los argumentos de palabras
clave, de manera similar a callable(*args, **kwargs) en el código Python. args debe ser no NULL (use
una tupla vacía si no hay argumentos) pero kwargs puede ser NULL si no hay argumentos de palabra clave.
Esta convención no solo es utilizada por tp_call: tp_new y tp_init también pasan argumentos de esta manera.
To call an object, use PyObject_Call() or another call API.
Advertencia: Una clase que admita vectorcall debe también implementar tp_call con la misma semántica.
Distinto en la versión 3.12: The Py_TPFLAGS_HAVE_VECTORCALL flag is now removed from a class when the
class’s __call__() method is reassigned. (This internally sets tp_call only, and thus may make it behave
differently than the vectorcall function.) In earlier Python versions, vectorcall should only be used with immutable
or static types.
Una clase no debería implementar vectorcall si eso fuera más lento que tp_call. Por ejemplo, si el destinatario de la
llamada necesita convertir los argumentos a una tupla args y un dict kwargs de todos modos, entonces no tiene sentido
implementar vectorcall.
Classes can implement the vectorcall protocol by enabling the Py_TPFLAGS_HAVE_VECTORCALL flag and setting
tp_vectorcall_offset to the offset inside the object structure where a vectorcallfunc appears. This is a pointer
to a function with the following signature:
typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Part of the Stable ABI since version 3.12.
• callable es el objeto siendo invocado.
• args es un arreglo en C que consta de los argumentos posicionales seguidos por el
valores de los argumentos de la palabra clave. Puede ser NULL si no hay argumentos.
• nargsf es el número de argumentos posicionales más posiblemente el
PY_VECTORCALL_ARGUMENTS_OFFSET flag. To get the actual number of positional arguments
from nargsf, use PyVectorcall_NARGS().
• kwnames es una tupla que contiene los nombres de los argumentos de la palabra clave;
en otras palabras, las claves del diccionario kwargs. Estos nombres deben ser cadenas (instancias de str
o una subclase) y deben ser únicos. Si no hay argumentos de palabras clave, entonces kwnames puede ser
NULL.
PY_VECTORCALL_ARGUMENTS_OFFSET
Part of the Stable ABI since version 3.12. Si este flag se establece en un argumento vectorcall nargsf, el desti-
natario de la llamada puede cambiar temporalmente args[-1]. En otras palabras, args apunta al argumento
1 (no 0) en el vector asignado. El destinatario de la llamada debe restaurar el valor de args[-1] antes de
regresar.
Para PyObject_VectorcallMethod(), este flag significa en cambio que args[0] puede cambiarse.
Whenever they can do so cheaply (without additional allocation), callers are encouraged to use
PY_VECTORCALL_ARGUMENTS_OFFSET. Doing so will allow callables such as bound methods to ma-
ke their onward calls (which include a prepended self argument) very efficiently.
Added in version 3.8.
Para llamar a un objeto que implementa vectorcall, use una función call API como con cualquier otro invocable.
PyObject_Vectorcall() normalmente será más eficiente.
Control de recursión
Cuando se usa tp_call, los destinatarios no necesitan preocuparse por recursividad: CPython usa
Py_EnterRecursiveCall() y Py_LeaveRecursiveCall() para llamadas realizadas usando tp_call.
Por eficiencia, este no es el caso de las llamadas realizadas mediante vectorcall: el destinatario de la llamada debe
utilizar Py_EnterRecursiveCall y Py_LeaveRecursiveCall si es necesario.
Sin embargo, la función PyVectorcall_NARGS debe usarse para permitir futuras extensiones.
Added in version 3.8.
vectorcallfunc PyVectorcall_Function(PyObject *op)
Si op no admite el protocolo vectorcall (ya sea porque el tipo no lo hace o porque la instancia específica no
lo hace), retorna NULL. De lo contrario, retorna el puntero de la función vectorcall almacenado en op. Esta
función nunca lanza una excepción.
Esto es principalmente útil para verificar si op admite vectorcall, lo cual se puede hacer marcando
PyVectorcall_Function(op) != NULL.
Added in version 3.9.
PyObject *PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict)
Part of the Stable ABI since version 3.12. Llama a la vectorcallfunc de callable con argumentos posi-
cionales y de palabras clave dados en una tupla y dict, respectivamente.
This is a specialized function, intended to be put in the tp_call slot or be used in an implementation of
tp_call. It does not check the Py_TPFLAGS_HAVE_VECTORCALL flag and it does not fall back to
tp_call.
Added in version 3.8.
Hay varias funciones disponibles para llamar a un objeto Python. Cada una convierte sus argumentos a una convención
respaldada por el objeto llamado, ya sea tp_call o vectorcall. Para realizar la menor conversión posible, elija la que
mejor se adapte al formato de datos que tiene disponible.
La siguiente tabla resume las funciones disponibles; consulte la documentación individual para obtener más detalles.
base dos. Esta función puede retornar un valor de punto flotante cuando se pasan dos enteros. Es equivalente
a la expresión de Python o1 / o2.
PyObject *PyNumber_Remainder(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resto de la división entera a la baja entre o1 y
o2, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 % o2.
PyObject *PyNumber_Divmod(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Vea la función incorporada divmod(). Retorna NULL
en caso de falla. Este es el equivalente de la expresión de Python divmod (o1, o2).
PyObject *PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3)
Return value: New reference. Part of the Stable ABI. Consulte la función incorporada pow(). Retorna NULL
en caso de falla. Este es el equivalente de la expresión de Python pow(o1, o2, o3), donde o3 es opcional.
Si se ignora o3, pase Py_None en su lugar (pasar NULL por o3 provocaría un acceso ilegal a la memoria).
PyObject *PyNumber_Negative(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna la negación de o en caso de éxito o NULL en caso
de error. Este es el equivalente de la expresión de Python -o.
PyObject *PyNumber_Positive(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna o en caso de éxito o NULL en caso de error. Este
es el equivalente de la expresión de Python +o.
PyObject *PyNumber_Absolute(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna el valor absoluto de o o NULL en caso de error.
Este es el equivalente de la expresión de Python abs(o).
PyObject *PyNumber_Invert(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna la negación bit a bit de o en caso de éxito o NULL
en caso de error. Este es el equivalente de la expresión de Python ~o.
PyObject *PyNumber_Lshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado del desplazamiento a la izquierda o1
por o2 en caso de éxito o NULL en caso de error. Este es el equivalente de la expresión de Python o1 << o2.
PyObject *PyNumber_Rshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado del desplazamiento a la derecha o1
por o2 en caso de éxito o NULL en caso de error. Este es el equivalente de la expresión de Python o1 >> o2.
PyObject *PyNumber_And(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit y» (bitwise and) de o1 y o2 en caso
de éxito y NULL en caso de error. Este es el equivalente de la expresión de Python o1 & o2.
PyObject *PyNumber_Xor(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit o exclusivo» (bitwise exclusive or) de
o1 por o2 en caso de éxito, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 ^
o2.
PyObject *PyNumber_Or(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit o» (bitwise or) de o1 y o2 en caso de
éxito, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 | o2.
PyObject *PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de agregar o1 y o2, o NULL en caso de
falla. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es el equivalente de la declaración
de Python o1 += o2.
PyObject *PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de restar o2 de o1, o NULL en caso de
falla. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es el equivalente de la declaración
de Python o1 -= o2.
Nota: Exceptions which occur when this calls __getitem__() method are silently ignored. For proper
error handling, use PyObject_GetItem() instead.
Nota: Exceptions that occur when this calls __getitem__() method or while creating the temporary str
object are silently ignored. For proper error handling, use PyMapping_GetItemString() instead.