C Api
C Api
Versión 3.13.0a5
1 Introducción 3
1.1 Estándares de codificación . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Archivos de cabecera (Include) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Macros útiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Objetos, tipos y conteos de referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.1 Conteo de Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4.2 Tipos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5 Excepciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.6 Integración de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.7 Depuración de compilaciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
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 51
5 Manejo de excepciones 55
5.1 Impresión y limpieza . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.2 Lanzando excepciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.3 Emitir advertencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.4 Consultando el indicador de error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.5 Manejo de señal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.6 Clases de excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.7 Objetos excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.8 Objetos unicode de excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.9 Control de recursión . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.10 Excepciones estándar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.11 Categorías de advertencia estándar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
i
6 Utilidades 71
6.1 Utilidades del sistema operativo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.2 Funciones del Sistema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.3 Control de procesos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.4 Importando módulos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.5 Soporte de empaquetado (marshalling) de datos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.6 Analizando argumentos y construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.6.1 Analizando argumentos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.6.2 Construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.7 Conversión y formato de cadenas de caracteres . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.8 PyHash API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.9 Reflexión . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.10 Registro de códec y funciones de soporte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
6.10.1 API de búsqueda de códec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.10.2 API de registro para controladores de errores de codificación Unicode . . . . . . . . . . . . . 95
6.11 PyTime C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.11.1 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.11.2 Clock Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.11.3 Conversion functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.12 Support for Perf Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
ii
8.4 Objetos contenedor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
8.4.1 Objetos diccionario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
8.4.2 Objetos conjunto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
8.5 Objetos de función . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.5.1 Objetos función . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.5.2 Objetos de método de instancia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
8.5.3 Objetos método . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.5.4 Objetos celda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.5.5 Objetos código . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
8.5.6 Extra information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
8.6 Otros objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.1 Objetos archivo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.2 Objetos módulo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
8.6.3 Objetos iteradores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
8.6.4 Objetos descriptores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
8.6.5 Objetos rebanada (slice) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
8.6.6 Objetos de vista de memoria (MemoryView) . . . . . . . . . . . . . . . . . . . . . . . . . . 197
8.6.7 Objetos de referencia débil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
8.6.8 Cápsulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
8.6.9 Objetos frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
8.6.10 Objetos generadores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
8.6.11 Objetos corrutina . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
8.6.12 Objetos de variables de contexto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
8.6.13 Objetos DateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
8.6.14 Objetos para indicaciones de tipado . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
iii
10.7 Inicialización con PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
10.8 Configuración aislada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
10.9 Configuración de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
10.10 Configuración de la ruta de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
10.11 Py_RunMain() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
10.12 Py_GetArgcArgv() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
10.13 API Provisional Privada de Inicialización Multifásica . . . . . . . . . . . . . . . . . . . . . . . . . . 259
A Glosario 329
iv
C Historia y Licencia 349
C.1 Historia del software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
C.2 Términos y condiciones para acceder o usar Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
C.2.1 ACUERDO DE LICENCIA DE PSF PARA PYTHON | lanzamiento | . . . . . . . . . . . . 350
C.2.2 ACUERDO DE LICENCIA DE BEOPEN.COM PARA PYTHON 2.0 . . . . . . . . . . . . 351
C.2.3 ACUERDO DE LICENCIA CNRI PARA PYTHON 1.6.1 . . . . . . . . . . . . . . . . . . 352
C.2.4 ACUERDO DE LICENCIA CWI PARA PYTHON 0.9.0 HASTA 1.2 . . . . . . . . . . . . 353
C.2.5 LICENCIA BSD DE CLÁUSULA CERO PARA CÓDIGO EN EL PYTHON | lanzamiento
| DOCUMENTACIÓN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
C.3 Licencias y reconocimientos para software incorporado . . . . . . . . . . . . . . . . . . . . . . . . . 354
C.3.1 Mersenne Twister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
C.3.2 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
C.3.3 Servicios de socket asincrónicos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
C.3.4 Gestión de cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
C.3.5 Seguimiento de ejecución . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
C.3.6 funciones UUencode y UUdecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
C.3.7 Llamadas a procedimientos remotos XML . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
C.3.8 test_epoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
C.3.9 Seleccionar kqueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
C.3.10 SipHash24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
C.3.11 strtod y dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
C.3.18 Conjunto de pruebas W3C C14N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
C.3.19 mimalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
C.3.20 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
C.3.21 Global Unbounded Sequences (GUS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Índice 371
v
vi
The Python/C API, Versión 3.13.0a5
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.13.0a5
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 como 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 pro-
bablemente sea una buena idea familiarizarse con la escritura de una extensión antes de intentar integrar Python en una
aplicación real.
3
The Python/C API, Versión 3.13.0a5
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.
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 argumentos 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 imple-
mentació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 ins-
tallation 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++.
4 Capítulo 1. Introducción
The Python/C API, Versión 3.13.0a5
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 necesariamente
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:
PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModule_Create(&spam_module);
}
Py_ABS(x)
Retorna el valor absoluto de x.
Nuevo en la versión 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:
Ejemplo:
6 Capítulo 1. Introducción
The Python/C API, Versión 3.13.0a5
Py_UNUSED(arg)
Use esto para argumentos no utilizados en una definición de función para silenciar las advertencias del compilador.
Ejemplo: int func(int a, int Py_UNUSED(b)) {return a; }.
Nuevo en la versión 3.4.
PyDoc_STRVAR(name, str)
Crea una variable con el nombre name que se puede usar en docstrings. Si Python se construye sin docstrings, el
valor estará vacío.
Utilice PyDoc_STRVAR para que los docstrings admitan la construcción de Python sin docstrings, como se espe-
cifica en PEP 7.
Ejemplo:
PyDoc_STR(str)
Crea un docstring para la cadena de caracteres de entrada dada o una cadena vacía si los docstrings están deshabi-
litados.
Utilice PyDoc_STR al especificar docstrings para admitir la construcción de Python sin docstrings, como se espe-
cifica 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 reference»
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.
8 Capítulo 1. Introducción
The Python/C API, Versión 3.13.0a5
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 coloca 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):
It is much more common to use PyObject_SetItem() and friends with items whose references you are only borro-
wing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding 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 mayorí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 funciones 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;
(continúe en la próxima página)
10 Capítulo 1. Introducción
The Python/C API, Versión 3.13.0a5
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 excepcio-
nes 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 fun-
ciones 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 almacenamiento
global en una aplicación sin subprocesos). Un subproceso puede estar en uno de dos estados: se ha producido 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
1.5. Excepciones 11
The Python/C API, Versión 3.13.0a5
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) */
error:
/* Cleanup code, shared by success and failure path */
(continúe en la próxima página)
12 Capítulo 1. Introducción
The Python/C API, Versión 3.13.0a5
La única tarea importante de la que solo tienen que preocuparse los integradores (a diferencia de los escritores de ex-
tensió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 bibliotecas
están en /usr/local/lib/pythonX.Y. (De hecho, esta ruta particular también es la ubicación «alternativa», uti-
lizada 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.
The embedding application can steer the search by setting PyConfig.program_name before calling
Py_InitializeFromConfig(). Note that PYTHONHOME still overrides this and PYTHONPATH is still inser-
ted in front of the standard path. An application that requires total control has to provide its own implementation of
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), and Py_GetProgramFullPath() (all defi-
ned in 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 adicionales,
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 ac-
tivos 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 detallada.
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.13.0a5
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 ejem-
plo, 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 biblio-
teca 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 estructuras 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 prefe-
riblemente 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
• PyCFunctionFast
• PyCFunctionFastWithKeywords
• PyCFunctionWithKeywords
• 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_GetItemRef()
• PyDict_GetItemString()
• PyDict_GetItemStringRef()
• 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_AcquireThread()
• PyEval_EvalCode()
• PyEval_EvalCodeEx()
• PyEval_EvalFrame()
• PyEval_EvalFrameEx()
• PyEval_GetBuiltins()
• PyEval_GetFrame()
• PyEval_GetFuncDesc()
• PyEval_GetFuncName()
• PyEval_GetGlobals()
• PyEval_GetLocals()
• PyEval_ReleaseThread()
• PyEval_RestoreThread()
• PyEval_SaveThread()
• 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_IncompleteInputError
• 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_AddModuleRef()
• 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_GetItemRef()
• PyList_GetSlice()
• PyList_Insert()
• PyList_New()
• PyList_Reverse()
• PyList_SetItem()
• PyList_SetSlice()
• PyList_Size()
• PyList_Sort()
• PyList_Type
• PyLongObject
• PyLongRangeIter_Type
• PyLong_AsDouble()
• PyLong_AsInt()
• 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_GetOptionalItem()
• PyMapping_GetOptionalItemString()
• PyMapping_HasKey()
• PyMapping_HasKeyString()
• PyMapping_HasKeyStringWithError()
• PyMapping_HasKeyWithError()
• PyMapping_Items()
• PyMapping_Keys()
• PyMapping_Length()
• PyMapping_SetItemString()
• PyMapping_Size()
• PyMapping_Values()
• PyMem_Calloc()
• PyMem_Free()
• PyMem_Malloc()
• PyMem_RawCalloc()
• PyMem_RawFree()
• PyMem_RawMalloc()
• PyMem_RawRealloc()
• 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_Add()
• 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_AsFileDescriptor()
• PyObject_Bytes()
• PyObject_Call()
• PyObject_CallFunction()
• PyObject_CallFunctionObjArgs()
• PyObject_CallMethod()
• PyObject_CallMethodObjArgs()
• PyObject_CallNoArgs()
• PyObject_CallObject()
• PyObject_Calloc()
• PyObject_CheckBuffer()
• PyObject_ClearWeakRefs()
• PyObject_CopyData()
• PyObject_DelAttr()
• PyObject_DelAttrString()
• 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_GetOptionalAttr()
• PyObject_GetOptionalAttrString()
• PyObject_GetTypeData()
• PyObject_HasAttr()
• PyObject_HasAttrString()
• PyObject_HasAttrStringWithError()
• PyObject_HasAttrWithError()
• 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_Audit()
• PySys_AuditTuple()
• PySys_FormatStderr()
• PySys_FormatStdout()
• PySys_GetObject()
• PySys_GetXOptions()
• PySys_ResetWarnOptions()
• PySys_SetObject()
• 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_GetFullyQualifiedName()
• PyType_GetModule()
• PyType_GetModuleName()
• 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_EqualToUTF8()
• PyUnicode_EqualToUTF8AndSize()
• 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_GetRef()
• 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_IsFinalizing()
• Py_IsInitialized()
• Py_IsNone()
• Py_IsTrue()
• Py_LeaveRecursiveCall()
• Py_Main()
• Py_MakePendingCalls()
• Py_NewInterpreter()
• Py_NewRef()
• Py_ReprEnter()
• Py_ReprLeave()
• 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 care-
fully 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.
Nuevo en la versión 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.
45
The Python/C API, Versión 3.13.0a5
Nota: En Windows, fp debe abrirse en modo binario (por ejemplo, fopen(filename, "rb"). De lo con-
trario, Python puede no manejar correctamente el archivo de script con la terminación de línea LF.
47
The Python/C API, Versión 3.13.0a5
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 decodi-
ficado 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.
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 aba-
jo, 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) )
Nuevo en la versión 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.
Nuevo en la versión 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 modification
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.
49
The Python/C API, Versión 3.13.0a5
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 exam-
ple, 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.
On Python build with Free Threading, if refcnt is larger than UINT32_MAX, the object is made immortal.
This function has no effect on immortal objects.
Nuevo en la versión 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.
This function has no effect on immortal objects.
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 is 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.
51
The Python/C API, Versión 3.13.0a5
Py_INCREF(obj);
self->attr = obj;
self->attr = Py_NewRef(obj);
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.
Nuevo en la versión 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().
Nuevo en la versión 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.
53
The Python/C API, Versión 3.13.0a5
Manejo de excepciones
Las funciones descritas en este capítulo le permitirán manejar y lanzar excepciones de Python. Es importante comprender
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 excepció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.
Nota: El indicador de error es no el resultado de sys.exc_info(). El primero corresponde a una excepción que aún
no se detecta (y, por lo tanto, todavía se está propagando), mientras que el segundo retorna una excepción después de que
se detecta (y, por lo tanto, ha dejado de propagarse).
55
The Python/C API, Versión 3.13.0a5
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.
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 com-
patibility, 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 impos-
sible 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_FormatUnraisable(const char *format, ...)
Similar to PyErr_WriteUnraisable(), but the format and subsequent parame-
ters help format the warning message; they have the same meaning and values as in
PyUnicode_FromFormat(). PyErr_WriteUnraisable(obj) is roughtly equivalent to
PyErr_FormatUnraisable("Exception ignored in: %R", obj). If format is NULL, only the
traceback is printed.
Nuevo en la versión 3.13.
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.
Nuevo en la versión 3.12.
Estas funciones lo ayudan a configurar el indicador de error del hilo actual. Por conveniencia, algunas de estas funciones
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.
Nuevo en la versión 3.5.
void PyErr_SetNone(PyObject *type)
Part of the Stable ABI. Esta es una abreviatura de PyErr_SetObject(type, Py_None).
int PyErr_BadArgument()
Part of the Stable ABI. Esta es una abreviatura de PyErr_SetString(PyExc_TypeError, message),
donde message indica que se invocó una operación incorporada con un argumento ilegal. Es principalmente para
uso interno.
PyObject *PyErr_NoMemory()
Return value: Always NULL. Part of the Stable ABI. Esta es una abreviatura de
PyErr_SetNone(PyExc_MemoryError); retorna NULL para que una función de asignación de ob-
jetos pueda escribir return PyErr_NoMemory(); cuando se queda sin memoria.
PyObject *PyErr_SetFromErrno(PyObject *type)
Return value: Always NULL. Part of the Stable ABI. This is a convenience function to raise an exception when a C
library function has returned an error and set the C variable errno. It constructs a tuple object whose first item is
the integer errno value and whose second item is the corresponding error message (gotten from strerror()),
and then calls PyErr_SetObject(type, object). On Unix, when the errno value is EINTR, indicating
an interrupted system call, this calls PyErr_CheckSignals(), and if that set the error indicator, leaves it
set to that. The function always returns NULL, so a wrapper function around a system call can write return
PyErr_SetFromErrno(type); when the system call returns an error.
PyObject *PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
Return value: Always NULL. Part of the Stable ABI. Similar to PyErr_SetFromErrno(), with the additional
behavior that if filenameObject is not NULL, it is passed to the constructor of type as a third parameter. In the case
of OSError exception, this is used to define the filename attribute of the exception instance.
PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject,
PyObject *filenameObject2)
Return value: Always NULL. Part of the Stable ABI since version 3.7. Similar a
PyErr_SetFromErrnoWithFilenameObject(), pero toma un segundo objeto de nombre de ar-
chivo, para lanzar errores cuando falla una función que toma dos nombres de archivo.
Nuevo en la versión 3.4.
PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
Return value: Always NULL. Part of the Stable ABI. Similar a PyErr_SetFromErrnoWithFilenameObject(),
pero el nombre del archivo se da como una cadena de caracteres de C. filename se decodifica a partir de la
codificación de filesystem encoding and error handler.
PyObject *PyErr_SetFromWindowsErr(int ierr)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. This is a convenience function
to raise WindowsError. If called with ierr of 0, the error code returned by a call to GetLastError()
is used instead. It calls the Win32 function FormatMessage() to retrieve the Windows description of error
code given by ierr or GetLastError(), then it constructs a tuple object whose first item is the ierr value
and whose second item is the corresponding error message (gotten from FormatMessage()), and then calls
PyErr_SetObject(PyExc_WindowsError, object). This function always returns NULL.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a
PyErr_SetFromWindowsErr(), con un parámetro adicional que especifica el tipo de excepción que
se lanzará.
Disponibilidad: Windows.
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar to
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.
Nuevo en la versión 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
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 subclase de
PyExc_Exception; la categoría de advertencia predeterminada es PyExc_RuntimeWarning. Las catego-
rí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 conte-
nedor 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 predetermi-
nado que se describe allí.
Nuevo en la versión 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 cade-
nas 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.
Nuevo en la versión 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.
Nuevo en la versión 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).
PyErr_SetRaisedException(exc);
}
Ver también:
PyErr_GetHandledException(), to save the exception currently being handled.
Nuevo en la versión 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 tem-
porarily. 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 lanzada. 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 inmediatamente (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.
Nuevo en la versión 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 funciones facilitan
esta funcionalidad. Efectivamente, estos son los C equivalentes a reprlib.recursive_repr().
int Py_ReprEnter(PyObject *object)
Part of the Stable ABI. Llamado al comienzo de la implementación tp_repr para detectar ciclos.
Si el objeto ya ha sido procesado, la función retorna un entero positivo. En ese caso, la implementación tp_repr
debería retornar un objeto de cadena que indique un ciclo. Como ejemplos, los objetos dict retornan {...} y
los objetos list retornan [...].
La función retornará un entero negativo si se alcanza el límite de recursión. En ese caso, la implementación
tp_repr normalmente debería retornar NULL.
De lo contrario, la función retorna cero y la implementación tp_repr puede continuar normalmente.
void Py_ReprLeave(PyObject *object)
Part of the Stable ABI. Termina a Py_ReprEnter(). Se debe llamar una vez por cada invocación de
Py_ReprEnter() que retorna cero.
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:
1 Esta es una clase base para otras excepciones estándar.
2 Solo se define en Windows; proteja el código que usa esto probando que la macro del preprocesador MS_WINDOWS está definida.
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().
71
The Python/C API, Versión 3.13.0a5
void PyOS_AfterFork_Parent()
Part of the Stable ABI on platforms with fork() since version 3.7. Función para actualizar algún estado interno
después de una bifurcación de proceso. Se debe invocar desde el proceso principal después de llamar a fork() 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().
72 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
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().
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().
Nuevo en la versión 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 configuración
local LC_CTYPE esté correctamente configurada: véase la función Py_PreInitialize().
Ver también:
Las funciones PyUnicode_EncodeFSDefault() y PyUnicode_EncodeLocale().
Nuevo en la versión 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().
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Clear sys.warnoptions and warnings.
filters instead.
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.
void PySys_WriteStderr(const char *format, ...)
Part of the Stable ABI. Como PySys_WriteStdout(), pero escribe a sys.stderr o stderr en su lugar.
void PySys_FormatStdout(const char *format, ...)
Part of the Stable ABI. Función similar a PySys_WriteStdout() pero formatea el mensaje usando
PyUnicode_FromFormatV() y no trunca el mensaje a una longitud arbitraria.
Nuevo en la versión 3.2.
void PySys_FormatStderr(const char *format, ...)
Part of the Stable ABI. Como PySys_FormatStdout(), pero escribe a sys.stderr o stderr en su lugar.
Nuevo en la versión 3.2.
PyObject *PySys_GetXOptions()
Return value: Borrowed reference. Part of the Stable ABI since version 3.7. Retorna el diccionario actual de opciones
-X, de manera similar a sys._xoptions. En caso de error, se retorna NULL y se establece una excepción.
Nuevo en la versión 3.2.
74 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
76 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
78 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
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.
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 (marshalled)
de value. version indica el formato del archivo.
Las siguientes funciones permiten volver a leer los valores empaquetados (marshalled).
80 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
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 formato 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.
Nota: On Python 3.12 and older, the macro PY_SSIZE_T_CLEAN must be defined before including Python.h to
use all # variants of formats (s#, y#, etc.) explained below. This is not necessary on Python 3.13 and later.
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 da-
ta 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 immutable
(e.g. whether it would honor a request for a writable buffer, or whether another thread can mutate the data).
s (str) [const char *]
Convierte un objeto Unicode a un puntero C a una cadena de caracteres. Un puntero a una cadena de caracteres
existente se almacena en la variable puntero del carácter cuya dirección se pasa. La cadena de caracteres en C es
terminada en NULL. La cadena de caracteres de Python no debe contener puntos de código incrustado nulos; si
lo hace, se lanza una excepción ValueError. Los objetos Unicode se convierten en cadenas de caracteres de C
utilizando codificación 'utf-8'. Si esta conversión fallase lanza un UnicodeError.
Nota: Este formato no acepta objetos de tipo bytes. Si desea aceptar los caminos del sistema de archivos y con-
vertirlos 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 propor-
cionada 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.
82 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
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 codifica-
dos 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 ubicación
como el búfer e interpretará el valor inicial de *buffer_length como el tamaño del búfer. Luego copiará los da-
tos 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
84 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
Otros objetos
O (object) [PyObject *]
Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual 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.
O& (object) [converter, anything]
Convert a Python object to a C variable through a converter function. This takes two arguments: the first is a function,
the second is the address of a C variable (of arbitrary type), converted to void*. The converter function in turn is
called as follows:
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 argumento
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 original.
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 verdade-
ro/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.
Nuevo en la versión 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 argumen-
tos 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.
Nuevo en la versión 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 corres-
ponding to that and the following format units are left untouched.
Funciones API
86 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
Nota: The keywords parameter declaration is char *const* in C and const char *const* in C++.
This can be overridden with the PY_CXX_CONST macro.
int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
Part of the Stable ABI. A simpler form of parameter retrieval which does not use a format string to specify
the types of the arguments. Functions which use this method to retrieve their parameters should be declared as
METH_VARARGS in function or method tables. The tuple containing the actual parameters should be passed as
args; it must actually be a tuple. The length of the tuple must be at least min and no more than max; min and
max may be equal. Additional arguments must be passed to the function, each of which should be a pointer to a
PyObject* variable; these will be filled in with the values from args; they will contain borrowed references. The
variables which correspond to optional parameters not given by args will not be filled in; these should be initialized
by the caller. This function returns true on success and false if args is not a tuple or contains the wrong number of
elements; an exception will be set if there was a failure.
This is an example of the use of this function, taken from the sources for the _weakref helper module for weak
references:
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
(continúe en la próxima página)
PY_CXX_CONST
The value to be inserted, if any, before char *const* in the keywords parameter declaration of
PyArg_ParseTupleAndKeywords() and PyArg_VaParseTupleAndKeywords(). Default empty
for C and const for C++ (const char *const*). To override, define it to the desired value before inclu-
ding Python.h.
Nuevo en la versión 3.13.
88 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
90 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
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.
Nuevo en la versión 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.
• Py_DTSF_ALT significa aplicar reglas de formato «alternativas». Consulte la documentación del especifi-
cador 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, respectiva-
mente.
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().
Nuevo en la versión 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.
92 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
PyHASH_MODULUS
The Mersenne prime P = 2**n -1, used for numeric hash scheme.
Nuevo en la versión 3.13.
PyHASH_BITS
The exponent n of P in PyHASH_MODULUS.
Nuevo en la versión 3.13.
PyHASH_INF
The hash value returned for a positive infinity.
Nuevo en la versión 3.13.
PyHASH_IMAG
The multiplier used for the imaginary part of a complex number.
Nuevo en la versión 3.13.
type PyHash_FuncDef
Hash function definition used by PyHash_GetFuncDef().
const char *name
Hash function name (UTF-8 encoded string).
const int hash_bits
Internal size of the hash value in bits.
const int seed_bits
Size of seed input in bits.
Nuevo en la versión 3.4.
PyHash_FuncDef *PyHash_GetFuncDef(void)
Get the hash function definition.
Ver también:
PEP 456 «Secure and interchangeable hash algorithm».
Nuevo en la versión 3.4.
Py_hash_t Py_HashPointer(const void *ptr)
Hash a pointer value: process the pointer value as an integer (cast it to uintptr_t internally). The pointer is not
dereferenced.
The function cannot fail: it cannot return -1.
Nuevo en la versión 3.13.
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.
6.9. Reflexión 93
The Python/C API, Versión 3.13.0a5
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.
94 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
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.
6.11.1 Types
type PyTime_t
A timestamp or duration in nanoseconds, represented as a signed 64-bit integer.
The reference point for timestamps depends on the clock used. For example, PyTime_Time() returns times-
tamps relative to the UNIX epoch.
The supported range is around [-292.3 years; +292.3 years]. Using the Unix epoch (January 1st, 1970) as reference,
the supported date range is around [1677-09-21; 2262-04-11]. The exact limits are exposed as constants:
PyTime_t PyTime_MIN
Minimum value of PyTime_t.
PyTime_t PyTime_MAX
Maximum value of PyTime_t.
The following functions take a pointer to a PyTime_t that they set to the value of a particular clock. Details of each
clock are given in the documentation of the corresponding Python function.
The functions return 0 on success, or -1 (with an exception set) on failure.
On integer overflow, they set the PyExc_OverflowError exception and set *result to the value clamped to the
[PyTime_MIN; PyTime_MAX] range. (On current systems, integer overflows are likely caused by misconfigured
system time.)
As any other C API (unless otherwise specified), the functions must be called with the GIL held.
96 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5
double PyTime_AsSecondsDouble(PyTime_t t)
Convert a timestamp to a number of seconds as a C double.
The function cannot fail, but note that double has limited accuracy for large values.
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 documen-
tation 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()). Normally, 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.
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.
98 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 combinació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_HasAttrWithError(PyObject *o, const char *attr_name)
Part of the Stable ABI since version 3.13. Returns 1 if o has the attribute attr_name, and 0 otherwise. This is
equivalent to the Python expression hasattr(o, attr_name). On failure, return -1.
Nuevo en la versión 3.13.
99
The Python/C API, Versión 3.13.0a5
Nota: Exceptions that occur when this calls __getattr__() and __getattribute__() met-
hods are silently ignored. For proper error handling, use PyObject_HasAttrWithError(),
PyObject_GetOptionalAttr() or PyObject_GetAttr() instead.
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_HasAttrStringWithError(), PyObject_GetOptionalAttrString() or
PyObject_GetAttrString() instead.
así como un atributo en el objeto __ dict__ (si está presente). Como se describe en descriptors, los descriptores
de datos tienen preferencia sobre los atributos de instancia, mientras que los descriptores que no son de datos no lo
hacen. De lo contrario, se lanza un AttributeError.
int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)
Part of the Stable ABI. Establece el valor del atributo llamado attr_name, para el objeto o, en el valor v. Lanza
una excepción y retorna -1 en caso de falla; retorna 0 en caso de éxito. Este es el equivalente de la declaración de
Python o.attr_name = v.
Si v es NULL, el atributo se elimina. Este comportamiento está deprecado en favor de usar
PyObject_DelAttr(), pero por el momento no hay planes de quitarlo.
int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)
Part of the Stable ABI. This is the same as PyObject_SetAttr(), but attr_name is specified as a const
char* UTF-8 encoded bytes string, rather than a PyObject*.
Si v es NULL, el atributo se elimina, sin embargo, esta característica está deprecada en favor de usar
PyObject_DelAttrString().
int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)
Part of the Stable ABI. Establecimiento de atributo genérico y función de eliminación que está destinada a colocarse
en la ranura de un objeto tipo tp_setattro. Busca un descriptor de datos en el diccionario de clases en el MRO
del objeto y, si se encuentra, tiene preferencia sobre la configuración o eliminación del atributo en el diccionario de
instancias. De lo contrario, el atributo se establece o elimina en el objeto __dict__ (si está presente). En caso de
éxito, se retorna 0; de lo contrario, se lanza un AttributeError y se retorna -1.
int PyObject_DelAttr(PyObject *o, PyObject *attr_name)
Part of the Stable ABI since version 3.13. Elimina el atributo llamado attr_name, para el objeto o. Retorna -1 en
caso de falla. Este es el equivalente de la declaración de Python del o.attr_name.
int PyObject_DelAttrString(PyObject *o, const char *attr_name)
Part of the Stable ABI since version 3.13. This is the same as PyObject_DelAttr(), but attr_name is specified
as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
PyObject *PyObject_GenericGetDict(PyObject *o, void *context)
Return value: New reference. Part of the Stable ABI since version 3.10. Una implementación genérica para obtener
un descriptor __dict__. Crea el diccionario si es necesario.
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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nota: If o1 and o2 are the same object, PyObject_RichCompareBool() will always return 1 for Py_EQ and 0
for Py_NE.
Si cls tiene un método __subclasscheck__(), se llamará para determinar el estado de la subclase como se
describe en PEP 3119. De lo contrario, derived es una subclase de cls si es una subclase directa o indirecta, es
decir, contenida en cls.__ mro__.
Normally only class objects, i.e. instances of type or a derived class, are considered classes. However, objects can
override this by having a __bases__ attribute (which must be a tuple of base classes).
int PyObject_IsInstance(PyObject *inst, PyObject *cls)
Part of the Stable ABI. Retorna 1 si inst es una instancia de la clase cls o una subclase de cls, o 0 si no. En caso de
error, retorna -1 y establece una excepción.
Si cls es una tupla, la verificación se realizará con cada entrada en cls. El resultado será 1 cuando al menos una de
las verificaciones retorne 1, de lo contrario será 0.
Si cls tiene un método __instancecheck__(), se llamará para determinar el estado de la subclase como se
describe en PEP 3119. De lo contrario, inst es una instancia de cls si su clase es una subclase de cls.
An instance inst can override what is considered its class by having a __class__ attribute.
An object cls can override if it is considered a class, and what its base classes are, by having a __bases__ attribute
(which must be a tuple of base classes).
Py_hash_t PyObject_Hash(PyObject *o)
Part of the Stable ABI. Calcula y retorna el valor hash de un objeto o. En caso de fallo, retorna -1. Este es el
equivalente de la expresión de Python hash(o).
Distinto en la versión 3.2: El tipo de retorno ahora es Py_hash_t. Este es un entero con signo del mismo tamaño
que Py_ssize_t.
Py_hash_t PyObject_HashNotImplemented(PyObject *o)
Part of the Stable ABI. Set a TypeError indicating that type(o) is not hashable and return -1. This function
receives special treatment when stored in a tp_hash slot, allowing a type to explicitly indicate to the interpreter
that it is not hashable.
int PyObject_IsTrue(PyObject *o)
Part of the Stable ABI. Retorna 1 si el objeto o se considera verdadero y 0 en caso contrario. Esto es equivalente a
la expresión de Python not not o. En caso de error, retorna -1.
int PyObject_Not(PyObject *o)
Part of the Stable ABI. Retorna 0 si el objeto o se considera verdadero, y 1 de lo contrario. Esto es equivalente a
la expresión de Python not o. En caso de error, retorna -1.
PyObject *PyObject_Type(PyObject *o)
Return value: New reference. Part of the Stable ABI. When o is non-NULL, returns a type object corresponding to
the object type of object o. On failure, raises SystemError and returns NULL. This is equivalent to the Python
expression type(o). This function creates a new strong reference to the return value. There’s really no reason to
use this function instead of the Py_TYPE() function, which returns a pointer of type PyTypeObject*, except
when a new strong reference is needed.
int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)
Retorna un valor no-nulo si el objeto o es de tipo type o un subtipo de type, y 0 en cualquier otro caso. Ninguno de
los dos parámetros debe ser NULL.
Py_ssize_t PyObject_Size(PyObject *o)
Py_ssize_t PyObject_Length(PyObject *o)
Part of the Stable ABI. Retorna la longitud del objeto o. Si el objeto o proporciona los protocolos de secuencia y
mapeo, se retorna la longitud de la secuencia. En caso de error, se retorna -1. Este es el equivalente a la expresión
de Python len(o).
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 destinatario
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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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 posicionales
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.
Nuevo en la versión 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.
If the object has the Py_TPFLAGS_METHOD_DESCRIPTOR feature, this will call the unbound method object
with the full args vector as arguments.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Nuevo en la versión 3.9.
Nota: Exceptions which occur when this calls __getitem__() method are silently ignored. For pro-
per error handling, use PyMapping_HasKeyWithError(), PyMapping_GetOptionalItem() or
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_HasKeyStringWithError(),
PyMapping_GetOptionalItemString() or PyMapping_GetItemString() instead.
if (iterator == NULL) {
/* propagate error */
}
Py_DECREF(iterator);
if (PyErr_Occurred()) {
(continúe en la próxima página)
type PySendResult
El valor de enumeración utilizado para representar diferentes resultados de PyIter_Send().
Nuevo en la versión 3.10.
PySendResult PyIter_Send(PyObject *iter, PyObject *arg, PyObject **presult)
Part of the Stable ABI since version 3.10. Envía el valor arg al iterador iter. Retorna:
• PYGEN_RETURN si el iterador regresa. El valor de retorno se retorna a través de presult.
• PYGEN_NEXT si el iterador cede. El valor cedido se retorna a través de presult.
• PYGEN_ERROR si el iterador ha lanzado una excepción. presult se establece en NULL.
Nuevo en la versión 3.10.
Ciertos objetos disponibles en Python ajustan el acceso a un arreglo de memoria subyacente o buffer. Dichos objetos
incluyen el incorporado bytes y bytearray, y algunos tipos de extensión como array.array. Las bibliotecas de
terceros pueden definir sus propios tipos para fines especiales, como el procesamiento de imágenes o el análisis numérico.
Si bien cada uno de estos tipos tiene su propia semántica, comparten la característica común de estar respaldados por un
búfer de memoria posiblemente grande. Es deseable, en algunas situaciones, acceder a ese búfer directamente y sin copia
intermedia.
Python proporciona una instalación de este tipo en el nivel C en la forma de protocolo búfer. Este protocolo tiene dos
lados:
• en el lado del productor, un tipo puede exportar una «interfaz de búfer» que permite a los objetos de ese tipo
exponer información sobre su búfer subyacente. Esta interfaz se describe en la sección Estructuras de objetos búfer;
• en el lado del consumidor, hay varios medios disponibles para obtener un puntero a los datos subyacentes sin
procesar de un objeto (por ejemplo, un parámetro de método).
Los objetos simples como bytes y bytearray exponen su búfer subyacente en forma orientada a bytes. Otras formas
son posibles; por ejemplo, los elementos expuestos por un array.array pueden ser valores de varios bytes.
An example consumer of the buffer interface is the write() method of file objects: any object that can export a series
of bytes through the buffer interface can be written to a file. While write() only needs read-only access to the internal
contents of the object passed to it, other methods such as readinto() need write access to the contents of their
argument. The buffer interface allows objects to selectively allow or reject exporting of read-write and read-only buffers.
Hay dos formas para que un consumidor de la interfaz del búfer adquiera un búfer sobre un objeto de destino:
• llamar PyObject_GetBuffer() con los parámetros correctos;
• llamar PyArg_ParseTuple() (o uno de sus hermanos) con uno de los y*, w* o s* códigos de formato.
En ambos casos, se debe llamar a PyBuffer_Release() cuando ya no se necesita el búfer. De lo contrario, podrían
surgir varios problemas, como pérdidas de recursos.
Las estructuras de búfer (o simplemente «búferes») son útiles como una forma de exponer los datos binarios de otro objeto
al programador de Python. También se pueden usar como un mecanismo de corte de copia cero. Usando su capacidad para
hacer referencia a un bloque de memoria, es posible exponer cualquier información al programador Python con bastante
facilidad. La memoria podría ser una matriz grande y constante en una extensión C, podría ser un bloque de memoria
sin procesar para su manipulación antes de pasar a una biblioteca del sistema operativo, o podría usarse para pasar datos
estructurados en su formato nativo en memoria .
Contrariamente a la mayoría de los tipos de datos expuestos por el intérprete de Python, los búferes no son punteros
PyObject sino estructuras C simples. Esto les permite ser creados y copiados de manera muy simple. Cuando se
necesita un contenedor genérico alrededor de un búfer, un objeto memoryview puede ser creado.
Para obtener instrucciones breves sobre cómo escribir un objeto de exportación, consulte Estructuras de objetos búfer.
Para obtener un búfer, consulte PyObject_GetBuffer().
type Py_buffer
Part of the Stable ABI (including all members) since version 3.11.
void *buf
Un puntero al inicio de la estructura lógica descrita por los campos del búfer. Puede ser cualquier ubicación
dentro del bloque de memoria física subyacente del exportador. Por ejemplo, con negativo strides el valor
puede apuntar al final del bloque de memoria.
Para arreglos contiguous, el valor apunta al comienzo del bloque de memoria.
PyObject *obj
A new reference to the exporting object. The reference is owned by the consumer and automatically released
(i.e. reference count decremented) and set to NULL by PyBuffer_Release(). The field is the equivalent
of the return value of any standard C-API function.
Como un caso especial, para los búferes temporary que están envueltos por
PyMemoryView_FromBuffer() o PyBuffer_FillInfo() este campo es NULL. En gene-
ral, los objetos de exportación NO DEBEN usar este esquema.
Py_ssize_t len
product(shape) * itemize. Para arreglos contiguos, esta es la longitud del bloque de memoria sub-
yacente. Para arreglos no contiguos, es la longitud que tendría la estructura lógica si se copiara en una repre-
sentación contigua.
Accede a ((char *)buf)[0] hasta ((char *)buf)[len-1] solo es válido si el búfer se ha
obtenido mediante una solicitud que garantiza la contigüidad. En la mayoría de los casos, dicha solicitud será
PyBUF_SIMPLE o PyBUF_WRITABLE.
int readonly
Un indicador de si el búfer es de solo lectura. Este campo está controlado por el indicador
PyBUF_WRITABLE.
Py_ssize_t itemsize
Tamaño del elemento en bytes de un solo elemento. Igual que el valor de struct.calcsize() invocado
en valores no NULL format.
Excepción importante: si un consumidor solicita un búfer sin el indicador PyBUF_FORMAT, format se
establecerá en NULL, pero itemsize todavía tiene el valor para el formato original.
Si shape está presente, la igualdad product(shape) * itemsize == len aún se mantiene y el
consumidor puede usar itemsize para navegar el búfer.
Si shape es NULL como resultado de un PyBUF_SIMPLE o un PyBUF_WRITABLE, el consumidor debe
ignorar itemsize y asume itemsize == 1.
Los búferes obtienen generalmente enviando una solicitud de búfer a un objeto de exportación a través de
PyObject_GetBuffer(). Dado que la complejidad de la estructura lógica de la memoria puede variar drástica-
mente, el consumidor usa el argumento flags para especificar el tipo de búfer exacto que puede manejar.
All Py_buffer fields are unambiguously defined by the request type.
Los siguientes campos no están influenciados por flags y siempre deben completarse con los valores correctos: obj, buf,
len, itemsize, ndim.
PyBUF_WRITABLE
Controla el campo readonly. Si se establece, el exportador DEBE proporcionar un búfer de escritura
o, de lo contrario, informar de un error. De lo contrario, el exportador PUEDE proporcionar un búfer
de solo lectura o de escritura, pero la elección DEBE ser coherente para todos los consumidores.
PyBUF_FORMAT
Controla el campo format. Si se establece, este campo DEBE completarse correctamente. De lo
contrario, este campo DEBE ser NULL.
PyBUF_WRITABLE puede ser |”d a cualquiera de las banderas en la siguiente sección. Dado que PyBUF_SIMPLE se
define como 0, PyBUF_WRITABLE puede usarse como un indicador independiente para solicitar un búfer de escritura
simple.
PyBUF_FORMAT puede ser |”d para cualquiera de las banderas excepto PyBUF_SIMPLE. Este último ya implica el
formato B (bytes sin signo).
Las banderas que controlan la estructura lógica de la memoria se enumeran en orden decreciente de complejidad. Tenga
en cuenta que cada bandera contiene todos los bits de las banderas debajo de ella.
sí sí NULL
PyBUF_STRIDES
sí NULL NULL
PyBUF_ND
solicitudes de contigüidad
La contigüidad C o Fortran se puede solicitar explícitamente, con y sin información de paso. Sin información de paso, el
búfer debe ser C-contiguo.
sí sí NULL F
PyBUF_F_CONTIGUOUS
sí sí NULL CoF
PyBUF_ANY_CONTIGUOUS
solicitudes compuestas
Todas las solicitudes posibles están completamente definidas por alguna combinación de las banderas en la sección an-
terior. Por conveniencia, el protocolo de memoria intermedia proporciona combinaciones de uso frecuente como indica-
dores únicos.
En la siguiente tabla U significa contigüidad indefinida. El consumidor tendría que llamar a
PyBuffer_IsContiguous() para determinar la contigüidad.
sí sí si es necesario U 1o0 sí
PyBUF_FULL_RO
sí sí NULL U 0 sí
PyBUF_RECORDS
sí sí NULL U 1o0 sí
PyBUF_RECORDS_RO
sí sí NULL U 0 NULL
PyBUF_STRIDED
La estructura lógica de las matrices de estilo NumPy está definida por itemsize, ndim, shape y strides.
Si ndim == 0, la ubicación de memoria señalada por buf se interpreta como un escalar de tamaño itemsize. En
ese caso, tanto shape como strides son NULL.
Si strides es NULL, el arreglo se interpreta como un arreglo C n-dimensional estándar. De lo contrario, el consumidor
debe acceder a un arreglo n-dimensional de la siguiente manera:
Como se señaló anteriormente, buf puede apuntar a cualquier ubicación dentro del bloque de memoria real. Un expor-
tador puede verificar la validez de un búfer con esta función:
if ndim <= 0:
return ndim == 0 and not shape and not strides
if 0 in shape:
return True
Además de los elementos normales, los arreglos de estilo PIL pueden contener punteros que deben seguirse para llegar al
siguiente elemento en una dimensión. Por ejemplo, el arreglo C tridimensional regular char v[2][2][3] también se
puede ver como un arreglo de 2 punteros a 2 arreglos bidimensionales: char (*v[2])[2][3]. En la representación
de suboffsets, esos dos punteros pueden incrustarse al comienzo de buf, apuntando a dos matrices char x[2][3] que
pueden ubicarse en cualquier lugar de la memoria.
Aquí hay una función que retorna un puntero al elemento en un arreglo N-D a la que apunta un índice N-dimensional
cuando hay strides y suboffsets no NULL:
int PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
Part of the Stable ABI since version 3.11. Copia len bytes contiguos de buf a view. fort puede ser 'C' o 'F' (para
pedidos al estilo C o al estilo Fortran). 0 se retorna en caso de éxito, -1 en caso de error.
int PyBuffer_ToContiguous(void *buf, const Py_buffer *src, Py_ssize_t len, char order)
Part of the Stable ABI since version 3.11. Copia len bytes de src a su representación contigua en buf. order puede
ser 'C' o 'F' o ''A' (para pedidos al estilo C o al estilo Fortran o cualquiera) 0 se retorna en caso de éxito, -1
en caso de error.
Esta función falla si len != src->len.
int PyObject_CopyData(PyObject *dest, PyObject *src)
Part of the Stable ABI since version 3.11. Copiar datos del búfer src al dest. Puede convertir entre búferes de estilo
C o Fortran.
Se retorna 0 en caso de éxito, -1 en caso de error.
void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char
order)
Part of the Stable ABI since version 3.11. Rellena el arreglo strides con bytes de paso de un contiguous (estilo C
si order es 'C' o estilo Fortran si order es 'F ' ) arreglo de la forma dada con el número dado de bytes por
elemento.
int PyBuffer_FillInfo(Py_buffer *view, PyObject *exporter, void *buf, Py_ssize_t len, int readonly, int flags)
Part of the Stable ABI since version 3.11. Maneje las solicitudes de búfer para un exportador que quiera exponer
buf de tamaño len con capacidad de escritura establecida de acuerdo con readonly. buf se interpreta como una
secuencia de bytes sin signo.
El argumento flags indica el tipo de solicitud. Esta función siempre llena view según lo especificado por flags, a
menos que buf haya sido designado como solo lectura y PyBUF_WRITABLE esté configurado en flags.
On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise BufferError, set
view->obj to NULL and return -1;
Si esta función se usa como parte de a getbufferproc, exporter DEBE establecerse en el objeto exportador y flags
deben pasarse sin modificaciones. De lo contrario, exporter DEBE ser NULL.
Las funciones de este capítulo son específicas de ciertos tipos de objetos de Python. Pasarles un objeto del tipo inco-
rrecto no es una buena idea; si recibe un objeto de un programa Python y no está seguro de que tenga el tipo correc-
to, primero debe realizar una verificación de tipo; por ejemplo, para verificar que un objeto es un diccionario, utilice
PyDict_Check(). El capítulo está estructurado como el «árbol genealógico» de los tipos de objetos Python.
Advertencia: Si bien las funciones descritas en este capítulo verifican cuidadosamente el tipo de objetos que se pasan,
muchos de ellos no verifican si se pasa NULL en lugar de un objeto válido. Permitir que se pase NULL puede causar
violaciones de acceso a la memoria y la terminación inmediata del intérprete.
Esta sección describe los objetos de tipo Python y el objeto singleton None.
type PyTypeObject
Part of the Limited API (as an opaque struct). La estructura C de los objetos utilizados para describir los tipos
incorporados.
PyTypeObject PyType_Type
Part of the Stable ABI. Este es el objeto tipo para objetos tipo; es el mismo objeto que type en la capa Python.
int PyType_Check(PyObject *o)
Retorna un valor distinto de cero si el objeto o es un objeto tipo, incluidas las instancias de tipos derivados del
objeto de tipo estándar. Retorna 0 en todos los demás casos. Esta función siempre finaliza con éxito.
int PyType_CheckExact(PyObject *o)
Retorna un valor distinto de cero si el objeto o es un objeto tipo, pero no un subtipo del objeto tipo estándar. Retorna
0 en todos los demás casos. Esta función siempre finaliza con éxito.
127
The Python/C API, Versión 3.13.0a5
Nota: If some of the base classes implements the GC protocol and the provided type does not include the
Py_TPFLAGS_HAVE_GC in its flags, then the GC protocol will be automatically implemented from its parents.
On the contrary, if the type being created does include Py_TPFLAGS_HAVE_GC in its flags then it must imple-
ment the GC protocol itself by at least implementing the tp_traverse handle.
Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the provided base classes.
Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
PyObject *PyType_FromSpec(PyType_Spec *spec)
Return value: New reference. Part of the Stable ABI. Equivalent to PyType_FromMetaclass(NULL, NULL,
spec, NULL).
Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the base classes provided
in Py_tp_base[s] slots. Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
type PyType_Spec
Part of the Stable ABI (including all members). Estructura que define el comportamiento de un tipo.
const char *name
Nombre del tipo, utilizado para establecer PyTypeObject.tp_name.
int basicsize
If positive, specifies the size of the instance in bytes. It is used to set PyTypeObject.tp_basicsize.
If zero, specifies that tp_basicsize should be inherited.
If negative, the absolute value specifies how much space instances of the class need in addition to the su-
perclass. Use PyObject_GetTypeData() to get a pointer to subclass-specific memory reserved this
way.
Distinto en la versión 3.12: Previously, this field could not be negative.
int itemsize
Size of one element of a variable-size type, in bytes. Used to set PyTypeObject.tp_itemsize. See
tp_itemsize documentation for caveats.
If zero, tp_itemsize is inherited. Extending arbitrary variable-sized classes is dangerous, since some
types use a fixed offset for variable-sized memory, which can then overlap fixed-sized memory used by a
subclass. To help prevent mistakes, inheriting itemsize is only possible in the following situations:
• The base is not variable-sized (its tp_itemsize).
• The requested PyType_Spec.basicsize is positive, suggesting that the memory layout of the base
class is known.
• The requested PyType_Spec.basicsize is zero, suggesting that the subclass does not access the
instance’s memory directly.
• With the Py_TPFLAGS_ITEMS_AT_END flag.
unsigned int flags
Banderas (flags) del tipo, que se usan para establecer PyTypeObject.tp_flags.
Si el indicador Py_TPFLAGS_HEAPTYPE no está establecido, PyType_FromSpecWithBases() lo
establece automáticamente.
PyType_Slot *slots
Arreglo de estructuras PyType_Slot. Terminado por el valor de ranura especial {0, NULL}.
Each slot ID should be specified at most once.
type PyType_Slot
Part of the Stable ABI (including all members). Estructura que define la funcionalidad opcional de un tipo, que
contiene una ranura ID y un puntero de valor.
int slot
Note that the PyTypeObject for None is not directly exposed in the Python/C API. Since None is a singleton, testing
for object identity (using == in C) is sufficient. There is no PyNone_Check() function for the same reason.
PyObject *Py_None
The Python None object, denoting lack of value. This object has no methods and is immortal.
Distinto en la versión 3.12: Py_None is immortal.
Py_RETURN_NONE
Return Py_None from a function.
Todos los enteros se implementan como objetos enteros «largos» (long) de tamaño arbitrario.
En caso de error, la mayoría de las API PyLong_As* retornan (tipo de retorno) -1 que no se puede distinguir
de un número. Use PyErr_Occurred() para desambiguar.
type PyLongObject
Part of the Limited API (as an opaque struct). Este subtipo de PyObject representa un objeto entero de Python.
PyTypeObject PyLong_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo entero de Python. Este es el mismo
objeto que int en la capa de Python.
int PyLong_Check(PyObject *p)
Retorna verdadero si su argumento es un PyLongObject o un subtipo de PyLongObject. Esta función siem-
pre finaliza con éxito.
int PyLong_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyLongObject, pero no un subtipo de PyLongObject. Esta función
siempre finaliza con éxito.
PyObject *PyLong_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde v, o NULL
en caso de error.
The current implementation keeps an array of integer objects for all integers between -5 and 256. When you
create an int in that range you actually just get back a reference to the existing object.
PyObject *PyLong_FromUnsignedLong(unsigned long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C unsigned
long, or NULL on failure.
PyObject *PyLong_FromSsize_t(Py_ssize_t v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde un C
Py_ssize_t, o NULL en caso de error.
PyObject *PyLong_FromSize_t(size_t v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde un C
size_t, o NULL en caso de error.
PyObject *PyLong_FromLongLong(long long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C long long,
or NULL on failure.
PyObject *PyLong_FromUnsignedLongLong(unsigned long long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C unsigned
long long, or NULL on failure.
PyObject *PyLong_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto PyLongObject de la parte entera
de v, o NULL en caso de error.
int32_t value;
Py_ssize_t bytes = PyLong_AsNativeBits(pylong, &value, sizeof(value), -1);
if (bytes < 0) {
// A Python exception was set with the reason.
return NULL;
}
else if (bytes <= (Py_ssize_t)sizeof(value)) {
// Success!
(continúe en la próxima página)
The above example may look similar to PyLong_As* but instead fills in a specific caller defined type and never
raises an error about of the int pylong’s value regardless of n_bytes or the returned byte count.
To get at the entire potentially big Python value, this can be used to reserve enough space and copy it:
endianness may be passed -1 for the native endian that CPython was compiled with, or 0 for big endian and 1 for
little.
Returns -1 with an exception raised if pylong cannot be interpreted as an integer. Otherwise, return the size of the
buffer required to store the value. If this is equal to or less than n_bytes, the entire value was copied. 0 will never
be returned.
Unless an exception is raised, all n_bytes of the buffer will always be written. In the case of truncation, as many of
the lowest bits of the value as could fit are written. This allows the caller to ignore all non-negative results if the
intent is to match the typical behavior of a C-style downcast. No exception is set on truncation.
Values are always copied as two’s-complement and sufficient buffer will be requested to include a sign bit. For
example, this may cause an value that fits into 8 bytes when treated as unsigned to request 9 bytes, even though
all eight bytes were copied into the buffer. What has been omitted is the zero sign bit – redundant if the caller’s
intention is to treat the value as unsigned.
Passing zero to n_bytes will return the size of a buffer that would be large enough to hold the value. This may be
larger than technically necessary, but not unreasonably so.
Nota: Passing n_bytes=0 to this function is not an accurate way to determine the bit length of a value.
Booleans in Python are implemented as a subclass of integers. There are only two booleans, Py_False and Py_True.
As such, the normal creation and deletion functions don’t apply to booleans. The following macros are available, however.
PyTypeObject PyBool_Type
Part of the Stable ABI. This instance of PyTypeObject represents the Python boolean type; it is the same object
as bool in the Python layer.
int PyBool_Check(PyObject *o)
Retorna verdadero si o es de tipo PyBool_Type. Esta función siempre finaliza con éxito.
PyObject *Py_False
The Python False object. This object has no methods and is immortal.
Distinto en la versión 3.12: Py_False is immortal.
PyObject *Py_True
The Python True object. This object has no methods and is immortal.
Distinto en la versión 3.12: Py_True is immortal.
Py_RETURN_FALSE
Return Py_False from a function.
Py_RETURN_TRUE
Return Py_True from a function.
PyObject *PyBool_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Return Py_True or Py_False, depending on the truth
value of v.
type PyFloatObject
Este subtipo de PyObject representa un objeto de punto flotante de Python.
PyTypeObject PyFloat_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de punto flotante de Python. Este es
el mismo objeto que float en la capa de Python.
int PyFloat_Check(PyObject *p)
Retorna verdadero si su argumento es un PyFloatObject o un subtipo de PyFloatObject. Esta función
siempre finaliza con éxito.
int PyFloat_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyFloatObject, pero no un subtipo de PyFloatObject. Esta
función siempre finaliza con éxito.
PyObject *PyFloat_FromString(PyObject *str)
Return value: New reference. Part of the Stable ABI. Crea un objeto PyFloatObject basado en la cadena de
caracteres en str, o NULL en caso de error.
PyObject *PyFloat_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. Crea un objeto PyFloatObject a partir de v, o NULL en
caso de error.
double PyFloat_AsDouble(PyObject *pyfloat)
Part of the Stable ABI. Return a C double representation of the contents of pyfloat. If pyfloat is not a Python
floating point object but has a __float__() method, this method will first be called to convert pyfloat into a
float. If __float__() is not defined then it falls back to __index__(). This method returns -1.0 upon
failure, so one should call PyErr_Occurred() to check for errors.
Distinto en la versión 3.8: Use __index__() if available.
double PyFloat_AS_DOUBLE(PyObject *pyfloat)
Retorna una representación C double de los contenidos de pyfloat, pero sin verificación de errores.
PyObject *PyFloat_GetInfo(void)
Return value: New reference. Part of the Stable ABI. Retorna una instancia de structseq que contiene información
sobre la precisión, los valores mínimos y máximos de un flotante. Es un contenedor reducido alrededor del archivo
de encabezado float.h.
double PyFloat_GetMax()
Part of the Stable ABI. Retorna el máximo flotante finito representable DBL_MAX como C double.
double PyFloat_GetMin()
Part of the Stable ABI. Retorna el flotante positivo normalizado mínimo DBL_MIN como C double.
Las funciones de empaquetar y desempaquetar proporcionan una manera eficiente e independiente de la plataforma para
almacenar valores de coma flotante como cadenas de bytes. Las rutinas Pack producen una cadena de bytes a partir de un
C double, y las rutinas Desempaquetar producen un C double a partir de dicha cadena de bytes. El sufijo (2, 4 u 8)
especifica el número de bytes en la cadena de bytes.
En plataformas que parecen usar formatos IEEE 754, estas funciones actúan copiando los bits. En otras plataformas, el
formato 2-byte es idéntico al formato de media precision IEEE 754 binary16, el formato de 4-byte (32 bits) es idéntico
al formato de precisión simple binario IEEE 754 binary32, y el formato de 8-byte al formato de doble precisión binario
IEEE 754 binary64, aunque el empaquetado de INFs y NaNs (si existen en la plataforma) no se maneja correctamente,
mientras que intentar desempaquetar una cadena de bytes que contenga un IEEE INF o NaN generará una excepción.
En plataformas que no son IEEE con más precisión, o mayor rango dinámico, que el IEEE 754 admite, no se pueden
empaquetar todos los valores; en plataformas que no son IEEE con menos precisión o con un rango dinámico más pequeño,
no se pueden desempaquetar todos los valores. Lo que sucede en tales casos es en parte accidental (desafortunadamente).
Nuevo en la versión 3.11.
Funciones de Empaquetado
The pack routines write 2, 4 or 8 bytes, starting at p. le is an int argument, non-zero if you want the bytes string in
little-endian format (exponent last, at p+1, p+3, or p+6 p+7), zero if you want big-endian format (exponent first, at p).
The PY_BIG_ENDIAN constant can be used to use the native endian: it is equal to 1 on big endian processor, or 0 on
little endian processor.
Valor retornado: 0 si todo está bien, -1 si hay error (y se establece una excepción, probablemente OverflowError).
Hay dos problemas en plataformas que no son IEEE:
• Lo que esto hace es indefinido si x es un NaN o infinito.
• -0.0 and +0.0 produce la misma cadena de bytes.
int PyFloat_Pack2(double x, unsigned char *p, int le)
Empaquete un C doble como el formato de media precisión IEEE 754 binary16.
int PyFloat_Pack4(double x, unsigned char *p, int le)
Empaque un C doble como el formato de precisión simple IEEE 754 binary32.
int PyFloat_Pack8(double x, unsigned char *p, int le)
Empaque un C doble como el formato de doble precisión IEEE 754 binary64.
Funciones de Desempaquetado
The unpack routines read 2, 4 or 8 bytes, starting at p. le is an int argument, non-zero if the bytes string is in little-endian
format (exponent last, at p+1, p+3 or p+6 and p+7), zero if big-endian (exponent first, at p). The PY_BIG_ENDIAN
constant can be used to use the native endian: it is equal to 1 on big endian processor, or 0 on little endian processor.
Valor retornado: Doble desempaquetado. Si hay error, -1.0 y PyErr_Occurred() es verdadero (y se establece una
excepción, probablemente OverflowError).
Hay que tener en cuenta que en una plataforma que no sea IEEE, esto se negará a desempaquetar una cadena de bytes
que representa un NaN o infinito.
double PyFloat_Unpack2(const unsigned char *p, int le)
Descomprima el formato de media precisión IEEE 754 binary16 como un doble C.
Los objetos de números complejos de Python se implementan como dos tipos distintos cuando se ven desde la API de C:
uno es el objeto de Python expuesto a los programas de Python, y el otro es una estructura en C que representa el valor
de número complejo real. La API proporciona funciones para trabajar con ambos.
Tenga en cuenta que las funciones que aceptan estas estructuras como parámetros y las retornan como resultados lo hacen
por valor en lugar de desreferenciarlas a través de punteros. Esto es consistente en toda la API.
type Py_complex
La estructura C que corresponde a la porción de valor de un objeto de número complejo de Python. La mayoría
de las funciones para tratar con objetos de números complejos utilizan estructuras de este tipo como valores de
entrada o salida, según corresponda. Se define como:
typedef struct {
double real;
double imag;
} Py_complex;
type PyComplexObject
Este subtipo de PyObject representa un objeto de número complejo de Python.
PyTypeObject PyComplex_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de número complejo de Python. Es
el mismo objeto que complex en la capa de Python.
int PyComplex_Check(PyObject *p)
Retorna verdadero si su argumento es un PyComplexObject o un subtipo de PyComplexObject. Esta
función siempre finaliza con éxito.
int PyComplex_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyComplexObject, pero no un subtipo de PyComplexObject.
Esta función siempre finaliza con éxito.
PyObject *PyComplex_FromCComplex(Py_complex v)
Return value: New reference. Crea un nuevo objeto de número complejo de Python a partir de un valor C
Py_complex.
PyObject *PyComplex_FromDoubles(double real, double imag)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto PyComplexObject de real e
imag.
double PyComplex_RealAsDouble(PyObject *op)
Part of the Stable ABI. Return the real part of op as a C double.
If op is not a Python complex number object but has a __complex__() method, this method will first be
called to convert op to a Python complex number object. If __complex__() is not defined then it falls back to
call PyFloat_AsDouble() and returns its result. Upon failure, this method returns -1.0, so one should call
PyErr_Occurred() to check for errors.
Distinto en la versión 3.13: Use __complex__() if available.
double PyComplex_ImagAsDouble(PyObject *op)
Part of the Stable ABI. Return the imaginary part of op as a C double.
If op is not a Python complex number object but has a __complex__() method, this method will first be called
to convert op to a Python complex number object. If __complex__() is not defined then it falls back to call
PyFloat_AsDouble() and returns 0.0 on success. Upon failure, this method returns -1.0, so one should
call PyErr_Occurred() to check for errors.
Distinto en la versión 3.13: Use __complex__() if available.
Py_complex PyComplex_AsCComplex(PyObject *op)
Retorna el valor Py_complex del número complejo op.
If op is not a Python complex number object but has a __complex__() method, this method will first be
called to convert op to a Python complex number object. If __complex__() is not defined then it falls back to
__float__(). If __float__() is not defined then it falls back to __index__(). Upon failure, this method
returns -1.0 as a real value.
Distinto en la versión 3.8: Use __index__() if available.
Las operaciones genéricas en los objetos de secuencia se discutieron en el capítulo anterior; Esta sección trata sobre los
tipos específicos de objetos de secuencia que son intrínsecos al lenguaje Python.
Estas funciones lanzan TypeError cuando se espera un parámetro de bytes y se llama con un parámetro que no es
bytes.
type PyBytesObject
Este subtipo de PyObject representa un objeto bytes de Python.
PyTypeObject PyBytes_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo bytes de Python; es el mismo objeto
que bytes en la capa de Python.
int PyBytes_Check(PyObject *o)
Retorna verdadero si el objeto o es un objeto bytes o una instancia de un subtipo del tipo bytes. Esta función siempre
finaliza con éxito.
int PyBytes_CheckExact(PyObject *o)
Retorna verdadero si el objeto o es un objeto bytes, pero no una instancia de un subtipo del tipo bytes. Esta función
siempre finaliza con éxito.
PyObject *PyBytes_FromString(const char *v)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto bytes con una copia de la cadena
de caracteres v como valor en caso de éxito y NULL en caso de error. El parámetro v no debe ser NULL; no se
comprobará.
PyObject *PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto bytes con una copia de la cadena de
caracteres v como valor y longitud len en caso de éxito y NULL en caso de error. Si v es NULL, el contenido del
objeto bytes no se inicializa.
PyObject *PyBytes_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI. Toma una cadena de caracteres format del estilo C printf()
y un número variable de argumentos, calcula el tamaño del objeto bytes Python resultante y retorna un objeto bytes
con los valores formateados. Los argumentos variables deben ser tipos C y deben corresponder exactamente a los
caracteres de formato en la cadena de caracteres format. Se permiten los siguientes caracteres de formato:
Un carácter de formato no reconocido hace que todo el resto de la cadena de caracteres de formato se copie como
está en el objeto de resultado y se descartan los argumentos adicionales.
PyObject *PyBytes_FromFormatV(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Idéntica a PyBytes_FromFormat() excepto que toma
exactamente dos argumentos.
PyObject *PyBytes_FromObject(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna la representación en bytes del objeto o que implementa
el protocolo de búfer.
Py_ssize_t PyBytes_Size(PyObject *o)
Part of the Stable ABI. Retorna la longitud de los bytes en el objeto bytes o.
Py_ssize_t PyBytes_GET_SIZE(PyObject *o)
Forma macro de PyBytes_Size() pero sin verificación de errores.
char *PyBytes_AsString(PyObject *o)
Part of the Stable ABI. Retorna un puntero al contenido de o. El puntero se refiere al búfer interno de o, que
consiste en len(o) + 1 bytes. El último byte en el búfer siempre es nulo, independientemente de si hay otros
bytes nulos. Los datos no deben modificarse de ninguna manera, a menos que el objeto se haya creado usando
PyBytes_FromStringAndSize(NULL, size). No debe ser desasignado. Si o no es un objeto de bytes
en absoluto, PyBytes_AsString() retorna NULL y lanza un TypeError.
char *PyBytes_AS_STRING(PyObject *string)
Forma macro de PyBytes_AsString() pero sin verificación de errores.
int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
Part of the Stable ABI. Return the null-terminated contents of the object obj through the output variables buffer
and length. Returns 0 on success.
Si length es NULL, el objeto bytes no puede contener bytes nulos incrustados; en caso contrario, la función retorna
-1 y se lanza un ValueError.
El búfer se refiere a un búfer interno de obj, que incluye un byte nulo adicional al final (no está considerado
en length). Los datos no deben modificarse de ninguna manera, a menos que el objeto se haya creado usando
1 Para especificadores de enteros (d, u, ld, lu, zd, zu, i, x): el indicador de conversión 0 tiene efecto incluso cuando se proporciona una precisión.
type PyByteArrayObject
Este subtipo de PyObject representa un objeto arreglo de bytes de Python.
PyTypeObject PyByteArray_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo arreglo de bytes de Python; es el
mismo objeto que bytearray en la capa de Python.
Macros
Objetos unicode
Desde la implementación del PEP 393 en Python 3.3, los objetos Unicode utilizan internamente una variedad de re-
presentaciones, para permitir el manejo del rango completo de caracteres Unicode mientras se mantiene la eficiencia de
memoria. Hay casos especiales para cadenas de caracteres donde todos los puntos de código están por debajo de 128,
256 o 65536; de lo contrario, los puntos de código deben estar por debajo de 1114112 (que es el rango completo de
Unicode).
UTF-8 representation is created on demand and cached in the Unicode object.
Nota: The Py_UNICODE representation has been removed since Python 3.12 with deprecated APIs. See PEP 623 for
more information.
Tipo unicode
Estos son los tipos básicos de objetos Unicode utilizados para la implementación de Unicode en Python:
type Py_UCS4
type Py_UCS2
type Py_UCS1
Part of the Stable ABI. Estos tipos son definiciones de tipo (typedefs) para los tipos “enteros sin signo” (unsigned
int) lo suficientemente anchos como para contener caracteres de 32 bits, 16 bits y 8 bits, respectivamente. Cuando
se trate con caracteres Unicode individuales, use Py_UCS4.
Nuevo en la versión 3.3.
type Py_UNICODE
This is a typedef of wchar_t, which is a 16-bit type or 32-bit type depending on the platform.
Distinto en la versión 3.3: En versiones anteriores, este era un tipo de 16 bits o de 32 bits, dependiendo de si
seleccionó una versión Unicode «estrecha» o «amplia» de Python en el momento de la compilación.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15.
type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject
Estos subtipos de PyObject representan un objeto Python Unicode. En casi todos los casos, no deben usar-
se directamente, ya que todas las funciones API que se ocupan de objetos Unicode toman y retornan punteros
PyObject.
Nuevo en la versión 3.3.
PyTypeObject PyUnicode_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo Python Unicode. Está expuesto al
código de Python como str.
The following APIs are C macros and static inlined functions for fast checks and access to internal read-only data of
Unicode objects:
int PyUnicode_Check(PyObject *obj)
Return true if the object obj is a Unicode object or an instance of a Unicode subtype. This function always succeeds.
int PyUnicode_CheckExact(PyObject *obj)
Return true if the object obj is a Unicode object, but not an instance of a subtype. This function always succeeds.
int PyUnicode_READY(PyObject *unicode)
Returns 0. This API is kept only for backward compatibility.
Nuevo en la versión 3.3.
Obsoleto desde la versión 3.10: This API does nothing since Python 3.12.
Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)
Return the length of the Unicode string, in code points. unicode has to be a Unicode object in the «canonical»
representation (not checked).
Nuevo en la versión 3.3.
Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *unicode)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *unicode)
Unicode proporciona muchas propiedades de caracteres diferentes. Los que se necesitan con mayor frecuencia están
disponibles a través de estas macros que se asignan a las funciones de C según la configuración de Python.
int Py_UNICODE_ISSPACE(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter de espacio en blanco.
int Py_UNICODE_ISLOWER(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter en minúscula.
int Py_UNICODE_ISUPPER(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter en mayúscula.
int Py_UNICODE_ISTITLE(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter en caso de título (titlecase).
int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter de salto de línea.
int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter decimal o no.
int Py_UNICODE_ISDIGIT(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter de dígitos.
int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter numérico.
int Py_UNICODE_ISALPHA(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter alfabético.
int Py_UNICODE_ISALNUM(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter alfanumérico.
int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter imprimible. Los caracteres no imprimibles son aquellos definidos
en la base de datos de caracteres Unicode como «Otro» o «Separador», excepto el espacio ASCII (0x20) que se
considera imprimible. (Tenga en cuenta que los caracteres imprimibles en este contexto son aquellos a los que no se
debe escapar cuando repr() se invoca en una cadena de caracteres. No tiene relación con el manejo de cadenas
de caracteres escritas en sys.stdout o sys.stderr.)
Estas API se pueden usar para conversiones caracteres rápidas y directos:
Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)
Retorna el carácter ch convertido a minúsculas.
Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)
Retorna el carácter ch convertido a mayúsculas.
Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)
Retorna el carácter ch convertido a formato de título (titlecase).
int Py_UNICODE_TODECIMAL(Py_UCS4 ch)
Return the character ch converted to a decimal positive integer. Return -1 if this is not possible. This function does
not raise exceptions.
Para crear objetos Unicode y acceder a sus propiedades de secuencia básicas, use estas API:
PyObject *PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
Return value: New reference. Crea un nuevo objeto Unicode. maxchar debe ser el punto de código máximo que
se colocará en la cadena de caracteres. Como una aproximación, se puede redondear al valor más cercano en la
secuencia 127, 255, 65535, 1114111.
Esta es la forma recomendada de asignar un nuevo objeto Unicode. Los objetos creados con esta función no se
pueden redimensionar.
Nuevo en la versión 3.3.
PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
Return value: New reference. Crea un nuevo objeto Unicode con el tipo kind dado (los valores posibles son
PyUnicode_1BYTE_KIND etc., según lo retornado por PyUnicode_KIND()). El búfer debe apuntar a un
vector (array) de tamaño unidades de 1, 2 o 4 bytes por carácter, según el tipo.
Si es necesario, la entrada buffer se copia y se transforma en la representación canónica. Por ejemplo, si el buffer
es una cadena de caracteres UCS4 (PyUnicode_4BYTE_KIND) y consta solo de puntos de código en el rango
UCS1, se transformará en UCS1 (PyUnicode_1BYTE_KIND).
Nuevo en la versión 3.3.
PyObject *PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from the char buffer str. The bytes
will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. The return value might be a
shared object, i.e. modification of the data is not allowed.
This function raises SystemError when:
• size < 0,
• str is NULL and size > 0
Distinto en la versión 3.12: str == NULL with size > 0 is not allowed anymore.
PyObject *PyUnicode_FromString(const char *str)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from a UTF-8 encoded null-terminated
char buffer str.
PyObject *PyUnicode_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI. Take a C printf()-style format string and a variable number
of arguments, calculate the size of the resulting Python Unicode string and return a string with the values formatted
into it. The variable arguments must be C types and must correspond exactly to the format characters in the format
ASCII-encoded string.
A conversion specifier contains two or more characters and has the following components, which must occur in this
order:
1. The '%' character, which marks the start of the specifier.
2. Conversion flags (optional), which affect the result of some conversion types.
3. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is given in the next ar-
gument, which must be of type int, and the object to convert comes after the minimum field width and
optional precision.
4. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the
actual precision is given in the next argument, which must be of type int, and the value to convert comes
after the precision.
5. Length modifier (optional).
6. Conversion type.
The conversion flag characters are:
Flag Meaning
0 The conversion will be zero padded for numeric values.
- The converted value is left adjusted (overrides the 0 flag if both are given).
The length modifiers for following integer conversions (d, i, o, u, x, or X) specify the type of the argument (int
by default):
Modifier Types
l long or unsigned long
ll long long or unsigned long long
j intmax_t or uintmax_t
z size_t or ssize_t
t ptrdiff_t
The length modifier l for following conversions s or V specify that the type of the argument is const wchar_t*.
The conversion specifiers are:
Nota: The width formatter unit is number of characters rather than bytes. The precision formatter unit is number
of bytes or wchar_t items (if the length modifier l is used) for "%s" and "%V" (if the PyObject* argument
is NULL), and a number of characters for "%A", "%U", "%S", "%R" and "%V" (if the PyObject* argument
is not NULL).
Nota: Unlike to C printf() the 0 flag has effect even when a precision is given for integer conversions (d, i,
u, o, x, or X).
Codificación regional
La codificación local actual se puede utilizar para decodificar texto del sistema operativo.
PyObject *PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t length, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7. Decodifica una cadena de caracteres UTF-8
en Android y VxWorks, o de la codificación de configuración regional actual en otras plataformas. Los maneja-
dores de errores admitidos son "estricto" y "subrogateescape" (PEP 383). El decodificador usa el
controlador de errores "estricto" si errors es NULL. str debe terminar con un carácter nulo pero no puede
contener caracteres nulos incrustados.
Use PyUnicode_DecodeFSDefaultAndSize() to decode a string from the filesystem encoding and error
handler.
Esta función ignora el modo Python UTF-8.
Ver también:
La función Py_DecodeLocale().
Nuevo en la versión 3.3.
Distinto en la versión 3.7: La función ahora también usa la codificación de configuración regional actual para el
controlador de errores subrogateescape, excepto en Android. Anteriormente, Py_DecodeLocale() se
usaba para el subrogateescape, y la codificación local actual se usaba para estricto.
PyObject *PyUnicode_DecodeLocale(const char *str, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7. Similar to
PyUnicode_DecodeLocaleAndSize(), but compute the string length using strlen().
Nuevo en la versión 3.3.
PyObject *PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7. Codifica un objeto Unicode UTF-8 en
Android y VxWorks, o en la codificación local actual en otras plataformas. Los manejadores de errores admiti-
dos son "estricto" y "subrogateescape" (PEP 383). El codificador utiliza el controlador de errores
"estricto" si errors es NULL. Retorna un objeto bytes. unicode no puede contener caracteres nulos incrus-
tados.
Use PyUnicode_EncodeFSDefault() to encode a string to the filesystem encoding and error handler.
Functions encoding to and decoding from the filesystem encoding and error handler (PEP 383 and PEP 529).
To encode file names to bytes during argument parsing, the "O&" converter should be used, passing
PyUnicode_FSConverter() as the conversion function:
int PyUnicode_FSConverter(PyObject *obj, void *result)
Part of the Stable ABI. ParseTuple converter: encode str objects – obtained directly or through the os.
PathLike interface – to bytes using PyUnicode_EncodeFSDefault(); bytes objects are output as-is.
result must be a PyBytesObject* which must be released when it is no longer used.
Nuevo en la versión 3.1.
Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).
Para decodificar nombres de archivo a str durante el análisis de argumentos, se debe usar el convertidor "O&", pasando
PyUnicode_FSDecoder() como la función de conversión:
int PyUnicode_FSDecoder(PyObject *obj, void *result)
Part of the Stable ABI. ParseTuple converter: decode bytes objects – obtained either directly or indirectly through
the os.PathLike interface – to str using PyUnicode_DecodeFSDefaultAndSize(); str objects are
output as-is. result must be a PyUnicodeObject* which must be released when it is no longer used.
Nuevo en la versión 3.2.
Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).
PyObject *PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Decodifica una cadena desde el codificador de sistema de
archivos y gestor de errores.
If you need to decode a string from the current locale encoding, use
PyUnicode_DecodeLocaleAndSize().
Ver también:
La función Py_DecodeLocale().
Distinto en la versión 3.6: The filesystem error handler is now used.
PyObject *PyUnicode_DecodeFSDefault(const char *str)
Return value: New reference. Part of the Stable ABI. Decodifica una cadena terminada en nulo desde el codificador
de sistema de archivos y gestor de errores.
If the string length is known, use PyUnicode_DecodeFSDefaultAndSize().
Distinto en la versión 3.6: The filesystem error handler is now used.
soporte wchar_t
Códecs incorporados
Python proporciona un conjunto de códecs integrados que están escritos en C para mayor velocidad. Todos estos códecs
se pueden usar directamente a través de las siguientes funciones.
Muchas de las siguientes API toman dos argumentos de encoding y errors, y tienen la misma semántica que las del
constructor de objetos de cadena incorporado str().
Setting encoding to NULL causes the default encoding to be used which is UTF-8. The file system calls should use
PyUnicode_FSConverter() for encoding file names. This uses the filesystem encoding and error handler internally.
El manejo de errores se establece mediante errors que también pueden establecerse en NULL, lo que significa usar el
manejo predeterminado definido para el códec. El manejo de errores predeterminado para todos los códecs integrados es
«estricto» (se lanza ValueError).
The codecs all use a similar interface. Only deviations from the following generic ones are documented for simplicity.
Códecs genéricos
Códecs UTF-8
Códecs UTF-32
Si *byteorder es cero, y los primeros cuatro bytes de los datos de entrada son una marca de orden de bytes
(BOM), el decodificador cambia a este orden de bytes y la BOM no se copia en la cadena de caracteres Unicode
resultante. Si *byteorder es -1 o 1, cualquier marca de orden de bytes se copia en la salida.
Una vez completado, *byteorder se establece en el orden de bytes actual al final de los datos de entrada.
Si byteorder es NULL, el códec se inicia en modo de orden nativo.
Retorna NULL si el códec provocó una excepción.
PyObject *PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF32(). Si consumed no es NULL, PyUnicode_DecodeUTF32Stateful() no
tratará las secuencias de bytes UTF-32 incompletas finales (como un número de bytes no divisible por cuatro)
como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se almacenará
en consumed.
Códecs UTF-16
Si *byteorder es cero, y los primeros dos bytes de los datos de entrada son una marca de orden de bytes (BOM),
el decodificador cambia a este orden de bytes y la BOM no se copia en la cadena de caracteres Unicode resultante.
Si *byteorder es -1 o 1, cualquier marca de orden de bytes se copia en la salida (donde dará como resultado
un \ufeff o un carácter \ufffe).
After completion, *byteorder is set to the current byte order at the end of input data.
Si byteorder es NULL, el códec se inicia en modo de orden nativo.
Retorna NULL si el códec provocó una excepción.
PyObject *PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF16(). Si consumed no es NULL, PyUnicode_DecodeUTF16Stateful() no
tratará las secuencias de bytes UTF-16 incompletas finales (como un número impar de bytes o un par sustituto
dividido) como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se
almacenará en consumed.
PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Retorna una cadena de bytes de Python usando la codificación
UTF-16 en orden de bytes nativo. La cadena siempre comienza con una marca BOM. El manejo de errores es
«estricto». Retorna NULL si el códec provocó una excepción.
Códecs UTF-7
Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF7(). Si consumed no es NULL, las secciones UTF-7 base-64 incompletas no se tra-
tarán como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se
almacenará en consumed.
Estas son las API del códec Unicode escapado en bruto (Raw Unicode Escape):
PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the Raw-
Unicode-Escape encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando Unicode escapado en bruto
(Raw-Unicode-Escape) y retorna el resultado como un objeto de bytes. El manejo de errores es «estricto». Retorna
NULL si el códec provocó una excepción.
Códecs Latin-1
Estas son las API del códec Latin-1: Latin-1 corresponde a los primeros 256 ordinales Unicode y solo estos son aceptados
por los códecs durante la codificación.
PyObject *PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the Latin-1
encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando Latin-1 y retorna el resul-
tado como un objeto de bytes Python. El manejo de errores es «estricto». Retorna NULL si el códec provocó una
excepción.
Códecs ASCII
Estas son las API del códec ASCII. Solo se aceptan datos ASCII de 7 bits. Todos los demás códigos generan errores.
PyObject *PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the ASCII
encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando ASCII y retorna el resultado
como un objeto de bytes de Python. El manejo de errores es «estricto». Retorna NULL si el códec provocó una
excepción.
This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to
obtain most of the standard codecs included in the encodings package). The codec uses mappings to encode and
decode characters. The mapping objects provided must support the __getitem__() mapping interface; dictionaries
and sequences work well.
Estos son las API de códec de mapeo:
PyObject *PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, PyObject *mapping, const char
*errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the encoded
string str using the given mapping object. Return NULL if an exception was raised by the codec.
Si mapping es NULL, se aplicará la decodificación Latin-1. De lo contrario, mapping debe asignar bytes ordinales
(enteros en el rango de 0 a 255) a cadenas de caracteres Unicode, enteros (que luego se interpretan como ordinales
Unicode) o None. Los bytes de datos sin asignar - los que causan un LookupError, así como los que se asignan
a None, 0xFFFE o '\ ufffe', se tratan como asignaciones indefinidas y causan un error.
PyObject *PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando el objeto mapping dado y
retorna el resultado como un objeto de bytes. El manejo de errores es «estricto». Retorna NULL si el códec provocó
una excepción.
El objeto mapping debe asignar enteros ordinales Unicode a objetos de bytes, enteros en el rango de 0 a 255 o
None. Los ordinales de caracteres no asignados (los que causan un LookupError), así como los asignados a
Ninguno, se tratan como «mapeo indefinido» y causan un error.
La siguiente API de códec es especial en que asigna Unicode a Unicode.
PyObject *PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
Return value: New reference. Part of the Stable ABI. Traduce una cadena de caracteres aplicando una tabla de
mapeo y retornando el objeto Unicode resultante. Retorna NULL cuando el códec provocó una excepción.
La tabla de mapeo debe mapear enteros ordinales Unicode a enteros ordinales Unicode o None (causando la
eliminación del carácter).
Mapping tables need only provide the __getitem__() interface; dictionaries and sequences work well. Un-
mapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is.
errors tiene el significado habitual para los códecs. Puede ser NULL, lo que indica que debe usar el manejo de
errores predeterminado.
Estas son las API de códec MBCS. Actualmente solo están disponibles en Windows y utilizan los convertidores Win32
MBCS para implementar las conversiones. Tenga en cuenta que MBCS (o DBCS) es una clase de codificaciones, no solo
una. La codificación de destino está definida por la configuración del usuario en la máquina que ejecuta el códec.
PyObject *PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Create a Unicode object by
decoding size bytes of the MBCS encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeMBCSStateful(const char *str, Py_ssize_t size, const char *errors, Py_ssize_t
*consumed)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Si consu-
med es NULL, se comporta como PyUnicode_DecodeMBCS(). Si consumed no es NULL,
PyUnicode_DecodeMBCSStateful() no decodificará el byte inicial y el número de bytes que se
han decodificado se almacenará en consumed.
PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Codifica un objeto Unicode
usando MBCS y retorna el resultado como un objeto de bytes de Python. El manejo de errores es «estricto».
Retorna NULL si el códec provocó una excepción.
PyObject *PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Encode the Unicode object using
the specified code page and return a Python bytes object. Return NULL if an exception was raised by the codec.
Use CP_ACP code page to get the MBCS encoder.
Nuevo en la versión 3.3.
Las siguientes API son capaces de manejar objetos Unicode y cadenas de caracteres en la entrada (nos referimos a ellos
como cadenas de caracteres en las descripciones) y retorna objetos Unicode o enteros según corresponda.
Todos retornan NULL o -1 si ocurre una excepción.
PyObject *PyUnicode_Concat(PyObject *left, PyObject *right)
Return value: New reference. Part of the Stable ABI. Une dos cadenas de caracteres que dan una nueva cadena de
caracteres Unicode.
PyObject *PyUnicode_Split(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
Return value: New reference. Part of the Stable ABI. Divide una cadena de caracteres dando una lista de cadenas de
caracteres Unicode. Si sep es NULL, la división se realizará en todas las subcadenas de espacios en blanco. De lo
contrario, las divisiones ocurren en el separador dado. A lo sumo se realizarán maxsplit divisiones. Si es negativo,
no se establece ningún límite. Los separadores no están incluidos en la lista resultante.
PyObject *PyUnicode_Splitlines(PyObject *unicode, int keepends)
Return value: New reference. Part of the Stable ABI. Split a Unicode string at line breaks, returning a list of Unicode
strings. CRLF is considered to be one line break. If keepends is 0, the Line break characters are not included in the
resulting strings.
PyObject *PyUnicode_Join(PyObject *separator, PyObject *seq)
Return value: New reference. Part of the Stable ABI. Une una secuencia de cadenas de caracteres usando el separator
dado y retorna la cadena de caracteres Unicode resultante.
Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
Part of the Stable ABI. Return 1 if substr matches unicode[start:end] at the given tail end (direction ==
-1 means to do a prefix match, direction == 1 a suffix match), 0 otherwise. Return -1 if an error occurred.
Py_ssize_t PyUnicode_Find(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI. Return the first position of substr in unicode[start:end] using the given direction
(direction == 1 means to do a forward search, direction == -1 a backward search). The return value is the index
of the first match; a value of -1 indicates that no match was found, and -2 indicates that an error occurred and an
exception has been set.
Py_ssize_t PyUnicode_FindChar(PyObject *unicode, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI since version 3.7. Return the first position of the character ch in unicode[start:end]
using the given direction (direction == 1 means to do a forward search, direction == -1 a backward search). The
return value is the index of the first match; a value of -1 indicates that no match was found, and -2 indicates that
an error occurred and an exception has been set.
Nuevo en la versión 3.3.
Distinto en la versión 3.7: start and end are now adjusted to behave like unicode[start:end].
Py_ssize_t PyUnicode_Count(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
Part of the Stable ABI. Return the number of non-overlapping occurrences of substr in unicode[start:end].
Return -1 if an error occurred.
PyObject *PyUnicode_Replace(PyObject *unicode, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
Return value: New reference. Part of the Stable ABI. Replace at most maxcount occurrences of substr in unicode
with replstr and return the resulting Unicode object. maxcount == -1 means replace all occurrences.
int PyUnicode_Compare(PyObject *left, PyObject *right)
Part of the Stable ABI. Compara dos cadenas de caracteres y retorna -1, 0, 1 para menor que, igual y mayor que,
respectivamente.
Esta función retorna -1 en caso de falla, por lo que se debe llamar a PyErr_Occurred() para verificar si hay
errores.
int PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *string, Py_ssize_t size)
Part of the Stable ABI since version 3.13. Compare a Unicode object with a char buffer which is interpreted as
being UTF-8 or ASCII encoded and return true (1) if they are equal, or false (0) otherwise. If the Unicode object
contains surrogate characters or the C string is not valid UTF-8, false (0) is returned.
Esta función no lanza excepciones.
Nuevo en la versión 3.13.
int PyUnicode_EqualToUTF8(PyObject *unicode, const char *string)
Part of the Stable ABI since version 3.13. Similar to PyUnicode_EqualToUTF8AndSize(), but compute
string length using strlen(). If the Unicode object contains null characters, false (0) is returned.
Nuevo en la versión 3.13.
int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
Part of the Stable ABI. Compare a Unicode object, unicode, with string and return -1, 0, 1 for less than, equal,
and greater than, respectively. It is best to pass only ASCII-encoded strings, but the function interprets the input
string as ISO-8859-1 if it contains non-ASCII characters.
Esta función no lanza excepciones.
type PyTupleObject
Este subtipo de PyObject representa un objeto tupla de Python.
PyTypeObject PyTuple_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo tupla de Python; es el mismo objeto
que tuple en la capa de Python.
int PyTuple_Check(PyObject *p)
Retorna verdadero si p es un objeto tupla o una instancia de un subtipo del tipo tupla. Esta función siempre finaliza
con éxito.
int PyTuple_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto tupla pero no una instancia de un subtipo del tipo tupla. Esta función siempre
finaliza con éxito.
PyObject *PyTuple_New(Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto tupla de tamaño len o NULL en caso
de falla.
Nota: Esta función «roba» una referencia a o y descarta una referencia a un elemento que ya está en la tupla en la
posición afectada.
Nota: Esta función «roba» una referencia a o y, a diferencia de PyTuple_SetItem(), no descarta una refe-
rencia a ningún elemento que se está reemplazando; cualquier referencia en la tupla en la posición pos se filtrará.
Los objetos de secuencia de estructura son el equivalente en C de los objetos namedtuple(), es decir, una secuencia
a cuyos elementos también se puede acceder a través de atributos. Para crear una secuencia de estructura, primero debe
crear un tipo de secuencia de estructura específico.
PyTypeObject *PyStructSequence_NewType(PyStructSequence_Desc *desc)
Return value: New reference. Part of the Stable ABI. Crea un nuevo tipo de secuencia de estructura a partir
de los datos en desc, que se describen a continuación. Las instancias del tipo resultante se pueden crear con
PyStructSequence_New().
void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)
Inicializa una secuencia de estructura tipo type desde desc en su lugar.
int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc)
Lo mismo que PyStructSequence_InitType, pero retorna 0 en caso de éxito y -1 en caso de error.
Nuevo en la versión 3.4.
type PyStructSequence_Desc
Part of the Stable ABI (including all members). Contiene la meta información de un tipo de secuencia de estructura
para crear.
const char *name
Name of the struct sequence type.
const char *doc
Pointer to docstring for the type or NULL to omit.
PyStructSequence_Field *fields
Pointer to NULL-terminated array with field names of the new type.
int n_in_sequence
Number of fields visible to the Python side (if used as tuple).
type PyStructSequence_Field
Part of the Stable ABI (including all members). Describes a field of a struct sequence. As a struct sequen-
ce is modeled as a tuple, all fields are typed as PyObject*. The index in the fields array of the
PyStructSequence_Desc determines which field of the struct sequence is described.
const char *name
Name for the field or NULL to end the list of named fields, set to PyStructSequence_UnnamedField
to leave unnamed.
const char *doc
Field docstring or NULL to omit.
const char *const PyStructSequence_UnnamedField
Part of the Stable ABI since version 3.11. Valor especial para un nombre de campo para dejarlo sin nombre.
Distinto en la versión 3.9: El tipo se cambió de char *.
PyObject *PyStructSequence_New(PyTypeObject *type)
Return value: New reference. Part of the Stable ABI. Crea una instancia de type, que debe haberse creado con
PyStructSequence_NewType().
type PyListObject
Este subtipo de PyObject representa un objeto lista de Python.
PyTypeObject PyList_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de lista de Python. Este es el mismo
objeto que list en la capa de Python.
int PyList_Check(PyObject *p)
Retorna verdadero si p es un objeto de lista o una instancia de un subtipo del tipo lista. Esta función siempre finaliza
con éxito.
int PyList_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto lista, pero no una instancia de un subtipo del tipo lista. Esta función siempre
finaliza con éxito.
PyObject *PyList_New(Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Retorna una nueva lista de longitud len en caso de éxito o
NULL en caso de error.
Nota: Si len es mayor que cero, los elementos del objeto de la lista retornada se establecen en NULL. Por lo tanto, no
puede utilizar funciones API abstractas como PySequence_SetItem() o exponer el objeto al código Python
antes de configurar todos los elementos en un objeto real con PyList_SetItem().
Nota: Esta función «roba» una referencia a item y descarta una referencia a un elemento que ya está en la lista en
la posición afectada.
Nota: Este macro «roba» una referencia a item y, a diferencia de PyList_SetItem(), no descarta una refe-
rencia a ningún elemento que se está reemplazando; cualquier referencia en list en la posición i se filtrará.
type PyDictObject
Este subtipo de PyObject representa un objeto diccionario de Python.
PyTypeObject PyDict_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo diccionario de Python. Este es el
mismo objeto que dict en la capa de Python.
int PyDict_Check(PyObject *p)
Retorna verdadero si p es un objeto dict o una instancia de un subtipo del tipo dict. Esta función siempre
finaliza con éxito.
int PyDict_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto dict, pero no una instancia de un subtipo del tipo dict. Esta función siempre
finaliza con éxito.
PyObject *PyDict_New()
Return value: New reference. Part of the Stable ABI. Retorna un nuevo diccionario vacío, o NULL en caso de falla.
PyObject *PyDictProxy_New(PyObject *mapping)
Return value: New reference. Part of the Stable ABI. Retorna un objeto a types.MappingProxyType para
una asignación que imponga un comportamiento de solo lectura. Esto normalmente se usa para crear una vista para
evitar la modificación del diccionario para los tipos de clase no dinámicos.
Nota: Exceptions that occur while this calls __hash__() and __eq__() methods are silently ignored. Prefer
the PyDict_GetItemWithError() function instead.
Distinto en la versión 3.10: Llamar a esta API sin retener el GIL había sido permitido por motivos históricos.Ya no
está permitido.
Nota: Exceptions that occur while this calls __hash__() and __eq__() methods or while creating the tem-
porary str object are silently ignored. Prefer using the PyDict_GetItemWithError() function with your
own PyUnicode_FromString() key instead.
El diccionario p no debe mutarse durante la iteración. Es seguro modificar los valores de las claves a medida que
recorre el diccionario, pero solo mientras el conjunto de claves no cambie. Por ejemplo:
PyObject *key, *value;
Py_ssize_t pos = 0;
es verdadero, los pares existentes en a se reemplazarán si se encuentra una clave coincidente en b, de lo contrario,
los pares solo se agregarán si no hay una clave coincidente en a. Retorna 0 en caso de éxito o -1 si se lanza una
excepción.
int PyDict_Update(PyObject *a, PyObject *b)
Part of the Stable ABI. Esto es lo mismo que PyDict_Merge(a, b, 1) en C, y es similar a a.update(b)
en Python excepto que PyDict_Update() no vuelve a la iteración sobre una secuencia de pares de valores clave
si el segundo argumento no tiene el atributo «claves». Retorna 0 en caso de éxito o -1 si se produjo una excepción.
int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
Part of the Stable ABI. Actualiza o combina en el diccionario a, desde los pares clave-valor en seq2. seq2 debe ser
un objeto iterable que produzca objetos iterables de longitud 2, vistos como pares clave-valor. En el caso de claves
duplicadas, el último gana si override es verdadero, de lo contrario, el primero gana. Retorna 0 en caso de éxito o
-1 si se produjo una excepción. El equivalente en Python (excepto el valor de retorno)
for key. If event is PyDict_EVENT_DELETED, key is being deleted from the dictionary and new_value will be
NULL.
PyDict_EVENT_CLONED occurs when dict was previously empty and another dict is merged into it. To maintain
efficiency of this operation, per-key PyDict_EVENT_ADDED events are not issued in this case; instead a single
PyDict_EVENT_CLONED is issued, and key will be the source dictionary.
The callback may inspect but must not modify dict; doing so could have unpredictable effects, including infinite
recursion. Do not trigger Python code execution in the callback, as it could modify the dict as a side effect.
If event is PyDict_EVENT_DEALLOCATED, taking a new reference in the callback to the about-to-be-destroyed
dictionary will resurrect it and prevent it from being freed at this time. When the resurrected object is destroyed
later, any watcher callbacks active at that time will be called again.
Callbacks occur before the notified modification to dict takes place, so the prior state of dict can be inspected.
If the callback sets an exception, it must return -1; this exception will be printed as an unraisable exception using
PyErr_WriteUnraisable(). Otherwise it should return 0.
There may already be a pending exception set on entry to the callback. In this case, the callback should return 0
with the same exception still set. This means the callback may not call any other API that can set an exception
unless it saves and clears the exception state first, and restores it before returning.
Nuevo en la versión 3.12.
Esta sección detalla la API pública de los objetos set y frozenset. Cualquier funcionalidad que no esté listada a
continuación se accede mejor utilizando el protocolo abstracto de objetos (incluyendo PyObject_CallMethod(),
PyObject_RichCompareBool(), PyObject_Hash(), PyObject_Repr(), PyObject_IsTrue(),
PyObject_Print(), y PyObject_GetIter()) o el protocolo numérico abstracto (inclu-
yendo PyNumber_And(), PyNumber_Subtract(), PyNumber_Or(), PyNumber_Xor(),
PyNumber_InPlaceAnd(), PyNumber_InPlaceSubtract(), PyNumber_InPlaceOr(), y
PyNumber_InPlaceXor()).
type PySetObject
Este subtipo de PyObject se utiliza para mantener los datos internos de los objetos set y frozenset. Es
como un PyDictObject en el sentido de que tiene un tamaño fijo para los conjuntos pequeños (muy parecido al
almacenamiento de tuplas) y apuntará a un bloque de memoria separado y de tamaño variable para los conjuntos de
tamaño medio y grande (muy parecido al almacenamiento de listas). Ninguno de los campos de esta estructura debe
considerarse público y todos están sujetos a cambios. Todo el acceso debe hacerse a través de la API documentada
en lugar de manipular los valores de la estructura.
PyTypeObject PySet_Type
Part of the Stable ABI. Esta es una instancia de PyTypeObject que representa el tipo Python set.
PyTypeObject PyFrozenSet_Type
Part of the Stable ABI. Esta es una instancia de PyTypeObject que representa el tipo Python frozenset.
Los siguientes macros de comprobación de tipos funcionan en punteros a cualquier objeto de Python. Del mismo modo,
las funciones del constructor funcionan con cualquier objeto Python iterable.
int PySet_Check(PyObject *p)
Retorna verdadero si p es un objeto set o una instancia de un subtipo. Esta función siempre finaliza con éxito.
int PyFrozenSet_Check(PyObject *p)
Retorna verdadero si p es un objeto frozenset o una instancia de un subtipo. Esta función siempre finaliza con
éxito.
the Python discard() method, this function does not automatically convert unhashable sets into temporary
frozensets. Raise SystemError if set is not an instance of set or its subtype.
PyObject *PySet_Pop(PyObject *set)
Return value: New reference. Part of the Stable ABI. Retorna una nueva referencia a un objeto arbitrario en el set
y elimina el objeto del set. Retorna NULL en caso de falla. Lanza KeyError si el conjunto está vacío. Lanza a
SystemError si set no es una instancia de set o su subtipo.
int PySet_Clear(PyObject *set)
Part of the Stable ABI. Empty an existing set of all elements. Return 0 on success. Return -1 and raise
SystemError if set is not an instance of set or its subtype.
An instance method is a wrapper for a PyCFunction and the new way to bind a PyCFunction to a class object. It
replaces the former call PyMethod_New(func, NULL, class).
PyTypeObject PyInstanceMethod_Type
Esta instancia de PyTypeObject representa el tipo de método de instancia de Python. No está expuesto a los
programas de Python.
int PyInstanceMethod_Check(PyObject *o)
Retorna verdadero si o es un objeto de método de instancia (tiene tipo PyInstanceMethod_Type). El pará-
metro no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PyInstanceMethod_New(PyObject *func)
Return value: New reference. Return a new instance method object, with func being any callable object. func is the
function that will be called when the instance method is called.
PyObject *PyInstanceMethod_Function(PyObject *im)
Return value: Borrowed reference. Retorna el objeto de función asociado con el método de instancia im.
PyObject *PyInstanceMethod_GET_FUNCTION(PyObject *im)
Return value: Borrowed reference. Versión macro de PyInstanceMethod_Function() que evita la com-
probación de errores.
Los métodos son objetos de función enlazados. Los métodos siempre están vinculados a una instancia de una clase definida
por el usuario. Los métodos no vinculados (métodos vinculados a un objeto de clase) ya no están disponibles.
PyTypeObject PyMethod_Type
Esta instancia de PyTypeObject representa el tipo de método Python. Esto está expuesto a los programas de
Python como types.MethodType.
int PyMethod_Check(PyObject *o)
Retorna verdadero si o es un objeto de método (tiene tipo PyMethod_Type). El parámetro no debe ser NULL.
Esta función siempre finaliza con éxito.
PyObject *PyMethod_New(PyObject *func, PyObject *self)
Return value: New reference. Retorna un nuevo objeto de método, con func como cualquier objeto invocable y self
la instancia en la que se debe vincular el método. func es la función que se llamará cuando se llame al método. self
no debe ser NULL.
PyObject *PyMethod_Function(PyObject *meth)
Return value: Borrowed reference. Retorna el objeto de función asociado con el método meth.
PyObject *PyMethod_GET_FUNCTION(PyObject *meth)
Return value: Borrowed reference. Versión macro de PyMethod_Function() que evita la comprobación de
errores.
PyObject *PyMethod_Self(PyObject *meth)
Return value: Borrowed reference. Retorna la instancia asociada con el método meth.
PyObject *PyMethod_GET_SELF(PyObject *meth)
Return value: Borrowed reference. Versión macro de PyMethod_Self() que evita la comprobación de errores.
Los objetos celda (cell) se utilizan para implementar variables a las que hacen referencia varios ámbitos. Para cada variable,
se crea un objeto de celda para almacenar el valor; Las variables locales de cada marco de pila que hace referencia al valor
contienen una referencia a las celdas de ámbitos externos que también usan esa variable. Cuando se accede al valor, se
utiliza el valor contenido en la celda en lugar del objeto de la celda en sí. Esta desreferenciación del objeto de celda requiere
soporte del código de bytes generado; estos no se eliminan automáticamente cuando se accede a ellos. No es probable que
los objetos celda sean útiles en otros lugares.
type PyCellObject
La estructura C utilizada para objetos celda.
PyTypeObject PyCell_Type
El objeto tipo correspondiente a los objetos celda.
int PyCell_Check(PyObject *ob)
Retorna verdadero si ob es un objeto de celda; ob no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PyCell_New(PyObject *ob)
Return value: New reference. Crea y retorna un nuevo objeto de celda que contiene el valor ob. El parámetro puede
ser NULL.
PyObject *PyCell_Get(PyObject *cell)
Return value: New reference. Retorna el contenido de la celda cell.
Los objetos código son un detalle de bajo nivel de la implementación de CPython. Cada uno representa un fragmento de
código ejecutable que aún no se ha vinculado a una función.
type PyCodeObject
La estructura en C de los objetos utilizados para describir objetos código. Los campos de este tipo están sujetos a
cambios en cualquier momento.
PyTypeObject PyCode_Type
This is an instance of PyTypeObject representing the Python code object.
int PyCode_Check(PyObject *co)
Return true if co is a code object. This function always succeeds.
Py_ssize_t PyCode_GetNumFree(PyCodeObject *co)
Return the number of free variables in a code object.
int PyCode_GetFirstFree(PyCodeObject *co)
Return the position of the first free variable in a code object.
PyCodeObject *PyUnstable_Code_New(int argcount, int kwonlyargcount, int nlocals, int stacksize, int flags,
PyObject *code, PyObject *consts, PyObject *names, PyObject
*varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename,
PyObject *name, PyObject *qualname, int firstlineno, PyObject
*linetable, PyObject *exceptiontable)
Return a new code object. If you need a dummy code object to create a frame, use PyCode_NewEmpty()
instead.
Since the definition of the bytecode changes often, calling PyUnstable_Code_New() directly can bind you
to a precise Python version.
The many arguments of this function are inter-dependent in complex ways, meaning that subtle changes to values
are likely to result in incorrect execution or VM crashes. Use this function only with extreme care.
Distinto en la versión 3.11: Added qualname and exceptiontable parameters.
Distinto en la versión 3.12: Renamed from PyCode_New as part of Unstable C API. The old name is deprecated,
but will remain available until the signature changes again.
To support low-level extensions to frame evaluation, such as external just-in-time compilers, it is possible to attach arbitrary
extra data to code objects.
These functions are part of the unstable C API tier: this functionality is a CPython implementation detail, and the API
may change without deprecation warnings.
Py_ssize_t PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)
Return a new an opaque index value used to adding data to code objects.
You generally call this function once (per interpreter) and use the result with PyCode_GetExtra and
PyCode_SetExtra to manipulate data on individual code objects.
If free is not NULL: when a code object is deallocated, free will be called on non-NULL data stored under the new
index. Use Py_DecRef() when storing PyObject.
Nuevo en la versión 3.6: as _PyEval_RequestCodeExtraIndex
Distinto en la versión 3.12: Renamed to PyUnstable_Eval_RequestCodeExtraIndex. The old private
name is deprecated, but will be available until the API changes.
int PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
Set extra to the extra data stored under the given index. Return 0 on success. Set an exception and return -1 on
failure.
If no data was set under the index, set extra to NULL and return 0 without setting an exception.
Nuevo en la versión 3.6: as _PyCode_GetExtra
Distinto en la versión 3.12: Renamed to PyUnstable_Code_GetExtra. The old private name is deprecated,
but will be available until the API changes.
int PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
Set the extra data stored under the given index to extra. Return 0 on success. Set an exception and return -1 on
failure.
Nuevo en la versión 3.6: as _PyCode_SetExtra
Distinto en la versión 3.12: Renamed to PyUnstable_Code_SetExtra. The old private name is deprecated,
but will be available until the API changes.
These APIs are a minimal emulation of the Python 2 C API for built-in file objects, which used to rely on the buffered
I/O (FILE*) support from the C standard library. In Python 3, files and streams use the new io module, which defines
several layers over the low-level unbuffered I/O of the operating system. The functions described below are convenience C
wrappers over these new APIs, and meant mostly for internal error reporting in the interpreter; third-party code is advised
to access the io APIs instead.
PyObject *PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const
char *errors, const char *newline, int closefd)
Return value: New reference. Part of the Stable ABI. Crea un objeto archivo Python a partir del descriptor de
archivo de un archivo ya abierto fd. Los argumentos name, encoding, errors y newline pueden ser NULL para usar
los valores predeterminados; buffering puede ser -1 para usar el valor predeterminado. name se ignora y se mantiene
por compatibilidad con versiones anteriores. Retorna NULL en caso de error. Para obtener una descripción más
completa de los argumentos, consulte la documentación de la función io.open().
Advertencia: Dado que las transmisiones (streams) de Python tienen su propia capa de almacenamiento en
búfer, combinarlas con descriptores de archivos a nivel del sistema operativo puede producir varios problemas
(como un pedido inesperado de datos).
Una vez que se ha establecido un hook, no se puede quitar ni reemplazar, y luego llamadas a
PyFile_SetOpenCodeHook() fallarán. En caso de error, la función retorna -1 y establece una excepción
si el intérprete se ha inicializado.
Es seguro llamar a esta función antes de Py_Initialize().
Genera un evento de auditoría setopencodehook sin argumentos.
Nuevo en la versión 3.8.
int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
Part of the Stable ABI. Write object obj to file object p. The only supported flag for flags is Py_PRINT_RAW;
if given, the str() of the object is written instead of the repr(). Return 0 on success or -1 on failure; the
appropriate exception will be set.
int PyFile_WriteString(const char *s, PyObject *p)
Part of the Stable ABI. Escribe la cadena s en el objeto archivo p. Retorna 0 en caso de éxito o -1 en caso de error;
se establecerá la excepción apropiada.
PyTypeObject PyModule_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de módulo Python. Esto está expuesto
a los programas de Python como types.ModuleType.
int PyModule_Check(PyObject *p)
Retorna verdadero si p es un objeto de módulo o un subtipo de un objeto de módulo. Esta función siempre finaliza
con éxito.
int PyModule_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto módulo, pero no un subtipo de PyModule_Type. Esta función siempre
finaliza con éxito.
PyObject *PyModule_NewObject(PyObject *name)
Return value: New reference. Part of the Stable ABI since version 3.7. Retorna un nuevo objeto módulo con el
atributo __name__ establecido en name. Los atributos del módulo __name__, __doc__, __package__, y
__loader__ se completan (todos menos __name__ están configurados en None); quien llama es responsable
de proporcionar un atributo __file__.
Nuevo en la versión 3.3.
Distinto en la versión 3.4: __package__ y __loader__ están configurados en None.
PyObject *PyModule_New(const char *name)
Return value: New reference. Part of the Stable ABI. Similar a PyModule_NewObject(), pero el nombre es
una cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
PyObject *PyModule_GetDict(PyObject *module)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto del diccionario que implementa el
espacio de nombres de module; este objeto es el mismo que el atributo __dict__ del objeto módulo. Si module
no es un objeto módulo (o un subtipo de un objeto de módulo), se lanza SystemError y se retorna NULL.
It is recommended extensions use other PyModule_* and PyObject_* functions rather than directly manipu-
late a module’s __dict__.
Inicializando módulos en C
Los objetos módulos generalmente se crean a partir de módulos de extensión (bibliotecas compartidas que ex-
portan una función de inicialización) o módulos compilados (donde la función de inicialización se agrega usando
PyImport_AppendInittab()). Consulte building o extendiendo con incrustación para más detalles.
La función de inicialización puede pasar una instancia de definición de módulo a PyModule_Create(), y retornar el
objeto módulo resultante, o solicitar una «inicialización de múltiples fases» retornando la estructura de definición.
type PyModuleDef
Part of the Stable ABI (including all members). La estructura de definición de módulo, que contiene toda la infor-
mación necesaria para crear un objeto módulo. Por lo general, solo hay una variable estáticamente inicializada de
este tipo para cada módulo.
PyModuleDef_Base m_base
Always initialize this member to PyModuleDef_HEAD_INIT.
const char *m_name
Nombre para el nuevo módulo.
const char *m_doc
Docstring para el módulo; por lo general, se usa una variable docstring creada con PyDoc_STRVAR.
Py_ssize_t m_size
El estado del módulo se puede mantener en un área de memoria por módulo que se puede recuperar con
PyModule_GetState(), en lugar de en globales estáticos. Esto hace que los módulos sean seguros para
su uso en múltiples sub-interpretadores.
This memory area is allocated based on m_size on module creation, and freed when the module object is
deallocated, after the m_free function has been called, if present.
Establecer m_size en -1 significa que el módulo no admite sub-interpretadores, porque tiene un estado
global.
Establecerlo en un valor no negativo significa que el módulo se puede reinicializar y especifica la cantidad
adicional de memoria que requiere para su estado. Se requiere m_size no negativo para la inicialización de
múltiples fases.
Ver PEP 3121 para más detalles.
PyMethodDef *m_methods
Un puntero a una tabla de funciones de nivel de módulo, descrito por valores PyMethodDef. Puede ser
NULL si no hay funciones presentes.
PyModuleDef_Slot *m_slots
Un conjunto de definiciones de ranura para la inicialización de múltiples fases, terminadas por una entrada
{0, NULL}. Cuando se utiliza la inicialización monofásica, m_slots debe ser NULL.
Distinto en la versión 3.5: Antes de la versión 3.5, este miembro siempre estaba configurado en NULL y se
definía como:
inquiry m_reload
traverseproc m_traverse
Una función transversal para llamar durante el recorrido GC del objeto del módulo, o NULL si no es necesario.
This function is not called if the module state was requested but is not allocated yet. This is the case im-
mediately after the module is created and before the module is executed (Py_mod_exec function). Mo-
re precisely, this function is not called if m_size is greater than 0 and the module state (as returned by
PyModule_GetState()) is NULL.
Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.
inquiry m_clear
Una función clara para llamar durante la limpieza GC del objeto del módulo, o NULL si no es necesario.
This function is not called if the module state was requested but is not allocated yet. This is the case im-
mediately after the module is created and before the module is executed (Py_mod_exec function). Mo-
re precisely, this function is not called if m_size is greater than 0 and the module state (as returned by
PyModule_GetState()) is NULL.
Tal como PyTypeObject.tp_clear, esta función no siempre es llamada antes de la designación de un
módulo. Por ejemplo, cuando el recuento de referencias está listo para determinar que un objeto no se usa
más, la recolección de basura cíclica no se involucra y se llama a m_free directamente.
Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.
freefunc m_free
Una función para llamar durante la desasignación del objeto del módulo, o NULL si no es necesario.
This function is not called if the module state was requested but is not allocated yet. This is the case im-
mediately after the module is created and before the module is executed (Py_mod_exec function). Mo-
re precisely, this function is not called if m_size is greater than 0 and the module state (as returned by
PyModule_GetState()) is NULL.
Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.
Inicialización monofásica
La función de inicialización del módulo puede crear y retornar el objeto módulo directamente. Esto se conoce como
«inicialización monofásica» y utiliza una de las siguientes funciones de creación de dos módulos:
PyObject *PyModule_Create(PyModuleDef *def)
Return value: New reference. Create a new module object, given the definition in def. This behaves like
PyModule_Create2() with module_api_version set to PYTHON_API_VERSION.
PyObject *PyModule_Create2(PyModuleDef *def, int module_api_version)
Return value: New reference. Part of the Stable ABI. Crea un nuevo objeto de módulo, dada la definición en def, asu-
miendo la versión de API module_api_version. Si esa versión no coincide con la versión del intérprete en ejecución,
se emite un RuntimeWarning.
Nota: La mayoría de los usos de esta función deberían usar PyModule_Create() en su lugar; solo use esto si
está seguro de que lo necesita.
Antes de que se retorne desde la función de inicialización, el objeto del módulo resultante normalmente se llena utilizando
funciones como PyModule_AddObjectRef().
Inicialización multifase
An alternate way to specify extensions is to request «multi-phase initialization». Extension modules created this way
behave more like Python modules: the initialization is split between the creation phase, when the module object is created,
and the execution phase, when it is populated. The distinction is similar to the __new__() and __init__() methods
of classes.
Unlike modules created using single-phase initialization, these modules are not singletons: if the sys.modules entry is
removed and the module is re-imported, a new module object is created, and the old module is subject to normal garbage
collection – as with Python modules. By default, multiple modules created from the same definition should be independent:
changes to one should not affect the others. This means that all state should be specific to the module object (using e.g.
using PyModule_GetState()), or its contents (such as the module’s __dict__ or individual classes created with
PyType_FromSpec()).
Se espera que todos los módulos creados mediante la inicialización de múltiples fases admitan sub-interpretadores. Ase-
gurándose de que varios módulos sean independientes suele ser suficiente para lograr esto.
Para solicitar la inicialización de múltiples fases, la función de inicialización (PyInit_modulename) retorna una instancia
de PyModuleDef con un m_slots no vacío. Antes de que se retorna, la instancia PyModuleDef debe inicializarse
con la siguiente función:
PyObject *PyModuleDef_Init(PyModuleDef *def)
Return value: Borrowed reference. Part of the Stable ABI since version 3.5. Asegura que la definición de un módulo
sea un objeto Python correctamente inicializado que informe correctamente su tipo y conteo de referencias.
Retorna def convertido a PyObject* o NULL si se produjo un error.
Nuevo en la versión 3.5.
El miembro m_slots de la definición del módulo debe apuntar a un arreglo de estructuras PyModuleDef_Slot:
type PyModuleDef_Slot
int slot
Una ranura ID, elegida entre los valores disponibles que se explican a continuación.
void *value
Valor de la ranura, cuyo significado depende de la ID de la ranura.
Nuevo en la versión 3.5.
El arreglo m_slots debe estar terminada por una ranura con id 0.
Los tipos de ranura disponibles son:
Py_mod_create
Especifica una función que se llama para crear el objeto del módulo en sí. El puntero value de este espacio debe
apuntar a una función de la firma:
PyObject *create_module(PyObject *spec, PyModuleDef *def)
La función recibe una instancia de ModuleSpec, como se define en PEP 451, y la definición del módulo. Debería
retornar un nuevo objeto de módulo, o establecer un error y retornar NULL.
Esta función debe mantenerse mínima. En particular, no debería llamar a código arbitrario de Python, ya que
intentar importar el mismo módulo nuevamente puede dar como resultado un bucle infinito.
Múltiples ranuras Py_mod_create no pueden especificarse en una definición de módulo.
Si no se especifica Py_mod_create, la maquinaria de importación creará un objeto de módulo normal usando
PyModule_New(). El nombre se toma de spec, no de la definición, para permitir que los módulos de extensión
se ajusten dinámicamente a su lugar en la jerarquía de módulos y se importen bajo diferentes nombres a través de
enlaces simbólicos, todo mientras se comparte una definición de módulo único.
No es necesario que el objeto retornado sea una instancia de PyModule_Type. Se puede usar cualquier tipo,
siempre que admita la configuración y la obtención de atributos relacionados con la importación. Sin embargo, solo
se pueden retornar instancias PyModule_Type si el PyModuleDef no tiene NULL m_traverse, m_clear,
m_free; m_size distinto de cero; o ranuras que no sean Py_mod_create.
Py_mod_exec
Especifica una función que se llama para ejecutar (execute) el módulo. Esto es equivalente a ejecutar el código de
un módulo Python: por lo general, esta función agrega clases y constantes al módulo. La firma de la función es:
int exec_module(PyObject *module)
Si se especifican varias ranuras Py_mod_exec, se procesan en el orden en que aparecen en el arreglo m_slots.
Py_mod_multiple_interpreters
Specifies one of the following values:
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
The module does not support being imported in subinterpreters.
Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
The module supports being imported in subinterpreters, but only when they share the main interpreter’s GIL.
(See isolating-extensions-howto.)
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
The module supports being imported in subinterpreters, even when they have their own GIL. (See isolating-
extensions-howto.)
This slot determines whether or not importing this module in a subinterpreter will fail.
Multiple Py_mod_multiple_interpreters slots may not be specified in one module definition.
Las siguientes funciones se invocan en segundo plano cuando se utiliza la inicialización de múltiples fases. Se pue-
den usar directamente, por ejemplo, al crear objetos de módulo de forma dinámica. Tenga en cuenta que tanto
PyModule_FromDefAndSpec como PyModule_ExecDef deben llamarse para inicializar completamente un mó-
dulo.
PyObject *PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)
Return value: New reference. Create a new module object, given the definition in def and the ModuleSpec spec. This
behaves like PyModule_FromDefAndSpec2() with module_api_version set to PYTHON_API_VERSION.
Nuevo en la versión 3.5.
PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)
Return value: New reference. Part of the Stable ABI since version 3.7. Create a new module object, given the
definition in def and the ModuleSpec spec, assuming the API version module_api_version. If that version does
not match the version of the running interpreter, a RuntimeWarning is emitted.
Nota: La mayoría de los usos de esta función deberían usar PyModule_FromDefAndSpec() en su lugar;
solo use esto si está seguro de que lo necesita.
Funciones de soporte
La función de inicialización del módulo (si usa la inicialización de fase única) o una función llamada desde un intervalo
de ejecución del módulo (si usa la inicialización de múltiples fases), puede usar las siguientes funciones para ayudar a
inicializar el estado del módulo:
int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
Part of the Stable ABI since version 3.10. Agrega un objeto a module como name. Esta es una función de conve-
niencia que se puede usar desde la función de inicialización del módulo.
En caso de éxito, retorna 0. En caso de error, lanza una excepción y retorna -1.
Retorna NULL si value es NULL. Debe llamarse lanzando una excepción en este caso.
Ejemplo de uso
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_DECREF(obj);
return res;
}
El ejemplo puede también ser escrito sin verificar explicitamente si obj es NULL:
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_XDECREF(obj);
return res;
}
Note que Py_XDECREF() debería ser usado en vez de Py_DECREF() en este caso, ya que obj puede ser NULL.
Nuevo en la versión 3.10.
int PyModule_Add(PyObject *module, const char *name, PyObject *value)
Part of the Stable ABI since version 3.13. Similar to PyModule_AddObjectRef(), but «steals» a reference
to value. It can be called with a result of function that returns a new reference without bothering to check its result
or even saving it to a variable.
Ejemplo de uso
Nota: Unlike other functions that steal references, PyModule_AddObject() only releases the reference to
value on success.
This means that its return value must be checked, and calling code must Py_XDECREF() value manually on error.
Ejemplo de uso
Búsqueda de módulos
La inicialización monofásica crea módulos singleton que se pueden buscar en el contexto del intérprete actual. Esto permite
que el objeto módulo se recupere más tarde con solo una referencia a la definición del módulo.
Estas funciones no funcionarán en módulos creados mediante la inicialización de múltiples fases, ya que se pueden crear
múltiples módulos de este tipo desde una sola definición.
PyObject *PyState_FindModule(PyModuleDef *def)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto módulo que se creó a partir de def
para el intérprete actual. Este método requiere que el objeto módulo se haya adjuntado al estado del intérprete con
PyState_AddModule() de antemano. En caso de que el objeto módulo correspondiente no se encuentre o no
se haya adjuntado al estado del intérprete, retornará NULL.
int PyState_AddModule(PyObject *module, PyModuleDef *def)
Part of the Stable ABI since version 3.3. Adjunta el objeto del módulo pasado a la función al estado del intérprete.
Esto permite que se pueda acceder al objeto del módulo a través de PyState_FindModule().
Solo es efectivo en módulos creados con la inicialización monofásica.
Python llama a PyState_AddModule automáticamente después de importar un módulo, por lo que es innece-
sario (pero inofensivo) llamarlo desde el código de inicialización del módulo. Solo se necesita una llamada explícita
si el propio código de inicio del módulo llama posteriormente PyState_FindModule. La función está des-
tinada principalmente a implementar mecanismos de importación alternativos (ya sea llamándolo directamente o
refiriéndose a su implementación para obtener detalles de las actualizaciones de estado requeridas).
La persona que llama debe retener el GIL.
Retorna 0 en caso de éxito o -1 en caso de error.
Nuevo en la versión 3.3.
int PyState_RemoveModule(PyModuleDef *def)
Part of the Stable ABI since version 3.3. Elimina el objeto del módulo creado a partir de def del estado del intérprete.
Retorna 0 en caso de éxito o -1 en caso de error.
La persona que llama debe retener el GIL.
Nuevo en la versión 3.3.
Python provides two general-purpose iterator objects. The first, a sequence iterator, works with an arbitrary sequence
supporting the __getitem__() method. The second works with a callable object and a sentinel value, calling the
callable for each item in the sequence, and ending the iteration when the sentinel value is returned.
PyTypeObject PySeqIter_Type
Part of the Stable ABI. Objeto tipo para objetos iteradores retornados por PySeqIter_New() y la forma de un
argumento de la función incorporada iter() para los tipos de secuencia incorporados.
int PySeqIter_Check(PyObject *op)
Retorna verdadero si el tipo de op es PySeqIter_Type. Esta función siempre finaliza con éxito.
PyObject *PySeqIter_New(PyObject *seq)
Return value: New reference. Part of the Stable ABI. Retorna un iterador que funciona con un objeto de secuencia
general, seq. La iteración termina cuando la secuencia lanza IndexError para la operación de suscripción.
PyTypeObject PyCallIter_Type
Part of the Stable ABI. Objeto tipo para los objetos iteradores retornados por PyCallIter_New() y la forma
de dos argumentos de la función incorporada iter().
int PyCallIter_Check(PyObject *op)
Retorna verdadero si el tipo de op es PyCallIter_Type. Esta función siempre finaliza con éxito.
PyObject *PyCallIter_New(PyObject *callable, PyObject *sentinel)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo iterador. El primer parámetro, callable,
puede ser cualquier objeto invocable de Python que se pueda invocar sin parámetros; cada llamada debe retornar
el siguiente elemento en la iteración. Cuando callable retorna un valor igual a sentinel, la iteración finalizará.
Los «descriptores» son objetos que describen algún atributo de un objeto. Se encuentran en el diccionario de objetos tipo.
PyTypeObject PyProperty_Type
Part of the Stable ABI. El objeto de tipo para los tipos de descriptor incorporado.
PyObject *PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
Return value: New reference.
PyObject *PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
Return value: New reference. Part of the Stable ABI.
int PyDescr_IsData(PyObject *descr)
Retorna distinto de cero si el descriptor objetos descr describe un atributo de datos, o 0 si describe un método.
descr debe ser un objeto descriptor; no hay comprobación de errores.
PyObject *PyWrapper_New(PyObject*, PyObject*)
Return value: New reference. Part of the Stable ABI.
PyTypeObject PySlice_Type
Part of the Stable ABI. El objeto tipo para objetos rebanadas. Esto es lo mismo que slice en la capa de Python.
int PySlice_Check(PyObject *ob)
Retorna verdadero si ob es un objeto rebanada; ob no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto rebanada con los valores dados. Los
parámetros start, stop y step se utilizan como los valores de los atributos del objeto rebanada de los mismos nombres.
Cualquiera de los valores puede ser NULL, en cuyo caso se usará None para el atributo correspondiente. Retorna
NULL si no se puedo asignar el nuevo objeto.
int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
Part of the Stable ABI. Recupera los índices start, stop y step del objeto rebanada slice, suponiendo una secuencia
de longitud length. Trata los índices mayores que length como errores.
Returns 0 on success and -1 on error with no exception set (unless one of the indices was not None and failed to
be converted to an integer, in which case -1 is returned with an exception set).
Probablemente no quiera usar esta función.
Distinto en la versión 3.2: El tipo de parámetro para el parámetro slice era PySliceObject* antes.
int PySlice_GetIndicesEx(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t
*step, Py_ssize_t *slicelength)
Part of the Stable ABI. Reemplazo utilizable para PySlice_GetIndices(). Recupera los índices de start,
stop, y step del objeto rebanada slice asumiendo una secuencia de longitud length, y almacena la longitud de la
rebanada en slicelength. Los índices fuera de los límites se recortan de manera coherente con el manejo de sectores
normales.
Retorna 0 en caso de éxito y -1 en caso de error con excepción establecida.
Nota: Esta función se considera no segura para secuencias redimensionables. Su invocación debe ser reemplazada
por una combinación de PySlice_Unpack() y PySlice_AdjustIndices() donde:
es reemplazado por:
Distinto en la versión 3.2: El tipo de parámetro para el parámetro slice era PySliceObject* antes.
Distinto en la versión 3.6.1: Si Py_LIMITED_API no se establece o establece el valor entre 0x03050400 y
0x03060000 (sin incluir) o 0x03060100 o un superior PySlice_GetIndicesEx() se implementa como
un macro usando PySlice_Unpack() y PySlice_AdjustIndices(). Los argumentos start, stop y step
se evalúan más de una vez.
Obsoleto desde la versión 3.6.1: Si Py_LIMITED_API se establece en un valor menor que 0x03050400 o entre
0x03060000 y 0x03060100 (sin incluir) PySlice_GetIndicesEx() es una función obsoleta.
int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
Part of the Stable ABI since version 3.7. Extrae los miembros de datos start, stop, y step de un objeto rebanada co-
mo enteros en C. Reduce silenciosamente los valores mayores que PY_SSIZE_T_MAX a PY_SSIZE_T_MAX,
aumenta silenciosamente los valores start y stop inferiores a PY_SSIZE_T_MIN a PY_SSIZE_T_MIN, y silen-
ciosamente aumenta los valores de step a menos de -PY_SSE a -PY_SSIZE_T_MAX.
Retorna -1 en caso de error, 0 en caso de éxito.
Nuevo en la versión 3.6.1.
Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)
Part of the Stable ABI since version 3.7. Ajusta los índices de corte de inicio/fin asumiendo una secuencia de la
longitud especificada. Los índices fuera de los límites se recortan de manera coherente con el manejo de sectores
normales.
Objeto elipsis
PyObject *Py_Ellipsis
The Python Ellipsis object. This object has no methods. Like Py_None, it is an immortal singleton object.
Distinto en la versión 3.12: Py_Ellipsis is immortal.
Un objeto memoryview expone la interfaz de búfer a nivel de C como un objeto Python que luego puede pasarse como
cualquier otro objeto.
PyObject *PyMemoryView_FromObject(PyObject *obj)
Return value: New reference. Part of the Stable ABI. Crea un objeto de vista de memoria memoryview a partir de
un objeto que proporciona la interfaz del búfer. Si obj admite exportaciones de búfer de escritura, el objeto de vista
de memoria será de lectura/escritura, de lo contrario puede ser de solo lectura o de lectura/escritura a discreción
del exportador.
PyBUF_READ
Flag to request a readonly buffer.
PyBUF_WRITE
Flag to request a writable buffer.
PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
Return value: New reference. Part of the Stable ABI since version 3.7. Crea un objeto de vista de memoria usando
mem como el búfer subyacente. flags pueden ser uno de PyBUF_READ o PyBUF_WRITE.
Nuevo en la versión 3.3.
PyObject *PyMemoryView_FromBuffer(const Py_buffer *view)
Return value: New reference. Part of the Stable ABI since version 3.11. Crea un objeto de vista de
memoria que ajuste la estructura de búfer dada view. Para memorias intermedias de bytes simples,
PyMemoryView_FromMemory() es la función preferida.
PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
Return value: New reference. Part of the Stable ABI. Crea un objeto de vista de memoria memoryview para un
fragmento de memoria contiguo (contiguous, en order “C” o “F” de Fortran) desde un objeto que define la interfaz
del búfer. Si la memoria es contigua, el objeto de vista de memoria apunta a la memoria original. De lo contrario,
se realiza una copia y la vista de memoria apunta a un nuevo objeto de bytes.
buffertype can be one of PyBUF_READ or PyBUF_WRITE.
int PyMemoryView_Check(PyObject *obj)
Retorna verdadero si el objeto obj es un objeto de vista de memoria. Actualmente no está permitido crear subclases
de memoryview. Esta función siempre finaliza con éxito.
Py_buffer *PyMemoryView_GET_BUFFER(PyObject *mview)
Retorna un puntero a la copia privada de la vista de memoria del búfer del exportador. mview debe ser una instancia
de memoryview; este macro no verifica su tipo, debe hacerlo usted mismo o correrá el riesgo de fallas.
Python soporta referencias débiles como objetos de primera clase. Hay dos tipos de objetos específicos que implementan
directamente referencias débiles. El primero es un objeto con referencia simple, y el segundo actúa como un proxy del
objeto original tanto como pueda.
int PyWeakref_Check(PyObject *ob)
Return non-zero if ob is either a reference or proxy object. This function always succeeds.
int PyWeakref_CheckRef(PyObject *ob)
Return non-zero if ob is a reference object. This function always succeeds.
int PyWeakref_CheckProxy(PyObject *ob)
Return non-zero if ob is a proxy object. This function always succeeds.
PyObject *PyWeakref_NewRef(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference object for the object ob. This will
always return a new reference, but is not guaranteed to create a new object; an existing reference object may be
returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage
collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be
None or NULL. If ob is not a weakly referencable object, or if callback is not callable, None, or NULL, this will
return NULL and raise TypeError.
PyObject *PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference proxy object for the object ob. This
will always return a new reference, but is not guaranteed to create a new object; an existing proxy object may be
returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage
collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be
None or NULL. If ob is not a weakly referencable object, or if callback is not callable, None, or NULL, this will
return NULL and raise TypeError.
int PyWeakref_GetRef(PyObject *ref, PyObject **pobj)
Part of the Stable ABI since version 3.13. Get a strong reference to the referenced object from a weak reference,
ref, into *pobj.
• On success, set *pobj to a new strong reference to the referenced object and return 1.
• If the reference is dead, set *pobj to NULL and return 0.
• On error, raise an exception and return -1.
Nuevo en la versión 3.13.
PyObject *PyWeakref_GetObject(PyObject *ref)
Return value: Borrowed reference. Part of the Stable ABI. Return a borrowed reference to the referenced object
from a weak reference, ref. If the referent is no longer live, returns Py_None.
Nota: Esta función retorna una referencia borrowed reference al objeto referenciado. Esto significa que siempre
debe llamar a Py_INCREF() sobre el objeto, excepto cuando no pueda ser destruido antes del último uso de la
referencia prestada.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Use PyWeakref_GetRef() instead.
PyObject *PyWeakref_GET_OBJECT(PyObject *ref)
Return value: Borrowed reference. Similar to PyWeakref_GetObject(), but does no error checking.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Use PyWeakref_GetRef() instead.
void PyObject_ClearWeakRefs(PyObject *object)
Part of the Stable ABI. This function is called by the tp_dealloc handler to clear weak references.
This iterates through the weak references for object and calls callbacks for those references which have one. It
returns when all callbacks have been attempted.
8.6.8 Cápsulas
Consulta using-capsules para obtener más información sobre el uso de estos objetos.
Nuevo en la versión 3.1.
type PyCapsule
Este subtipo de PyObject representa un valor opaco, útil para los módulos de extensión C que necesitan pasar un
valor opaco (como un puntero void*) a través del código Python a otro código C . A menudo se usa para hacer
que un puntero de función C definido en un módulo esté disponible para otros módulos, por lo que el mecanismo
de importación regular se puede usar para acceder a las API C definidas en módulos cargados dinámicamente.
type PyCapsule_Destructor
Part of the Stable ABI. El tipo de devolución de llamada de un destructor para una cápsula. Definido como:
type PyFrameObject
Part of the Limited API (as an opaque struct). La estructura C de los objetos utilizados para describir los objetos
del frame.
No hay miembros públicos en esta estructura.
Distinto en la versión 3.11: Los miembros de esta estructura se han eliminado de la API pública de C. Consulte la
entrada Novedades para más detalles.
Las funciones PyEval_GetFrame() y PyThreadState_GetFrame() pueden utilizarse para obtener un objeto
frame.
Véase también Reflexión.
PyTypeObject PyFrame_Type
The type of frame objects. It is the same object as types.FrameType in the Python layer.
Distinto en la versión 3.11: Previously, this type was only available after including <frameobject.h>.
int PyFrame_Check(PyObject *obj)
Return non-zero if obj is a frame object.
Distinto en la versión 3.11: Previously, this function was only available after including <frameobject.h>.
PyFrameObject *PyFrame_GetBack(PyFrameObject *frame)
Obtiene el frame exterior siguiente.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Nuevo en la versión 3.9.
PyObject *PyFrame_GetBuiltins(PyFrameObject *frame)
Get the frame’s f_builtins attribute.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Nuevo en la versión 3.11.
PyCodeObject *PyFrame_GetCode(PyFrameObject *frame)
Part of the Stable ABI since version 3.10. Obtenga el código frame.
Retorna un strong reference.
El resultado (frame code) no puede ser NULL.
Nuevo en la versión 3.9.
PyObject *PyFrame_GetGenerator(PyFrameObject *frame)
Obtiene el generador, rutina o generador asíncrono al que pertenece este frame, o NULL si este frame no es pro-
piedad de un generador. No lanza una excepción, incluso si el valor de retorno es NULL.
Retorna un strong reference, o NULL.
Nuevo en la versión 3.11.
Internal Frames
Los objetos generadores son lo que Python usa para implementar iteradores generadores. Normalmente se
crean iterando sobre una función que produce valores, en lugar de llamar explícitamente PyGen_New() o
PyGen_NewWithQualName().
type PyGenObject
La estructura en C utilizada para los objetos generadores.
PyTypeObject PyGen_Type
El objeto tipo correspondiente a los objetos generadores.
int PyGen_Check(PyObject *ob)
Retorna verdadero si ob es un objeto generador; ob no debe ser NULL. Esta función siempre finaliza con éxito.
int PyGen_CheckExact(PyObject *ob)
Retorna verdadero si el tipo de ob es PyGen_Type; ob no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PyGen_New(PyFrameObject *frame)
Return value: New reference. Crea y retorna un nuevo objeto generador basado en el objeto frame. Una referencia
a frame es robada por esta función. El argumento no debe ser NULL.
PyObject *PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname)
Return value: New reference. Crea y retorna un nuevo objeto generador basado en el objeto frame, con __name__
y __qualname__ establecido en name y qualname. Una referencia a frame es robada por esta función. El argu-
mento frame no debe ser NULL.
PyTypeObject PyCoro_Type
El tipo de objeto correspondiente a los objetos corrutina.
int PyCoro_CheckExact(PyObject *ob)
Retorna verdadero si el tipo de ob es PyCoro_Type; ob no debe ser NULL. Esta función siempre finaliza con
éxito.
PyObject *PyCoro_New(PyFrameObject *frame, PyObject *name, PyObject *qualname)
Return value: New reference. Crea y retorna un nuevo objeto corrutina basado en el objeto frame, con __name__
y __qualname__ establecido en name y qualname. Una referencia a frame es robada por esta función. El argu-
mento frame no debe ser NULL.
Nota: En Python 3.7.1, las firmas de todas las variables de contexto C APIs fueron cambiadas para usar punteros
PyObject en lugar de PyContext, PyContextVar, y PyContextToken, por ejemplo:
// in 3.7.0:
PyContext *PyContext_New(void);
// in 3.7.1+:
PyObject *PyContext_New(void);
Various date and time objects are supplied by the datetime module. Before using any of these functions, the hea-
der file datetime.h must be included in your source (note that this is not included by Python.h), and the macro
PyDateTime_IMPORT must be invoked, usually as part of the module initialisation function. The macro puts a pointer
to a C structure into a static variable, PyDateTimeAPI, that is used by the following macros.
type PyDateTime_Date
This subtype of PyObject represents a Python date object.
type PyDateTime_DateTime
This subtype of PyObject represents a Python datetime object.
type PyDateTime_Time
This subtype of PyObject represents a Python time object.
type PyDateTime_Delta
This subtype of PyObject represents the difference between two datetime values.
PyTypeObject PyDateTime_DateType
This instance of PyTypeObject represents the Python date type; it is the same object as datetime.date in
the Python layer.
PyTypeObject PyDateTime_DateTimeType
This instance of PyTypeObject represents the Python datetime type; it is the same object as datetime.
datetime in the Python layer.
PyTypeObject PyDateTime_TimeType
This instance of PyTypeObject represents the Python time type; it is the same object as datetime.time in
the Python layer.
PyTypeObject PyDateTime_DeltaType
This instance of PyTypeObject represents Python type for the difference between two datetime values; it is the
same object as datetime.timedelta in the Python layer.
PyTypeObject PyDateTime_TZInfoType
This instance of PyTypeObject represents the Python time zone info type; it is the same object as datetime.
tzinfo in the Python layer.
Macro para acceder al singleton UTC:
PyObject *PyDateTime_TimeZone_UTC
Retorna la zona horaria singleton que representa UTC, el mismo objeto que datetime.timezone.utc.
Nuevo en la versión 3.7.
Macros de verificación de tipo:
int PyDate_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DateType or a subtype of PyDateTime_DateType. ob must not
be NULL. This function always succeeds.
int PyDate_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_DateType. ob no debe ser NULL. Esta función siempre finaliza
con éxito.
int PyDateTime_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DateTimeType or a subtype of PyDateTime_DateTimeType.
ob must not be NULL. This function always succeeds.
Se proporcionan varios tipos incorporados para indicaciones de tipado. Actualmente existen dos tipos – GenericAlias y
Union. Solo GenericAlias es expuesto a C.
PyObject *Py_GenericAlias(PyObject *origin, PyObject *args)
Part of the Stable ABI since version 3.9. Create a GenericAlias object. Equivalent to calling the Python class
types.GenericAlias. The origin and args arguments set the GenericAlias“s __origin__ and
__args__ attributes respectively. origin should be a PyTypeObject*, and args can be a PyTupleObject*
or any PyObject*. If args passed is not a tuple, a 1-tuple is automatically constructed and __args__ is set
to (args,). Minimal checking is done for the arguments, so the function will succeed even if origin is not a
type. The GenericAlias“s __parameters__ attribute is constructed lazily from __args__. On failure,
an exception is raised and NULL is returned.
Aquí hay un ejemplo sobre cómo hacer un tipo de extensión genérica:
...
static PyMethodDef my_obj_methods[] = {
// Other methods.
...
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}
...
}
Ver también:
The data model method __class_getitem__().
Nuevo en la versión 3.9.
PyTypeObject Py_GenericAliasType
Part of the Stable ABI since version 3.9. El tipo en C del objeto retornado por Py_GenericAlias(). Equivalente
a types.GenericAlias en Python.
Nuevo en la versión 3.9.
En una aplicación que incorpora Python, se debe llamar a la función Py_Initialize() antes de usar cualquier otra
función de API Python/C; con la excepción de algunas funciones y variables de configuración global.
Las siguientes funciones se pueden invocar de forma segura antes de que se inicializa Python:
• Funciones de configuración:
– PyImport_AppendInittab()
– PyImport_ExtendInittab()
– PyInitFrozenExtensions()
– PyMem_SetAllocator()
– PyMem_SetupDebugHooks()
– PyObject_SetArenaAllocator()
– PySys_ResetWarnOptions()
• Funciones informativas:
– Py_IsInitialized()
– PyMem_GetAllocator()
– PyObject_GetArenaAllocator()
– Py_GetBuildInfo()
– Py_GetCompiler()
– Py_GetCopyright()
211
The Python/C API, Versión 3.13.0a5
– Py_GetPlatform()
– Py_GetVersion()
• Utilidades:
– Py_DecodeLocale()
• Asignadores de memoria:
– PyMem_RawMalloc()
– PyMem_RawRealloc()
– PyMem_RawCalloc()
– PyMem_RawFree()
Nota: The following functions should not be called before Py_Initialize(): Py_EncodeLocale(),
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), Py_GetProgramFullPath(),
Py_GetPythonHome(), and Py_GetProgramName().
Python tiene variables para la configuración global para controlar diferentes características y opciones. De forma prede-
terminada, estos indicadores están controlados por opciones de línea de comando.
Cuando una opción establece un indicador, el valor del indicador es la cantidad de veces que se configuró la opción. Por
ejemplo, -b establece Py_BytesWarningFlag en 1 y -bb establece Py_BytesWarningFlag en 2.
int Py_BytesWarningFlag
This API is kept for backward compatibility: setting PyConfig.bytes_warning should be used instead, see
Python Initialization Configuration.
Emite una advertencia al comparar bytes o bytearray con str o bytes con int. Emite un error si es
mayor o igual a 2.
Establecido por la opción -b.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_DebugFlag
This API is kept for backward compatibility: setting PyConfig.parser_debug should be used instead, see
Python Initialization Configuration.
Activa la salida de depuración del analizador (solo para expertos, según las opciones de compilación).
Establecido por la opción -d y la variable de entorno PYTHONDEBUG.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_DontWriteBytecodeFlag
This API is kept for backward compatibility: setting PyConfig.write_bytecode should be used instead,
see Python Initialization Configuration.
Si se establece en un valor distinto de cero, Python no intentará escribir archivos .pyc en la importación de
módulos fuente.
Establecido por la opción -B y la variable de entorno PYTHONDONTWRITEBYTECODE.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_FrozenFlag
This API is kept for backward compatibility: setting PyConfig.pathconfig_warnings should be used
instead, see Python Initialization Configuration.
Suprime los mensajes de error al calcular la ruta de búsqueda del módulo en Py_GetPath().
Indicador privado utilizado por los programas _freeze_module y frozenmain.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_HashRandomizationFlag
This API is kept for backward compatibility: setting PyConfig.hash_seed and PyConfig.
use_hash_seed should be used instead, see Python Initialization Configuration.
Se establece en 1 si la variable de entorno PYTHONHASHSEED se establece en una cadena de caracteres no vacía.
Si el indicador no es cero, lee la variable de entorno PYTHONHASHSEED para inicializar la semilla de hash secreta.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_IgnoreEnvironmentFlag
This API is kept for backward compatibility: setting PyConfig.use_environment should be used instead,
see Python Initialization Configuration.
Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME, that might be set.
Establecido por las opciones -E y -I.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_InspectFlag
This API is kept for backward compatibility: setting PyConfig.inspect should be used instead, see Python
Initialization Configuration.
Cuando se pasa una secuencia de comandos (script) como primer argumento o se usa la opción -c, ingresa al modo
interactivo después de ejecutar la secuencia de comandos o el comando, incluso cuando sys.stdin no parece
ser un terminal.
Establecido por la opción -i y la variable de entorno PYTHONINSPECT.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_InteractiveFlag
This API is kept for backward compatibility: setting PyConfig.interactive should be used instead, see
Python Initialization Configuration.
Establecido por la opción -i.
Obsoleto desde la versión 3.12.
int Py_IsolatedFlag
This API is kept for backward compatibility: setting PyConfig.isolated should be used instead, see Python
Initialization Configuration.
Ejecuta Python en modo aislado. En modo aislado sys.path no contiene ni el directorio de la secuencia de
comandos (script) ni el directorio de paquetes del sitio del usuario (site-pacages).
Establecido por la opción -I.
Nuevo en la versión 3.4.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_LegacyWindowsFSEncodingFlag
This API is kept for backward compatibility: setting PyPreConfig.legacy_windows_fs_encoding
should be used instead, see Python Initialization Configuration.
Si la bandera no es cero, utilice la codificación mbcs con el gestor de errores replace en lugar de la codificación
UTF-8 con el gestor de error surrogatepass, para la filesystem encoding and error handler (codificación del
sistema de archivos y gestor de errores).
Establece en 1 si la variable de entorno PYTHONLEGACYWINDOWSFSENCODING está configurada en una cadena
de caracteres no vacía.
Ver PEP 529 para más detalles.
Disponibilidad: Windows.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_LegacyWindowsStdioFlag
This API is kept for backward compatibility: setting PyConfig.legacy_windows_stdio should be used
instead, see Python Initialization Configuration.
If the flag is non-zero, use io.FileIO instead of io._WindowsConsoleIO for sys standard streams.
Establece en 1 si la variable de entorno PYTHONLEGACYWINDOWSSTDIO está configurada en una cadena de
caracteres no vacía.
Ver PEP 528 para más detalles.
Disponibilidad: Windows.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_NoSiteFlag
This API is kept for backward compatibility: setting PyConfig.site_import should be used instead, see
Python Initialization Configuration.
Deshabilita la importación del módulo site y las manipulaciones dependientes del sitio de sys.path que con-
lleva. También deshabilita estas manipulaciones si site se importa explícitamente más tarde (llama a site.
main() si desea que se activen).
Establecido por la opción -S.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_NoUserSiteDirectory
This API is kept for backward compatibility: setting PyConfig.user_site_directory should be used
instead, see Python Initialization Configuration.
No agregue el directorio de paquetes de sitio del usuario (site-packages) a sys.path.
Establecido por las opciones -s y -I, y la variable de entorno PYTHONNOUSERSITE.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_OptimizeFlag
This API is kept for backward compatibility: setting PyConfig.optimization_level should be used ins-
tead, see Python Initialization Configuration.
Establecido por la opción -O y la variable de entorno PYTHONOPTIMIZE.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_QuietFlag
This API is kept for backward compatibility: setting PyConfig.quiet should be used instead, see Python
Initialization Configuration.
No muestre los mensajes de copyright y de versión incluso en modo interactivo.
Establecido por la opción -q.
Nuevo en la versión 3.2.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_UnbufferedStdioFlag
This API is kept for backward compatibility: setting PyConfig.buffered_stdio should be used instead,
see Python Initialization Configuration.
Obliga a las secuencias stdout y stderr a que no tengan búfer.
Establecido por la opción -u y la variable de entorno PYTHONUNBUFFERED.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
int Py_VerboseFlag
This API is kept for backward compatibility: setting PyConfig.verbose should be used instead, see Python
Initialization Configuration.
Imprime un mensaje cada vez que se inicializa un módulo, mostrando el lugar (nombre de archivo o módulo in-
corporado) desde el que se carga. Si es mayor o igual a 2, imprime un mensaje para cada archivo que se verifica
al buscar un módulo. También proporciona información sobre la limpieza del módulo a la salida.
Establecido por la opción -v y la variable de entorno PYTHONVERBOSE.
Obsoleto desde la versión 3.12, se eliminará en la versión 3.14.
void Py_Initialize()
Part of the Stable ABI. Inicializa el intérprete de Python. En una aplicación que incorpora Python, se debe llamar
antes de usar cualquier otra función de API Python/C; vea Antes de la inicialización de Python para ver algunas
excepciones.
This initializes the table of loaded modules (sys.modules), and creates the fundamental modules builtins,
__main__ and sys. It also initializes the module search path (sys.path). It does not set sys.argv; use the
new PyConfig API of the Python Initialization Configuration for that. This is a no-op when called for a second
time (without calling Py_FinalizeEx() first). There is no return value; it is a fatal error if the initialization
fails.
Use the Py_InitializeFromConfig() function to customize the Python Initialization Configuration.
Nota: En Windows, cambia el modo de consola de O_TEXT a O_BINARY, lo que también afectará los usos de
la consola que no sean de Python utilizando C Runtime.
int Py_IsInitialized()
Part of the Stable ABI. Retorna verdadero (distinto de cero) cuando el intérprete de Python se ha inicializado, falso
(cero) si no. Después de que se llama a Py_FinalizeEx(), esto retorna falso hasta que Py_Initialize()
se llama de nuevo.
int Py_IsFinalizing()
Part of the Stable ABI since version 3.13. Return true (non-zero) if the main Python interpreter is shutting down.
Return false (zero) otherwise.
Nuevo en la versión 3.13.
int Py_FinalizeEx()
Part of the Stable ABI since version 3.6. Deshace todas las inicializaciones realizadas por Py_Initialize()
y el uso posterior de las funciones de Python/C API, y destruye todos los sub-intérpretes (ver
Py_NewInterpreter() a continuación) que se crearon y aún no se destruyeron desde el última llamada a
Py_Initialize(). Idealmente, esto libera toda la memoria asignada por el intérprete de Python. Este es un
no-op cuando se llama por segunda vez (sin llamar a Py_Initialize() nuevamente primero). Normalmente
el valor de retorno es 0. Si hubo errores durante la finalización (lavado de datos almacenados en el búfer), se retorna
-1.
Esta función se proporciona por varias razones. Una aplicación de incrustación puede querer reiniciar Python sin
tener que reiniciar la aplicación misma. Una aplicación que ha cargado el intérprete de Python desde una biblioteca
cargable dinámicamente (o DLL) puede querer liberar toda la memoria asignada por Python antes de descargar la
DLL. Durante una búsqueda de pérdidas de memoria en una aplicación, un desarrollador puede querer liberar toda
la memoria asignada por Python antes de salir de la aplicación.
Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause
destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules. Dy-
namically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by
the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references
between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions
may not work properly if their initialization routine is called more than once; this can happen if an application calls
Py_Initialize() and Py_FinalizeEx() more than once.
Genera un evento de auditoría cpython._PySys_ClearAuditHooks sin argumentos.
Nuevo en la versión 3.6.
void Py_Finalize()
Part of the Stable ABI. Esta es una versión compatible con versiones anteriores de Py_FinalizeEx() que
ignora el valor de retorno.
wchar_t *Py_GetProgramName()
Part of the Stable ABI. Return the program name set with PyConfig.program_name, or the default. The
returned string points into static storage; the caller should not modify its value.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.executable instead.
wchar_t *Py_GetPrefix()
Part of the Stable ABI. Return the prefix for installed platform-independent files. This is derived through a number
of complicated rules from the program name set with PyConfig.program_name and some environment va-
riables; for example, if the program name is '/usr/local/bin/python', the prefix is '/usr/local'.
The returned string points into static storage; the caller should not modify its value. This corresponds to the prefix
variable in the top-level Makefile and the --prefix argument to the configure script at build time. The
value is available to Python code as sys.prefix. It is only useful on Unix. See also the next function.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.prefix instead.
wchar_t *Py_GetExecPrefix()
Part of the Stable ABI. Return the exec-prefix for installed platform-dependent files. This is derived through a
number of complicated rules from the program name set with PyConfig.program_name and some envi-
ronment variables; for example, if the program name is '/usr/local/bin/python', the exec-prefix is '/
usr/local'. The returned string points into static storage; the caller should not modify its value. This corres-
ponds to the exec_prefix variable in the top-level Makefile and the --exec-prefix argument to the
configure script at build time. The value is available to Python code as sys.exec_prefix. It is only useful
on Unix.
Antecedentes: el prefijo exec difiere del prefijo cuando los archivos dependientes de la plataforma (como ejecutables
y bibliotecas compartidas) se instalan en un árbol de directorios diferente. En una instalación típica, los archivos
dependientes de la plataforma pueden instalarse en el subárbol /usr/local/plat mientras que la plataforma
independiente puede instalarse en /usr/local.
En términos generales, una plataforma es una combinación de familias de hardware y software, por ejemplo, las
máquinas Sparc que ejecutan el sistema operativo Solaris 2.x se consideran la misma plataforma, pero las máquinas
Intel que ejecutan Solaris 2.x son otra plataforma, y las máquinas Intel que ejecutan Linux son otra plataforma
más. Las diferentes revisiones importantes del mismo sistema operativo generalmente también forman plataformas
diferentes. Los sistemas operativos que no son Unix son una historia diferente; Las estrategias de instalación en esos
sistemas son tan diferentes que el prefijo y el prefijo exec no tienen sentido y se configuran en la cadena vacía.
Tenga en cuenta que los archivos de bytecode compilados de Python son independientes de la plataforma (¡pero
no independientes de la versión de Python con la que fueron compilados!).
Los administradores de sistemas sabrán cómo configurar los programas mount o automount para compartir
/usr/local entre plataformas mientras que /usr/local/plat sea un sistema de archivos diferente para
cada plataforma.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.exec_prefix instead.
wchar_t *Py_GetProgramFullPath()
Part of the Stable ABI. Return the full program name of the Python executable; this is computed as a side-effect
of deriving the default module search path from the program name (set by PyConfig.program_name). The
returned string points into static storage; the caller should not modify its value. The value is available to Python
code as sys.executable.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.executable instead.
wchar_t *Py_GetPath()
Part of the Stable ABI. Return the default module search path; this is computed from the program name (set
by PyConfig.program_name) and some environment variables. The returned string consists of a series of
directory names separated by a platform dependent delimiter character. The delimiter character is ':' on Unix
and macOS, ';' on Windows. The returned string points into static storage; the caller should not modify its value.
The list sys.path is initialized with this value on interpreter startup; it can be (and usually is) modified later to
change the search path for loading modules.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.path instead.
const char *Py_GetVersion()
Part of the Stable ABI. Retorna la versión de este intérprete de Python. Esta es una cadena de caracteres que se
parece a
La primera palabra (hasta el primer carácter de espacio) es la versión actual de Python; los primeros tres caracteres
son la versión mayor y menor separados por un punto. La cadena de caracteres retornada apunta al almacenamiento
estático; la persona que llama no debe modificar su valor. El valor está disponible para el código Python como sys.
version.
Consulta también la constante Py_Version.
const char *Py_GetPlatform()
Part of the Stable ABI. Retorna el identificador de plataforma para la plataforma actual. En Unix, esto se forma a
partir del nombre «oficial» del sistema operativo, convertido a minúsculas, seguido del número de revisión principal;
por ejemplo, para Solaris 2.x, que también se conoce como SunOS 5.x, el valor es 'sunos5'. En macOS, es
'darwin'. En Windows, es 'win'. La cadena de caracteres retornada apunta al almacenamiento estático; la
persona que llama no debe modificar su valor. El valor está disponible para el código de Python como sys.
platform.
const char *Py_GetCopyright()
Part of the Stable ABI. Retorna la cadena de caracteres de copyright oficial para la versión actual de Python, por
ejemplo
'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'
La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no debe modificar su
valor. El valor está disponible para el código de Python como sys.copyright.
const char *Py_GetCompiler()
Part of the Stable ABI. Retorna una indicación del compilador utilizado para construir la versión actual de Python,
entre corchetes, por ejemplo:
"[GCC 2.7.2.2]"
La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no debe modificar su
valor. El valor está disponible para el código Python como parte de la variable sys.version.
const char *Py_GetBuildInfo()
Part of the Stable ABI. Retorna información sobre el número de secuencia y la fecha y hora de compilación de la
instancia actual de intérprete de Python, por ejemplo:
La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no debe modificar su
valor. El valor está disponible para el código Python como parte de la variable sys.version.
wchar_t *Py_GetPythonHome()
Part of the Stable ABI. Return the default «home», that is, the value set by PyConfig.home, or the value of the
PYTHONHOME environment variable if it is set.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get PyConfig.home or PYTHONHOME envi-
ronment variable instead.
El intérprete de Python no es completamente seguro para hilos (thread-safe). Para admitir programas Python multipro-
ceso, hay un bloqueo global, denominado global interpreter lock o GIL, que debe mantener el hilo actual antes de que
pueda acceder de forma segura a los objetos Python. Sin el bloqueo, incluso las operaciones más simples podrían causar
problemas en un programa de hilos múltiples: por ejemplo, cuando dos hilos incrementan simultáneamente el conteo de
referencias del mismo objeto, el conteo de referencias podría terminar incrementándose solo una vez en lugar de dos
veces.
Por lo tanto, existe la regla de que solo el hilo que ha adquirido GIL puede operar en objetos Python o llamar a funciones
API Python/C. Para emular la concurrencia de ejecución, el intérprete regularmente intenta cambiar los hilos (ver sys.
setswitchinterval()). El bloqueo también se libera para bloquear potencialmente las operaciones de E/S, como
leer o escribir un archivo, para que otros hilos de Python puedan ejecutarse mientras tanto.
El intérprete de Python mantiene cierta información de contabilidad específica de hilos dentro de una estructura de da-
tos llamada PyThreadState. También hay una variable global que apunta a la actual PyThreadState: se puede
recuperar usando PyThreadState_Get().
La mayoría del código de extensión que manipula el GIL tiene la siguiente estructura simple
Py_BEGIN_ALLOW_THREADS
... Do some blocking I/O operation ...
Py_END_ALLOW_THREADS
La macro Py_BEGIN_ALLOW_THREADS abre un nuevo bloque y declara una variable local oculta; la macro
Py_END_ALLOW_THREADS cierra el bloque.
El bloque anterior se expande al siguiente código:
PyThreadState *_save;
_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
PyEval_RestoreThread(_save);
Así es como funcionan estas funciones: el bloqueo global del intérprete se usa para proteger el puntero al estado actual del
hilo. Al liberar el bloqueo y guardar el estado del hilo, el puntero del estado del hilo actual debe recuperarse antes de que
se libere el bloqueo (ya que otro hilo podría adquirir inmediatamente el bloqueo y almacenar su propio estado de hilo en
la variable global). Por el contrario, al adquirir el bloqueo y restaurar el estado del hilo, el bloqueo debe adquirirse antes
de almacenar el puntero del estado del hilo.
Nota: Llamar a las funciones de E/S del sistema es el caso de uso más común para liberar el GIL, pero también puede
ser útil antes de llamar a cálculos de larga duración que no necesitan acceso a objetos de Python, como las funciones
de compresión o criptográficas que operan sobre memorias intermedias. Por ejemplo, los módulos estándar zlib y
hashlib liberan el GIL al comprimir o mezclar datos.
Cuando se crean hilos utilizando las API dedicadas de Python (como el módulo threading), se les asocia automáti-
camente un estado del hilo y, por lo tanto, el código que se muestra arriba es correcto. Sin embargo, cuando los hilos se
crean desde C (por ejemplo, por una biblioteca de terceros con su propia administración de hilos), no contienen el GIL,
ni existe una estructura de estado de hilos para ellos.
Si necesita llamar al código Python desde estos subprocesos (a menudo esto será parte de una API de devolución de
llamada proporcionada por la biblioteca de terceros mencionada anteriormente), primero debe registrar estos subproce-
sos con el intérprete creando una estructura de datos de estado del subproceso, luego adquiriendo el GIL, y finalmente
almacenando su puntero de estado de hilo, antes de que pueda comenzar a usar la API Python/C Cuando haya terminado,
debe restablecer el puntero del estado del hilo, liberar el GIL y finalmente liberar la estructura de datos del estado del
hilo.
Las funciones PyGILState_Ensure() y PyGILState_Release() hacen todo lo anterior automáticamente. El
idioma típico para llamar a Python desde un hilo C es:
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
Tenga en cuenta que las funciones PyGILState_* asumen que solo hay un intérprete global (creado automáticamente
por Py_Initialize()). Python admite la creación de intérpretes adicionales (usando Py_NewInterpreter()),
pero la mezcla de varios intérpretes y la API PyGILState_* no está soportada.
Otra cosa importante a tener en cuenta sobre los hilos es su comportamiento frente a la llamada C fork(). En la mayoría
de los sistemas con fork(), después de que un proceso se bifurca, solo existirá el hilo que emitió el fork. Esto tiene
un impacto concreto tanto en cómo se deben manejar las cerraduras como en todo el estado almacenado en el tiempo de
ejecución de CPython.
The fact that only the «current» thread remains means any locks held by other threads will never be released. Python solves
this for os.fork() by acquiring the locks it uses internally before the fork, and releasing them afterwards. In addition, it
resets any lock-objects in the child. When extending or embedding Python, there is no way to inform Python of additional
(non-Python) locks that need to be acquired before or reset after a fork. OS facilities such as pthread_atfork()
would need to be used to accomplish the same thing. Additionally, when extending or embedding Python, calling fork()
directly rather than through os.fork() (and returning to or calling into Python) may result in a deadlock by one of
Python’s internal locks being held by a thread that is defunct after the fork. PyOS_AfterFork_Child() tries to reset
the necessary locks, but is not always able to.
El hecho de que todos los otros hilos desaparezcan también significa que el estado de ejecución de CPython debe limpiar-
se correctamente, lo que os.fork() lo hace. Esto significa finalizar todos los demás objetos PyThreadState que
pertenecen al intérprete actual y todos los demás objetos PyInterpreterState. Debido a esto y a la naturaleza es-
pecial del intérprete «principal», fork() solo debería llamarse en el hilo «principal» de ese intérprete, donde el CPython
global el tiempo de ejecución se inicializó originalmente. La única excepción es si exec() se llamará inmediatamente
después.
Estos son los tipos y funciones más utilizados al escribir código de extensión C o al incrustar el intérprete de Python:
type PyInterpreterState
Part of the Limited API (as an opaque struct). Esta estructura de datos representa el estado compartido por varios
subprocesos cooperantes. Los hilos que pertenecen al mismo intérprete comparten la administración de su módulo
y algunos otros elementos internos. No hay miembros públicos en esta estructura.
Los hilos que pertenecen a diferentes intérpretes inicialmente no comparten nada, excepto el estado del proceso
como memoria disponible, descriptores de archivos abiertos y demás. El bloqueo global del intérprete también es
compartido por todos los hilos, independientemente de a qué intérprete pertenezcan.
type PyThreadState
Part of the Limited API (as an opaque struct). This data structure represents the state of a single thread. The only
public data member is:
PyInterpreterState *interp
This thread’s interpreter state.
PyThreadState *PyEval_SaveThread()
Part of the Stable ABI. Libere el bloqueo global del intérprete (si se ha creado) y restablezca el estado del hilo
a NULL, retornando el estado del hilo anterior (que no es NULL). Si se ha creado el bloqueo, el hilo actual debe
haberlo adquirido.
void PyEval_RestoreThread(PyThreadState *tstate)
Part of the Stable ABI. Adquiera el bloqueo global del intérprete (si se ha creado) y establezca el estado del hilo en
tstate, que no debe ser NULL. Si se ha creado el bloqueo, el hilo actual no debe haberlo adquirido, de lo contrario
se produce un deadlock.
Nota: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread
was not created by Python. You can use Py_IsFinalizing() or sys.is_finalizing() to check if the
interpreter is in process of being finalized before calling this function to avoid unwanted termination.
PyThreadState *PyThreadState_Get()
Part of the Stable ABI. Retorna el estado actual del hilo. Se debe mantener el bloqueo global del intérprete. Cuando
el estado actual del hilo es NULL, esto genera un error fatal (por lo que la persona que llama no necesita verificar
NULL).
See also PyThreadState_GetUnchecked().
PyThreadState *PyThreadState_GetUnchecked()
Similar to PyThreadState_Get(), but don’t kill the process with a fatal error if it is NULL. The caller is
responsible to check if the result is NULL.
Nuevo en la versión 3.13: In Python 3.5 to 3.12, the function was private and known as
_PyThreadState_UncheckedGet().
PyThreadState *PyThreadState_Swap(PyThreadState *tstate)
Part of the Stable ABI. Cambia el estado del hilo actual con el estado del hilo dado por el argumento tstate, que
puede ser NULL. El bloqueo global del intérprete debe mantenerse y no se libera.
Las siguientes funciones utilizan almacenamiento local de hilos y no son compatibles con subinterpretes:
PyGILState_STATE PyGILState_Ensure()
Part of the Stable ABI. Asegúrese de que el subproceso actual esté listo para llamar a la API de Python C, inde-
pendientemente del estado actual de Python o del bloqueo global del intérprete. Esto se puede invocar tantas veces
como lo desee un subproceso siempre que cada llamada coincida con una llamada a PyGILState_Release().
En general, se pueden usar otras API relacionadas con subprocesos entre PyGILState_Ensure() y
PyGILState_Release() invoca siempre que el estado del subproceso se restablezca a su estado an-
terior antes del Release(). Por ejemplo, el uso normal de las macros Py_BEGIN_ALLOW_THREADS y
Py_END_ALLOW_THREADS es aceptable.
El valor de retorno es un «identificador» opaco al estado del hilo cuando PyGILState_Ensure() fue lla-
mado, y debe pasarse a PyGILState_Release() para asegurar que Python se deje en el mismo estado.
Aunque las llamadas recursivas están permitidas, estos identificadores no pueden compartirse; cada llamada única
a PyGILState_Ensure() debe guardar el identificador para su llamada a PyGILState_Release().
Cuando la función regrese, el hilo actual contendrá el GIL y podrá llamar a código arbitrario de Python. El fracaso
es un error fatal.
Nota: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread
was not created by Python. You can use Py_IsFinalizing() or sys.is_finalizing() to check if the
interpreter is in process of being finalized before calling this function to avoid unwanted termination.
void PyGILState_Release(PyGILState_STATE)
Part of the Stable ABI. Libera cualquier recurso previamente adquirido. Después de esta llamada, el estado de
Python será el mismo que antes de la llamada correspondiente PyGILState_Ensure() (pero en general este
estado será desconocido para la persona que llama, de ahí el uso de la API GILState).
Cada llamada a PyGILState_Ensure() debe coincidir con una llamada a PyGILState_Release() en
el mismo hilo.
PyThreadState *PyGILState_GetThisThreadState()
Part of the Stable ABI. Obtenga el estado actual del hilo para este hilo. Puede retornar NULL si no se ha utilizado
la API GILState en el hilo actual. Tenga en cuenta que el subproceso principal siempre tiene dicho estado de
subproceso, incluso si no se ha realizado una llamada de estado de subproceso automático en el subproceso principal.
Esta es principalmente una función auxiliar y de diagnóstico.
int PyGILState_Check()
Retorna 1 si el hilo actual mantiene el GIL y 0 de lo contrario. Esta función se puede llamar desde cualquier hilo
en cualquier momento. Solo si se ha inicializado el hilo de Python y actualmente mantiene el GIL, retornará 1. Esta
es principalmente una función auxiliar y de diagnóstico. Puede ser útil, por ejemplo, en contextos de devolución
de llamada o funciones de asignación de memoria cuando saber que el GIL está bloqueado puede permitir que la
persona que llama realice acciones confidenciales o se comporte de otra manera de manera diferente.
Nuevo en la versión 3.4.
Las siguientes macros se usan normalmente sin punto y coma final; busque, por ejemplo, el uso en la distribución fuente
de Python.
Py_BEGIN_ALLOW_THREADS
Part of the Stable ABI. Esta macro se expande a {PyThreadState *_save; _save =
PyEval_SaveThread();. Tenga en cuenta que contiene una llave de apertura; debe coincidir con la
siguiente macro Py_END_ALLOW_THREADS. Ver arriba para una discusión más detallada de esta macro.
Py_END_ALLOW_THREADS
Part of the Stable ABI. Esta macro se expande a PyEval_RestoreThread(_save); }. Tenga en cuenta
que contiene una llave de cierre; debe coincidir con una macro anterior Py_BEGIN_ALLOW_THREADS. Ver
arriba para una discusión más detallada de esta macro.
Py_BLOCK_THREADS
Part of the Stable ABI. Esta macro se expande a PyEval_RestoreThread(_save);: es equivalente a
Py_END_ALLOW_THREADS sin la llave de cierre.
Py_UNBLOCK_THREADS
Part of the Stable ABI. Esta macro se expande a _save = PyEval_SaveThread();: es equivalente a
Py_BEGIN_ALLOW_THREADS sin la llave de apertura y la declaración de variable.
Nota: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread
was not created by Python. You can use Py_IsFinalizing() or sys.is_finalizing() to check if the
interpreter is in process of being finalized before calling this function to avoid unwanted termination.
Si bien en la mayoría de los usos, solo incrustará un solo intérprete de Python, hay casos en los que necesita crear varios
intérpretes independientes en el mismo proceso y tal vez incluso en el mismo hilo. Los subinterpretes le permiten hacer
eso.
El intérprete «principal» es el primero creado cuando se inicializa el tiempo de ejecución. Suele ser el único intérpre-
te de Python en un proceso. A diferencia de los subinterpretes, el intérprete principal tiene responsabilidades globales
de proceso únicas, como el manejo de señales. También es responsable de la ejecución durante la inicialización del
tiempo de ejecución y generalmente es el intérprete activo durante la finalización del tiempo de ejecución. La función
PyInterpreterState_Main() retorna un puntero a su estado.
Puede cambiar entre subinterpretes utilizando la función PyThreadState_Swap(). Puede crearlos y destruirlos
utilizando las siguientes funciones:
type PyInterpreterConfig
Structure containing most parameters to configure a sub-interpreter. Its values are used only in
Py_NewInterpreterFromConfig() and never modified by the runtime.
Nuevo en la versión 3.12.
Structure fields:
int use_main_obmalloc
If this is 0 then the sub-interpreter will use its own «object» allocator state. Otherwise it will use (share) the
main interpreter’s.
If this is 0 then check_multi_interp_extensions must be 1 (non-zero). If this is 1 then gil must
not be PyInterpreterConfig_OWN_GIL.
int allow_fork
If this is 0 then the runtime will not support forking the process in any thread where the sub-interpreter is
currently active. Otherwise fork is unrestricted.
Note that the subprocess module still works when fork is disallowed.
int allow_exec
If this is 0 then the runtime will not support replacing the current process via exec (e.g. os.execv()) in
any thread where the sub-interpreter is currently active. Otherwise exec is unrestricted.
Note that the subprocess module still works when exec is disallowed.
int allow_threads
If this is 0 then the sub-interpreter’s threading module won’t create threads. Otherwise threads are allo-
wed.
int allow_daemon_threads
If this is 0 then the sub-interpreter’s threading module won’t create daemon threads. Otherwise daemon
threads are allowed (as long as allow_threads is non-zero).
int check_multi_interp_extensions
If this is 0 then all extension modules may be imported, including legacy (single-phase init) modules, in any
thread where the sub-interpreter is currently active. Otherwise only multi-phase init extension modules (see
PEP 489) may be imported. (Also see Py_mod_multiple_interpreters.)
This must be 1 (non-zero) if use_main_obmalloc is 0.
int gil
This determines the operation of the GIL for the sub-interpreter. It may be one of the following:
PyInterpreterConfig_DEFAULT_GIL
Use the default selection (PyInterpreterConfig_SHARED_GIL).
PyInterpreterConfig_SHARED_GIL
Use (share) the main interpreter’s GIL.
PyInterpreterConfig_OWN_GIL
Use the sub-interpreter’s own GIL.
If this is PyInterpreterConfig_OWN_GIL then PyInterpreterConfig.
use_main_obmalloc must be 0.
PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)
Crea un nuevo subinterprete. Este es un entorno (casi) totalmente separado para la ejecución de código Python. En
particular, el nuevo intérprete tiene versiones separadas e independientes de todos los módulos importados, incluidos
los módulos fundamentales builtins, __main__ y sys. La tabla de módulos cargados (sys.modules) y
la ruta de búsqueda del módulo (sys.path) también están separados. El nuevo entorno no tiene variable sys.
argv. Tiene nuevos objetos de archivo de flujo de E/S estándar sys.stdin, sys.stdout y sys.stderr
(sin embargo, estos se refieren a los mismos descriptores de archivo subyacentes).
The given config controls the options with which the interpreter is initialized.
Upon success, tstate_p will be set to the first thread state created in the new sub-interpreter. This thread state is
made in the current thread state. Note that no actual thread is created; see the discussion of thread states below. If
creation of the new interpreter is unsuccessful, tstate_p is set to NULL; no exception is set since the exception state
is stored in the current thread state and there may not be a current thread state.
Like all other Python/C API functions, the global interpreter lock must be held before calling this function and
is still held when it returns. Likewise a current thread state must be set on entry. On success, the returned thread
state will be set as current. If the sub-interpreter is created with its own GIL then the GIL of the calling interpreter
will be released. When the function returns, the new interpreter’s GIL will be held by the current thread and the
previously interpreter’s GIL will remain released here.
Nuevo en la versión 3.12.
Sub-interpreters are most effective when isolated from each other, with certain functionality restricted:
PyInterpreterConfig config = {
.use_main_obmalloc = 0,
.allow_fork = 0,
.allow_exec = 0,
.allow_threads = 1,
.allow_daemon_threads = 0,
.check_multi_interp_extensions = 1,
.gil = PyInterpreterConfig_OWN_GIL,
};
PyThreadState *tstate = Py_NewInterpreterFromConfig(&config);
Note that the config is used only briefly and does not get modified. During initialization the config’s values are
converted into various PyInterpreterState values. A read-only copy of the config may be stored internally
on the PyInterpreterState.
Los módulos de extensión se comparten entre (sub) intérpretes de la siguiente manera:
• Para módulos que usan inicialización multifase, por ejemplo PyModule_FromDefAndSpec(), se crea
e inicializa un objeto de módulo separado para cada intérprete. Solo las variables estáticas y globales de nivel
C se comparten entre estos objetos de módulo.
• Para módulos que utilizan inicialización monofásica, por ejemplo PyModule_Create(), la primera vez
que se importa una extensión en particular, se inicializa normalmente y una copia (superficial) del diccionario
de su módulo se guarda. Cuando otro (sub) intérprete importa la misma extensión, se inicializa un nuevo mó-
dulo y se llena con el contenido de esta copia; no se llama a la función init de la extensión. Los objetos en el
diccionario del módulo terminan compartidos entre (sub) intérpretes, lo que puede causar un comportamiento
no deseado (ver Errores y advertencias (Bugs and caveats) a continuación).
Tenga en cuenta que esto es diferente de lo que sucede cuando se importa una extensión después de que el
intérprete se haya reiniciado por completo llamando a Py_FinalizeEx() y Py_Initialize(); en
ese caso, la función initmodule de la extensión es llamada nuevamente. Al igual que con la inicialización
de múltiples fases, esto significa que solo se comparten variables estáticas y globales de nivel C entre estos
módulos.
PyThreadState *Py_NewInterpreter(void)
Part of the Stable ABI. Create a new sub-interpreter. This is essentially just a wrapper around
Py_NewInterpreterFromConfig() with a config that preserves the existing behavior. The result is an
unisolated sub-interpreter that shares the main interpreter’s GIL, allows fork/exec, allows daemon threads, and
allows single-phase init modules.
void Py_EndInterpreter(PyThreadState *tstate)
Part of the Stable ABI. Destroy the (sub-)interpreter represented by the given thread state. The given thread state
must be the current thread state. See the discussion of thread states below. When the call returns, the current thread
state is NULL. All thread states associated with this interpreter are destroyed. The global interpreter lock used by
the target interpreter must be held before calling this function. No GIL is held when it returns.
Py_FinalizeEx() will destroy all sub-interpreters that haven’t been explicitly destroyed at that point.
Using Py_NewInterpreterFromConfig() you can create a sub-interpreter that is completely isolated from other
interpreters, including having its own GIL. The most important benefit of this isolation is that such an interpreter can
execute Python code without being blocked by other interpreters or blocking any others. Thus a single Python process
can truly take advantage of multiple CPU cores when running Python code. The isolation also encourages a different
approach to concurrency than that of just using threads. (See PEP 554.)
Using an isolated interpreter requires vigilance in preserving that isolation. That especially means not sharing any objects
or mutable state without guarantees about thread-safety. Even objects that are otherwise immutable (e.g. None, (1,
5)) can’t normally be shared because of the refcount. One simple but less-efficient approach around this is to use a global
lock around all use of some state (or object). Alternately, effectively immutable objects (like integers or strings) can be
made safe in spite of their refcounts by making them immortal. In fact, this has been done for the builtin singletons, small
integers, and a number of other builtin objects.
If you preserve isolation then you will have access to proper multi-core computing without the complications that come
with free-threading. Failure to preserve isolation will expose you to the full consequences of free-threading, including
races and hard-to-debug crashes.
Aside from that, one of the main challenges of using multiple isolated interpreters is how to communicate between them
safely (not break isolation) and efficiently. The runtime and stdlib do not provide any standard approach to this yet. A
future stdlib module would help mitigate the effort of preserving isolation and expose effective tools for communicating
(and sharing) data between interpreters.
Nuevo en la versión 3.12.
Debido a que los subinterpretes (y el intérprete principal) son parte del mismo proceso, el aislamiento entre ellos no es
perfecto — por ejemplo, usando operaciones de archivos de bajo nivel como os.close() pueden (accidentalmente o
maliciosamente) afectar los archivos abiertos del otro. Debido a la forma en que las extensiones se comparten entre (sub)
intérpretes, algunas extensiones pueden no funcionar correctamente; esto es especialmente probable cuando se utiliza la
inicialización monofásica o las variables globales (estáticas). Es posible insertar objetos creados en un subinterprete en un
espacio de nombres de otro (sub) intérprete; Esto debe evitarse si es posible.
Se debe tener especial cuidado para evitar compartir funciones, métodos, instancias o clases definidas por el usuario entre
los subinterpretes, ya que las operaciones de importación ejecutadas por dichos objetos pueden afectar el diccionario
(sub-) intérprete incorrecto de los módulos cargados. Es igualmente importante evitar compartir objetos desde los que se
pueda acceder a lo anterior.
También tenga en cuenta que la combinación de esta funcionalidad con PyGILState_* APIs es delicada, porque estas
APIs suponen una biyección entre los estados de hilo de Python e hilos a nivel del sistema operativo, una suposición rota por
la presencia de subinterpretes. Se recomienda encarecidamente que no cambie los subinterpretes entre un par de llamadas
coincidentes PyGILState_Ensure() y PyGILState_Release(). Además, las extensiones (como ctypes)
que usan estas APIs para permitir la llamada de código Python desde hilos no creados por Python probablemente se
rompan cuando se usan subinterpretes.
Se proporciona un mecanismo para hacer notificaciones asincrónicas al hilo principal del intérprete. Estas notificaciones
toman la forma de un puntero de función y un argumento de puntero nulo.
int Py_AddPendingCall(int (*func)(void*), void *arg)
Part of the Stable ABI. Programa una función para que se llame desde el hilo principal del intérprete. En caso de
éxito, se retorna 0 y se pone en cola func para ser llamado en el hilo principal. En caso de fallo, se retorna -1 sin
establecer ninguna excepción.
Cuando se puso en cola con éxito, func será eventualmente invocado desde el hilo principal del intérprete con el
argumento arg. Se llamará de forma asincrónica con respecto al código Python que se ejecuta normalmente, pero
con ambas condiciones cumplidas:
• en un límite bytecode;
• con el hilo principal que contiene el global interpreter lock (func, por lo tanto, puede usar la API C completa).
func debe retornar 0 en caso de éxito o -1 en caso de error con una excepción establecida. func no se interrumpirá
para realizar otra notificación asíncrona de forma recursiva, pero aún se puede interrumpir para cambiar hilos si se
libera el bloqueo global del intérprete.
Esta función no necesita un estado de hilo actual para ejecutarse y no necesita el bloqueo global del intérprete.
Para llamar a esta función en un subinterprete, quien llama debe mantener el GIL. De lo contrario, la función func
se puede programar para que se llame desde el intérprete incorrecto.
Advertencia: Esta es una función de bajo nivel, solo útil para casos muy especiales. No hay garantía de que
func se llame lo más rápido posible. Si el hilo principal está ocupado ejecutando una llamada al sistema, no se
llamará func antes de que vuelva la llamada del sistema. Esta función generalmente no es adecuada para llamar
a código Python desde hilos C arbitrarios. En su lugar, use PyGILState API.
El intérprete de Python proporciona soporte de bajo nivel para adjuntar funciones de creación de perfiles y seguimiento
de ejecución. Estos se utilizan para herramientas de análisis de perfiles, depuración y cobertura.
Esta interfaz C permite que el código de perfilado o rastreo evite la sobrecarga de llamar a través de objetos invocables
a nivel de Python, haciendo una llamada directa a la función C en su lugar. Los atributos esenciales de la instalación no
han cambiado; la interfaz permite instalar funciones de rastreo por hilos, y los eventos básicos informados a la función de
rastreo son los mismos que se informaron a las funciones de rastreo a nivel de Python en versiones anteriores.
typedef int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
The type of the trace function registered using PyEval_SetProfile() and PyEval_SetTrace(). The
first parameter is the object passed to the registration function as obj, frame is the frame object to which the event
pertains, what is one of the constants PyTrace_CALL, PyTrace_EXCEPTION, PyTrace_LINE,
PyTrace_RETURN, PyTrace_C_CALL, PyTrace_C_EXCEPTION, PyTrace_C_RETURN, or
PyTrace_OPCODE, and arg depends on the value of what:
int PyTrace_CALL
El valor del parámetro what para una función Py_tracefunc cuando se informa una nueva llamada a una
función o método, o una nueva entrada en un generador. Tenga en cuenta que la creación del iterador para una
función de generador no se informa ya que no hay transferencia de control al código de bytes de Python en la marco
correspondiente.
int PyTrace_EXCEPTION
El valor del parámetro what para una función Py_tracefunc cuando se ha producido una excepción. La función
de devolución de llamada se llama con este valor para what cuando después de que se procese cualquier bytecode,
después de lo cual la excepción se establece dentro del marco que se está ejecutando. El efecto de esto es que a
medida que la propagación de la excepción hace que la pila de Python se desenrolle, el retorno de llamada se llama
al retornar a cada marco a medida que se propaga la excepción. Solo las funciones de rastreo reciben estos eventos;
el perfilador (profiler) no los necesita.
int PyTrace_LINE
The value passed as the what parameter to a Py_tracefunc function (but not a profiling function) when a
line-number event is being reported. It may be disabled for a frame by setting f_trace_lines to 0 on that
frame.
int PyTrace_RETURN
El valor para el parámetro what para Py_tracefunc funciona cuando una llamada está por regresar.
int PyTrace_C_CALL
El valor del parámetro what para Py_tracefunc funciona cuando una función C está a punto de ser invocada.
int PyTrace_C_EXCEPTION
El valor del parámetro what para funciones Py_tracefunc cuando una función C ha lanzado una excepción.
int PyTrace_C_RETURN
El valor del parámetro what para Py_tracefunc funciona cuando una función C ha retornado.
int PyTrace_OPCODE
The value for the what parameter to Py_tracefunc functions (but not profiling functions) when a new op-
code is about to be executed. This event is not emitted by default: it must be explicitly requested by setting
f_trace_opcodes to 1 on the frame.
void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
Set the profiler function to func. The obj parameter is passed to the function as its first parameter, and may be
any Python object, or NULL. If the profile function needs to maintain state, using a different value for obj for each
thread provides a convenient and thread-safe place to store it. The profile function is called for all monitored events
except PyTrace_LINE PyTrace_OPCODE and PyTrace_EXCEPTION.
Consulte también la función sys.setprofile().
La persona que llama debe mantener el GIL.
Estas funciones solo están destinadas a ser utilizadas por herramientas de depuración avanzadas.
PyInterpreterState *PyInterpreterState_Head()
Retorna el objeto de estado del intérprete al principio de la lista de todos esos objetos.
PyInterpreterState *PyInterpreterState_Main()
Retorna el objeto de estado del intérprete principal.
PyInterpreterState *PyInterpreterState_Next(PyInterpreterState *interp)
Retorna el siguiente objeto de estado de intérprete después de interp de la lista de todos esos objetos.
PyThreadState *PyInterpreterState_ThreadHead(PyInterpreterState *interp)
Retorna el puntero al primer objeto PyThreadState en la lista de hilos asociados con el intérprete interp.
PyThreadState *PyThreadState_Next(PyThreadState *tstate)
Retorna el siguiente objeto de estado del hilo después de tstate de la lista de todos los objetos que pertenecen al
mismo objeto PyInterpreterState.
El intérprete de Python proporciona soporte de bajo nivel para el almacenamiento local de hilos (TLS) que envuelve
la implementación de TLS nativa subyacente para admitir la API de almacenamiento local de hilos de nivel Python
(threading.local). Las APIs de nivel CPython C son similares a las ofrecidas por pthreads y Windows: use una
clave de hilo y funciones para asociar un valor de void* por hilo.
El GIL no necesita ser retenido al llamar a estas funciones; proporcionan su propio bloqueo.
Tenga en cuenta que Python.h no incluye la declaración de las API de TLS, debe incluir pythread.h para usar el
almacenamiento local de hilos.
Nota: Ninguna de estas funciones API maneja la administración de memoria en nombre de los valores void*. De-
be asignarlos y desasignarlos usted mismo. Si los valores void* son PyObject*, estas funciones tampoco realizan
operaciones de conteo de referencias en ellos.
La API de TSS se introduce para reemplazar el uso de la API TLS existente dentro del intérprete de CPython. Esta API
utiliza un nuevo tipo Py_tss_t en lugar de int para representar las claves del hilo.
Nuevo en la versión 3.7.
Ver también:
«Una nueva C-API para Thread-Local Storage en CPython» (PEP 539)
type Py_tss_t
Esta estructura de datos representa el estado de una clave del hilo, cuya definición puede depender de la imple-
mentación de TLS subyacente, y tiene un campo interno que representa el estado de inicialización de la clave. No
hay miembros públicos en esta estructura.
Cuando Py_LIMITED_API no está definido, la asignación estática de este tipo por Py_tss_NEEDS_INIT está
permitida.
Py_tss_NEEDS_INIT
Esta macro se expande al inicializador para variables Py_tss_t. Tenga en cuenta que esta macro no se definirá
con Py_LIMITED_API.
Asignación dinámica
Asignación dinámica de Py_tss_t, requerida en los módulos de extensión construidos con Py_LIMITED_API, donde la
asignación estática de este tipo no es posible debido a que su implementación es opaca en el momento de la compilación.
Py_tss_t *PyThread_tss_alloc()
Part of the Stable ABI since version 3.7. Retorna un valor que es el mismo estado que un valor inicializado con
Py_tss_NEEDS_INIT, o NULL en caso de falla de asignación dinámica.
void PyThread_tss_free(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Libera la clave asignada por PyThread_tss_alloc(), después de
llamar por primera vez PyThread_tss_delete() para asegurarse de que los hilos locales asociados no hayan
sido asignados. Esto es un no-op si el argumento clave es NULL.
Nota: Una clave liberada se convierte en un puntero colgante. Debería restablecer la clave a NULL.
Métodos
El parámetro key de estas funciones no debe ser NULL. Además, los comportamientos de PyThread_tss_set()
y PyThread_tss_get() no están definidos si el Py_tss_t dado no ha sido inicializado por
PyThread_tss_create().
int PyThread_tss_is_created(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Retorna un valor distinto de cero si Py_tss_t ha sido inicializado por
PyThread_tss_create().
int PyThread_tss_create(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Retorna un valor cero en la inicialización exitosa de una cla-
ve TSS. El comportamiento no está definido si el valor señalado por el argumento key no se inicializa con
Py_tss_NEEDS_INIT. Esta función se puede invocar repetidamente en la misma tecla: llamarla a una tecla
ya inicializada es un no-op e inmediatamente retorna el éxito.
void PyThread_tss_delete(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Destruye una clave TSS para olvidar los valores asociados con la clave
en todos los hilos y cambie el estado de inicialización de la clave a no inicializado. Una clave destruida se puede
inicializar nuevamente mediante PyThread_tss_create(). Esta función se puede invocar repetidamente en
la misma llave; llamarla en una llave ya destruida es un no-op.
int PyThread_tss_set(Py_tss_t *key, void *value)
Part of the Stable ABI since version 3.7. Retorna un valor cero para indicar la asociación exitosa de un valor a
void* con una clave TSS en el hilo actual. Cada hilo tiene un mapeo distinto de la clave a un valor void*.
void *PyThread_tss_get(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Retorna el valor void* asociado con una clave TSS en el hilo actual. Esto
retorna NULL si no hay ningún valor asociado con la clave en el hilo actual.
Obsoleto desde la versión 3.7: Esta API es reemplazada por API de Almacenamiento Específico de Hilos (TSS, por sus
significado en inglés *Thread Specific Storage*).
Nota: Esta versión de la API no es compatible con plataformas donde la clave TLS nativa se define de una mane-
ra que no se puede transmitir de forma segura a int. En tales plataformas, PyThread_create_key() regresará
inmediatamente con un estado de falla, y las otras funciones TLS serán no operativas en tales plataformas.
Debido al problema de compatibilidad mencionado anteriormente, esta versión de la API no debe usarse en código nuevo.
int PyThread_create_key()
Part of the Stable ABI.
void PyThread_delete_key(int key)
Part of the Stable ABI.
10.1 Ejemplo
PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;
237
The Python/C API, Versión 3.13.0a5
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return Py_RunMain();
exception:
PyConfig_Clear(&config);
if (PyStatus_IsExit(status)) {
return status.exitcode;
}
/* Display the error message and exit the process with
non-zero exit code */
Py_ExitStatusException(status);
}
10.2 PyWideStringList
type PyWideStringList
Lista de cadenas de caracteres wchar_t*.
Si length no es cero, items no deben ser NULL y todas las cadenas de caracteres deben ser no NULL.
Métodos:
PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)
Agregar item a list.
Python debe estar preinicializado para llamar a esta función.
PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)
Inserta item en list en index.
Si index es mayor o igual que el largo de list, agrega item a list.
index must be greater than or equal to 0.
Python debe estar preinicializado para llamar a esta función.
Campos de estructura:
Py_ssize_t length
Longitud de la lista.
wchar_t **items
Elementos de la lista.
10.3 PyStatus
type PyStatus
Estructura para almacenar el estado de una función de inicialización: éxito, error o salida.
Para un error, puede almacenar el nombre de la función C que creó el error.
Campos de estructura:
int exitcode
Código de salida El argumento pasó a exit().
const char *err_msg
Mensaje de error.
const char *func
El nombre de la función que creó un error puede ser NULL.
Funciones para crear un estado:
PyStatus PyStatus_Ok(void)
Éxito.
PyStatus PyStatus_Error(const char *err_msg)
Error de inicialización con un mensaje.
err_msg no debe ser NULL.
PyStatus PyStatus_NoMemory(void)
Error de asignación de memoria (sin memoria).
PyStatus PyStatus_Exit(int exitcode)
Sale de Python con el código de salida especificado.
Funciones para manejar un estado:
int PyStatus_Exception(PyStatus status)
¿Es el estado un error o una salida? Si es verdadero, la excepción debe ser manejada; por ejemplo llamando
a Py_ExitStatusException().
int PyStatus_IsError(PyStatus status)
¿Es el resultado un error?
int PyStatus_IsExit(PyStatus status)
¿El resultado es una salida?
void Py_ExitStatusException(PyStatus status)
Llama a exit(exitcode) si status es una salida. Imprime el mensaje de error y sale con un código de
salida distinto de cero si status es un error. Solo se debe llamar si PyStatus_Exception(status) no
es cero.
Nota: Internamente, Python usa macros que establecen PyStatus.func, mientras que las funciones para crear un
estado establecen func en NULL.
Ejemplo:
10.4 PyPreConfig
type PyPreConfig
Estructura utilizada para preinicializar Python.
Función para inicializar una preconfiguración:
void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
Inicializa la preconfiguración con Configuración de Python.
void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
Inicializa la preconfiguración con Configuración aislada.
Campos de estructura:
int allocator
Nombre de los asignadores de memoria de Python:
• PYMEM_ALLOCATOR_NOT_SET (0): no cambia asignadores de memoria (usa los valores predetermi-
nados)
• PYMEM_ALLOCATOR_DEFAULT (1): asignadores de memoria predeterminados.
• PYMEM_ALLOCATOR_DEBUG (2): asignadores de memoria predeterminados con ganchos de depura-
ción.
• PYMEM_ALLOCATOR_MALLOC (3): usa malloc() de la biblioteca C.
• PYMEM_ALLOCATOR_MALLOC_DEBUG (4): fuerza el uso de malloc() con ganchos de depuración.
• PYMEM_ALLOCATOR_PYMALLOC (5): asignador de memoria pymalloc de Python
• PYMEM_ALLOCATOR_PYMALLOC_DEBUG (6): asignador de memoria pymalloc de Python con gan-
chos de depuración.
• PYMEM_ALLOCATOR_MIMALLOC (6): use mimalloc, a fast malloc replacement.
• PYMEM_ALLOCATOR_MIMALLOC_DEBUG (7): use mimalloc, a fast malloc replacement with de-
bug hooks.
int use_environment
¿Utiliza variables de entorno? Consulte PyConfig.use_environment.
Predeterminado: 1 en la configuración de Python y 0 en la configuración aislada.
int utf8_mode
Si es distinto de cero, habilite Python UTF-8 Mode.
Set to 0 or 1 by the -X utf8 command line option and the PYTHONUTF8 environment variable.
También se pone a 1 si la configuración regional LC_CTYPE es C o POSIX.
Predeterminado: -1 en la configuración de Python y 0 en la configuración aislada.
La preinicialización de Python:
• Establecer los asignadores de memoria de Python (PyPreConfig.allocator)
• Configurar la configuración regional LC_CTYPE (locale encoding)
• Establecer el Python UTF-8 Mode (PyPreConfig.utf8_mode)
La preconfiguración actual (tipo PyPreConfig) se almacena en _PyRuntime.preconfig.
Funciones para preinicializar Python:
PyStatus Py_PreInitialize(const PyPreConfig *preconfig)
Preinicializa Python desde la preconfiguración preconfig.
preconfig no debe ser NULL.
PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char *const *argv)
Preinicializa Python desde la preconfiguración preconfig.
Analice los argumentos de la línea de comando argv (cadenas de bytes) si parse_argv de preconfig no es cero.
preconfig no debe ser NULL.
PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t *const *argv)
Preinicializa Python desde la preconfiguración preconfig.
Analice los argumentos de la línea de comando argv (cadenas anchas) si parse_argv de preconfig no es cero.
preconfig no debe ser NULL.
La persona que llama es responsable de manejar las excepciones (error o salida) usando PyStatus_Exception() y
Py_ExitStatusException().
Para Configuración de Python (PyPreConfig_InitPythonConfig()), si Python se inicializa con argumentos de
línea de comando, los argumentos de la línea de comando también deben pasarse para preinicializar Python, ya que tienen
un efecto en la preconfiguración como codificaciones. Por ejemplo, la opción de línea de comando -X utf8 habilita el
Python UTF-8 Mode.
PyMem_SetAllocator() se puede llamar después de Py_PreInitialize() y antes
Py_InitializeFromConfig() para instalar un asignador de memoria personalizado. Se puede llamar antes
Py_PreInitialize() si PyPreConfig.allocator está configurado en PYMEM_ALLOCATOR_NOT_SET.
Las funciones de asignación de memoria de Python como PyMem_RawMalloc() no deben usarse antes de la preini-
cialización de Python, mientras que llamar directamente a malloc() y free() siempre es seguro. No se debe llamar
a Py_DecodeLocale() antes de la preinicialización de Python.
PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);
preconfig.utf8_mode = 1;
status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();
10.6 PyConfig
type PyConfig
Estructura que contiene la mayoría de los parámetros para configurar Python.
Cuando termine, se debe utilizar la función PyConfig_Clear() para liberar la memoria de configuración.
Métodos de estructura:
void PyConfig_InitPythonConfig(PyConfig *config)
Inicialice la configuración con la Configuración de Python.
void PyConfig_InitIsolatedConfig(PyConfig *config)
Inicialice la configuración con la Configuración Aislada.
PyStatus PyConfig_SetString(PyConfig *config, wchar_t *const *config_str, const wchar_t *str)
Copia la cadena de caracteres anchos str en *config_str.
Preinicializa Python si es necesario.
PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t *const *config_str, const char *str)
Decodifique str usando Py_DecodeLocale() y establezca el resultado en *config_str.
Preinicializa Python si es necesario.
PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t *const *argv)
Configure los argumentos de la línea de comando (miembro argv de config) de la lista argv de cadenas de
caracteres anchas.
Preinicializa Python si es necesario.
PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char *const *argv)
Establezca argumentos de línea de comando (miembro argv de config) de la lista argv de cadenas de bytes.
Decodifica bytes usando Py_DecodeLocale().
Preinicializa Python si es necesario.
Si argv está vacío, se agrega una cadena vacía para garantizar que sys.argv siempre exista y nunca esté
vacío.
Valor predeterminado: NULL.
Consulte también el miembro orig_argv.
int safe_path
Si es igual a cero, Py_RunMain() agrega una ruta potencialmente insegura a sys.path al inicio:
• Si argv[0] es igual a L"-m" (python -m module), añade el directorio de trabajo actual.
• If running a script (python script.py), prepend the script’s directory. If it’s a symbolic link, re-
solve symbolic links.
• En caso contrario (python -c code and python), añade una cadena vacía, que significa el direc-
torio de trabajo actual.
Set to 1 by the -P command line option and the PYTHONSAFEPATH environment variable.
Default: 0 in Python config, 1 in isolated config.
Nuevo en la versión 3.11.
wchar_t *base_exec_prefix
sys.base_exec_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.exec_prefix.
wchar_t *base_executable
Ejecutable base de Python: sys._base_executable.
Establecido por la variable de entorno __PYVENV_LAUNCHER__.
Establecido desde PyConfig.executable si NULL.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.executable.
wchar_t *base_prefix
sys.base_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.prefix.
int buffered_stdio
If equals to 0 and configure_c_stdio is non-zero, disable buffering on the C streams stdout and stderr.
Set to 0 by the -u command line option and the PYTHONUNBUFFERED environment variable.
stdin siempre se abre en modo de búfer.
Predeterminado: 1.
int bytes_warning
If equals to 1, issue a warning when comparing bytes or bytearray with str, or comparing bytes
with int.
If equal or greater to 2, raise a BytesWarning exception in these cases.
Incrementado por la opción de línea de comando -b.
Predeterminado: 0.
int warn_default_encoding
Si no es cero, emite una advertencia EncodingWarning cuando io.TextIOWrapper usa su codifica-
ción predeterminada. Consulte io-encoding-warning para obtener más detalles.
Predeterminado: 0.
Nuevo en la versión 3.10.
int code_debug_ranges
If equals to 0, disables the inclusion of the end line and column mappings in code objects. Also disables
traceback printing carets to specific error locations.
Set to 0 by the PYTHONNODEBUGRANGES environment variable and by the -X no_debug_ranges
command line option.
Predeterminado: 1.
Nuevo en la versión 3.11.
wchar_t *check_hash_pycs_mode
Controla el comportamiento de validación de archivos .pyc basados en hash: valor de la opción de línea de
comando --check-hash-based-pycs.
Valores válidos:
• L"always": Calcula el hash el archivo fuente para invalidación independientemente del valor de la
marca “check_source”.
• L"never": suponga que los pycs basados en hash siempre son válidos.
• L"default": El indicador “check_source” en pycs basados en hash determina la invalidación.
Predeterminado: L"default".
Consulte también PEP 552 «Pycs deterministas».
int configure_c_stdio
Si es distinto de cero, configure los flujos estándar de C:
• En Windows, configure el modo binario (O_BINARY) en stdin, stdout y stderr.
• Si buffered_stdio es igual a cero, deshabilite el almacenamiento en búfer de los flujos stdin, stdout
y stderr.
• Si interactive no es cero, habilite el almacenamiento en búfer de flujo en stdin y stdout (solo stdout
en Windows).
Predeterminado: 1 en la configuración de Python, 0 en la configuración aislada.
int dev_mode
Si es distinto de cero, habilita Modo de desarrollo de Python.
Set to 1 by the -X dev option and the PYTHONDEVMODE environment variable.
Por defecto: -1 en modo Python, 0 en modo aislado.
int dump_refs
Dump Python references?
Si no es cero, volcar todos los objetos que aún están vivos en la salida.
Establecido en 1 por la variable de entorno PYTHONDUMPREFS.
Needs a special build of Python with the Py_TRACE_REFS macro defined: see the configure
--with-trace-refs option.
Predeterminado: 0.
wchar_t *exec_prefix
El prefijo de directorio específico del sitio donde se instalan los archivos Python dependientes de la plataforma:
sys.exec_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.base_exec_prefix.
wchar_t *executable
La ruta absoluta del binario ejecutable para el intérprete de Python: sys.executable.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.base_executable.
int faulthandler
¿Habilitar administrador de fallas?
Si no es cero, llama a faulthandler.enable() al inicio.
Establecido en 1 por -X faulthandler y la variable de entorno PYTHONFAULTHANDLER.
Por defecto: -1 en modo Python, 0 en modo aislado.
wchar_t *filesystem_encoding
Codificación del sistema de archvios: sys.getfilesystemencoding().
En macOS, Android y VxWorks: use "utf-8" de forma predeterminada.
En Windows: utilice "utf-8" de forma predeterminada o "mbcs" si
legacy_windows_fs_encoding de PyPreConfig no es cero.
Codificación predeterminada en otras plataformas:
• "utf-8" si PyPreConfig.utf8_mode es distinto de cero.
• "ascii" if Python detects that nl_langinfo(CODESET) announces the ASCII encoding, whereas
the mbstowcs() function decodes from a different encoding (usually Latin1).
• "utf-8" si nl_langinfo(CODESET) retorna una cadena vacía.
• De lo contrario, utilice el resultado locale encoding: nl_langinfo(CODESET).
Al inicio de Python, el nombre de codificación se normaliza al nombre del códec de Python. Por ejemplo,
"ANSI_X3.4-1968" se reemplaza por "ascii".
Consulte también el miembro filesystem_errors.
wchar_t *filesystem_errors
Manejador de errores del sistema de archivos: sys.getfilesystemencodeerrors().
En Windows: utilice "surrogatepass" de forma predeterminada o "replace" si
legacy_windows_fs_encoding de PyPreConfig no es cero.
En otras plataformas: utilice "surrogateescape" de forma predeterminada.
Controladores de errores admitidos:
• "strict"
• "surrogateescape"
• "surrogatepass" (solo compatible con la codificación UTF-8)
Consulte también el miembro filesystem_encoding.
unsigned long hash_seed
int use_hash_seed
Funciones de semillas aleatorias hash.
Si use_hash_seed es cero, se elige una semilla al azar en el inicio de Python y se ignora hash_seed.
Establecido por la variable de entorno PYTHONHASHSEED.
Valor predeterminado de use_hash_seed: -1 en modo Python, 0 en modo aislado.
wchar_t *home
Set the default Python «home» directory, that is, the location of the standard Python libraries (see
PYTHONHOME).
Establecido por la variable de entorno PYTHONHOME.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
int import_time
Si no es cero, el tiempo de importación del perfil.
Configure el 1 mediante la opción -X importtime y la variable de entorno
PYTHONPROFILEIMPORTTIME.
Predeterminado: 0.
int inspect
Ingresa al modo interactivo después de ejecutar un script o un comando.
If greater than 0, enable inspect: when a script is passed as first argument or the -c option is used, enter
interactive mode after executing the script or the command, even when sys.stdin does not appear to be
a terminal.
Incrementado por la opción de línea de comando -i. Establecido en 1 si la variable de entorno
PYTHONINSPECT no está vacía.
Predeterminado: 0.
int install_signal_handlers
¿Instalar controladores de señales de Python?
Por defecto: 1 en modo Python, 0 en modo aislado.
int interactive
If greater than 0, enable the interactive mode (REPL).
Incrementado por la opción de línea de comando -i.
Predeterminado: 0.
int int_max_str_digits
Configures the integer string conversion length limitation. An initial value of -1 means the value will
be taken from the command line or environment or otherwise default to 4300 (sys.int_info.
default_max_str_digits). A value of 0 disables the limitation. Values greater than zero but less
than 640 (sys.int_info.str_digits_check_threshold) are unsupported and will produce an
error.
Configured by the -X int_max_str_digits command line flag or the PYTHONINTMAXSTRDIGITS
environment variable.
Default: -1 in Python mode. 4300 (sys.int_info.default_max_str_digits) in isolated mode.
Nuevo en la versión 3.12.
int cpu_count
If the value of cpu_count is not -1 then it will override the return values of os.cpu_count(), os.
process_cpu_count(), and multiprocessing.cpu_count().
Configured by the -X cpu_count=n|default command line flag or the PYTHON_CPU_COUNT en-
vironment variable.
Default: -1.
Nuevo en la versión 3.13.
int isolated
If greater than 0, enable isolated mode:
• Set safe_path to 1: don’t prepend a potentially unsafe path to sys.path at Python startup, such as
the current directory, the script’s directory or an empty string.
• Set use_environment to 0: ignore PYTHON environment variables.
• Set user_site_directory to 0: don’t add the user site directory to sys.path.
• Python REPL no importa readline ni habilita la configuración predeterminada de readline en men-
sajes interactivos.
Set to 1 by the -I command line option.
Por defecto: 0 en modo Python, 1 en modo aislado.
See also the Isolated Configuration and PyPreConfig.isolated.
int legacy_windows_stdio
If non-zero, use io.FileIO instead of io._WindowsConsoleIO for sys.stdin, sys.stdout
and sys.stderr.
Establecido en 1 si la variable de entorno PYTHONLEGACYWINDOWSSTDIO está establecida en una cadena
no vacía.
Solo disponible en Windows. La macro #ifdef MS_WINDOWS se puede usar para el código específico de
Windows.
Predeterminado: 0.
Consulte también PEP 528 (Cambiar la codificación de la consola de Windows a UTF-8).
int malloc_stats
Si no es cero, volcar las estadísticas en Asignador de memoria Python pymalloc en la salida.
Establecido en 1 por la variable de entorno PYTHONMALLOCSTATS.
La opción se ignora si Python es configurado usando la opción --without-pymalloc.
Predeterminado: 0.
wchar_t *platlibdir
Nombre del directorio de la biblioteca de la plataforma: sys.platlibdir.
Establecido por la variable de entorno PYTHONPLATLIBDIR.
Default: value of the PLATLIBDIR macro which is set by the configure --with-platlibdir
option (default: "lib", or "DLLs" on Windows).
Parte de la entrada Python Path Configuration.
Nuevo en la versión 3.9.
Distinto en la versión 3.11: Esta macro se utiliza ahora en Windows para localizar los módulos de extensión
de la biblioteca estándar, normalmente en DLLs. Sin embargo, por compatibilidad, tenga en cuenta que este
valor se ignora para cualquier disposición no estándar, incluyendo las construcciones dentro del árbol y los
entornos virtuales.
wchar_t *pythonpath_env
Module search paths (sys.path) as a string separated by DELIM (os.pathsep).
Establecido por la variable de entorno PYTHONPATH.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
PyWideStringList module_search_paths
int module_search_paths_set
Rutas de búsqueda del módulo: sys.path.
If module_search_paths_set is equal to 0, Py_InitializeFromConfig() will replace
module_search_paths and sets module_search_paths_set to 1.
Por defecto: lista vacía (module_search_paths) y 0 (module_search_paths_set).
Parte de la salida Python Path Configuration.
int optimization_level
Nivel de optimización de compilación:
• 0: Optimizador de mirilla, configure __debug__ en True.
• 1: Nivel 0, elimina las aserciones, establece __debug__ en False.
• 2: Nivel 1, elimina docstrings.
Incrementado por la opción de línea de comando -O. Establecido en el valor de la variable de entorno
PYTHONOPTIMIZE.
Predeterminado: 0.
PyWideStringList orig_argv
La lista de los argumentos originales de la línea de comandos pasados al ejecutable de Python: sys.
orig_argv.
Si la lista orig_argv está vacía y argv no es una lista que solo contiene una cadena vacía,
PyConfig_Read() copia argv en orig_argv antes de modificar argv (si parse_argv no es
cero).
Consulte también el miembro argv y la función Py_GetArgcArgv().
Predeterminado: lista vacía.
Nuevo en la versión 3.10.
int parse_argv
¿Analizar los argumentos de la línea de comando?
Si es igual a 1, analiza argv de la misma forma que Python normal analiza argumentos de línea de comando
y elimina los argumentos de Python de argv.
La función PyConfig_Read() solo analiza los argumentos PyConfig.argv una vez: PyConfig.
parse_argv se establece en 2 después de analizar los argumentos. Dado que los argumentos de Python se
eliminan de PyConfig.argv, analizar los argumentos dos veces analizaría las opciones de la aplicación
como opciones de Python.
Por defecto: 1 en modo Python, 0 en modo aislado.
Distinto en la versión 3.10: Los argumentos PyConfig.argv ahora solo se analizan si PyConfig.
parse_argv es igual a 1.
int parser_debug
Parser debug mode. If greater than 0, turn on parser debugging output (for expert only, depending on com-
pilation options).
Incrementado por la opción de línea de comando -d. Establecido en el valor de la variable de entorno
PYTHONDEBUG.
Needs a debug build of Python (the Py_DEBUG macro must be defined).
Predeterminado: 0.
int pathconfig_warnings
If non-zero, calculation of path configuration is allowed to log warnings into stderr. If equals to 0, suppress
these warnings.
Por defecto: 1 en modo Python, 0 en modo aislado.
Parte de la entrada Python Path Configuration.
Distinto en la versión 3.11: Ahora también se aplica en Windows.
wchar_t *prefix
El prefijo de directorio específico del sitio donde se instalan los archivos Python independientes de la plata-
forma: sys.prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.base_prefix.
wchar_t *program_name
Nombre del programa utilizado para inicializar executable y en los primeros mensajes de error durante
la inicialización de Python.
• En macOS, usa la variable de entorno PYTHONEXECUTABLE si está configurada.
• Si se define la macro WITH_NEXT_FRAMEWORK, utiliza la variable de entorno
__PYVENV_LAUNCHER__ si está configurada.
• Utiliza argv[0] de argv si está disponible y no está vacío.
• De lo contrario, utiliza L"python" en Windows o L"python3" en otras plataformas.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
wchar_t *pycache_prefix
Directorio donde se escriben los archivos .pyc almacenados en caché: sys.pycache_prefix.
Set by the -X pycache_prefix=PATH command line option and the PYTHONPYCACHEPREFIX en-
vironment variable. The command-line option takes precedence.
Si NULL, sys.pycache_prefix es establecido a None.
Valor predeterminado: NULL.
int quiet
Quiet mode. If greater than 0, don’t display the copyright and version at Python startup in interactive mode.
Incrementado por la opción de línea de comando -q.
Predeterminado: 0.
wchar_t *run_command
Valor de la opción de línea de comando -c.
Usado por Py_RunMain().
Valor predeterminado: NULL.
wchar_t *run_filename
Filename passed on the command line: trailing command line argument without -c or -m. It is used by the
Py_RunMain() function.
For example, it is set to script.py by the python3 script.py arg command line.
See also the PyConfig.skip_source_first_line option.
Valor predeterminado: NULL.
wchar_t *run_module
Valor de la opción de línea de comando -m.
Usado por Py_RunMain().
Valor predeterminado: NULL.
wchar_t *run_presite
package.module path to module that should be imported before site.py is run.
Set by the -X presite=package.module command-line option and the PYTHON_PRESITE envi-
ronment variable. The command-line option takes precedence.
Needs a debug build of Python (the Py_DEBUG macro must be defined).
wchar_t *stdio_errors
Codificación y errores de codificación de sys.stdin, sys.stdout y sys.stderr (pero sys.
stderr siempre usa el controlador de errores "backslashreplace").
Utilice la variable de entorno PYTHONIOENCODING si no está vacía.
Codificación predeterminada:
• "UTF-8" si PyPreConfig.utf8_mode es distinto de cero.
• De lo contrario, usa el locale encoding.
Manejador de errores predeterminado:
• En Windows: use "surrogateescape".
• "surrogateescape" si PyPreConfig.utf8_mode no es cero o si la configuración regional
LC_CTYPE es «C» o «POSIX».
• "strict" de lo contrario.
See also PyConfig.legacy_windows_stdio.
int tracemalloc
¿Habilitar tracemalloc?
Si no es cero, llama a tracemalloc.start() al inicio.
int write_bytecode
If equal to 0, Python won’t try to write .pyc files on the import of source modules.
Establecido en 0 por la opción de línea de comando -B y la variable de entorno
PYTHONDONTWRITEBYTECODE.
sys.dont_write_bytecode se inicializa al valor invertido de write_bytecode.
Predeterminado: 1.
PyWideStringList xoptions
Valores de las opciones de la línea de comando -X: sys._xoptions.
Predeterminado: lista vacía.
Si parse_argv no es cero, los argumentos de argv se analizan de la misma forma que Python normal analiza argu-
mentos de línea de comando, y los argumentos de Python se eliminan de argv.
Las opciones de xoptions se analizan para establecer otras opciones: consulte la opción de línea de comando -X.
Distinto en la versión 3.9: El campo show_alloc_count fue removido.
PyConfig config;
PyConfig_InitPythonConfig(&config);
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
(continúe en la próxima página)
exception:
PyConfig_Clear(&config);
Py_ExitStatusException(status);
}
More complete example modifying the default configuration, read the configuration, and then override some parameters.
Note that since 3.11, many parameters are not calculated until initialization, and so values cannot be read from the
configuration structure. Any values set before initialize is called will be left unchanged by initialization:
PyConfig config;
PyConfig_InitPythonConfig(&config);
status = Py_InitializeFromConfig(&config);
done:
PyConfig_Clear(&config);
return status;
}
10.11 Py_RunMain()
int Py_RunMain(void)
Ejecuta el comando (PyConfig.run_command), el script (PyConfig.run_filename) o el módulo
(PyConfig.run_module) especificado en la línea de comando o en la configuración.
Por defecto y cuando se usa la opción -i, ejecuta el REPL.
Finalmente, finaliza Python y retorna un estado de salida que se puede pasar a la función exit().
Consulte Configuración de Python para ver un ejemplo de Python personalizado que siempre se ejecuta en modo aislado
usando Py_RunMain().
10.12 Py_GetArgcArgv()
This section is a private provisional API introducing multi-phase initialization, the core feature of PEP 432:
• Fase de inicialización «Core», «Python mínimo»:
– Tipos incorporados;
– Excepciones incorporadas;
– Módulos incorporados y congelados;
– El módulo sys solo se inicializa parcialmente (por ejemplo sys.path aún no existe).
• Fase de inicialización «principal», Python está completamente inicializado:
– Instala y configura importlib;
– Aplique la Configuración de ruta;
– Instala manejadores de señal;
– Finaliza la inicialización del módulo sys (por ejemplo: crea sys.stdout y sys.path);
– Habilita características opcionales como faulthandler y tracemalloc;
– Importe el módulo site;
– etc.
API provisional privada:
• PyConfig._init_main: if set to 0, Py_InitializeFromConfig() stops at the «Core» initialization
phase.
PyStatus _Py_InitializeMain(void)
Vaya a la fase de inicialización «Principal», finalice la inicialización de Python.
No se importa ningún módulo durante la fase «Core» y el módulo importlib no está configurado: la Configuración
de ruta solo se aplica durante la fase «Principal». Puede permitir personalizar Python en Python para anular o ajustar
Configuración de ruta, tal vez instale un importador personalizado sys.meta_path o un enlace de importación, etc.
It may become possible to calculate the Path Configuration in Python, after the Core phase and before the Main phase,
which is one of the PEP 432 motivation.
La fase «Núcleo» no está definida correctamente: lo que debería estar y lo que no debería estar disponible en esta fase
aún no se ha especificado. La API está marcada como privada y provisional: la API se puede modificar o incluso eliminar
en cualquier momento hasta que se diseñe una API pública adecuada.
Ejemplo de ejecución de código Python entre las fases de inicialización «Core» y «Main»:
void init_python(void)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
config._init_main = 0;
status = Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
status = _Py_InitializeMain();
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
}
Gestión de la memoria
La gestión de memoria en Python implica un montón privado que contiene todos los objetos de Python y estructuras de
datos. El administrador de memoria de Python garantiza internamente la gestión de este montón privado. El administra-
dor de memoria de Python tiene diferentes componentes que se ocupan de varios aspectos de la gestión dinámica del
almacenamiento, como compartir, segmentación, asignación previa o almacenamiento en caché.
En el nivel más bajo, un asignador de memoria sin procesar asegura que haya suficiente espacio en el montón privado
para almacenar todos los datos relacionados con Python al interactuar con el administrador de memoria del sistema
operativo. Además del asignador de memoria sin procesar, varios asignadores específicos de objeto operan en el mismo
montón e implementan políticas de administración de memoria distintas adaptadas a las peculiaridades de cada tipo de
objeto. Por ejemplo, los objetos enteros se administran de manera diferente dentro del montón que las cadenas, tuplas
o diccionarios porque los enteros implican diferentes requisitos de almacenamiento y compensaciones de velocidad /
espacio. El administrador de memoria de Python delega parte del trabajo a los asignadores específicos de objeto, pero
asegura que este último opere dentro de los límites del montón privado.
Es importante comprender que la gestión del montón de Python la realiza el propio intérprete y que el usuario no tiene
control sobre él, incluso si manipulan regularmente punteros de objetos a bloques de memoria dentro de ese montón. El
administrador de memoria de Python realiza la asignación de espacio de almacenamiento dinámico para los objetos de
Python y otros búferes internos a pedido a través de las funciones de API de Python/C enumeradas en este documento.
Para evitar daños en la memoria, los escritores de extensiones nunca deberían intentar operar en objetos Python con las
funciones exportadas por la biblioteca C: malloc(), calloc(), realloc() y free(). Esto dará como resultado
llamadas mixtas entre el asignador de C y el administrador de memoria de Python con consecuencias fatales, ya que
implementan diferentes algoritmos y operan en diferentes montones. Sin embargo, uno puede asignar y liberar de forma
segura bloques de memoria con el asignador de la biblioteca C para fines individuales, como se muestra en el siguiente
ejemplo:
PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
(continúe en la próxima página)
261
The Python/C API, Versión 3.13.0a5
En este ejemplo, la solicitud de memoria para el búfer de E/S es manejada por el asignador de la biblioteca C. El admi-
nistrador de memoria de Python solo participa en la asignación del objeto de bytes retornado como resultado.
Sin embargo, en la mayoría de las situaciones, se recomienda asignar memoria del montón de Python específicamente
porque este último está bajo el control del administrador de memoria de Python. Por ejemplo, esto es necesario cuando
el intérprete se amplía con nuevos tipos de objetos escritos en C. Otra razón para usar el montón de Python es el deseo
de informar al administrador de memoria de Python sobre las necesidades de memoria del módulo de extensión. Incluso
cuando la memoria solicitada se usa exclusivamente para fines internos y altamente específicos, delegar todas las solicitudes
de memoria al administrador de memoria de Python hace que el intérprete tenga una imagen más precisa de su huella
de memoria en su conjunto. En consecuencia, bajo ciertas circunstancias, el administrador de memoria de Python puede
o no desencadenar acciones apropiadas, como recolección de basura, compactación de memoria u otros procedimientos
preventivos. Tenga en cuenta que al usar el asignador de la biblioteca C como se muestra en el ejemplo anterior, la memoria
asignada para el búfer de E/S escapa completamente al administrador de memoria Python.
Ver también:
La variable de entorno PYTHONMALLOC puede usarse para configurar los asignadores de memoria utilizados por Python.
La variable de entorno PYTHONMALLOCSTATS se puede utilizar para imprimir estadísticas de asignador de memoria
pymalloc cada vez que se crea un nuevo escenario de objetos pymalloc, y en el apagado.
Todas las funciones de asignación pertenecen a uno de los tres «dominios» diferentes (ver también
PyMemAllocatorDomain). Estos dominios representan diferentes estrategias de asignación y están optimiza-
dos para diferentes propósitos. Los detalles específicos sobre cómo cada dominio asigna memoria o qué funciones
internas llama cada dominio se considera un detalle de implementación, pero para fines de depuración, se puede
encontrar una tabla simplificada en here. No existe un requisito estricto para usar la memoria retornada por las funciones
de asignación que pertenecen a un dominio dado solo para los propósitos sugeridos por ese dominio (aunque esta es la
práctica recomendada). Por ejemplo, se podría usar la memoria retornada por PyMem_RawMalloc() para asignar
objetos Python o la memoria retornada por PyObject_Malloc() para asignar memoria para búferes.
Los tres dominios de asignación son:
• Dominio sin formato: destinado a asignar memoria para búferes de memoria de uso general donde la asignación
debe ir al asignador del sistema o donde el asignador puede operar sin el GIL. La memoria se solicita directamente
al sistema.
• Dominio «Mem»: destinado a asignar memoria para búferes de Python y búferes de memoria de propósito general
donde la asignación debe realizarse con el GIL retenido. La memoria se toma del montículo privado de Python.
• Dominio de objeto: destinado a asignar memoria perteneciente a objetos de Python. La memoria se toma del
montículo privado de Python.
Cuando se libera memoria previamente asignada por las funciones de asignación que pertenecen a un dominio dado, se
deben utilizar las funciones de desasignación específicas coincidentes. Por ejemplo, PyMem_Free() debe usarse para
liberar memoria asignada usando PyMem_Malloc().
Los siguientes conjuntos de funciones son envoltorios para el asignador del sistema. Estas funciones son seguras para
subprocesos, no es necesario mantener el GIL.
The default raw memory allocator uses the following functions: malloc(), calloc(), realloc() and free();
call malloc(1) (or calloc(1, 1)) when requesting zero bytes.
Nuevo en la versión 3.4.
void *PyMem_RawMalloc(size_t n)
Part of the Stable ABI since version 3.13. Asigna n bytes y retorna un puntero de tipo void* a la memoria asignada,
o NULL si la solicitud falla.
Solicitar cero bytes retorna un puntero distinto que no sea NULL si es posible, como si en su lugar se hubiera llamado
a PyMem_RawMalloc(1). La memoria no se habrá inicializado de ninguna manera.
void *PyMem_RawCalloc(size_t nelem, size_t elsize)
Part of the Stable ABI since version 3.13. Asigna nelem elementos cada uno cuyo tamaño en bytes es elsize y retorna
un puntero de tipo void* a la memoria asignada, o NULL si la solicitud falla. La memoria se inicializa a ceros.
Solicitar elementos cero o elementos de tamaño cero bytes retorna un puntero distinto NULL si es posible, como si
en su lugar se hubiera llamado PyMem_RawCalloc(1, 1).
Nuevo en la versión 3.5.
void *PyMem_RawRealloc(void *p, size_t n)
Part of the Stable ABI since version 3.13. Cambia el tamaño del bloque de memoria señalado por p a n bytes. Los
contenidos no se modificarán al mínimo de los tamaños antiguo y nuevo.
Si p es NULL, la llamada es equivalente a PyMem_RawMalloc(n); de lo contrario, si n es igual a cero, el bloque
de memoria cambia de tamaño pero no se libera, y el puntero retornado no es NULL.
A menos que p sea NULL, debe haber sido retornado por una llamada previa a PyMem_RawMalloc(),
PyMem_RawRealloc() o PyMem_RawCalloc().
Si la solicitud falla, PyMem_RawRealloc() retorna NULL y p sigue siendo un puntero válido al área de memoria
anterior.
void PyMem_RawFree(void *p)
Part of the Stable ABI since version 3.13. Libera el bloque de memoria al que apunta p, que debe haber sido retornado
por una llamada anterior a PyMem_RawMalloc(), PyMem_RawRealloc() o PyMem_RawCalloc(). De
lo contrario, o si se ha llamado antes a PyMem_RawFree(p), se produce un comportamiento indefinido.
Si p es NULL, no se realiza ninguna operación.
Los siguientes conjuntos de funciones, modelados según el estándar ANSI C, pero que especifican el comportamiento
cuando se solicitan cero bytes, están disponibles para asignar y liberar memoria del montón de Python.
El asignador de memoria predeterminado usa el asignador de memorya pymalloc.
Distinto en la versión 3.6: El asignador predeterminado ahora es pymalloc en lugar del malloc() del sistema.
void *PyMem_Malloc(size_t n)
Part of the Stable ABI. Asigna n bytes y retorna un puntero de tipo void* a la memoria asignada, o NULL si la
solicitud falla.
Solicitar cero bytes retorna un puntero distinto que no sea NULL si es posible, como si en su lugar se hubiera llamado
a PyMem_Malloc(1). La memoria no se habrá inicializado de ninguna manera.
void *PyMem_Calloc(size_t nelem, size_t elsize)
Part of the Stable ABI since version 3.7. Asigna nelem elementos cada uno cuyo tamaño en bytes es elsize y retorna
un puntero de tipo void* a la memoria asignada, o NULL si la solicitud falla. La memoria se inicializa a ceros.
Solicitar elementos cero o elementos de tamaño cero bytes retorna un puntero distinto NULL si es posible, como si
en su lugar se hubiera llamado PyMem_Calloc(1, 1).
Nuevo en la versión 3.5.
void *PyMem_Realloc(void *p, size_t n)
Part of the Stable ABI. Cambia el tamaño del bloque de memoria señalado por p a n bytes. Los contenidos no se
modificarán al mínimo de los tamaños antiguo y nuevo.
Si p es NULL, la llamada es equivalente a PyMem_Malloc(n); de lo contrario, si n es igual a cero, el bloque de
memoria cambia de tamaño pero no se libera, y el puntero retornado no es NULL.
A menos que p sea NULL, debe haber sido retornado por una llamada previa a PyMem_Malloc(),
PyMem_Realloc() o PyMem_Calloc().
Si la solicitud falla, PyMem_Realloc() retorna NULL y p sigue siendo un puntero válido al área de memoria
anterior.
void PyMem_Free(void *p)
Part of the Stable ABI. Libera el bloque de memoria señalado por p, que debe haber sido retornado por una llamada
anterior a PyMem_Malloc(), PyMem_Realloc() o PyMem_Calloc(). De lo contrario, o si se ha llamado
antes a PyMem_Free(p), se produce un comportamiento indefinido.
Si p es NULL, no se realiza ninguna operación.
Las siguientes macros orientadas a tipos se proporcionan por conveniencia. Tenga en cuenta que TYPE se refiere a cualquier
tipo de C.
PyMem_New(TYPE, n)
Same as PyMem_Malloc(), but allocates (n * sizeof(TYPE)) bytes of memory. Returns a pointer cast
to TYPE*. The memory will not have been initialized in any way.
PyMem_Resize(p, TYPE, n)
Same as PyMem_Realloc(), but the memory block is resized to (n * sizeof(TYPE)) bytes. Returns a
pointer cast to TYPE*. On return, p will be a pointer to the new memory area, or NULL in the event of failure.
Esta es una macro de preprocesador C; p siempre se reasigna. Guarde el valor original de p para evitar perder
memoria al manejar errores.
void PyMem_Del(void *p)
La misma que PyMem_Free().
Además, se proporcionan los siguientes conjuntos de macros para llamar al asignador de memoria de Python directamente,
sin involucrar las funciones de API de C mencionadas anteriormente. Sin embargo, tenga en cuenta que su uso no conserva
la compatibilidad binaria entre las versiones de Python y, por lo tanto, está en desuso en los módulos de extensión.
• PyMem_MALLOC(size)
• PyMem_NEW(type, size)
• PyMem_REALLOC(ptr, size)
Los siguientes conjuntos de funciones, modelados según el estándar ANSI C, pero que especifican el comportamiento
cuando se solicitan cero bytes, están disponibles para asignar y liberar memoria del montón de Python.
Nota: No hay garantía de que la memoria retornada por estos asignadores se pueda convertir con éxito en un objeto
Python al interceptar las funciones de asignación en este dominio mediante los métodos descritos en la sección Personalizar
Asignadores de Memoria.
void *PyObject_Malloc(size_t n)
Part of the Stable ABI. Asigna n bytes y retorna un puntero de tipo void* a la memoria asignada, o NULL si la
solicitud falla.
Solicitar cero bytes retorna un puntero distinto que no sea NULL si es posible, como si en su lugar se hubiera llamado
a PyObject_Malloc(1). La memoria no se habrá inicializado de ninguna manera.
void *PyObject_Calloc(size_t nelem, size_t elsize)
Part of the Stable ABI since version 3.7. Asigna nelem elementos cada uno cuyo tamaño en bytes es elsize y retorna
un puntero de tipo void* a la memoria asignada, o NULL si la solicitud falla. La memoria se inicializa a ceros.
Solicitar elementos cero o elementos de tamaño cero bytes retorna un puntero distinto NULL si es posible, como si
en su lugar se hubiera llamado PyObject_Calloc(1, 1).
Nuevo en la versión 3.5.
void *PyObject_Realloc(void *p, size_t n)
Part of the Stable ABI. Cambia el tamaño del bloque de memoria señalado por p a n bytes. Los contenidos no se
modificarán al mínimo de los tamaños antiguo y nuevo.
Si p es NULL, la llamada es equivalente a PyObject_Malloc(n); de lo contrario, si n es igual a cero, el bloque
de memoria cambia de tamaño pero no se libera, y el puntero retornado no es NULL.
A menos que p sea NULL, debe haber sido retornado por una llamada previa a PyObject_Malloc(),
PyObject_Realloc() o PyObject_Calloc().
Si la solicitud falla, PyObject_Realloc() retorna NULL y p sigue siendo un puntero válido al área de memoria
anterior.
void PyObject_Free(void *p)
Part of the Stable ABI. Libera el bloque de memoria al que apunta p, que debe haber sido retornado por una llamada
anterior a PyObject_Malloc(), PyObject_Realloc() o PyObject_Calloc(). De lo contrario, o
si se ha llamado antes a PyObject_Free(p), se produce un comportamiento indefinido.
Si p es NULL, no se realiza ninguna operación.
Leyenda:
• Nombre: valor para variable de entorno PYTHONMALLOC.
• malloc: asignadores del sistema de la biblioteca C estándar, funciones C: malloc(), calloc(), realloc()
y free().
• pymalloc: asignador de memoria pymalloc.
• mimalloc: mimalloc memory allocator. The pymalloc allocator will be used if mimalloc support isn’t available.
• «+ debug»: con enlaces de depuración en los asignadores de memoria de Python.
• «Debug build»: Compilación de Python en modo de depuración.
Campo Significado
void *ctx contexto de usuario pasado como primer ar-
gumento
void* malloc(void *ctx, size_t size) asignar un bloque de memoria
void* calloc(void *ctx, size_t nelem, asignar un bloque de memoria inicializado
size_t elsize) con ceros
void* realloc(void *ctx, void *ptr, asignar o cambiar el tamaño de un bloque de
size_t new_size) memoria
void free(void *ctx, void *ptr) liberar un bloque de memoria
Distinto en la versión 3.5: The PyMemAllocator structure was renamed to PyMemAllocatorEx and a new
calloc field was added.
type PyMemAllocatorDomain
Enum se utiliza para identificar un dominio asignador. Dominios:
PYMEM_DOMAIN_RAW
Funciones:
• PyMem_RawMalloc()
• PyMem_RawRealloc()
• PyMem_RawCalloc()
• PyMem_RawFree()
PYMEM_DOMAIN_MEM
Funciones:
• PyMem_Malloc(),
• PyMem_Realloc()
• PyMem_Calloc()
• PyMem_Free()
PYMEM_DOMAIN_OBJ
Funciones:
• PyObject_Malloc()
• PyObject_Realloc()
• PyObject_Calloc()
• PyObject_Free()
void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Obtenga el asignador de bloque de memoria del dominio especificado.
void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Establece el asignador de bloque de memoria del dominio especificado.
El nuevo asignador debe retornar un puntero distinto NULL al solicitar cero bytes.
For the PYMEM_DOMAIN_RAW domain, the allocator must be thread-safe: the GIL is not held when the allocator
is called.
For the remaining domains, the allocator must also be thread-safe: the allocator may be called in different inter-
preters that do not share a GIL.
Si el nuevo asignador no es un enlace (no llama al asignador anterior), se debe llamar a la función
PyMem_SetupDebugHooks() para reinstalar los enlaces de depuración en la parte superior del nuevo asigna-
dor.
Vea también PyPreConfig.allocator y Preinicialización de Python con PyPreConfig.
Cuando Python está construido en modo de depuración, la función PyMem_SetupDebugHooks() se llama en Preini-
cialización de Python para configurar los enlaces de depuración en Python asignadores de memoria para detectar errores
de memoria.
La variable de entorno PYTHONMALLOC se puede utilizar para instalar enlaces de depuración en un Python compilado
en modo de lanzamiento (por ejemplo: PYTHONMALLOC=debug).
La función PyMem_SetupDebugHooks() se puede utilizar para establecer enlaces de depuración después de llamar
a PyMem_SetAllocator().
Estos enlaces de depuración llenan bloques de memoria asignados dinámicamente con patrones de bits especiales y reco-
nocibles. La memoria recién asignada se llena con el byte 0xCD (PYMEM_CLEANBYTE), la memoria liberada se llena
con el byte 0xDD (PYMEM_DEADBYTE). Los bloques de memoria están rodeados por «bytes prohibidos» rellenos con
el byte 0xFD (PYMEM_FORBIDDENBYTE). Es poco probable que las cadenas de estos bytes sean direcciones válidas,
flotantes o cadenas ASCII.
Verificaciones de tiempo de ejecución:
• Detecte violaciones de API, por ejemplo: PyObject_Free() llamado en un búfer asignado por
PyMem_Malloc().
• Detectar escritura antes del inicio del búfer (desbordamiento del búfer)
• Detectar escritura después del final del búfer (desbordamiento del búfer)
• Check that the GIL is held when allocator functions of PYMEM_DOMAIN_OBJ (ex: PyObject_Malloc())
and PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) domains are called.
En caso de error, los enlaces de depuración usan el módulo tracemalloc para obtener el rastreo donde se asignó un
bloque de memoria. El rastreo solo se muestra si tracemalloc rastrea las asignaciones de memoria de Python y se
rastrea el bloque de memoria.
Sea S = sizeof(size_t). Se agregan 2*S bytes en cada extremo de cada bloque de N bytes solicitados. El diseño de
la memoria es así, donde p representa la dirección retornada por una función similar a malloc o realloc (p[i:j] significa
el segmento de bytes de *(p+i) inclusive hasta *(p+j) exclusivo; tenga en cuenta que el tratamiento de los índices
negativos difiere de un segmento de Python):
p[-2*S:-S]
Número de bytes solicitados originalmente. Este es un size_t, big-endian (más fácil de leer en un volcado de me-
moria).
p[-S]
Identificador de API (carácter ASCII):
• 'r' for PYMEM_DOMAIN_RAW.
• 'm' for PYMEM_DOMAIN_MEM .
• 'o' for PYMEM_DOMAIN_OBJ.
p[-S+1:0]
Copias de PYMEM_FORBIDDENBYTE. Se utiliza para detectar suscripciones y lecturas.
p[0:N]
La memoria solicitada, llena de copias de PYMEM_CLEANBYTE, utilizada para capturar la referencia a la me-
moria no inicializada. Cuando se llama a una función similar a realloc solicitando un bloque de memoria más
grande, los nuevos bytes en exceso también se llenan con PYMEM_CLEANBYTE. Cuando se llama a una fun-
ción de tipo free, se sobrescriben con PYMEM_DEADBYTE, para captar la referencia a la memoria liberada.
Cuando se llama a una función similar a la realloc solicitando un bloque de memoria más pequeño, los bytes
antiguos sobrantes también se llenan con PYMEM_DEADBYTE.
p[N:N+S]
Copias de PYMEM_FORBIDDENBYTE. Se utiliza para detectar sobrescrituras y lecturas.
p[N+S:N+2*S]
Solo se utiliza si la macro PYMEM_DEBUG_SERIALNO está definida (no definida por defecto).
A serial number, incremented by 1 on each call to a malloc-like or realloc-like function. Big-endian size_t. If
«bad memory» is detected later, the serial number gives an excellent way to set a breakpoint on the next run, to
capture the instant at which this block was passed out. The static function bumpserialno() in obmalloc.c is the only
place the serial number is incremented, and exists so you can set such a breakpoint easily.
Una función de tipo realloc o de tipo free primero verifica que los bytes PYMEM_FORBIDDENBYTE en cada extremo
estén intactos. Si se han modificado, la salida de diagnóstico se escribe en stderr y el programa se aborta mediante
Py_FatalError(). El otro modo de falla principal es provocar un error de memoria cuando un programa lee uno de los
patrones de bits especiales e intenta usarlo como una dirección. Si ingresa a un depurador y observa el objeto, es probable
que vea que está completamente lleno de PYMEM_DEADBYTE (lo que significa que se está usando la memoria liberada)
o PYMEM_CLEANBYTE (que significa que se está usando la memoria no inicializada).
Distinto en la versión 3.6: The PyMem_SetupDebugHooks() function now also works on Python compiled in release
mode. On error, the debug hooks now use tracemalloc to get the traceback where a memory block was allocated. The
debug hooks now also check if the GIL is held when functions of PYMEM_DOMAIN_OBJ and PYMEM_DOMAIN_MEM
domains are called.
Distinto en la versión 3.8: Los patrones de bytes 0xCB (PYMEM_CLEANBYTE), 0xDB (PYMEM_DEADBYTE) y 0xFB
(PYMEM_FORBIDDENBYTE) se han reemplazado por 0xCD, 0xDD y 0xFD para usar los mismos valores que la depu-
ración de Windows CRT malloc() y free().
Python has a pymalloc allocator optimized for small objects (smaller or equal to 512 bytes) with a short lifetime. It uses
memory mappings called «arenas» with a fixed size of either 256 KiB on 32-bit platforms or 1 MiB on 64-bit platforms.
It falls back to PyMem_RawMalloc() and PyMem_RawRealloc() for allocations larger than 512 bytes.
pymalloc is the default allocator of the PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) and PYMEM_DOMAIN_OBJ
(ex: PyObject_Malloc()) domains.
El asignador de arena utiliza las siguientes funciones:
• VirtualAlloc() and VirtualFree() on Windows,
• mmap() and munmap() if available,
• malloc() y free() en caso contrario.
Este asignador está deshabilitado si Python está configurado con la opción --without-pymalloc. También
se puede deshabilitar en tiempo de ejecución usando la variable de entorno PYTHONMALLOC (por ejemplo:
PYTHONMALLOC=malloc).
Campo Significado
void *ctx contexto de usuario pasado como primer argu-
mento
void* alloc(void *ctx, size_t size) asignar una arena de bytes de tamaño
void free(void *ctx, void *ptr, size_t liberar la arena
size)
11.12 Ejemplos
Aquí está el ejemplo de la sección Visión general, reescrito para que el búfer de E/S se asigne desde el montón de Python
utilizando el primer conjunto de funciones:
PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;
PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Del(buf); /* allocated with PyMem_New */
return res;
Tenga en cuenta que en los dos ejemplos anteriores, el búfer siempre se manipula a través de funciones que pertenecen al
mismo conjunto. De hecho, es necesario usar la misma familia de API de memoria para un bloque de memoria dado, de
modo que el riesgo de mezclar diferentes asignadores se reduzca al mínimo. La siguiente secuencia de código contiene dos
errores, uno de los cuales está etiquetado como fatal porque mezcla dos asignadores diferentes que operan en montones
diferentes.:
In addition to the functions aimed at handling raw memory blocks from the Python heap, objects in Python are allocated
and released with PyObject_New, PyObject_NewVar and PyObject_Del().
Esto se explicará en el próximo capítulo sobre cómo definir e implementar nuevos tipos de objetos en C.
Este capítulo describe las funciones, los tipos y las macros utilizados al definir nuevos tipos de objetos.
273
The Python/C API, Versión 3.13.0a5
Hay un gran número de estructuras que se utilizan en la definición de los tipos de objetos de Python. Esta sección describe
estas estructuras y la forma en que se utilizan.
All Python objects ultimately share a small number of fields at the beginning of the object’s representation in memory.
These are represented by the PyObject and PyVarObject types, which are defined, in turn, by the expansions of
some macros also used, whether directly or indirectly, in the definition of all other Python objects. Additional macros can
be found under reference counting.
type PyObject
Part of the Limited API. (Only some members are part of the stable ABI.) All object types are extensions of this
type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In a
normal «release» build, it contains only the object’s reference count and a pointer to the corresponding type object.
Nothing is actually declared to be a PyObject, but every pointer to a Python object can be cast to a PyObject*.
Access to the members must be done by using the macros Py_REFCNT and Py_TYPE.
type PyVarObject
Part of the Limited API. (Only some members are part of the stable ABI.) This is an extension of PyObject that
adds the ob_size field. This is only used for objects that have some notion of length. This type does not often
appear in the Python/C API. Access to the members must be done by using the macros Py_REFCNT, Py_TYPE,
and Py_SIZE.
PyObject_HEAD
Esta es una macro utilizado cuando se declara nuevos tipos que representan objetos sin una longitud variable. La
macro PyObject_HEAD se expande a:
PyObject ob_base;
_PyObject_EXTRA_INIT
1, type,
PyVarObject_HEAD_INIT(type, size)
This is a macro which expands to initialization values for a new PyVarObject type, including the ob_size
field. This macro expands to:
_PyObject_EXTRA_INIT
1, type, size,
type PyCFunction
Part of the Stable ABI. Type of the functions used to implement most Python callables in C. Functions of this type
take two PyObject* parameters and return one such value. If the return value is NULL, an exception shall have
been set. If not NULL, the return value is interpreted as the return value of the function as exposed in Python. The
function must return a new reference.
La firma de la función es:
type PyCFunctionWithKeywords
Part of the Stable ABI. Type of the functions used to implement Python callables in C with signature
METH_VARARGS | METH_KEYWORDS. The function signature is:
type PyCFunctionFast
Part of the Stable ABI since version 3.13. Type of the functions used to implement Python callables in C with
signature METH_FASTCALL. The function signature is:
type PyCFunctionFastWithKeywords
Part of the Stable ABI since version 3.13. Type of the functions used to implement Python callables in C with
signature METH_FASTCALL | METH_KEYWORDS. The function signature is:
type PyCMethod
Type of the functions used to implement Python callables in C with signature METH_METHOD |
METH_FASTCALL | METH_KEYWORDS. The function signature is:
METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL supporting also keyword arguments, with methods of type
PyCFunctionFastWithKeywords. Keyword arguments are passed the same way as in the vectorcall
protocol: there is an additional fourth PyObject* parameter which is a tuple representing the names of the
keyword arguments (which are guaranteed to be strings) or possibly NULL if there are no keywords. The values
of the keyword arguments are stored in the args array, after the positional arguments.
Nuevo en la versión 3.7.
METH_METHOD
Can only be used in the combination with other flags: METH_METHOD | METH_FASTCALL | METH_KEYWORDS.
METH_METHOD | METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL | METH_KEYWORDS supporting the defining class, that is, the class that contains
the method in question. The defining class might be a superclass of Py_TYPE(self).
El método debe ser de tipo PyCMethod, lo mismo que para METH_FASTCALL | METH_KEYWORDS con el
argumento defining_clase añadido después de self.
Nuevo en la versión 3.9.
METH_NOARGS
Methods without parameters don’t need to check whether arguments are given if they are listed with the
METH_NOARGS flag. They need to be of type PyCFunction. The first parameter is typically named self and
will hold a reference to the module or object instance. In all cases the second parameter will be NULL.
La función debe tener 2 parámetros. Dado que el segundo parámetro no se usa, Py_UNUSED se puede usar para
evitar una advertencia del compilador.
METH_O
Methods with a single object argument can be listed with the METH_O flag, instead of invoking
PyArg_ParseTuple() with a "O" argument. They have the type PyCFunction, with the self parameter,
and a PyObject* parameter representing the single argument.
Estas dos constantes no se utilizan para indicar la convención de llamada si no la vinculación cuando su usan con méto-
dos de las clases. Estos no se pueden usar para funciones definidas para módulos. A lo sumo uno de estos flags puede
establecerse en un método dado.
METH_CLASS
Al método se le pasará el objeto tipo como primer parámetro, en lugar de una instancia del tipo. Esto se utiliza para
crear métodos de clase (class methods), similar a lo que se crea cuando se utiliza la función classmethod()
incorporada.
METH_STATIC
El método pasará NULL como el primer parámetro en lugar de una instancia del tipo. Esto se utiliza para crear
métodos estáticos (static methods), similar a lo que se crea cuando se utiliza la función staticmethod() in-
corporada.
En otros controles constantes dependiendo si se carga un método en su lugar (in place) de otra definición con el mismo
nombre del método.
METH_COEXIST
The method will be loaded in place of existing definitions. Without METH_COEXIST, the default is to skip re-
peated definitions. Since slot wrappers are loaded before the method table, the existence of a sq_contains slot, for
example, would generate a wrapped method named __contains__() and preclude the loading of a corres-
ponding PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in place of the
wrapper object and will co-exist with the slot. This is helpful because calls to PyCFunctions are optimized more
than wrapper object calls.
type PyMemberDef
Part of the Stable ABI (including all members). Structure which describes an attribute of a type which corresponds
to a C struct member. When defining a class, put a NULL-terminated array of these structures in the tp_members
slot.
Its fields are, in order:
const char *name
Name of the member. A NULL value marks the end of a PyMemberDef[] array.
The string should be static, no copy is made of it.
int type
The type of the member in the C struct. See Member types for the possible values.
Py_ssize_t offset
The offset in bytes that the member is located on the type’s object struct.
int flags
Zero or more of the Member flags, combined using bitwise OR.
const char *doc
The docstring, or NULL. The string should be static, no copy is made of it. Typically, it is defined using
PyDoc_STR.
By default (when flags is 0), members allow both read and write access. Use the Py_READONLY flag for read-
only access. Certain types, like Py_T_STRING, imply Py_READONLY. Only Py_T_OBJECT_EX (and legacy
T_OBJECT) members can be deleted.
For heap-allocated types (created using PyType_FromSpec() or similar), PyMemberDef may contain a defi-
nition for the special member "__vectorcalloffset__", corresponding to tp_vectorcall_offset
in type objects. These must be defined with Py_T_PYSSIZET and Py_READONLY, for example:
static PyMemberDef spam_type_members[] = {
{"__vectorcalloffset__", Py_T_PYSSIZET,
offsetof(Spam_object, vectorcall), Py_READONLY},
{NULL} /* Sentinel */
};
Member flags
Member types
PyMemberDef.type can be one of the following macros corresponding to various C types. When the member is
accessed in Python, it will be converted to the equivalent Python type. When it is set from Python, it will be converted
back to the C type. If that is not possible, an exception such as TypeError or ValueError is raised.
Unless marked (D), attributes defined this way cannot be deleted using e.g. del or delattr().
short int
Py_T_SHORT
int int
Py_T_INT
long int
Py_T_LONG
Py_ssize_t int
Py_T_PYSSIZET
float float
Py_T_FLOAT
double float
Py_T_DOUBLE
(*): Zero-terminated, UTF8-encoded C string. With Py_T_STRING the C representation is a pointer; with
Py_T_STRING_INPLACE the string is stored directly in the structure.
(**): String of length 1. Only ASCII is accepted.
(RO): Implies Py_READONLY.
(D): Can be deleted, in which case the pointer is set to NULL. Reading a NULL pointer raises
AttributeError.
Nuevo en la versión 3.12: In previous versions, the macros were only available with #include "structmember.h"
and were named without the Py_ prefix (e.g. as T_INT). The header is still available and contains the old names, along
with the following deprecated types:
T_OBJECT
Like Py_T_OBJECT_EX, but NULL is converted to None. This results in surprising behavior in Python: deleting
the attribute effectively sets it to None.
T_NONE
Always None. Must be used with Py_READONLY.
type PyGetSetDef
Part of the Stable ABI (including all members). Estructura para definir el acceso para un tipo como el de una
propiedad. Véase también la descripción de la ranura PyTypeObject.tp_getset.
const char *name
nombre del atributo
getter get
C function to get the attribute.
setter set
Optional C function to set or delete the attribute. If NULL, the attribute is read-only.
const char *doc
docstring opcional
void *closure
Optional user data pointer, providing additional data for getter and setter.
typedef PyObject *(*getter)(PyObject*, void*)
Part of the Stable ABI. The get function takes one PyObject* parameter (the instance) and a user data pointer
(the associated closure):
Debe retornar una nueva referencia en caso de éxito o NULL con una excepción establecida en caso de error.
typedef int (*setter)(PyObject*, PyObject*, void*)
Part of the Stable ABI. set functions take two PyObject* parameters (the instance and the value to be set) and
a user data pointer (the associated closure):
En caso de que el atributo deba suprimirse el segundo parámetro es NULL. Debe retornar 0 en caso de éxito o -1
con una excepción explícita en caso de fallo.
Perhaps one of the most important structures of the Python object system is the structure that defines a new type: the
PyTypeObject structure. Type objects can be handled using any of the PyObject_* or PyType_* functions, but
do not offer much that’s interesting to most Python applications. These objects are fundamental to how objects behave, so
they are very important to the interpreter itself and to any extension module that implements new types.
Los objetos de tipo son bastante grandes en comparación con la mayoría de los tipos estándar. La razón del tamaño es
que cada objeto de tipo almacena una gran cantidad de valores, principalmente punteros de función C, cada uno de los
cuales implementa una pequeña parte de la funcionalidad del tipo. Los campos del objeto tipo se examinan en detalle en
esta sección. Los campos se describirán en el orden en que aparecen en la estructura.
Además de la siguiente referencia rápida, la sección Ejemplos proporciona una visión rápida del significado y uso de
PyTypeObject.
<>: Names in angle brackets should be initially set to NULL and treated as read-only.
[]: Names in square brackets are for internal use only.
<R> (as a prefix) means the field is required (must be non-NULL).
2 Columnas:
sub-ranuras (sub-slots)
bf_getbuffer getbufferproc()
bf_releasebuffer releasebufferproc()
ranura de typedefs
newfunc PyObject *
PyObject *
PyObject *
PyObject *
initproc int
PyObject *
PyObject *
PyObject *
setattrfunc int
PyObject *
const char *
PyObject *
getattrofunc PyObject *
PyObject *
PyObject *
setattrofunc int
PyObject *
PyObject *
PyObject *
descrgetfunc PyObject *
PyObject *
PyObject *
PyObject *
288 Capítulo 12. Soporte de implementación de objetos
descrsetfunc int
PyObject *
The Python/C API, Versión 3.13.0a5
destructor tp_dealloc;
Py_ssize_t tp_vectorcall_offset;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
or tp_reserved (Python 3) */
reprfunc tp_repr;
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
destructor tp_finalize;
vectorcallfunc tp_vectorcall;
The type object structure extends the PyVarObject structure. The ob_size field is used for dynamic types (crea-
ted by type_new(), usually called from a class statement). Note that PyType_Type (the metatype) initializes
tp_itemsize, which means that its instances (i.e. type objects) must have the ob_size field.
Py_ssize_t PyObject.ob_refcnt
Part of the Stable ABI. This is the type object’s reference count, initialized to 1 by the PyObject_HEAD_INIT
macro. Note that for statically allocated type objects, the type’s instances (objects whose ob_type points back to
the type) do not count as references. But for dynamically allocated type objects, the instances do count as references.
Herencia:
Este campo no es heredado por los subtipos.
PyTypeObject *PyObject.ob_type
Part of the Stable ABI. Este es el tipo del tipo, en otras palabras, su metatipo. Se inicializa mediante el argumen-
to de la macro PyObject_HEAD_INIT, y su valor normalmente debería ser &PyType_Type. Sin embargo,
para los módulos de extensión cargables dinámicamente que deben ser utilizables en Windows (al menos), el com-
pilador se queja de que este no es un inicializador válido. Por lo tanto, la convención es pasar NULL al macro
PyObject_HEAD_INIT e inicializar este campo explícitamente al comienzo de la función de inicialización del
módulo, antes de hacer cualquier otra cosa. Esto normalmente se hace así:
Foo_Type.ob_type = &PyType_Type;
This should be done before any instances of the type are created. PyType_Ready() checks if ob_type is
NULL, and if so, initializes it to the ob_type field of the base class. PyType_Ready() will not change this
field if it is non-zero.
Herencia:
Este campo es heredado por subtipos.
Py_ssize_t PyVarObject.ob_size
Part of the Stable ABI. Para objetos de tipo estáticamente asignados, debe inicializarse a cero. Para objetos de tipo
dinámicamente asignados, este campo tiene un significado interno especial.
Herencia:
Este campo no es heredado por los subtipos.
Each slot has a section describing inheritance. If PyType_Ready() may set a value when the field is set to NULL
then there will also be a «Default» section. (Note that many fields set on PyBaseObject_Type and PyType_Type
effectively act as defaults.)
const char *PyTypeObject.tp_name
Pointer to a NUL-terminated string containing the name of the type. For types that are accessible as module globals,
the string should be the full module name, followed by a dot, followed by the type name; for built-in types, it should
be just the type name. If the module is a submodule of a package, the full package name is part of the full module
name. For example, a type named T defined in module M in subpackage Q in package P should have the tp_name
initializer "P.Q.M.T".
Para objetos de tipo dinámicamente asignados, éste debe ser sólo el nombre del tipo, y el nombre del módulo
almacenado explícitamente en el dict tipo que el valor de '__module__' clave.
Para objetos de tipo estáticamente asignados, el campo tp_name debe contener un punto. Todo lo que está antes del
último punto se hace accesible como el atributo __module__, y todo lo que está después del último punto se
hace accesible como el atributo __name__.
Si no hay ningún punto, todo el campo tp_name se hace accesible como el atributo __name__, y el atributo
__module__ no está definido (a menos que sea explícitamente establecido en el diccionario, como se expli-
có anteriormente). Esto significa que su tipo será imposible de guardar como pickle. Además, no figurará en la
documentación del módulo creado con pydoc.
Este campo no debe ser NULL. Es el único campo obligatorio en PyTypeObject() (que no sea potencialmente
tp_itemsize).
Herencia:
Este campo no es heredado por los subtipos.
Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize
Estos campos permiten calcular el tamaño en bytes de instancias del tipo.
Hay dos tipos de tipos: los tipos con instancias de longitud fija tienen un campo cero tp_itemsize, los tipos
con instancias de longitud variable tienen un campo distinto de cero tp_itemsize. Para un tipo con instancias
de longitud fija, todas las instancias tienen el mismo tamaño, dado en tp_basicsize.
For a type with variable-length instances, the instances must have an ob_size field, and the instance size is
tp_basicsize plus N times tp_itemsize, where N is the «length» of the object. The value of N is typically
stored in the instance’s ob_size field. There are exceptions: for example, ints use a negative ob_size to indicate
a negative number, and N is abs(ob_size) there. Also, the presence of an ob_size field in the instance layout
doesn’t mean that the instance structure is variable-length (for example, the structure for the list type has fixed-length
instances, yet those instances have a meaningful ob_size field).
The basic size includes the fields in the instance declared by the macro PyObject_HEAD or
PyObject_VAR_HEAD (whichever is used to declare the instance struct) and this in turn includes the
_ob_prev and _ob_next fields if they are present. This means that the only correct way to get an initializer
for the tp_basicsize is to use the sizeof operator on the struct used to declare the instance layout. The
basic size does not include the GC header size.
Una nota sobre la alineación: si los elementos variables requieren una alineación particular, esto debe ser atendido
por el valor de tp_basicsize. Ejemplo: supongamos que un tipo implementa un arreglo de dobles (double).
tp_itemsize es sizeof(double). Es responsabilidad del programador que tp_basicsize es un múl-
tiplo de sizeof(double) (suponiendo que este sea el requisito de alineación para double).
Para cualquier tipo con instancias de longitud variable, este campo no debe ser NULL.
Herencia:
Estos campos se heredan por separado por subtipos. Si el tipo base tiene un miembro distinto de cero
tp_itemsize, generalmente no es seguro establecer tp_itemsize en un valor diferente de cero en un subtipo
( aunque esto depende de la implementación del tipo base).
destructor PyTypeObject.tp_dealloc
Un puntero a la función destructor de instancias. Esta función debe definirse a menos que el tipo garantice que sus
instancias nunca se desasignarán (como es el caso de los singletons None y Ellipsis). La firma de la función
es:
The destructor function is called by the Py_DECREF() and Py_XDECREF() macros when the new reference
count is zero. At this point, the instance is still in existence, but there are no references to it. The destructor fun-
ction should free all references which the instance owns, free all memory buffers owned by the instance (using the
freeing function corresponding to the allocation function used to allocate the buffer), and call the type’s tp_free
function. If the type is not subtypable (doesn’t have the Py_TPFLAGS_BASETYPE flag bit set), it is permissible
to call the object deallocator directly instead of via tp_free. The object deallocator should be the one used to
allocate the instance; this is normally PyObject_Del() if the instance was allocated using PyObject_New
or PyObject_NewVar, or PyObject_GC_Del() if the instance was allocated using PyObject_GC_New
or PyObject_GC_NewVar.
If the type supports garbage collection (has the Py_TPFLAGS_HAVE_GC flag bit set), the destructor should call
PyObject_GC_UnTrack() before clearing any member fields.
Finally, if the type is heap allocated (Py_TPFLAGS_HEAPTYPE), the deallocator should release the owned refe-
rence to its type object (via Py_DECREF()) after calling the type deallocator. In order to avoid dangling pointers,
the recommended way to achieve this is:
Herencia:
Este campo es heredado por subtipos.
Py_ssize_t PyTypeObject.tp_vectorcall_offset
Un desplazamiento opcional a una función por instancia que implementa la llamada al objeto usando vectorcall
protocol, una alternativa más eficiente del simple tp_call.
This field is only used if the flag Py_TPFLAGS_HAVE_VECTORCALL is set. If so, this must be a positive integer
containing the offset in the instance of a vectorcallfunc pointer.
The vectorcallfunc pointer may be NULL, in which case the instance behaves as if
Py_TPFLAGS_HAVE_VECTORCALL was not set: calling the instance falls back to tp_call.
Cualquier clase que establezca _Py_TPFLAGS_HAVE_VECTORCALL también debe establecer tp_call y ase-
gurarse de que su comportamiento sea coherente con la función vectorcallfunc. Esto se puede hacer configurando
tp_call en PyVectorcall_Call().
Distinto en la versión 3.8: Antes de la versión 3.8, este slot se llamaba tp_print. En Python 2.x, se usó para
imprimir en un archivo. En Python 3.0 a 3.7, no se usó.
Distinto en la versión 3.12: Before version 3.12, it was not recommended for mutable heap types to implement
the vectorcall protocol. When a user sets __call__ in Python code, only tp_call is updated, likely making it
inconsistent with the vectorcall function. Since 3.12, setting __call__ will disable vectorcall optimization by
clearing the Py_TPFLAGS_HAVE_VECTORCALL flag.
Herencia:
This field is always inherited. However, the Py_TPFLAGS_HAVE_VECTORCALL flag is not always inherited. If
it’s not set, then the subclass won’t use vectorcall, except when PyVectorcall_Call() is explicitly called.
getattrfunc PyTypeObject.tp_getattr
Un puntero opcional a la función «obtener atributo cadena de caracteres» (get-attribute-string).
Este campo está en desuso. Cuando se define, debe apuntar a una función que actúe igual que la función
tp_getattro, pero tomando una cadena de caracteres C en lugar de un objeto de cadena Python para dar
el nombre del atributo.
Herencia:
Group: tp_getattr, tp_getattro
Este campo es heredado por los subtipos junto con tp_getattro: un subtipo hereda ambos tp_getattr y
tp_getattro de su base escriba cuando los subtipos tp_getattr y tp_getattro son ambos NULL.
setattrfunc PyTypeObject.tp_setattr
Un puntero opcional a la función para configurar y eliminar atributos.
Este campo está en desuso. Cuando se define, debe apuntar a una función que actúe igual que la función
tp_setattro, pero tomando una cadena de caracteres C en lugar de un objeto de cadena Python para dar
el nombre del atributo.
Herencia:
Group: tp_setattr, tp_setattro
Este campo es heredado por los subtipos junto con tp_setattro: un subtipo hereda ambos tp_setattr y
tp_setattro de su base escriba cuando los subtipos tp_setattr y tp_setattro son ambos NULL.
PyAsyncMethods *PyTypeObject.tp_as_async
Puntero a una estructura adicional que contiene campos relevantes solo para los objetos que implementan los pro-
tocolos «esperable» (awaitable) y «iterador asíncrono» (asynchronous iterator) en el nivel C. Ver Estructuras de
objetos asíncronos para más detalles.
Nuevo en la versión 3.5: Anteriormente conocidos como tp_compare y tp_reserved.
Herencia:
El campo tp_as_async no se hereda, pero los campos contenidos se heredan individualmente.
reprfunc PyTypeObject.tp_repr
Un puntero opcional a una función que implementa la función incorporada repr().
La firma es la misma que para PyObject_Repr():
La función debe retornar una cadena de caracteres o un objeto Unicode. Idealmente, esta función debería retornar
una cadena que, cuando se pasa a eval(), dado un entorno adecuado, retorna un objeto con el mismo valor. Si
esto no es factible, debe retornar una cadena que comience con '<' y termine con '>' desde la cual se puede
deducir tanto el tipo como el valor del objeto.
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Cuando este campo no está configurado, se retorna una cadena de caracteres de la forma <%s object at %p>,
donde %s se reemplaza por el nombre del tipo y %p por dirección de memoria del objeto.
PyNumberMethods *PyTypeObject.tp_as_number
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el protocolo
numérico. Estos campos están documentados en Estructuras de objetos de números.
Herencia:
El campo tp_as_number no se hereda, pero los campos contenidos se heredan individualmente.
PySequenceMethods *PyTypeObject.tp_as_sequence
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el protocolo
de secuencia. Estos campos están documentados en estructuras de secuencia.
Herencia:
El campo tp_as_sequence no se hereda, pero los campos contenidos se heredan individualmente.
PyMappingMethods *PyTypeObject.tp_as_mapping
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el protocolo
de mapeo. Estos campos están documentados en Estructuras de objetos mapeo.
Herencia:
El campo tp_as_mapping no se hereda, pero los campos contenidos se heredan individualmente.
hashfunc PyTypeObject.tp_hash
Un puntero opcional a una función que implementa la función incorporada hash().
La firma es la misma que para PyObject_Hash():
El valor -1 no debe retornarse como un valor de retorno normal; Cuando se produce un error durante el cálculo
del valor hash, la función debe establecer una excepción y retornar -1.
When this field is not set (and tp_richcompare is not set), an attempt to take the hash of the object raises
TypeError. This is the same as setting it to PyObject_HashNotImplemented().
Este campo se puede establecer explícitamente en PyObject_HashNotImplemented() para bloquear
la herencia del método hash de un tipo primario. Esto se interpreta como el equivalente de __hash__
= None en el nivel de Python, lo que hace que isinstance(o, collections.Hashable) retor-
ne correctamente False. Tenga en cuenta que lo contrario también es cierto: establecer __hash__ =
None en una clase en el nivel de Python dará como resultado que la ranura tp_hash se establezca en
PyObject_HashNotImplemented().
Herencia:
Group: tp_hash, tp_richcompare
Este campo es heredado por subtipos junto con tp_richcompare: un subtipo hereda ambos
tp_richcompare y tp_hash, cuando los subtipos tp_richcompare y tp_hash son ambos NULL.
ternaryfunc PyTypeObject.tp_call
Un puntero opcional a una función que implementa la llamada al objeto. Esto debería ser NULL si el objeto no es
invocable. La firma es la misma que para PyObject_Call():
Herencia:
Este campo es heredado por subtipos.
reprfunc PyTypeObject.tp_str
Un puntero opcional a una función que implementa la operación integrada str(). (Tenga en cuenta que str es
un tipo ahora, y str() llama al constructor para ese tipo. Este constructor llama a PyObject_Str() para
hacer el trabajo real, y PyObject_Str() llamará a este controlador.)
La firma es la misma que para PyObject_Str():
La función debe retornar una cadena de caracteres o un objeto Unicode. Debe ser una representación de cade-
na «amigable» del objeto, ya que esta es la representación que será utilizada, entre otras cosas, por la función
print().
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Cuando este campo no está configurado, se llama a PyObject_Repr() para retornar una representación de
cadena de caracteres.
getattrofunc PyTypeObject.tp_getattro
Un puntero opcional a la función «obtener atributo» (get-attribute).
La firma es la misma que para PyObject_GetAttr():
Además, se debe admitir la configuración de value en NULL para eliminar un atributo. Por lo general, es conveniente
establecer este campo en PyObject_GenericSetAttr(), que implementa la forma normal de establecer los
atributos del objeto.
Herencia:
Group: tp_setattr, tp_setattro
Los subtipos heredan este campo junto con tp_setattr: un subtipo hereda ambos tp_setattr y
tp_setattro de su base escriba cuando los subtipos tp_setattr y tp_setattro son ambos NULL.
Por defecto:
PyBaseObject_Type uses PyObject_GenericSetAttr().
PyBufferProcs *PyTypeObject.tp_as_buffer
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan la interfaz
del búfer. Estos campos están documentados en Estructuras de objetos búfer.
Herencia:
El campo tp_as_buffer no se hereda, pero los campos contenidos se heredan individualmente.
unsigned long PyTypeObject.tp_flags
Este campo es una máscara de bits de varias banderas. Algunas banderas indican semántica variante para ciertas
situaciones; otros se utilizan para indicar que ciertos campos en el tipo de objeto (o en las estructuras de ex-
tensión a las que se hace referencia a través de tp_as_number, tp_as_sequence, tp_as_mapping, y
tp_as_buffer) que históricamente no siempre estuvieron presentes son válidos; si dicho bit de bandera está
claro, no se debe acceder a los campos de tipo que protege y se debe considerar que tienen un valor cero o NULL.
Herencia:
Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag
bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if
the extension structure is inherited, i.e. the base type’s value of the flag bit is copied into the subtype together
with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the
tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and
the tp_traverse and tp_clear fields in the subtype exist and have NULL values. .. XXX are most flag bits
really inherited individually?
Por defecto:
PyBaseObject_Type uses Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE.
Máscaras de bits:
Las siguientes máscaras de bits están definidas actualmente; estos se pueden unidos por OR usando el operador |
para formar el valor del campo tp_flags. El macro PyType_HasFeature() toma un tipo y un valor de
banderas, tp y f, y comprueba si tp->tp_flags & f no es cero.
Py_TPFLAGS_HEAPTYPE
This bit is set when the type object itself is allocated on the heap, for example, types created dynamically
using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference
to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when an
instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the instance’s
ob_type gets INCREF’ed or DECREF’ed).
Herencia:
???
Py_TPFLAGS_BASETYPE
Este bit se establece cuando el tipo se puede usar como el tipo base de otro tipo. Si este bit es claro, el tipo
no puede subtiparse (similar a una clase «final» en Java).
Herencia:
???
Py_TPFLAGS_READY
Este bit se establece cuando el objeto tipo ha sido completamente inicializado por PyType_Ready().
Herencia:
???
Py_TPFLAGS_READYING
Este bit se establece mientras PyType_Ready() está en el proceso de inicialización del objeto tipo.
Herencia:
???
Py_TPFLAGS_HAVE_GC
This bit is set when the object supports garbage collection. If this bit is set, instances must be created using
PyObject_GC_New and destroyed using PyObject_GC_Del(). More information in section Apo-
yo a la recolección de basura cíclica. This bit also implies that the GC-related fields tp_traverse and
tp_clear are present in the type object.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear fields,
i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and tp_clear
fields in the subtype exist and have NULL values.
Py_TPFLAGS_DEFAULT
This is a bitmask of all the bits that pertain to the existence of certain fields in the type object and its extension
structures. Currently, it includes the following bits: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION.
Herencia:
???
Py_TPFLAGS_METHOD_DESCRIPTOR
Este bit indica que los objetos se comportan como métodos independientes.
Si este indicador está configurado para type(meth), entonces:
• meth.__get__(obj, cls)(*args, **kwds) (con obj no None) debe ser equivalente a
meth(obj, *args, **kwds).
• meth.__get__(None, cls)(*args, **kwds) debe ser equivalente a meth(*args,
**kwds).
Este indicador (flag) permite una optimización para llamadas a métodos típicos como obj.meth(): evita
crear un objeto temporal de «método vinculado» para obj.meth.
Nuevo en la versión 3.8.
Herencia:
This flag is never inherited by types without the Py_TPFLAGS_IMMUTABLETYPE flag set. For extension
types, it is inherited whenever tp_descr_get is inherited.
Py_TPFLAGS_MANAGED_DICT
This bit indicates that instances of the class have a __dict__ attribute, and that the space for the dictionary
is managed by the VM.
If this flag is set, Py_TPFLAGS_HAVE_GC should also be set.
The type traverse function must call PyObject_VisitManagedDict() and its clear function must call
PyObject_ClearManagedDict().
Nuevo en la versión 3.12.
Herencia:
This flag is inherited unless the tp_dictoffset field is set in a superclass.
Py_TPFLAGS_MANAGED_WEAKREF
This bit indicates that instances of the class should be weakly referenceable.
Nuevo en la versión 3.12.
Herencia:
This flag is inherited unless the tp_weaklistoffset field is set in a superclass.
Py_TPFLAGS_ITEMS_AT_END
Only usable with variable-size types, i.e. ones with non-zero tp_itemsize.
Indicates that the variable-sized portion of an instance of this type is at the end of the instance’s memory area,
at an offset of Py_TYPE(obj)->tp_basicsize (which may be different in each subclass).
When setting this flag, be sure that all superclasses either use this memory layout, or are not variable-sized.
Python does not check this.
Nuevo en la versión 3.12.
Herencia:
Py_TPFLAGS_LIST_SUBCLASS
Py_TPFLAGS_TUPLE_SUBCLASS
Py_TPFLAGS_BYTES_SUBCLASS
Py_TPFLAGS_UNICODE_SUBCLASS
Py_TPFLAGS_DICT_SUBCLASS
Py_TPFLAGS_BASE_EXC_SUBCLASS
Py_TPFLAGS_TYPE_SUBCLASS
Estas marcas son utilizadas por funciones como PyLong_Check() para determinar rápidamente si un
tipo es una subclase de un tipo incorporado; dichos controles específicos son más rápidos que un control
genérico, como PyObject_IsInstance(). Los tipos personalizados que heredan de los elementos in-
tegrados deben tener su tp_flags configurado correctamente, o el código que interactúa con dichos tipos
se comportará de manera diferente dependiendo del tipo de verificación que se use.
Py_TPFLAGS_HAVE_FINALIZE
Este bit se establece cuando la ranura tp_finalize está presente en la estructura de tipo.
Nuevo en la versión 3.4.
Obsoleto desde la versión 3.8: Este indicador ya no es necesario, ya que el intérprete asume que: el espacio
tp_finalize siempre está presente en la estructura de tipos.
Py_TPFLAGS_HAVE_VECTORCALL
Este bit se establece cuando la clase implementa protocolo vectorcall. Consulte tp_vectorcall_offset
para obtener más detalles.
Herencia:
This bit is inherited if tp_call is also inherited.
Nuevo en la versión 3.9.
Distinto en la versión 3.12: This flag is now removed from a class when the class’s __call__() method is
reassigned.
This flag can now be inherited by mutable classes.
Py_TPFLAGS_IMMUTABLETYPE
Este bit se establece para objetos de tipo que son inmutables: los atributos de tipo no se pueden establecer ni
eliminar.
PyType_Ready() aplica automáticamente este indicador a static types.
Herencia:
Este flag no se hereda.
Nuevo en la versión 3.10.
Py_TPFLAGS_DISALLOW_INSTANTIATION
No permita la creación de instancias del tipo: establezca tp_new en NULL y no cree la clave __new__ en
el diccionario de tipos.
La bandera debe establecerse antes de crear el tipo, no después. Por ejemplo, debe establecerse antes de que
se llame a PyType_Ready() en el tipo.
La bandera se establece automáticamente en static types si tp_base es NULL o &PyBaseObject_Type
y tp_new es NULL.
Herencia:
This flag is not inherited. However, subclasses will not be instantiable unless they provide a non-NULL
tp_new (which is only possible via the C API).
Nota: To disallow instantiating a class directly but allow instantiating its subclasses (e.g. for an abstract base
class), do not use this flag. Instead, make tp_new only succeed for subclasses.
Herencia:
This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.
Ver también:
PEP 634 - Coincidencia de patrones estructurales: especificación
Nuevo en la versión 3.10.
Py_TPFLAGS_SEQUENCE
Este bit indica que las instancias de la clase pueden coincidir con los patrones de secuencia cuando se utilizan
como sujeto de un bloque match. Se configura automáticamente al registrar o subclasificar collections.
abc.Sequence, y se desarma al registrar collections.abc.Mapping.
Herencia:
This flag is inherited by types that do not already set Py_TPFLAGS_MAPPING.
Ver también:
PEP 634 - Coincidencia de patrones estructurales: especificación
Nuevo en la versión 3.10.
Py_TPFLAGS_VALID_VERSION_TAG
Internal. Do not set or unset this flag. To indicate that a class has changed call PyType_Modified()
Advertencia: This flag is present in header files, but is an internal feature and should not be used. It will
be removed in a future version of CPython
Se puede encontrar más información sobre el esquema de recolección de basura de Python en la sección Apoyo a
la recolección de basura cíclica.
The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical implementation of
a tp_traverse function simply calls Py_VISIT() on each of the instance’s members that are Python objects
that the instance owns. For example, this is function local_traverse() from the _thread extension module:
static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
Py_VISIT(self->args);
Py_VISIT(self->kw);
Py_VISIT(self->dict);
return 0;
}
Tenga en cuenta que Py_VISIT() solo se llama a aquellos miembros que pueden participar en los ciclos de
referencia. Aunque también hay un miembro self->key, solo puede ser NULL o una cadena de caracteres de
Python y, por lo tanto, no puede ser parte de un ciclo de referencia.
Por otro lado, incluso si sabe que un miembro nunca puede ser parte de un ciclo, como ayuda para la depuración
puede visitarlo de todos modos solo para que la función get_referents() del módulo gc lo incluirá.
Heap types (Py_TPFLAGS_HEAPTYPE) must visit their type with:
Py_VISIT(Py_TYPE(self));
It is only needed since Python 3.9. To support Python 3.8 and older, this line must be conditionnal:
If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, the traverse function must call
PyObject_VisitManagedDict() like this:
Advertencia: Al implementar tp_traverse, solo se deben visitar los miembros que tienen la instancia
owns (por tener referencias fuertes). Por ejemplo, si un objeto admite referencias débiles a través de la ranura
tp_weaklist, el puntero que respalda la lista vinculada (a lo que apunta tp_weaklist) no debe visitarse ya
que la instancia no posee directamente las referencias débiles a sí misma (la lista de referencias débiles está ahí
para respaldar la maquinaria de referencia débil, pero la instancia no tiene una fuerte referencia a los elementos
dentro de ella, ya que pueden eliminarse incluso si la instancia todavía está viva).
Note that Py_VISIT() requires the visit and arg parameters to local_traverse() to have these specific
names; don’t name them just anything.
Las instancias de heap-allocated types contienen una referencia a su tipo. Por lo tanto, su función transversal debe
visitar Py_TYPE(self) o delegar esta responsabilidad llamando a tp_traverse de otro tipo asignado al heap
(como una superclase asignada al heap). Si no es así, es posible que el objeto de tipo no se recolecte como basura.
Distinto en la versión 3.9: Se espera que los tipos asignados al heap visiten Py_TYPE(self) en tp_traverse.
En versiones anteriores de Python, debido al bug 40217, hacer esto puede provocar fallas en las subclases.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the flag
bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.
inquiry PyTypeObject.tp_clear
An optional pointer to a clear function for the garbage collector. This is only used if the Py_TPFLAGS_HAVE_GC
flag bit is set. The signature is:
La función miembro tp_clear se usa para romper los ciclos de referencia en la basura cíclica detectada por el
recolector de basura. En conjunto, todas las funciones tp_clear en el sistema deben combinarse para romper
todos los ciclos de referencia. Esto es sutil y, en caso de duda, proporcione una función tp_clear. Por ejemplo, el
tipo de tupla no implementa una función tp_clear, porque es posible demostrar que ningún ciclo de referencia
puede estar compuesto completamente de tuplas. Por lo tanto, las funciones tp_clear de otros tipos deben ser
suficientes para romper cualquier ciclo que contenga una tupla. Esto no es inmediatamente obvio, y rara vez hay
una buena razón para evitar la implementación de tp_clear.
Las implementaciones de tp_clear deberían descartar las referencias de la instancia a las de sus miembros que
pueden ser objetos de Python, y establecer sus punteros a esos miembros en NULL, como en el siguiente ejemplo:
static int
local_clear(localobject *self)
{
Py_CLEAR(self->key);
Py_CLEAR(self->args);
Py_CLEAR(self->kw);
Py_CLEAR(self->dict);
return 0;
}
The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the contained
object must not be released (via Py_DECREF()) until after the pointer to the contained object is set to NULL. This
is because releasing the reference may cause the contained object to become trash, triggering a chain of reclamation
activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks, associated with the
contained object). If it’s possible for such code to reference self again, it’s important that the pointer to the contained
object be NULL at that time, so that self knows the contained object can no longer be used. The Py_CLEAR()
macro performs the operations in a safe order.
If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, the traverse function must call
PyObject_ClearManagedDict() like this:
PyObject_ClearManagedDict((PyObject*)self);
Tenga en cuenta que tp_clear no se llama siempre antes de que se desasigne una instancia. Por ejemplo, cuando
el recuento de referencias es suficiente para determinar que un objeto ya no se utiliza, el recolector de basura cíclico
no está involucrado y se llama directamente a tp_dealloc.
Debido a que el objetivo de tp_clear es romper los ciclos de referencia, no es necesario borrar objetos contenidos
como cadenas de caracteres de Python o enteros de Python, que no pueden participar en los ciclos de referencia. Por
otro lado, puede ser conveniente borrar todos los objetos Python contenidos y escribir la función tp_dealloc
para invocar tp_clear.
Se puede encontrar más información sobre el esquema de recolección de basura de Python en la sección Apoyo a
la recolección de basura cíclica.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit: the
flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.
richcmpfunc PyTypeObject.tp_richcompare
Un puntero opcional a la función de comparación enriquecida, cuya firma es:
Se garantiza que el primer parámetro será una instancia del tipo definido por PyTypeObject.
La función debería retornar el resultado de la comparación (generalmente Py_True o Py_False). Si la com-
paración no está definida, debe retornar Py_NotImplemented, si se produce otro error, debe retornar NULL
y establecer una condición de excepción.
Las siguientes constantes se definen para ser utilizadas como el tercer argumento para tp_richcompare y para
PyObject_RichCompare():
Constante Comparación
<
Py_LT
<=
Py_LE
==
Py_EQ
!=
Py_NE
>
Py_GT
>=
Py_GE
El siguiente macro está definido para facilitar la escritura de funciones de comparación enriquecidas:
Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)
Retorna Py_True o Py_False de la función, según el resultado de una comparación. VAL_A y VAL_B de-
ben ser ordenados por operadores de comparación C (por ejemplo, pueden ser enteros o punto flotantes de C).
El tercer argumento especifica la operación solicitada, como por ejemplo PyObject_RichCompare().
The returned value is a new strong reference.
En caso de error, establece una excepción y retorna NULL de la función.
Nuevo en la versión 3.7.
Herencia:
Group: tp_hash, tp_richcompare
Este campo es heredado por subtipos junto con tp_hash: un subtipo hereda tp_richcompare y tp_hash
cuando el subtipo tp_richcompare y tp_hash son ambos NULL.
Por defecto:
PyBaseObject_Type provides a tp_richcompare implementation, which may be inherited. However, if
only tp_hash is defined, not even the inherited function is used and instances of the type will not be able to
participate in any comparisons.
Py_ssize_t PyTypeObject.tp_weaklistoffset
While this field is still supported, Py_TPFLAGS_MANAGED_WEAKREF should be used instead, if at all possible.
If the instances of this type are weakly referenceable, this field is greater than zero and contains the offset in
the instance structure of the weak reference list head (ignoring the GC header, if present); this offset is used by
PyObject_ClearWeakRefs() and the PyWeakref_* functions. The instance structure needs to include a
field of type PyObject* which is initialized to NULL.
No confunda este campo con tp_weaklist; ese es el encabezado de la lista para referencias débiles al objeto
de tipo en sí.
It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_weaklist.
Herencia:
Este campo es heredado por subtipos, pero consulte las reglas que se enumeran a continuación. Un subtipo puede
anular este desplazamiento; Esto significa que el subtipo utiliza un encabezado de lista de referencia débil diferente
que el tipo base. Dado que el encabezado de la lista siempre se encuentra a través de tp_weaklistoffset,
esto no debería ser un problema.
Por defecto:
If the Py_TPFLAGS_MANAGED_WEAKREF bit is set in the tp_dict field, then tp_weaklistoffset will
be set to a negative value, to indicate that it is unsafe to use this field.
getiterfunc PyTypeObject.tp_iter
An optional pointer to a function that returns an iterator for the object. Its presence normally signals that the instances
of this type are iterable (although sequences may be iterable without this function).
Esta función tiene la misma firma que PyObject_GetIter():
PyObject *tp_iter(PyObject *self);
Herencia:
Este campo es heredado por subtipos.
iternextfunc PyTypeObject.tp_iternext
An optional pointer to a function that returns the next item in an iterator. The signature is:
PyObject *tp_iternext(PyObject *self);
Cuando el iterador está agotado, debe retornar NULL; a la excepción StopIteration puede o no establecerse.
Cuando se produce otro error, también debe retornar NULL. Su presencia indica que las instancias de este tipo son
iteradores.
Los tipos de iterador también deberían definir la función tp_iter, y esa función debería retornar la instancia de
iterador en sí (no una nueva instancia de iterador).
Esta función tiene la misma firma que PyIter_Next().
Herencia:
Este campo es heredado por subtipos.
struct PyMethodDef *PyTypeObject.tp_methods
Un puntero opcional a un arreglo estático terminado en NULL de estructuras PyMethodDef, declarando métodos
regulares de este tipo.
Para cada entrada en el arreglo, se agrega una entrada al diccionario del tipo (ver tp_dict a continuación) que
contiene un descriptor method.
Herencia:
Los subtipos no heredan este campo (los métodos se heredan mediante un mecanismo diferente).
struct PyMemberDef *PyTypeObject.tp_members
Un puntero opcional a un arreglo estático terminado en NULL de estructuras PyMemberDef, declarando miem-
bros de datos regulares (campos o ranuras) de instancias de este tipo.
Para cada entrada en el arreglo, se agrega una entrada al diccionario del tipo (ver tp_dict a continuación) que
contiene un descriptor member.
Herencia:
Los subtipos no heredan este campo (los miembros se heredan mediante un mecanismo diferente).
Nota: La inicialización de ranuras está sujeta a las reglas de inicialización de globales. C99 requiere que los
inicializadores sean «constantes de dirección». Los designadores de funciones como PyType_GenericNew(),
con conversión implícita a un puntero, son constantes de dirección C99 válidas.
However, the unary “&” operator applied to a non-static variable like PyBaseObject_Type is not required to
produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers are strictly
standard conforming in this particular behavior.
En consecuencia, tp_base debe establecerse en la función init del módulo de extensión.
Herencia:
Este campo no es heredado por los subtipos (obviamente).
Por defecto:
Este campo predeterminado es &PyBaseObject_Type (que para los programadores de Python se conoce como
el tipo objeto).
PyObject *PyTypeObject.tp_dict
El diccionario del tipo se almacena aquí por PyType_Ready().
This field should normally be initialized to NULL before PyType_Ready is called; it may also be initialized to
a dictionary containing initial attributes for the type. Once PyType_Ready() has initialized the type, extra
attributes for the type may be added to this dictionary only if they don’t correspond to overloaded operations (like
__add__()). Once initialization for the type has finished, this field should be treated as read-only.
Some types may not store their dictionary in this slot. Use PyType_GetDict() to retrieve the dictionary for an
arbitrary type.
Distinto en la versión 3.12: Internals detail: For static builtin types, this is always NULL. Instead, the dict for such
types is stored on PyInterpreterState. Use PyType_GetDict() to get the dict for an arbitrary type.
Herencia:
Este campo no es heredado por los subtipos (aunque los atributos definidos aquí se heredan a través de un mecanismo
diferente).
Por defecto:
Si este campo es NULL, PyType_Ready() le asignará un nuevo diccionario.
descrgetfunc PyTypeObject.tp_descr_get
Un puntero opcional a una función «obtener descriptor» (descriptor ger).
La firma de la función es:
Herencia:
Este campo es heredado por subtipos.
descrsetfunc PyTypeObject.tp_descr_set
Un puntero opcional a una función para configurar y eliminar el valor de un descriptor.
La firma de la función es:
initproc PyTypeObject.tp_init
Un puntero opcional a una función de inicialización de instancia.
This function corresponds to the __init__() method of classes. Like __init__(), it is possible to create an
instance without calling __init__(), and it is possible to reinitialize an instance by calling its __init__()
method again.
La firma de la función es:
int tp_init(PyObject *self, PyObject *args, PyObject *kwds);
The self argument is the instance to be initialized; the args and kwds arguments represent positional and keyword
arguments of the call to __init__().
La función tp_init, si no es NULL, se llama cuando una instancia se crea normalmente llamando a su tipo,
después de la función tp_new del tipo ha retornado una instancia del tipo. Si la función tp_new retorna una
instancia de otro tipo que no es un subtipo del tipo original, no se llama la función tp_init; if tp_new retorna
una instancia de un subtipo del tipo original, se llama al subtipo tp_init.
Retorna 0 en caso de éxito, -1 y establece una excepción en caso de error.
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Para tipos estáticos, este campo no tiene un valor predeterminado.
allocfunc PyTypeObject.tp_alloc
Un puntero opcional a una función de asignación de instancia.
La firma de la función es:
PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);
Herencia:
Este campo es heredado por subtipos estáticos, pero no por subtipos dinámicos (subtipos creados por una declara-
ción de clase).
Por defecto:
Para subtipos dinámicos, este campo siempre se establece en PyType_GenericAlloc(), para forzar una
estrategia de asignación de heap estándar.
For static subtypes, PyBaseObject_Type uses PyType_GenericAlloc(). That is the recommended va-
lue for all statically defined types.
newfunc PyTypeObject.tp_new
Un puntero opcional a una función de creación de instancias.
La firma de la función es:
PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);
El argumento subtype es el tipo de objeto que se está creando; los argumentos args y kwds representan argumentos
posicionales y de palabras clave de la llamada al tipo. Tenga en cuenta que subtype no tiene que ser igual al tipo
cuya función tp_new es llamada; puede ser un subtipo de ese tipo (pero no un tipo no relacionado).
La función tp_new debería llamar a subtype->tp_alloc(subtype, nitems) para asignar espacio
para el objeto, y luego hacer solo la inicialización adicional que sea absolutamente necesaria. La inicialización que
se puede ignorar o repetir de forma segura debe colocarse en el controlador tp_init. Una buena regla general
es que para los tipos inmutables, toda la inicialización debe tener lugar en tp_new, mientras que para los tipos
mutables, la mayoría de las inicializaciones se deben diferir a tp_init.
Set the Py_TPFLAGS_DISALLOW_INSTANTIATION flag to disallow creating instances of the type in Python.
Herencia:
Este campo se hereda por subtipos, excepto que no lo heredan tipos estáticos cuyo tp_base es NULL o
&PyBaseObject_Type.
Por defecto:
Para tipos estáticos, este campo no tiene ningún valor predeterminado. Esto significa que si la ranura se define como
NULL, no se puede llamar al tipo para crear nuevas instancias; presumiblemente hay alguna otra forma de crear
instancias, como una función de fábrica.
freefunc PyTypeObject.tp_free
Un puntero opcional a una función de desasignación de instancia. Su firma es:
(El único ejemplo de esto son los tipos en sí. El metatipo, PyType_Type, define esta función para distinguir entre
tipos estática y dinámicamente asignados.)
Herencia:
Este campo es heredado por subtipos.
Por defecto:
This slot has no default. If this field is NULL, Py_TPFLAGS_HAVE_GC is used as the functional equivalent.
PyObject *PyTypeObject.tp_bases
Tupla de tipos base.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
For dynamically created classes, the Py_tp_bases slot can be used instead of the bases argument of
PyType_FromSpecWithBases(). The argument form is preferred.
Advertencia: Multiple inheritance does not work well for statically defined types. If you set tp_bases to a
tuple, Python will not raise an error, but some slots will only be inherited from the first base.
Herencia:
Este campo no se hereda.
PyObject *PyTypeObject.tp_mro
Tupla que contiene el conjunto expandido de tipos base, comenzando con el tipo en sí y terminando con object,
en orden de resolución de método.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
Herencia:
Este campo no se hereda; se calcula fresco por PyType_Ready().
PyObject *PyTypeObject.tp_cache
No usado. Solo para uso interno.
Herencia:
Este campo no se hereda.
void *PyTypeObject.tp_subclasses
A collection of subclasses. Internal use only. May be an invalid pointer.
To get a list of subclasses, call the Python method __subclasses__().
Distinto en la versión 3.12: For some types, this field does not hold a valid PyObject*. The type was changed to
void* to indicate this.
Herencia:
Este campo no se hereda.
PyObject *PyTypeObject.tp_weaklist
Cabecera de lista de referencia débil, para referencias débiles a este tipo de objeto. No heredado Solo para uso
interno.
Distinto en la versión 3.12: Internals detail: For the static builtin types this is always NULL, even if weakrefs are
added. Instead, the weakrefs for each are stored on PyInterpreterState. Use the public C-API or the internal
_PyObject_GET_WEAKREFS_LISTPTR() macro to avoid the distinction.
Herencia:
Este campo no se hereda.
destructor PyTypeObject.tp_del
Este campo está en desuso. Use tp_finalize en su lugar.
unsigned int PyTypeObject.tp_version_tag
Se usa para indexar en el caché de métodos. Solo para uso interno.
Herencia:
Este campo no se hereda.
destructor PyTypeObject.tp_finalize
Un puntero opcional a una función de finalización de instancia. Su firma es:
Si tp_finalize está configurado, el intérprete lo llama una vez cuando finaliza una instancia. Se llama desde
el recolector de basura (si la instancia es parte de un ciclo de referencia aislado) o justo antes de que el objeto
se desasigne. De cualquier manera, se garantiza que se invocará antes de intentar romper los ciclos de referencia,
asegurando que encuentre el objeto en un estado sano.
tp_finalize no debe mutar el estado de excepción actual; por lo tanto, una forma recomendada de escribir un
finalizador no trivial es:
static void
local_finalize(PyObject *self)
{
PyObject *error_type, *error_value, *error_traceback;
/* ... */
Además, tenga en cuenta que, en un Python que ha recolectado basura, se puede llamar a tp_dealloc desde
cualquier hilo de Python, no solo el hilo que creó el objeto (si el objeto se convierte en parte de un ciclo de conteo de
referencias, ese ciclo puede ser recogido por una recolección de basura en cualquier hilo). Esto no es un problema
para las llamadas a la API de Python, ya que el hilo en el que se llama tp_dealloc será el propietario del
Bloqueo Global del Intérprete (GIL, por sus siglas en inglés Global Interpreter Lock). Sin embargo, si el objeto que
se destruye a su vez destruye objetos de alguna otra biblioteca C o C++, se debe tener cuidado para garantizar que
la destrucción de esos objetos en el hilo que se llama tp_dealloc no violará ningún supuesto de la biblioteca.
Herencia:
Este campo es heredado por subtipos.
Nuevo en la versión 3.4.
Distinto en la versión 3.8: Before version 3.8 it was necessary to set the Py_TPFLAGS_HAVE_FINALIZE flags
bit in order for this field to be used. This is no longer required.
Ver también:
«Finalización segura de objetos» (PEP 442)
vectorcallfunc PyTypeObject.tp_vectorcall
Vectorcall function to use for calls of this type object. In other words, it is used to implement vectorcall for
type.__call__. If tp_vectorcall is NULL, the default call implementation using __new__() and
__init__() is used.
Herencia:
Este campo nunca se hereda.
Nuevo en la versión 3.9: (el campo existe desde 3.8 pero solo se usa desde 3.9)
unsigned char PyTypeObject.tp_watched
Internal. Do not use.
Nuevo en la versión 3.12.
Tradicionalmente, los tipos definidos en el código C son static, es decir, una estructura estática PyTypeObject se define
directamente en el código y se inicializa usando PyType_Ready().
Esto da como resultado tipos que están limitados en relación con los tipos definidos en Python:
• Los tipos estáticos están limitados a una base, es decir, no pueden usar herencia múltiple.
• Los objetos de tipo estático (pero no necesariamente sus instancias) son inmutables. No es posible agregar o mo-
dificar los atributos del objeto tipo desde Python.
• Los objetos de tipo estático se comparten en sub intérpretes, por lo que no deben incluir ningún estado específico
del sub interpretador.
Also, since PyTypeObject is only part of the Limited API as an opaque struct, any extension modules using static types
must be compiled for a specific Python minor version.
An alternative to static types is heap-allocated types, or heap types for short, which correspond closely to classes created
by Python’s class statement. Heap types have the Py_TPFLAGS_HEAPTYPE flag set.
This is done by filling a PyType_Spec structure and calling PyType_FromSpec(),
PyType_FromSpecWithBases(), PyType_FromModuleAndSpec(), or PyType_FromMetaclass().
type PyNumberMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo numérico.
Cada función es utilizada por la función de un nombre similar documentado en la sección Protocolo de números.
Aquí está la definición de la estructura:
typedef struct {
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;
unaryfunc nb_negative;
unaryfunc nb_positive;
unaryfunc nb_absolute;
inquiry nb_bool;
unaryfunc nb_invert;
binaryfunc nb_lshift;
binaryfunc nb_rshift;
binaryfunc nb_and;
binaryfunc nb_xor;
binaryfunc nb_or;
unaryfunc nb_int;
void *nb_reserved;
unaryfunc nb_float;
binaryfunc nb_floor_divide;
binaryfunc nb_true_divide;
binaryfunc nb_inplace_floor_divide;
binaryfunc nb_inplace_true_divide;
unaryfunc nb_index;
binaryfunc nb_matrix_multiply;
binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;
Nota: Las funciones binarias y ternarias deben verificar el tipo de todos sus operandos e implementar las con-
versiones necesarias (al menos uno de los operandos es una instancia del tipo definido). Si la operación no está
definida para los operandos dados, las funciones binarias y ternarias deben retornar Py_NotImplemented, si
se produce otro error, deben retornar NULL y establecer una excepción.
Nota: The nb_reserved field should always be NULL. It was previously called nb_long, and was renamed
in Python 3.0.1.
binaryfunc PyNumberMethods.nb_add
binaryfunc PyNumberMethods.nb_subtract
binaryfunc PyNumberMethods.nb_multiply
binaryfunc PyNumberMethods.nb_remainder
binaryfunc PyNumberMethods.nb_divmod
ternaryfunc PyNumberMethods.nb_power
unaryfunc PyNumberMethods.nb_negative
unaryfunc PyNumberMethods.nb_positive
unaryfunc PyNumberMethods.nb_absolute
inquiry PyNumberMethods.nb_bool
unaryfunc PyNumberMethods.nb_invert
binaryfunc PyNumberMethods.nb_lshift
binaryfunc PyNumberMethods.nb_rshift
binaryfunc PyNumberMethods.nb_and
binaryfunc PyNumberMethods.nb_xor
binaryfunc PyNumberMethods.nb_or
unaryfunc PyNumberMethods.nb_int
void *PyNumberMethods.nb_reserved
unaryfunc PyNumberMethods.nb_float
binaryfunc PyNumberMethods.nb_inplace_add
binaryfunc PyNumberMethods.nb_inplace_subtract
binaryfunc PyNumberMethods.nb_inplace_multiply
binaryfunc PyNumberMethods.nb_inplace_remainder
ternaryfunc PyNumberMethods.nb_inplace_power
binaryfunc PyNumberMethods.nb_inplace_lshift
binaryfunc PyNumberMethods.nb_inplace_rshift
binaryfunc PyNumberMethods.nb_inplace_and
binaryfunc PyNumberMethods.nb_inplace_xor
binaryfunc PyNumberMethods.nb_inplace_or
binaryfunc PyNumberMethods.nb_floor_divide
binaryfunc PyNumberMethods.nb_true_divide
binaryfunc PyNumberMethods.nb_inplace_floor_divide
binaryfunc PyNumberMethods.nb_inplace_true_divide
unaryfunc PyNumberMethods.nb_index
binaryfunc PyNumberMethods.nb_matrix_multiply
binaryfunc PyNumberMethods.nb_inplace_matrix_multiply
type PyMappingMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo de mapeo.
Tiene tres miembros:
lenfunc PyMappingMethods.mp_length
Esta función es utilizada por PyMapping_Size() y PyObject_Size(), y tiene la misma firma. Esta ranura
puede establecerse en NULL si el objeto no tiene una longitud definida.
binaryfunc PyMappingMethods.mp_subscript
Esta función es utilizada por PyObject_GetItem() y PySequence_GetSlice(), y tiene la misma firma
que PyObject_GetItem(). Este espacio debe llenarse para que la función PyMapping_Check() retorna
1, de lo contrario puede ser NULL.
objobjargproc PyMappingMethods.mp_ass_subscript
This function is used by PyObject_SetItem(), PyObject_DelItem(), PySequence_SetSlice()
and PySequence_DelSlice(). It has the same signature as PyObject_SetItem(), but v can also be set
to NULL to delete an item. If this slot is NULL, the object does not support item assignment and deletion.
type PySequenceMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo de secuencia.
lenfunc PySequenceMethods.sq_length
Esta función es utilizada por PySequence_Size() y PyObject_Size(), y tiene la misma firma. También
se usa para manejar índices negativos a través de los espacios sq_item y sq_ass_item.
binaryfunc PySequenceMethods.sq_concat
Esta función es utilizada por PySequence_Concat() y tiene la misma firma. También es utilizado por el
operador +, después de intentar la suma numérica a través de la ranura nb_add.
ssizeargfunc PySequenceMethods.sq_repeat
Esta función es utilizada por PySequence_Repeat() y tiene la misma firma. También es utilizado por el
operador *, después de intentar la multiplicación numérica a través de la ranura nb_multiply.
ssizeargfunc PySequenceMethods.sq_item
Esta función es utilizada por PySequence_GetItem() y tiene la misma firma. También es utilizado por
PyObject_GetItem(), después de intentar la suscripción a través de la ranura mp_subscript. Este es-
pacio debe llenarse para que la función PySequence_Check() retorna 1, de lo contrario puede ser NULL.
Negative indexes are handled as follows: if the sq_length slot is filled, it is called and the sequence length is
used to compute a positive index which is passed to sq_item. If sq_length is NULL, the index is passed as is
to the function.
ssizeobjargproc PySequenceMethods.sq_ass_item
Esta función es utilizada por PySequence_SetItem() y tiene la misma firma. También lo usan
PyObject_SetItem() y PyObject_DelItem(), después de intentar la asignación y eliminación del ele-
mento a través de la ranura mp_ass_subscript. Este espacio puede dejarse en NULL si el objeto no admite
la asignación y eliminación de elementos.
objobjproc PySequenceMethods.sq_contains
Esta función puede ser utilizada por PySequence_Contains() y tiene la misma firma. Este espacio pue-
de dejarse en NULL, en este caso PySequence_Contains() simplemente atraviesa la secuencia hasta que
encuentra una coincidencia.
binaryfunc PySequenceMethods.sq_inplace_concat
Esta función es utilizada por PySequence_InPlaceConcat() y tiene la misma firma. Debe-
ría modificar su primer operando y retornarlo. Este espacio puede dejarse en NULL, en este caso
PySequence_InPlaceConcat() volverá a PySequence_Concat(). También es utilizado por la asig-
nación aumentada +=, después de intentar la suma numérica en el lugar a través de la ranura nb_inplace_add.
ssizeargfunc PySequenceMethods.sq_inplace_repeat
Esta función es utilizada por PySequence_InPlaceRepeat() y tiene la misma firma. Debe-
ría modificar su primer operando y retornarlo. Este espacio puede dejarse en NULL, en este caso
PySequence_InPlaceRepeat() volverá a PySequence_Repeat(). También es utilizado por la
asignación aumentada *=, después de intentar la multiplicación numérica en el lugar a través de la ranura
nb_inplace_multiply.
type PyBufferProcs
Esta estructura contiene punteros a las funciones requeridas por Buffer protocol. El protocolo define cómo un objeto
exportador puede exponer sus datos internos a objetos de consumo.
getbufferproc PyBufferProcs.bf_getbuffer
La firma de esta función es:
Maneja una solicitud a exporter para completar view según lo especificado por flags. Excepto por el punto (3), una
implementación de esta función DEBE seguir estos pasos:
(1) Check if the request can be met. If not, raise BufferError, set view->obj to NULL and return -1.
(2) Rellene los campos solicitados.
(3) Incrementa un contador interno para el número de exportaciones (exports).
(4) Set view->obj to exporter and increment view->obj.
(5) Retorna 0.
Si exporter es parte de una cadena o árbol de proveedores de búfer, se pueden usar dos esquemas principales:
• Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference to
itself.
• Redirect: The buffer request is redirected to the root object of the tree. Here, view->obj will be a new
reference to the root object.
Los campos individuales de view se describen en la sección Estructura de búfer, las reglas sobre cómo debe reac-
cionar un exportador a solicitudes específicas se encuentran en la sección Tipos de solicitud de búfer.
Toda la memoria señalada en la estructura Py_buffer pertenece al exportador y debe permanecer válida hasta
que no queden consumidores. format, shape, strides, suboffsets y internal son de solo lectura
para el consumidor.
PyBuffer_FillInfo() proporciona una manera fácil de exponer un búfer de bytes simple mientras se trata
correctamente con todos los tipos de solicitud.
PyObject_GetBuffer() es la interfaz para el consumidor que envuelve esta función.
releasebufferproc PyBufferProcs.bf_releasebuffer
La firma de esta función es:
Maneja una solicitud para liberar los recursos del búfer. Si no es necesario liberar recursos, PyBufferProcs.
bf_releasebuffer puede ser NULL. De lo contrario, una implementación estándar de esta función tomará
estos pasos opcionales:
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
sendfunc am_send;
} PyAsyncMethods;
unaryfunc PyAsyncMethods.am_await
La firma de esta función es:
The returned object must be an iterator, i.e. PyIter_Check() must return 1 for it.
Este espacio puede establecerse en NULL si un objeto no es awaitable.
unaryfunc PyAsyncMethods.am_aiter
La firma de esta función es:
Must return an awaitable object. See __anext__() for details. This slot may be set to NULL.
sendfunc PyAsyncMethods.am_send
La firma de esta función es:
Consulte PyIter_Send() para obtener más detalles. Esta ranura se puede establecer en NULL.
Nuevo en la versión 3.10.
12.10 Ejemplos
Los siguientes son ejemplos simples de definiciones de tipo Python. Incluyen el uso común que puede encontrar. Algunos
demuestran casos difíciles de esquina (corner cases). Para obtener más ejemplos, información práctica y un tutorial,
consulte «definiendo nuevos tipos» (defining-new-types) y «tópicos de nuevos tipos (new-types-topics).
Un tipo estático básico:
typedef struct {
PyObject_HEAD
const char *data;
} MyObject;
También puede encontrar código más antiguo (especialmente en la base de código CPython) con un inicializador más
detallado:
A str subclass that cannot be subclassed and cannot be called to create instances (e.g. uses a separate factory func) using
Py_TPFLAGS_DISALLOW_INSTANTIATION flag:
typedef struct {
PyUnicodeObject raw;
char *extra;
} MyStr;
typedef struct {
PyObject_VAR_HEAD
const char *data[1];
} MyObject;
El soporte de Python para detectar y recolectar basura que involucra referencias circulares requiere el soporte de tipos
de objetos que son «contenedores» para otros objetos que también pueden ser contenedores. Los tipos que no almacenan
referencias a otros objetos, o que solo almacenan referencias a tipos atómicos (como números o cadenas), no necesitan
proporcionar ningún soporte explícito para la recolección de basura.
To create a container type, the tp_flags field of the type object must include the Py_TPFLAGS_HAVE_GC and
provide an implementation of the tp_traverse handler. If instances of the type are mutable, a tp_clear imple-
mentation must also be provided.
Py_TPFLAGS_HAVE_GC
Los objetos con un tipo con este indicador establecido deben cumplir con las reglas documentadas aquí. Por con-
veniencia, estos objetos se denominarán objetos contenedor.
Los constructores para tipos de contenedores deben cumplir con dos reglas:
1. The memory for the object must be allocated using PyObject_GC_New or PyObject_GC_NewVar.
2. Una vez que se inicializan todos los campos que pueden contener referencias a otros contenedores, debe llamar a
PyObject_GC_Track().
Del mismo modo, el desasignador (deallocator) para el objeto debe cumplir con un par similar de reglas:
1. Antes de invalidar los campos que se refieren a otros contenedores, debe llamarse PyObject_GC_UnTrack().
2. La memoria del objeto debe ser desasignada (deallocated) usando PyObject_GC_Del().
implements the garbage collector protocol and the child class does not include the Py_TPFLAGS_HAVE_GC
flag.
PyObject_GC_New(TYPE, typeobj)
Analogous to PyObject_New but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
PyObject_GC_NewVar(TYPE, typeobj, size)
Analogous to PyObject_NewVar but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
PyObject *PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *type, size_t extra_size)
Analogous to PyObject_GC_New but allocates extra_size bytes at the end of the object (at offset
tp_basicsize). The allocated memory is initialized to zeros, except for the Python object header.
The extra data will be deallocated with the object, but otherwise it is not managed by Python.
Advertencia: The function is marked as unstable because the final mechanism for reserving extra data after
an instance is not yet decided. For allocating a variable number of fields, prefer using PyVarObject and
tp_itemsize instead.
static int
my_traverse(Noddy *self, visitproc visit, void *arg)
{
Py_VISIT(self->foo);
Py_VISIT(self->bar);
return 0;
}
El manejador tp_clear debe ser del tipo query, o NULL si el objeto es inmutable.
typedef int (*inquiry)(PyObject *self)
Part of the Stable ABI. Descarta referencias que pueden haber creado ciclos de referencia. Los objetos inmutables
no tienen que definir este método ya que nunca pueden crear directamente ciclos de referencia. Tenga en cuenta que
el objeto aún debe ser válido después de llamar a este método (no solo llame a Py_DECREF() en una referencia).
El recolector de basura llamará a este método si detecta que este objeto está involucrado en un ciclo de referencia.
La C-API proporciona las siguientes funciones para controlar las ejecuciones de recolección de basura.
Py_ssize_t PyGC_Collect(void)
Part of the Stable ABI. Realiza una recolección de basura completa, si el recolector de basura está habilitado. (Tenga
en cuenta que gc.collect() lo ejecuta incondicionalmente).
Retorna el número de objetos recolectados e inalcanzables que no se pueden recolectar. Si el recolector de basura
está deshabilitado o ya está recolectando, retorna 0 inmediatamente. Los errores durante la recolección de basura
se pasan a sys.unraisablehook. Esta función no genera excepciones.
int PyGC_Enable(void)
Part of the Stable ABI since version 3.10. Habilita el recolector de basura: similar a gc.enable(). Retorna el
estado anterior, 0 para deshabilitado y 1 para habilitado.
Nuevo en la versión 3.10.
int PyGC_Disable(void)
Part of the Stable ABI since version 3.10. Deshabilita el recolector de basura: similar a gc.disable(). Retorna
el estado anterior, 0 para deshabilitado y 1 para habilitado.
Nuevo en la versión 3.10.
int PyGC_IsEnabled(void)
Part of the Stable ABI since version 3.10. Consulta el estado del recolector de basura: similar a gc.isenabled().
Retorna el estado actual, 0 para deshabilitado y 1 para habilitado.
Nuevo en la versión 3.10.
The C-API provides the following interface for querying information about the garbage collector.
void PyUnstable_GC_VisitObjects(gcvisitobjects_t callback, void *arg)
Run supplied callback on all live GC-capable objects. arg is passed through to all invocations of callback.
Advertencia: If new objects are (de)allocated by the callback it is undefined if they will be visited.
Garbage collection is disabled during operation. Explicitly running a collection in the callback may lead to
undefined behaviour e.g. visiting the same objects multiple times or not at all.
CPython expone su número de versión en las siguientes macros. Tenga en cuenta que estos corresponden a la versión con
la que se construye el código, no necesariamente la versión utilizada en tiempo de ejecución.
Consulte Estabilidad de la API en C para obtener una discusión sobre la estabilidad de API y ABI en todas las versiones.
PY_MAJOR_VERSION
El 3 en 3.4.1a2.
PY_MINOR_VERSION
El 4 en 3.4.1a2.
PY_MICRO_VERSION
El 1 en 3.4.1a2.
PY_RELEASE_LEVEL
La a en 3.4.1a2. Puede ser 0xA para la versión alfa, 0xB para la versión beta, 0xC para la versión candidata o
0xF para la versión final.
PY_RELEASE_SERIAL
El 2 en 3.4.1a2, cero para lanzamientos finales.
PY_VERSION_HEX
El número de versión de Python codificado en un solo entero.
La información de la versión subyacente se puede encontrar tratándola como un número de 32 bits de la siguiente
manera:
327
The Python/C API, Versión 3.13.0a5
Glosario
>>>
El prompt en el shell interactivo de Python por omisión. Frecuentemente vistos en ejemplos de código que pueden
ser ejecutados interactivamente en el intérprete.
...
Puede referirse a:
• El prompt en el shell interactivo de Python por omisión cuando se ingresa código para un bloque indentado de
código, y cuando se encuentra entre dos delimitadores que emparejan (paréntesis, corchetes, llaves o comillas
triples), o después de especificar un decorador.
• La constante incorporada Ellipsis.
clase base abstracta
Las clases base abstractas (ABC, por sus siglas en inglés Abstract Base Class) complementan al duck-typing brindan-
do un forma de definir interfaces con técnicas como hasattr() que serían confusas o sutilmente erróneas (por
ejemplo con magic methods). Las ABC introduce subclases virtuales, las cuales son clases que no heredan desde una
clase pero aún así son reconocidas por isinstance() y issubclass(); vea la documentación del módulo
abc. Python viene con muchas ABC incorporadas para las estructuras de datos( en el módulo collections.
abc), números (en el módulo numbers ) , flujos de datos (en el módulo io ) , buscadores y cargadores de
importaciones (en el módulo importlib.abc ) . Puede crear sus propios ABCs con el módulo abc.
anotación
Una etiqueta asociada a una variable, atributo de clase, parámetro de función o valor de retorno, usado por con-
vención como un type hint.
Las anotaciones de variables no pueden ser accedidas en tiempo de ejecución, pero las anotaciones de variables
globales, atributos de clase, y funciones son almacenadas en el atributo especial __annotations__ de módulos,
clases y funciones, respectivamente.
Consulte variable annotation, function annotation, PEP 484 y PEP 526, que describen esta funcionalidad. Consulte
también annotations-howto para conocer las mejores prácticas sobre cómo trabajar con anotaciones.
argumento
Un valor pasado a una function (o method) cuando se llama a la función. Hay dos clases de argumentos:
329
The Python/C API, Versión 3.13.0a5
• argumento nombrado: es un argumento precedido por un identificador (por ejemplo, nombre=) en una llama-
da a una función o pasado como valor en un diccionario precedido por **. Por ejemplo 3 y 5 son argumentos
nombrados en las llamadas a complex():
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
• argumento posicional son aquellos que no son nombrados. Los argumentos posicionales deben aparecer al
principio de una lista de argumentos o ser pasados como elementos de un iterable precedido por *. Por
ejemplo, 3 y 5 son argumentos posicionales en las siguientes llamadas:
complex(3, 5)
complex(*(3, 5))
Los argumentos son asignados a las variables locales en el cuerpo de la función. Vea en la sección calls las reglas
que rigen estas asignaciones. Sintácticamente, cualquier expresión puede ser usada para representar un argumento;
el valor evaluado es asignado a la variable local.
Vea también el parameter en el glosario, la pregunta frecuente la diferencia entre argumentos y parámetros, y PEP
362.
administrador asincrónico de contexto
Un objeto que controla el entorno visible en un sentencia async with al definir los métodos __aenter__()
y __aexit__(). Introducido por PEP 492.
generador asincrónico
Una función que retorna un asynchronous generator iterator. Es similar a una función corrutina definida con async
def excepto que contiene expresiones yield para producir series de variables usadas en un ciclo async for.
Usualmente se refiere a una función generadora asincrónica, pero puede referirse a un iterador generador asincrónico
en ciertos contextos. En aquellos casos en los que el significado no está claro, usar los términos completos evita la
ambigüedad.
Una función generadora asincrónica puede contener expresiones await así como sentencias async for, y
async with.
iterador generador asincrónico
Un objeto creado por una función asynchronous generator.
Este es un asynchronous iterator el cual cuando es llamado usa el método __anext__() retornando un objeto a
la espera (awaitable) el cual ejecutará el cuerpo de la función generadora asincrónica hasta la siguiente expresión
yield.
Cada yield suspende temporalmente el procesamiento, recordando el estado local de ejecución (incluyendo a las
variables locales y las sentencias try pendientes). Cuando el iterador del generador asincrónico vuelve efectivamente
con otro objeto a la espera (awaitable) retornado por el método __anext__(), retoma donde lo dejó. Vea PEP
492 y PEP 525.
iterable asincrónico
Un objeto, que puede ser usado en una sentencia async for. Debe retornar un asynchronous iterator de su
método __aiter__(). Introducido por PEP 492.
iterador asincrónico
Un objeto que implementa los métodos __aiter__() y __anext__(). __anext__() debe retornar
un objeto awaitable. async for resuelve los esperables retornados por un método de iterador asincrónico
__anext__() hasta que lanza una excepción StopAsyncIteration. Introducido por PEP 492.
atributo
Un valor asociado a un objeto al que se suele hacer referencia por su nombre utilizando expresiones punteadas. Por
ejemplo, si un objeto o tiene un atributo a se referenciaría como o.a.
Es posible dar a un objeto un atributo cuyo nombre no sea un identificador definido por identifiers, por ejemplo
usando setattr(), si el objeto lo permite. Dicho atributo no será accesible utilizando una expresión con puntos,
y en su lugar deberá ser recuperado con getattr().
a la espera
Un objeto que puede utilizarse en una expresión await. Puede ser una corutina o un objeto con un método
__await__(). Véase también PEP 492.
BDFL
Sigla de Benevolent Dictator For Life, benevolente dictador vitalicio, es decir Guido van Rossum, el creador de
Python.
archivo binario
A file object able to read and write bytes-like objects. Examples of binary files are files opened in binary mode
('rb', 'wb' or 'rb+'), sys.stdin.buffer, sys.stdout.buffer, and instances of io.BytesIO
and gzip.GzipFile.
Vea también text file para un objeto archivo capaz de leer y escribir objetos str.
referencia prestada
En la API C de Python, una referencia prestada es una referencia a un objeto, donde el código usando el objeto no
posee la referencia. Se convierte en un puntero colgante si se destruye el objeto. Por ejemplo, una recolección de
basura puede eliminar el último strong reference del objeto y así destruirlo.
Se recomienda llamar a Py_INCREF() en la referencia prestada para convertirla en una referencia fuerte in
situ, excepto cuando el objeto no se puede destruir antes del último uso de la referencia prestada. La función
Py_NewRef() se puede utilizar para crear una nueva referencia fuerte.
objetos tipo binarios
Un objeto que soporta Protocolo búfer y puede exportar un búfer C-contiguous. Esto incluye todas los objetos
bytes, bytearray, y array.array, así como muchos objetos comunes memoryview. Los objetos tipo
binarios pueden ser usados para varias operaciones que usan datos binarios; éstas incluyen compresión, salvar a
archivos binarios, y enviarlos a través de un socket.
Algunas operaciones necesitan que los datos binarios sean mutables. La documentación frecuentemente se refie-
re a éstos como «objetos tipo binario de lectura y escritura». Ejemplos de objetos de búfer mutables incluyen a
bytearray y memoryview de la bytearray. Otras operaciones que requieren datos binarios almacenados
en objetos inmutables («objetos tipo binario de sólo lectura»); ejemplos de éstos incluyen bytes y memoryview
del objeto bytes.
bytecode
El código fuente Python es compilado en bytecode, la representación interna de un programa python en el intér-
prete CPython. El bytecode también es guardado en caché en los archivos .pyc de tal forma que ejecutar el mismo
archivo es más fácil la segunda vez (la recompilación desde el código fuente a bytecode puede ser evitada). Este
«lenguaje intermedio» deberá corren en una virtual machine que ejecute el código de máquina correspondiente
a cada bytecode. Note que los bytecodes no tienen como requisito trabajar en las diversas máquina virtuales de
Python, ni de ser estable entre versiones Python.
Una lista de las instrucciones en bytecode está disponible en la documentación de el módulo dis.
callable
Un callable es un objeto que puede ser llamado, posiblemente con un conjunto de argumentos (véase argument),
con la siguiente sintaxis:
Una function, y por extensión un method, es un callable. Una instancia de una clase que implementa el método
__call__() también es un callable.
331
The Python/C API, Versión 3.13.0a5
retrollamada
Una función de subrutina que se pasa como un argumento para ejecutarse en algún momento en el futuro.
clase
Una plantilla para crear objetos definidos por el usuario. Las definiciones de clase normalmente contienen defini-
ciones de métodos que operan una instancia de la clase.
variable de clase
Una variable definida en una clase y prevista para ser modificada sólo a nivel de clase (es decir, no en una instancia
de la clase).
número complejo
Una extensión del sistema familiar de número reales en el cual los números son expresados como la suma de
una parte real y una parte imaginaria. Los números imaginarios son múltiplos de la unidad imaginaria (la raíz
cuadrada de -1), usualmente escrita como i en matemáticas o j en ingeniería. Python tiene soporte incorporado
para números complejos, los cuales son escritos con la notación mencionada al final.; la parte imaginaria es escrita
con un sufijo j, por ejemplo, 3+1j. Para tener acceso a los equivalentes complejos del módulo math module,
use cmath. El uso de números complejos es matemática bastante avanzada. Si no le parecen necesarios, puede
ignorarlos sin inconvenientes.
administrador de contextos
An object which controls the environment seen in a with statement by defining __enter__() and
__exit__() methods. See PEP 343.
variable de contexto
Una variable que puede tener diferentes valores dependiendo del contexto. Esto es similar a un almacenamiento de
hilo local Thread-Local Storage en el cual cada hilo de ejecución puede tener valores diferentes para una variable. Sin
embargo, con las variables de contexto, podría haber varios contextos en un hilo de ejecución y el uso principal de las
variables de contexto es mantener registro de las variables en tareas concurrentes asíncronas. Vea contextvars.
contiguo
Un búfer es considerado contiguo con precisión si es C-contiguo o Fortran contiguo. Los búferes cero dimensio-
nales con C y Fortran contiguos. En los arreglos unidimensionales, los ítems deben ser dispuestos en memoria
uno siguiente al otro, ordenados por índices que comienzan en cero. En arreglos unidimensionales C-contiguos, el
último índice varía más velozmente en el orden de las direcciones de memoria. Sin embargo, en arreglos Fortran
contiguos, el primer índice vería más rápidamente.
corrutina
Las corrutinas son una forma más generalizadas de las subrutinas. A las subrutinas se ingresa por un punto y se sale
por otro punto. Las corrutinas pueden se iniciadas, finalizadas y reanudadas en muchos puntos diferentes. Pueden
ser implementadas con la sentencia async def. Vea además PEP 492.
función corrutina
Un función que retorna un objeto coroutine . Una función corrutina puede ser definida con la sentencia async
def, y puede contener las palabras claves await, async for, y async with. Las mismas son introducidas
en PEP 492.
CPython
La implementación canónica del lenguaje de programación Python, como se distribuye en python.org. El término
«CPython» es usado cuando es necesario distinguir esta implementación de otras como Jython o IronPython.
decorador
Una función que retorna otra función, usualmente aplicada como una función de transformación empleando la
sintaxis @envoltorio. Ejemplos comunes de decoradores son classmethod() y staticmethod().
La sintaxis del decorador es meramente azúcar sintáctico, las definiciones de las siguientes dos funciones son se-
mánticamente equivalentes:
def f(arg):
...
f = staticmethod(f)
@staticmethod
def f(arg):
...
El mismo concepto existe para clases, pero son menos usadas. Vea la documentación de function definitions y class
definitions para mayor detalle sobre decoradores.
descriptor
Any object which defines the methods __get__(), __set__(), or __delete__(). When a class attribute is
a descriptor, its special binding behavior is triggered upon attribute lookup. Normally, using a.b to get, set or delete
an attribute looks up the object named b in the class dictionary for a, but if b is a descriptor, the respective descriptor
method gets called. Understanding descriptors is a key to a deep understanding of Python because they are the basis
for many features including functions, methods, properties, class methods, static methods, and reference to super
classes.
Para obtener más información sobre los métodos de los descriptores, consulte descriptors o Guía práctica de uso
de los descriptores.
diccionario
An associative array, where arbitrary keys are mapped to values. The keys can be any object with __hash__()
and __eq__() methods. Called a hash in Perl.
comprensión de diccionarios
Una forma compacta de procesar todos o parte de los elementos en un iterable y retornar un diccionario con
los resultados. results = {n: n ** 2 for n in range(10)} genera un diccionario que contiene la
clave n asignada al valor n ** 2. Ver comprehensions.
vista de diccionario
Los objetos retornados por los métodos dict.keys(), dict.values(), y dict.items() son llamados
vistas de diccionarios. Proveen una vista dinámica de las entradas de un diccionario, lo que significa que cuando
el diccionario cambia, la vista refleja éstos cambios. Para forzar a la vista de diccionario a convertirse en una lista
completa, use list(dictview). Vea dict-views.
docstring
A string literal which appears as the first expression in a class, function or module. While ignored when the suite is
executed, it is recognized by the compiler and put into the __doc__ attribute of the enclosing class, function or
module. Since it is available via introspection, it is the canonical place for documentation of the object.
tipado de pato
Un estilo de programación que no revisa el tipo del objeto para determinar si tiene la interfaz correcta; en vez de
ello, el método o atributo es simplemente llamado o usado («Si se ve como un pato y grazna como un pato, debe
ser un pato»). Enfatizando las interfaces en vez de hacerlo con los tipos específicos, un código bien diseñado pues
tener mayor flexibilidad permitiendo la sustitución polimórfica. El tipado de pato duck-typing evita usar pruebas
llamando a type() o isinstance(). (Nota: si embargo, el tipado de pato puede ser complementado con
abstract base classes. En su lugar, generalmente pregunta con hasattr() o EAFP.
EAFP
Del inglés Easier to ask for forgiveness than permission, es más fácil pedir perdón que pedir permiso. Este estilo
de codificación común en Python asume la existencia de claves o atributos válidos y atrapa las excepciones si esta
suposición resulta falsa. Este estilo rápido y limpio está caracterizado por muchas sentencias try y except. Esta
técnica contrasta con estilo LBYL usual en otros lenguajes como C.
expresión
Una construcción sintáctica que puede ser evaluada, hasta dar un valor. En otras palabras, una expresión es una
333
The Python/C API, Versión 3.13.0a5
acumulación de elementos de expresión tales como literales, nombres, accesos a atributos, operadores o llamadas
a funciones, todos ellos retornando valor. A diferencia de otros lenguajes, no toda la sintaxis del lenguaje son
expresiones. También hay statements que no pueden ser usadas como expresiones, como la while. Las asignaciones
también son sentencias, no expresiones.
módulo de extensión
Un módulo escrito en C o C++, usando la API para C de Python para interactuar con el núcleo y el código del
usuario.
f-string
Son llamadas f-strings las cadenas literales que usan el prefijo 'f' o 'F', que es una abreviatura para formatted
string literals. Vea también PEP 498.
objeto archivo
An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.
Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of
storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.). File
objects are also called file-like objects or streams.
Existen tres categorías de objetos archivo: crudos raw archivos binarios, con búfer archivos binarios y archivos de
texto. Sus interfaces son definidas en el módulo io. La forma canónica de crear objetos archivo es usando la función
open().
objetos tipo archivo
Un sinónimo de file object.
codificación del sistema de archivos y manejador de errores
Controlador de errores y codificación utilizado por Python para decodificar bytes del sistema operativo y codificar
Unicode en el sistema operativo.
La codificación del sistema de archivos debe garantizar la decodificación exitosa de todos los bytes por debajo de
128. Si la codificación del sistema de archivos no proporciona esta garantía, las funciones de API pueden lanzar
UnicodeError.
Las funciones sys.getfilesystemencoding() y sys.getfilesystemencodeerrors() se pue-
den utilizar para obtener la codificación del sistema de archivos y el controlador de errores.
La codificación del sistema de archivos y el manejador de errores se configuran al inicio de Python mediante la
función PyConfig_Read(): consulte los miembros filesystem_encoding y filesystem_errors
de PyConfig.
Vea también locale encoding.
buscador
Un objeto que trata de encontrar el loader para el módulo que está siendo importado.
Desde la versión 3.3 de Python, existen dos tipos de buscadores: meta buscadores de ruta para usar con sys.
meta_path, y buscadores de entradas de rutas para usar con sys.path_hooks.
Vea PEP 302, PEP 420 y PEP 451 para mayores detalles.
división entera a la baja
Una división matemática que se redondea hacia el entero menor más cercano. El operador de la división entera
a la baja es //. Por ejemplo, la expresión 11 // 4 evalúa 2 a diferencia del 2.75 retornado por la verdadera
división de números flotantes. Note que (-11) // 4 es -3 porque es -2.75 redondeado para abajo. Ver PEP
238.
función
Una serie de sentencias que retornan un valor al que las llama. También se le puede pasar cero o más argumentos
los cuales pueden ser usados en la ejecución de la misma. Vea también parameter, method, y la sección function.
anotación de función
Una annotation del parámetro de una función o un valor de retorno.
Las anotaciones de funciones son usadas frecuentemente para indicadores de tipo, por ejemplo, se espera que una
función tome dos argumentos de clase int y también se espera que retorne dos valores int:
recolección de basura
El proceso de liberar la memoria de lo que ya no está en uso. Python realiza recolección de basura (garbage co-
llection) llevando la cuenta de las referencias, y el recogedor de basura cíclico es capaz de detectar y romper las
referencias cíclicas. El recogedor de basura puede ser controlado mediante el módulo gc .
generador
Una función que retorna un generator iterator. Luce como una función normal excepto que contiene la expresión
yield para producir series de valores utilizables en un bucle for o que pueden ser obtenidas una por una con la
función next().
Usualmente se refiere a una función generadora, pero puede referirse a un iterador generador en ciertos contextos.
En aquellos casos en los que el significado no está claro, usar los términos completos evita la ambigüedad.
iterador generador
Un objeto creado por una función generator.
Cada yield suspende temporalmente el procesamiento, recordando el estado de ejecución local (incluyendo las
variables locales y las sentencias try pendientes). Cuando el «iterador generado» vuelve, retoma donde ha dejado,
a diferencia de lo que ocurre con las funciones que comienzan nuevamente con cada invocación.
expresión generadora
An expression that returns an iterator. It looks like a normal expression followed by a for clause defining a loop
variable, range, and an optional if clause. The combined expression generates values for an enclosing function:
función genérica
Una función compuesta de muchas funciones que implementan la misma operación para diferentes tipos. Qué
implementación deberá ser usada durante la llamada a la misma es determinado por el algoritmo de despacho.
Vea también la entrada de glosario single dispatch, el decorador functools.singledispatch(), y PEP
443.
335
The Python/C API, Versión 3.13.0a5
tipos genéricos
Un type que se puede parametrizar; normalmente un container class como list o dict. Usado para type hints y
annotations.
Para más detalles, véase generic alias types, PEP 483, PEP 484, PEP 585, y el módulo typing.
GIL
Vea global interpreter lock.
bloqueo global del intérprete
Mecanismo empleado por el intérprete CPython para asegurar que sólo un hilo ejecute el bytecode Python por
vez. Esto simplifica la implementación de CPython haciendo que el modelo de objetos (incluyendo algunos críticos
como dict) están implícitamente a salvo de acceso concurrente. Bloqueando el intérprete completo se simplifica
hacerlo multi-hilos, a costa de mucho del paralelismo ofrecido por las máquinas con múltiples procesadores.
Sin embargo, algunos módulos de extensión, tanto estándar como de terceros, están diseñados para liberar el GIL
cuando se realizan tareas computacionalmente intensivas como la compresión o el hashing. Además, el GIL siempre
es liberado cuando se hace entrada/salida.
Esfuerzos previos hechos para crear un intérprete «sin hilos» (uno que bloquee los datos compartidos con una
granularidad mucho más fina) no han sido exitosos debido a que el rendimiento sufrió para el caso más común
de un solo procesador. Se cree que superar este problema de rendimiento haría la implementación mucho más
compleja y por tanto, más costosa de mantener.
hash-based pyc
Un archivo cache de bytecode que usa el hash en vez de usar el tiempo de la última modificación del archivo fuente
correspondiente para determinar su validez. Vea pyc-invalidation.
hashable
An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__()
method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare
equal must have the same hash value.
Ser hashable hace a un objeto utilizable como clave de un diccionario y miembro de un set, porque éstas estructuras
de datos usan los valores de hash internamente.
La mayoría de los objetos inmutables incorporados en Python son hashables; los contenedores mutables (como las
listas o los diccionarios) no lo son; los contenedores inmutables (como tuplas y conjuntos frozensets) son hashables
si sus elementos son hashables . Los objetos que son instancias de clases definidas por el usuario son hashables
por defecto. Todos se comparan como desiguales (excepto consigo mismos), y su valor de hash está derivado de su
función id().
IDLE
Un Entorno Integrado de Desarrollo y Aprendizaje para Python. idle es un editor básico y un entorno de intérprete
que se incluye con la distribución estándar de Python.
immortal
If an object is immortal, its reference count is never modified, and therefore it is never deallocated.
Built-in strings and singletons are immortal objects. For example, True and None singletons are immmortal.
See PEP 683 – Immortal Objects, Using a Fixed Refcount for more information.
inmutable
Un objeto con un valor fijo. Los objetos inmutables son números, cadenas y tuplas. Éstos objetos no pueden ser
alterados. Un nuevo objeto debe ser creado si un valor diferente ha de ser guardado. Juegan un rol importante en
lugares donde es necesario un valor de hash constante, por ejemplo como claves de un diccionario.
ruta de importación
Una lista de las ubicaciones (o entradas de ruta) que son revisadas por path based finder al importar módulos.
Durante la importación, ésta lista de localizaciones usualmente viene de sys.path, pero para los subpaquetes
también puede incluir al atributo __path__ del paquete padre.
importar
El proceso mediante el cual el código Python dentro de un módulo se hace alcanzable desde otro código Python en
otro módulo.
importador
Un objeto que buscan y lee un módulo; un objeto que es tanto finder como loader.
interactivo
Python tiene un intérprete interactivo, lo que significa que puede ingresar sentencias y expresiones en el prompt del
intérprete, ejecutarlos de inmediato y ver sus resultados. Sólo ejecute python sin argumentos (podría seleccionarlo
desde el menú principal de su computadora). Es una forma muy potente de probar nuevas ideas o inspeccionar
módulos y paquetes (recuerde help(x)).
interpretado
Python es un lenguaje interpretado, a diferencia de uno compilado, a pesar de que la distinción puede ser difusa
debido al compilador a bytecode. Esto significa que los archivos fuente pueden ser corridos directamente, sin crear
explícitamente un ejecutable que es corrido luego. Los lenguajes interpretados típicamente tienen ciclos de desa-
rrollo y depuración más cortos que los compilados, sin embargo sus programas suelen correr más lentamente. Vea
también interactive.
apagado del intérprete
Cuando se le solicita apagarse, el intérprete Python ingresa a un fase especial en la cual gradualmente libera todos los
recursos reservados, como módulos y varias estructuras internas críticas. También hace varias llamadas al recolector
de basura. Esto puede disparar la ejecución de código de destructores definidos por el usuario o weakref callbacks.
El código ejecutado durante la fase de apagado puede encontrar varias excepciones debido a que los recursos que
necesita pueden no funcionar más (ejemplos comunes son los módulos de bibliotecas o los artefactos de advertencias
warnings machinery)
La principal razón para el apagado del intérpreter es que el módulo __main__ o el script que estaba corriendo
termine su ejecución.
iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such
as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you
define with an __iter__() method or with a __getitem__() method that implements sequence semantics.
Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), …).
When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the
object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to
call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating
a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and
generator.
iterador
An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it
to the built-in function next()) return successive items in the stream. When no more data are available a
StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls
to its __next__() method just raise StopIteration again. Iterators are required to have an __iter__()
method that returns the iterator object itself so every iterator is also iterable and may be used in most places where
other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container
object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a
for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous
iteration pass, making it appear like an empty container.
Puede encontrar más información en typeiter.
337
The Python/C API, Versión 3.13.0a5
Detalles de implementación de CPython: CPython does not consistently apply the requirement that an iterator
define __iter__().
función clave
Una función clave o una función de colación es un invocable que retorna un valor usado para el ordenamiento o
clasificación. Por ejemplo, locale.strxfrm() es usada para producir claves de ordenamiento que se adaptan
a las convenciones específicas de ordenamiento de un locale.
Cierta cantidad de herramientas de Python aceptan funciones clave para controlar como los elementos son orde-
nados o agrupados. Incluyendo a min(), max(), sorted(), list.sort(), heapq.merge(), heapq.
nsmallest(), heapq.nlargest(), y itertools.groupby().
Hay varias formas de crear una función clave. Por ejemplo, el método str.lower() puede servir como fun-
ción clave para ordenamientos que no distingan mayúsculas de minúsculas. Como alternativa, una función clave
puede ser realizada con una expresión lambda como lambda r: (r[0], r[2]). Además, operator.
attrgetter(), operator.itemgetter() y operator.methodcaller() son tres constructores de
funciones clave. Consulte Sorting HOW TO para ver ejemplos de cómo crear y utilizar funciones clave.
argumento nombrado
Vea argument.
lambda
Una función anónima de una línea consistente en un sola expression que es evaluada cuando la función es llamada.
La sintaxis para crear una función lambda es lambda [parameters]: expression
LBYL
Del inglés Look before you leap, «mira antes de saltar». Es un estilo de codificación que prueba explícitamente
las condiciones previas antes de hacer llamadas o búsquedas. Este estilo contrasta con la manera EAFP y está
caracterizado por la presencia de muchas sentencias if.
En entornos multi-hilos, el método LBYL tiene el riesgo de introducir condiciones de carrera entre los hilos
que están «mirando» y los que están «saltando». Por ejemplo, el código, if key in mapping: return
mapping[key] puede fallar si otro hilo remueve key de mapping después del test, pero antes de retornar el
valor. Este problema puede ser resuelto usando bloqueos o empleando el método EAFP.
codificación de la configuración regional
En Unix, es la codificación de la configuración regional LC_CTYPE. Se puede configurar con locale.
setlocale(locale.LC_CTYPE, new_locale).
En Windows, es la página de códigos ANSI (por ejemplo, "cp1252").
En Android y VxWorks, Python utiliza "utf-8" como codificación regional.
locale.getencoding() se puede utilizar para obtener la codificación de la configuración regional.
Vea también filesystem encoding and error handler.
lista
A built-in Python sequence. Despite its name it is more akin to an array in other languages than to a linked list since
access to elements is O(1).
comprensión de listas
Una forma compacta de procesar todos o parte de los elementos en una secuencia y retornar una lista como re-
sultado. result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] genera
una lista de cadenas conteniendo números hexadecimales (0x..) entre 0 y 255. La cláusula if es opcional. Si es
omitida, todos los elementos en range(256) son procesados.
cargador
Un objeto que carga un módulo. Debe definir el método llamado load_module(). Un cargador es normalmente
retornados por un finder. Vea PEP 302 para detalles y importlib.abc.Loader para una abstract base class.
método mágico
Una manera informal de llamar a un special method.
mapeado
Un objeto contenedor que permite recupero de claves arbitrarias y que implementa los métodos especificados
en la collections.abc.Mapping o collections.abc.MutableMapping abstract base classes.
Por ejemplo, dict, collections.defaultdict, collections.OrderedDict y collections.
Counter.
meta buscadores de ruta
Un finder retornado por una búsqueda de sys.meta_path. Los meta buscadores de ruta están relacionados a
buscadores de entradas de rutas, pero son algo diferente.
Vea en importlib.abc.MetaPathFinder los métodos que los meta buscadores de ruta implementan.
metaclase
La clase de una clase. Las definiciones de clases crean nombres de clase, un diccionario de clase, y una lista de
clases base. Las metaclases son responsables de tomar estos tres argumentos y crear la clase. La mayoría de los
objetos de un lenguaje de programación orientado a objetos provienen de una implementación por defecto. Lo que
hace a Python especial que es posible crear metaclases a medida. La mayoría de los usuario nunca necesitarán esta
herramienta, pero cuando la necesidad surge, las metaclases pueden brindar soluciones poderosas y elegantes. Han
sido usadas para loggear acceso de atributos, agregar seguridad a hilos, rastrear la creación de objetos, implementar
singletons, y muchas otras tareas.
Más información hallará en metaclasses.
método
Una función que es definida dentro del cuerpo de una clase. Si es llamada como un atributo de una instancia de otra
clase, el método tomará el objeto instanciado como su primer argument (el cual es usualmente denominado self).
Vea function y nested scope.
orden de resolución de métodos
Orden de resolución de métodos es el orden en el cual una clase base es buscada por un miembro durante la
búsqueda. Mire en The Python 2.3 Method Resolution Order los detalles del algoritmo usado por el intérprete
Python desde la versión 2.3.
módulo
Un objeto que sirve como unidad de organización del código Python. Los módulos tienen espacios de nombres
conteniendo objetos Python arbitrarios. Los módulos son cargados en Python por el proceso de importing.
Vea también package.
especificador de módulo
Un espacio de nombres que contiene la información relacionada a la importación usada al leer un módulo. Una
instancia de importlib.machinery.ModuleSpec.
MRO
Vea method resolution order.
mutable
Los objetos mutables pueden cambiar su valor pero mantener su id(). Vea también immutable.
tupla nombrada
La denominación «tupla nombrada» se aplica a cualquier tipo o clase que hereda de una tupla y cuyos elemen-
tos indexables son también accesibles usando atributos nombrados. Este tipo o clase puede tener además otras
capacidades.
Varios tipos incorporados son tuplas nombradas, incluyendo los valores retornados por time.localtime() y
os.stat(). Otro ejemplo es sys.float_info:
339
The Python/C API, Versión 3.13.0a5
Some named tuples are built-in types (such as the above examples). Alternatively, a named tuple can be created
from a regular class definition that inherits from tuple and that defines named fields. Such a class can be written by
hand, or it can be created by inheriting typing.NamedTuple, or with the factory function collections.
namedtuple(). The latter techniques also add some extra methods that may not be found in hand-written or
built-in named tuples.
espacio de nombres
El lugar donde la variable es almacenada. Los espacios de nombres son implementados como diccionarios. Hay
espacio de nombre local, global, e incorporado así como espacios de nombres anidados en objetos (en métodos).
Los espacios de nombres soportan modularidad previniendo conflictos de nombramiento. Por ejemplo, las funciones
builtins.open y os.open() se distinguen por su espacio de nombres. Los espacios de nombres también
ayuda a la legibilidad y mantenibilidad dejando claro qué módulo implementa una función. Por ejemplo, escribiendo
random.seed() o itertools.islice() queda claro que éstas funciones están implementadas en los
módulos random y itertools, respectivamente.
paquete de espacios de nombres
Un PEP 420 package que sirve sólo para contener subpaquetes. Los paquetes de espacios de nombres pueden no
tener representación física, y específicamente se diferencian de los regular package porque no tienen un archivo
__init__.py.
Vea también module.
alcances anidados
La habilidad de referirse a una variable dentro de una definición encerrada. Por ejemplo, una función definida
dentro de otra función puede referir a variables en la función externa. Note que los alcances anidados por defecto
sólo funcionan para referencia y no para asignación. Las variables locales leen y escriben sólo en el alcance más
interno. De manera semejante, las variables globales pueden leer y escribir en el espacio de nombres global. Con
nonlocal se puede escribir en alcances exteriores.
clase de nuevo estilo
Old name for the flavor of classes now used for all class objects. In earlier Python versions, only new-style classes
could use Python’s newer, versatile features like __slots__, descriptors, properties, __getattribute__(),
class methods, and static methods.
objeto
Cualquier dato con estado (atributo o valor) y comportamiento definido (métodos). También es la más básica clase
base para cualquier new-style class.
paquete
Un module Python que puede contener submódulos o recursivamente, subpaquetes. Técnicamente, un paquete es
un módulo Python con un atributo __path__.
Vea también regular package y namespace package.
parámetro
Una entidad nombrada en una definición de una function (o método) que especifica un argument (o en algunos
casos, varios argumentos) que la función puede aceptar. Existen cinco tipos de argumentos:
• posicional o nombrado: especifica un argumento que puede ser pasado tanto como posicional o como nom-
brado. Este es el tipo por defecto de parámetro, como foo y bar en el siguiente ejemplo:
• sólo posicional: especifica un argumento que puede ser pasado sólo por posición. Los parámetros sólo po-
sicionales pueden ser definidos incluyendo un carácter / en la lista de parámetros de la función después de
ellos, como posonly1 y posonly2 en el ejemplo que sigue:
• sólo nombrado: especifica un argumento que sólo puede ser pasado por nombre. Los parámetros sólo por
nombre pueden ser definidos incluyendo un parámetro posicional de una sola variable o un simple *` antes
de ellos en la lista de parámetros en la definición de la función, como kw_only1 y kw_only2 en el ejemplo
siguiente:
• variable posicional: especifica una secuencia arbitraria de argumentos posicionales que pueden ser brindados
(además de cualquier argumento posicional aceptado por otros parámetros). Este parámetro puede ser definido
anteponiendo al nombre del parámetro *, como a args en el siguiente ejemplo:
• variable nombrado: especifica que arbitrariamente muchos argumentos nombrados pueden ser brindados
(además de cualquier argumento nombrado ya aceptado por cualquier otro parámetro). Este parámetro pue-
de ser definido anteponiendo al nombre del parámetro con **, como kwargs en el ejemplo precedente.
Los parámetros puede especificar tanto argumentos opcionales como requeridos, así como valores por defecto para
algunos argumentos opcionales.
Vea también el glosario de argument, la pregunta respondida en la diferencia entre argumentos y parámetros, la
clase inspect.Parameter, la sección function , y PEP 362.
entrada de ruta
Una ubicación única en el import path que el path based finder consulta para encontrar los módulos a importar.
buscador de entradas de ruta
Un finder retornado por un invocable en sys.path_hooks (esto es, un path entry hook) que sabe cómo localizar
módulos dada una path entry.
Vea en importlib.abc.PathEntryFinder los métodos que los buscadores de entradas de ruta implemen-
tan.
gancho a entrada de ruta
A callable on the sys.path_hooks list which returns a path entry finder if it knows how to find modules on a
specific path entry.
buscador basado en ruta
Uno de los meta buscadores de ruta por defecto que busca un import path para los módulos.
objeto tipo ruta
Un objeto que representa una ruta del sistema de archivos. Un objeto tipo ruta puede ser tanto una str como un
bytes representando una ruta, o un objeto que implementa el protocolo os.PathLike. Un objeto que soporta
el protocolo os.PathLike puede ser convertido a ruta del sistema de archivo de clase str o bytes usando la
función os.fspath(); os.fsdecode() os.fsencode() pueden emplearse para garantizar que retorne
respectivamente str o bytes. Introducido por PEP 519.
PEP
Propuesta de mejora de Python, del inglés Python Enhancement Proposal. Un PEP es un documento de diseño que
brinda información a la comunidad Python, o describe una nueva capacidad para Python, sus procesos o entorno.
Los PEPs deberían dar una especificación técnica concisa y una fundamentación para las capacidades propuestas.
341
The Python/C API, Versión 3.13.0a5
Los PEPs tienen como propósito ser los mecanismos primarios para proponer nuevas y mayores capacidad, para
recoger la opinión de la comunidad sobre un tema, y para documentar las decisiones de diseño que se han hecho
en Python. El autor del PEP es el responsable de lograr consenso con la comunidad y documentar las opiniones
disidentes.
Vea PEP 1.
porción
Un conjunto de archivos en un único directorio (posiblemente guardo en un archivo comprimido zip) que contribuye
a un espacio de nombres de paquete, como está definido en PEP 420.
argumento posicional
Vea argument.
API provisional
Una API provisoria es aquella que deliberadamente fue excluida de las garantías de compatibilidad hacia atrás de
la biblioteca estándar. Aunque no se esperan cambios fundamentales en dichas interfaces, como están marcadas
como provisionales, los cambios incompatibles hacia atrás (incluso remover la misma interfaz) podrían ocurrir
si los desarrolladores principales lo estiman. Estos cambios no se hacen gratuitamente – solo ocurrirán si fallas
fundamentales y serias son descubiertas que no fueron vistas antes de la inclusión de la API.
Incluso para APIs provisorias, los cambios incompatibles hacia atrás son vistos como una «solución de último
recurso» - se intentará todo para encontrar una solución compatible hacia atrás para los problemas identificados.
Este proceso permite que la biblioteca estándar continúe evolucionando con el tiempo, sin bloquearse por errores
de diseño problemáticos por períodos extensos de tiempo. Vea PEP 411 para más detalles.
paquete provisorio
Vea provisional API.
Python 3000
Apodo para la fecha de lanzamiento de Python 3.x (acuñada en un tiempo cuando llegar a la versión 3 era algo
distante en el futuro.) También se lo abrevió como Py3k.
Pythónico
Una idea o pieza de código que sigue ajustadamente la convenciones idiomáticas comunes del lenguaje Python,
en vez de implementar código usando conceptos comunes a otros lenguajes. Por ejemplo, una convención común
en Python es hacer bucles sobre todos los elementos de un iterable con la sentencia for. Muchos otros lenguajes
no tienen este tipo de construcción, así que los que no están familiarizados con Python podrían usar contadores
numéricos:
for i in range(len(food)):
print(food[i])
nombre calificado
Un nombre con puntos mostrando la ruta desde el alcance global del módulo a la clase, función o método definido
en dicho módulo, como se define en PEP 3155. Para las funciones o clases de más alto nivel, el nombre calificado
es el igual al nombre del objeto:
>>> class C:
... class D:
... def meth(self):
... pass
...
(continúe en la próxima página)
Cuando es usado para referirse a los módulos, nombre completamente calificado significa la ruta con puntos completo
al módulo, incluyendo cualquier paquete padre, por ejemplo, email.mime.text:
contador de referencias
The number of references to an object. When the reference count of an object drops to zero, it is deallocated.
Some objects are immortal and have reference counts that are never modified, and therefore the objects are never
deallocated. Reference counting is generally not visible to Python code, but it is a key element of the CPython
implementation. Programmers can call the sys.getrefcount() function to return the reference count for a
particular object.
paquete regular
Un package tradicional, como aquellos con un directorio conteniendo el archivo __init__.py.
Vea también namespace package.
__slots__
Es una declaración dentro de una clase que ahorra memoria predeclarando espacio para las atributos de la instancia
y eliminando diccionarios de la instancia. Aunque es popular, esta técnica es algo dificultosa de lograr correctamente
y es mejor reservarla para los casos raros en los que existen grandes cantidades de instancias en aplicaciones con
uso crítico de memoria.
secuencia
An iterable which supports efficient element access using integer indices via the __getitem__() special method
and defines a __len__() method that returns the length of the sequence. Some built-in sequence types are list,
str, tuple, and bytes. Note that dict also supports __getitem__() and __len__(), but is considered
a mapping rather than a sequence because the lookups use arbitrary immutable keys rather than integers.
The collections.abc.Sequence abstract base class defines a much richer interface that goes be-
yond just __getitem__() and __len__(), adding count(), index(), __contains__(), and
__reversed__(). Types that implement this expanded interface can be registered explicitly using
register(). For more documentation on sequence methods generally, see Common Sequence Operations.
comprensión de conjuntos
Una forma compacta de procesar todos o parte de los elementos en un iterable y retornar un conjunto con los
resultados. results = {c for c in 'abracadabra' if c not in 'abc'} genera el conjunto
de cadenas {'r', 'd'}. Ver comprehensions.
despacho único
Una forma de despacho de una generic function donde la implementación es elegida a partir del tipo de un sólo
argumento.
rebanada
Un objeto que contiene una porción de una sequence. Una rebanada es creada usando la notación de suscripto, []
con dos puntos entre los números cuando se ponen varios, como en nombre_variable[1:3:5]. La notación
con corchete (suscrito) usa internamente objetos slice.
343
The Python/C API, Versión 3.13.0a5
soft deprecated
A soft deprecation can be used when using an API which should no longer be used to write new code, but it remains
safe to continue using it in existing code. The API remains documented and tested, but will not be developed further
(no enhancement).
The main difference between a «soft» and a (regular) «hard» deprecation is that the soft deprecation does not imply
scheduling the removal of the deprecated API.
Another difference is that a soft deprecation does not issue a warning.
See PEP 387: Soft Deprecation.
método especial
Un método que es llamado implícitamente por Python cuando ejecuta ciertas operaciones en un tipo, como la
adición. Estos métodos tienen nombres que comienzan y terminan con doble barra baja. Los métodos especiales
están documentados en specialnames.
sentencia
Una sentencia es parte de un conjunto (un «bloque» de código). Una sentencia tanto es una expression como alguna
de las varias sintaxis usando una palabra clave, como if, while o for.
static type checker
An external tool that reads Python code and analyzes it, looking for issues such as incorrect types. See also type
hints and the typing module.
referencia fuerte
En la API de C de Python, una referencia fuerte es una referencia a un objeto que es propiedad del código que
mantiene la referencia. La referencia fuerte se toma llamando a Py_INCREF() cuando se crea la referencia y se
libera con Py_DECREF() cuando se elimina la referencia.
La función Py_NewRef() se puede utilizar para crear una referencia fuerte a un objeto. Por lo general, se debe
llamar a la función Py_DECREF() en la referencia fuerte antes de salir del alcance de la referencia fuerte, para
evitar filtrar una referencia.
Consulte también borrowed reference.
codificación de texto
Una cadena de caracteres en Python es una secuencia de puntos de código Unicode (en el rango U+0000–
U+10FFFF). Para almacenar o transferir una cadena de caracteres, es necesario serializarla como una secuencia
de bytes.
La serialización de una cadena de caracteres en una secuencia de bytes se conoce como «codificación», y la re-
creación de la cadena de caracteres a partir de la secuencia de bytes se conoce como «decodificación».
Existe una gran variedad de serializaciones de texto codecs, que se denominan colectivamente «codificaciones de
texto».
archivo de texto
Un file object capaz de leer y escribir objetos str. Frecuentemente, un archivo de texto también accede a un flujo
de datos binario y maneja automáticamente el text encoding. Ejemplos de archivos de texto que son abiertos en
modo texto ('r' o 'w'), sys.stdin, sys.stdout, y las instancias de io.StringIO.
Vea también binary file por objeto de archivos capaces de leer y escribir objeto tipo binario.
cadena con triple comilla
Una cadena que está enmarcada por tres instancias de comillas (») o apostrofes (“). Aunque no brindan ninguna
funcionalidad que no está disponible usando cadenas con comillas simple, son útiles por varias razones. Permiten
incluir comillas simples o dobles sin escapar dentro de las cadenas y pueden abarcar múltiples líneas sin el uso de
caracteres de continuación, haciéndolas particularmente útiles para escribir docstrings.
tipo
El tipo de un objeto Python determina qué tipo de objeto es; cada objeto tiene un tipo. El tipo de un objeto puede
ser accedido por su atributo __class__ o puede ser conseguido usando type(obj).
alias de tipos
Un sinónimo para un tipo, creado al asignar un tipo a un identificador.
Los alias de tipos son útiles para simplificar los indicadores de tipo. Por ejemplo:
def remove_gray_shades(
colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass
class C:
field: 'annotation'
Las anotaciones de variables son frecuentemente usadas para type hints: por ejemplo, se espera que esta variable
tenga valores de clase int:
count: int = 0
345
The Python/C API, Versión 3.13.0a5
Estos documentos son generados por reStructuredText desarrollado por Sphinx, un procesador de documentos específi-
camente escrito para la documentación de Python.
El desarrollo de la documentación y su cadena de herramientas es un esfuerzo enteramente voluntario, al igual que Python.
Si tu quieres contribuir, por favor revisa la página reporting-bugs para más información de cómo hacerlo. Los nuevos
voluntarios son siempre bienvenidos!
Agradecemos a:
• Fred L. Drake, Jr., el creador original de la documentación del conjunto de herramientas de Python y escritor de
gran parte del contenido;
• el proyecto Docutils para creación de reStructuredText y la suite Docutils;
• Fredrik Lundh por su proyecto Referencia Alternativa de Python del que Sphinx obtuvo muchas buenas ideas.
Muchas personas han contribuido para el lenguaje de Python, la librería estándar de Python, y la documentación de
Python. Revisa Misc/ACKS la distribución de Python para una lista parcial de contribuidores.
Es solamente con la aportación y contribuciones de la comunidad de Python que Python tiene tan fantástica documentación
– Muchas gracias!
347
The Python/C API, Versión 3.13.0a5
Historia y Licencia
Python fue creado a principios de la década de 1990 por Guido van Rossum en Stichting Mathematisch Centrum (CWI,
ver https://www.cwi.nl/) en los Países Bajos como sucesor de un idioma llamado ABC. Guido sigue siendo el autor
principal de Python, aunque incluye muchas contribuciones de otros.
En 1995, Guido continuó su trabajo en Python en la Corporation for National Research Initiatives (CNRI, consulte https:
//www.cnri.reston.va.us/) en Reston, Virginia, donde lanzó varias versiones del software.
En mayo de 2000, Guido y el equipo de desarrollo central de Python se trasladaron a BeOpen.com para formar el equipo
de BeOpen PythonLabs. En octubre del mismo año, el equipo de PythonLabs se trasladó a Digital Creations (ahora Zope
Corporation; consulte https://www.zope.org/). En 2001, se formó la Python Software Foundation (PSF, consulte https:
//www.python.org/psf/), una organización sin fines de lucro creada específicamente para poseer la propiedad intelectual
relacionada con Python. Zope Corporation es miembro patrocinador del PSF.
Todas las versiones de Python son de código abierto (consulte https://opensource.org/ para conocer la definición de código
abierto). Históricamente, la mayoría de las versiones de Python, pero no todas, también han sido compatibles con GPL;
la siguiente tabla resume las distintas versiones.
349
The Python/C API, Versión 3.13.0a5
Nota: Compatible con GPL no significa que estemos distribuyendo Python bajo la GPL. Todas las licencias de Python,
a diferencia de la GPL, le permiten distribuir una versión modificada sin que los cambios sean de código abierto. Las
licencias compatibles con GPL permiten combinar Python con otro software que se publica bajo la GPL; los otros no lo
hacen.
Gracias a los muchos voluntarios externos que han trabajado bajo la dirección de Guido para hacer posibles estos lanza-
mientos.
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to␣
,→reproduce,
prepared by Licensee.
agrees to include in any such work a brief summary of the changes made to␣
,→Python
3.13.0a5.
EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION␣
,→OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT␣
,→THE
USE OF PYTHON 3.13.0a5 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.13.0a5
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT␣
,→OF
Agreement does not grant permission to use PSF trademarks or trade name in␣
,→a
third party.
2. Subject to the terms and conditions of this BeOpen Python License Agreement,
BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
to reproduce, analyze, test, perform and/or display publicly, prepare derivative
works, distribute, and otherwise use the Software alone or in any derivative
version, provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
(continúe en la próxima página)
2. Subject to the terms and conditions of this License Agreement, CNRI hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
prepared by Licensee. Alternately, in lieu of CNRI's License Agreement,
Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
is made available subject to the terms and conditions in CNRI's License
Agreement. This Agreement together with Python 1.6.1 may be located on the
internet using the following unique, persistent identifier (known as a handle):
1895.22/1013. This Agreement may also be obtained from a proxy server on the
internet using the following URL: http://hdl.handle.net/1895.22/1013."
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI
MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
(continúe en la próxima página)
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
publicity pertaining to distribution of the software without specific, written
prior permission.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
Esta sección es una lista incompleta, pero creciente, de licencias y reconocimientos para software de terceros incorporado
en la distribución de Python.
La extensión C _random subyacente al módulo random incluye código basado en una descarga de http://www.math.
sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html. Los siguientes son los comentarios textuales del código
original:
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
C.3.2 Sockets
El módulo socket usa las funciones, getaddrinfo(), y getnameinfo(), que están codificadas en archivos
fuente separados del Proyecto WIDE, http://www.wide.ad.jp /.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
C.3.8 test_epoll
Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.10 SipHash24
El archivo Python/pyhash.c contiene la implementación de Marek Majkowski del algoritmo SipHash24 de Dan
Bernstein. Contiene la siguiente nota:
<MIT License>
Copyright (c) 2013 Marek Majkowski <[email protected]>
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</MIT License>
El archivo Python/dtoa.c, que proporciona las funciones de C dtoa y strtod para la conversión de dobles C hacia
y desde cadenas de caracteres, se deriva del archivo del mismo nombre por David M. Gay, actualmente disponible en
https://web.archive.org/web/20220517033456/http://www.netlib.org/fp/dtoa.c. El archivo original, recuperado el 16 de
marzo de 2009, contiene el siguiente aviso de licencia y derechos de autor:
/****************************************************************
*
* The author of this software is David M. Gay.
*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
***************************************************************/
C.3.12 OpenSSL
The modules hashlib, posix and ssl use the OpenSSL library for added performance if made available by the
operating system. Additionally, the Windows and macOS installers for Python may include a copy of the OpenSSL
libraries, so we include a copy of the OpenSSL license here. For the OpenSSL 3.0 release, and later releases derived
from that, the Apache License v2 applies:
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
(continúe en la próxima página)
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
C.3.13 expat
La extensión pyexpat se construye usando una copia incluida de las fuentes de expatriados a menos que la construcción
esté configurada --with-system-expat:
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
C.3.14 libffi
La extensión C _ctypes subyacente al módulo ctypes se construye usando una copia incluida de las fuentes de libffi
a menos que la construcción esté configurada --with-system-libffi:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
C.3.15 zlib
La extensión zlib se crea utilizando una copia incluida de las fuentes de zlib si la versión de zlib encontrada en el sistema
es demasiado antigua para ser utilizada para la compilación:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
C.3.16 cfuhash
C.3.17 libmpdec
La extension C _decimal subyacente al módulo decimal se construye usando una copia incluida de la biblioteca
libmpdec a menos que la construcción esté configurada --with-system-libmpdec:
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
El conjunto de pruebas C14N 2.0 en el paquete test (Lib/test/xmltestdata/c14n-20/) se recuperó del sitio
web de W3C en https://www.w3.org/TR/xml-c14n2-testcases/ y se distribuye bajo la licencia BSD de 3 cláusulas:
C.3.19 mimalloc
MIT License
Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PAR-
TICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWA-
RE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
C.3.20 asyncio
Parts of the asyncio module are incorporated from uvloop 0.16, which is distributed under the MIT license:
The file Python/qsbr.c is adapted from FreeBSD’s «Global Unbounded Sequences» safe memory reclamation sche-
me in subr_smr.c. The file is distributed under the 2-Clause BSD License:
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Derechos de autor
Consulte Historia y Licencia para obtener información completa sobre licencias y permisos.
369
The Python/C API, Versión 3.13.0a5
371
The Python/C API, Versión 3.13.0a5
372 Índice
The Python/C API, Versión 3.13.0a5
función, 334 K
función clave, 338 KeyboardInterrupt (built-in exception), 63, 64
función corrutina, 332
función genérica, 335 L
function
lambda, 338
object, 177
LBYL, 338
len
G built-in function, 103, 113, 115, 168, 173,
gancho a entrada de ruta, 341 176
gcvisitobjects_t (C type), 325 lenfunc (C type), 319
generador, 335 list
generador asincrónico, 330 object, 168
getattrfunc (C type), 318 lista, 338
getattrofunc (C type), 318 lock, interpreter, 219
getbufferproc (C type), 319 long integer
getiterfunc (C type), 319 object, 134
getter (C type), 283 LONG_MAX (C macro), 135
GIL, 336
global interpreter lock, 219 M
magic
H método, 339
hash main(), 244
built-in function, 103, 295 malloc (C function), 261
hash-based pyc, 336 mapeado, 339
hashable, 336 mapping
hashfunc (C type), 319 object, 170
máquina virtual, 346
I memoryview
IDLE, 336 object, 197
immortal, 336 meta buscadores de ruta, 339
importador, 337 metaclase, 339
importar, 337 METH_CLASS (C macro), 278
incr_item(), 12, 13 METH_COEXIST (C macro), 278
indicador de tipo, 345 METH_FASTCALL (C macro), 277
initproc (C type), 318 METH_KEYWORDS (C macro), 277
inmutable, 336 METH_METHOD (C macro), 278
inquiry (C type), 324 METH_NOARGS (C macro), 278
instancemethod METH_O (C macro), 278
object, 179 METH_STATIC (C macro), 278
int METH_VARARGS (C macro), 277
built-in function, 113 method
integer object, 180
object, 134 MethodType (in module types), 177, 180
interactivo, 337 método, 339
interpretado, 337 magic, 339
interpreter lock, 219 special, 344
iterable, 337 método especial, 344
iterable asincrónico, 330 método mágico, 339
iterador, 337 module
iterador asincrónico, 330 __main__, 13, 215, 227, 228
iterador generador, 335 builtins, 13, 215, 227, 228
iterador generador asincrónico, 330 object, 186
iternextfunc (C type), 319 search path, 13, 215, 218
Índice 373
The Python/C API, Versión 3.13.0a5
signal, 63, 64 P
sys, 13, 215, 227, 228 package variable
modules (in module sys), 76, 215 __all__, 76
ModuleType (in module types), 186 paquete, 340
módulo, 339 paquete de espacios de nombres, 340
módulo de extensión, 334 paquete provisorio, 342
MRO, 339 paquete regular, 343
mutable, 339 parámetro, 340
path
N module search, 13, 215, 218
newfunc (C type), 318 PATH, 13
nombre calificado, 342 path (in module sys), 13, 215, 218
None PEP, 341
object, 133 platform (in module sys), 218
numeric porción, 342
object, 134 pow
número complejo, 332 built-in function, 111, 112
Py_ABS (C macro), 5
O Py_AddPendingCall (C function), 230
object Py_ALWAYS_INLINE (C macro), 5
bytearray, 146 Py_AtExit (C function), 76
bytes, 144 Py_AUDIT_READ (C macro), 280
Capsule, 199 Py_AuditHookFunction (C type), 75
code, 181 Py_BEGIN_ALLOW_THREADS (C macro), 219, 223
complex number, 142 Py_BLOCK_THREADS (C macro), 223
dictionary, 170 Py_buffer (C type), 119
file, 185 Py_buffer.buf (C member), 119
floating point, 140 Py_buffer.format (C member), 120
frozenset, 175 Py_buffer.internal (C member), 120
function, 177 Py_buffer.itemsize (C member), 119
instancemethod, 179 Py_buffer.len (C member), 119
integer, 134 Py_buffer.ndim (C member), 120
list, 168 Py_buffer.obj (C member), 119
long integer, 134 Py_buffer.readonly (C member), 119
mapping, 170 Py_buffer.shape (C member), 120
memoryview, 197 Py_buffer.strides (C member), 120
method, 180 Py_buffer.suboffsets (C member), 120
module, 186 Py_BuildValue (C function), 88
None, 133 Py_BytesMain (C function), 45
numeric, 134 Py_BytesWarningFlag (C var), 212
sequence, 144 Py_CHARMASK (C macro), 5
set, 175 Py_CLEAR (C function), 53
tuple, 165 Py_CompileString (C function), 48, 49
type, 7, 127 Py_CompileStringExFlags (C function), 48
objeto, 340 Py_CompileStringFlags (C function), 48
objeto archivo, 334 Py_CompileStringObject (C function), 48
objeto tipo ruta, 341 Py_complex (C type), 142
objetos tipo archivo, 334 PY_CXX_CONST (C macro), 88
objetos tipo binarios, 331 Py_DEBUG (C macro), 14
objobjargproc (C type), 319 Py_DebugFlag (C var), 212
objobjproc (C type), 319 Py_DecodeLocale (C function), 72
orden de resolución de métodos, 339 Py_DecRef (C function), 53
OverflowError (built-in exception), 135137 Py_DECREF (C function), 8, 52
Py_DEPRECATED (C macro), 5
374 Índice
The Python/C API, Versión 3.13.0a5
Índice 375
The Python/C API, Versión 3.13.0a5
376 Índice
The Python/C API, Versión 3.13.0a5
Índice 377
The Python/C API, Versión 3.13.0a5
378 Índice
The Python/C API, Versión 3.13.0a5
Índice 379
The Python/C API, Versión 3.13.0a5
380 Índice
The Python/C API, Versión 3.13.0a5
Índice 381
The Python/C API, Versión 3.13.0a5
382 Índice
The Python/C API, Versión 3.13.0a5
Índice 383
The Python/C API, Versión 3.13.0a5
384 Índice
The Python/C API, Versión 3.13.0a5
Índice 385
The Python/C API, Versión 3.13.0a5
386 Índice
The Python/C API, Versión 3.13.0a5
Índice 387
The Python/C API, Versión 3.13.0a5
388 Índice
The Python/C API, Versión 3.13.0a5
Índice 389
The Python/C API, Versión 3.13.0a5
390 Índice
The Python/C API, Versión 3.13.0a5
Índice 391
The Python/C API, Versión 3.13.0a5
392 Índice
The Python/C API, Versión 3.13.0a5
V
variable de clase, 332
variable de contexto, 332
variables de entorno
__PYVENV_LAUNCHER__, 245, 252
PATH, 13
PYTHON_CPU_COUNT, 249
PYTHON_PRESITE, 252
PYTHONCOERCECLOCALE, 257
PYTHONDEBUG, 212, 251
PYTHONDEVMODE, 246
PYTHONDONTWRITEBYTECODE, 212, 255
PYTHONDUMPREFS, 247
PYTHONEXECUTABLE, 252
PYTHONFAULTHANDLER, 247
PYTHONHASHSEED, 213, 248
PYTHONHOME, 13, 213, 219, 248
PYTHONINSPECT, 213, 248
PYTHONINTMAXSTRDIGITS, 249
PYTHONIOENCODING, 253
PYTHONLEGACYWINDOWSFSENCODING, 214,
241
PYTHONLEGACYWINDOWSSTDIO, 214, 249
PYTHONMALLOC, 262, 266, 268, 269
PYTHONMALLOCSTATS, 250, 262
PYTHONNODEBUGRANGES, 246
PYTHONNOUSERSITE, 214, 254
PYTHONOPTIMIZE, 214, 250
PYTHONPATH, 13, 213, 250
PYTHONPERFSUPPORT, 254
PYTHONPLATLIBDIR, 250
PYTHONPROFILEIMPORTTIME, 248
PYTHONPYCACHEPREFIX, 252
PYTHONSAFEPATH, 245
PYTHONTRACEMALLOC, 254
PYTHONUNBUFFERED, 215, 245
PYTHONUTF8, 242, 257
PYTHONVERBOSE, 215, 254
PYTHONWARNINGS, 254
vectorcallfunc (C type), 106
version (in module sys), 218, 219
visitproc (C type), 324
vista de diccionario, 333
W
WRITE_RESTRICTED (C macro), 280
Z
Zen de Python, 346
Índice 393