0% encontró este documento útil (0 votos)
50 vistas374 páginas

The Python C - API

Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
50 vistas374 páginas

The Python C - API

Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 374

The Python/C API

Versión 3.12.4

Guido van Rossum and the Python development team

junio 21, 2024

Python Software Foundation


Email: [email protected]
Índice general

1 Introducción 3
1.1 Estándares de codificación . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Archivos de cabecera (Include) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Macros útiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Objetos, tipos y conteos de referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.1 Conteo de Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.2 Tipos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5 Excepciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.6 Integración de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.7 Depuración de compilaciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2 Estabilidad de la API en C 15
2.1 Unstable C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Interfaz binaria de aplicación estable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.1 Limited C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.2 Stable ABI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.3 Alcance y rendimiento de la API limitada . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.4 Advertencias de la API limitada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3 Consideraciones de la plataforma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4 Contenido de la API limitada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

3 La capa de muy alto nivel 41

4 Conteo de referencias 47

5 Manejo de excepciones 51
5.1 Impresión y limpieza . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 Lanzando excepciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3 Emitir advertencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.4 Consultando el indicador de error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.5 Manejo de señal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.6 Clases de excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.7 Objetos excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.8 Objetos unicode de excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.9 Control de recursión . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.10 Excepciones estándar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.11 Categorías de advertencia estándar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

6 Utilidades 65
6.1 Utilidades del sistema operativo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.2 Funciones del Sistema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

i
6.3 Control de procesos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.4 Importando módulos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.5 Soporte de empaquetado (marshalling) de datos . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.6 Analizando argumentos y construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.6.1 Analizando argumentos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.6.2 Construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.7 Conversión y formato de cadenas de caracteres . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
6.8 PyHash API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.9 Reflexión . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.10 Registro de códec y funciones de soporte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.10.1 API de búsqueda de códec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.10.2 API de registro para controladores de errores de codificación Unicode . . . . . . . . . . . 87
6.11 Support for Perf Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

7 Capa de objetos abstractos 91


7.1 Protocolo de objeto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
7.2 Protocolo de llamada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
7.2.1 El protocolo tp_call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
7.2.2 El protocolo vectorcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
7.2.3 API para invocar objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
7.2.4 API de soporte de llamadas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.3 Protocolo de números . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.4 Protocolo de secuencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
7.5 Protocolo de mapeo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
7.6 Protocolo iterador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
7.7 Protocolo búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
7.7.1 Estructura de búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
7.7.2 Tipos de solicitud búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
7.7.3 Arreglos complejos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
7.7.4 Funciones relacionadas a búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
7.8 Protocolo de búfer antiguo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

8 Capa de objetos concretos 117


8.1 Objetos fundamentales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.1.1 Objetos tipo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.1.2 El objeto None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.2 Objetos numéricos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.2.1 Objetos enteros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.2.2 Objetos booleanos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.2.3 Objetos de punto flotante . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.2.4 Objetos de números complejos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
8.3 Objetos de secuencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
8.3.1 Objetos bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
8.3.2 Objetos de arreglos de bytes (bytearrays) . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.3.3 Objetos y códecs unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
8.3.4 Objetos tupla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
8.3.5 Objetos de secuencia de estructura . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
8.3.6 Objetos lista . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
8.4 Objetos contenedor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
8.4.1 Objetos diccionario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
8.4.2 Objetos conjunto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
8.5 Objetos de función . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
8.5.1 Objetos función . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
8.5.2 Objetos de método de instancia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
8.5.3 Objetos método . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
8.5.4 Objetos celda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
8.5.5 Objetos código . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
8.5.6 Extra information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

ii
8.6 Otros objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
8.6.1 Objetos archivo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
8.6.2 Objetos módulo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
8.6.3 Objetos iteradores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.6.4 Objetos descriptores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.6.5 Objetos rebanada (slice) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
8.6.6 Objetos de vista de memoria (MemoryView) . . . . . . . . . . . . . . . . . . . . . . . . 179
8.6.7 Objetos de referencia débil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.6.8 Cápsulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
8.6.9 Objetos frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
8.6.10 Objetos generadores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.11 Objetos corrutina . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.12 Objetos de variables de contexto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.13 Objetos DateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
8.6.14 Objetos para indicaciones de tipado . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

9 Inicialización, finalización e hilos 193


9.1 Antes de la inicialización de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
9.2 Variables de configuración global . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
9.3 Inicializando y finalizando el intérprete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
9.4 Parámetros de todo el proceso . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
9.5 Estado del hilo y el bloqueo global del intérprete . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
9.5.1 Liberando el GIL del código de extensión . . . . . . . . . . . . . . . . . . . . . . . . . . 203
9.5.2 Hilos creados sin Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
9.5.3 Precauciones sobre fork() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
9.5.4 API de alto nivel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
9.5.5 API de bajo nivel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
9.6 Soporte de subinterprete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
9.6.1 A Per-Interpreter GIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
9.6.2 Errores y advertencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
9.7 Notificaciones asincrónicas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
9.8 Perfilado y Rastreo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
9.9 Soporte avanzado del depurador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
9.10 Soporte de almacenamiento local de hilo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
9.10.1 API de almacenamiento específico de hilo (TSS, Thread Specific Storage) . . . . . . . . . 216
9.10.2 API de almacenamiento local de hilos (TLS, Thread Local Storage) . . . . . . . . . . . . 218

10 Configuración de inicialización de Python 219


10.1 Ejemplo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
10.2 PyWideStringList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
10.3 PyStatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
10.4 PyPreConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
10.5 Preinicialización de Python con PyPreConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
10.6 PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
10.7 Inicialización con PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
10.8 Configuración aislada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
10.9 Configuración de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
10.10 Configuración de la ruta de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
10.11 Py_RunMain() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
10.12 Py_GetArgcArgv() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
10.13 API Provisional Privada de Inicialización Multifásica . . . . . . . . . . . . . . . . . . . . . . . . 239

11 Gestión de la memoria 241


11.1 Visión general . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
11.2 Dominios del asignador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
11.3 Interfaz de memoria sin procesar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
11.4 Interfaz de memoria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
11.5 Asignadores de objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
11.6 Asignadores de memoria predeterminados . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

iii
11.7 Personalizar asignadores de memoria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
11.8 Configurar enlaces para detectar errores en las funciones del asignador de memoria de Python . . . 248
11.9 El asignador pymalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
11.9.1 Personalizar asignador de arena de pymalloc . . . . . . . . . . . . . . . . . . . . . . . . 249
11.10 tracemalloc C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
11.11 Ejemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

12 Soporte de implementación de objetos 253


12.1 Asignación de objetos en el montículo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
12.2 Estructuras de objetos comunes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
12.2.1 Tipos objeto base y macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
12.2.2 Implementando funciones y métodos . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
12.2.3 Acceder a atributos de tipos de extensión . . . . . . . . . . . . . . . . . . . . . . . . . . 259
12.3 Objetos tipo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
12.3.1 Referencia rápida . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
12.3.2 Definición de PyTypeObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
12.3.3 Ranuras (Slots) PyObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
12.3.4 Ranuras PyVarObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
12.3.5 Ranuras PyTypeObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
12.3.6 Tipos estáticos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
12.3.7 Tipos Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
12.4 Estructuras de objetos de números . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
12.5 Estructuras de objetos mapeo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
12.6 Estructuras de objetos secuencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
12.7 Estructuras de objetos búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
12.8 Estructuras de objetos asíncronos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
12.9 Tipo Ranura typedefs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
12.10 Ejemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
12.11 Apoyo a la recolección de basura cíclica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
12.11.1 Controlar el estado del recolector de basura . . . . . . . . . . . . . . . . . . . . . . . . . 301
12.11.2 Querying Garbage Collector State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302

13 Versiones de API y ABI 303

A Glosario 305

B Acerca de estos documentos 321


B.1 Contribuidores de la documentación de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

C Historia y Licencia 323


C.1 Historia del software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
C.2 Términos y condiciones para acceder o usar Python . . . . . . . . . . . . . . . . . . . . . . . . . 324
C.2.1 ACUERDO DE LICENCIA DE PSF PARA PYTHON | lanzamiento | . . . . . . . . . . 324
C.2.2 ACUERDO DE LICENCIA DE BEOPEN.COM PARA PYTHON 2.0 . . . . . . . . . . 325
C.2.3 ACUERDO DE LICENCIA CNRI PARA PYTHON 1.6.1 . . . . . . . . . . . . . . . . 326
C.2.4 ACUERDO DE LICENCIA CWI PARA PYTHON 0.9.0 HASTA 1.2 . . . . . . . . . . 327
C.2.5 LICENCIA BSD DE CLÁUSULA CERO PARA CÓDIGO EN EL PYTHON | lanza-
miento | DOCUMENTACIÓN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
C.3 Licencias y reconocimientos para software incorporado . . . . . . . . . . . . . . . . . . . . . . . 328
C.3.1 Mersenne Twister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
C.3.2 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
C.3.3 Servicios de socket asincrónicos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
C.3.4 Gestión de cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
C.3.5 Seguimiento de ejecución . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
C.3.6 funciones UUencode y UUdecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
C.3.7 Llamadas a procedimientos remotos XML . . . . . . . . . . . . . . . . . . . . . . . . . 331
C.3.8 test_epoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
C.3.9 Seleccionar kqueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
C.3.10 SipHash24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333

iv
C.3.11 strtod y dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
C.3.18 Conjunto de pruebas W3C C14N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
C.3.19 Audioop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
C.3.20 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340

D Derechos de autor 343

Índice 345

v
vi
The Python/C API, Versión 3.12.4

Este manual documenta la API utilizada por los programadores de C y C ++ que desean escribir módulos de extensión
o incorporar Python. Es un complemento de extending-index, que describe los principios generales de la escritura de
extensión pero no documenta las funciones API en detalle.

Índice general 1
The Python/C API, Versión 3.12.4

2 Índice general
CAPÍTULO 1

Introducción

La interfaz del programador de aplicaciones (API) con Python brinda a los programadores de C y C++ acceso al
intérprete de Python en una variedad de niveles. La API es igualmente utilizable desde C++, pero por brevedad
generalmente se conoce como la API Python/C. Hay dos razones fundamentalmente diferentes para usar la API
Python/C. La primera razón es escribir módulos de extensión para propósitos específicos; Estos son módulos C que
extienden el intérprete de Python. Este es probablemente el uso más común. La segunda razón es usar Python co-
mo componente en una aplicación más grande; Esta técnica se conoce generalmente como integración (embedding)
Python en una aplicación.
Escribir un módulo de extensión es un proceso relativamente bien entendido, donde un enfoque de «libro de cocina»
(cookbook) funciona bien. Hay varias herramientas que automatizan el proceso hasta cierto punto. Si bien las personas
han integrado Python en otras aplicaciones desde su existencia temprana, el proceso de integrar Python es menos
sencillo que escribir una extensión.
Muchas funciones API son útiles independientemente de si está integrando o extendiendo Python; Además, la mayoría
de las aplicaciones que integran Python también necesitarán proporcionar una extensión personalizada, por lo que
probablemente sea una buena idea familiarizarse con la escritura de una extensión antes de intentar integrar Python
en una aplicación real.

1.1 Estándares de codificación

Si está escribiendo código C para su inclusión en CPython, debe seguir las pautas y estándares definidos en PEP
7. Estas pautas se aplican independientemente de la versión de Python a la que esté contribuyendo. Seguir estas
convenciones no es necesario para sus propios módulos de extensión de terceros, a menos que eventualmente espere
contribuir con ellos a Python.

3
The Python/C API, Versión 3.12.4

1.2 Archivos de cabecera (Include)

Todas las definiciones de función, tipo y macro necesarias para usar la API Python/C se incluyen en su código
mediante la siguiente línea:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

Esto implica la inclusión de los siguientes archivos de encabezado estándar: <stdio.h>, <string.h>, <errno.
h>, <limits.h>, <assert.h> y <stdlib.h> (si está disponible).

Nota: Dado que Python puede definir algunas definiciones de preprocesador que afectan los encabezados estándar
en algunos sistemas, debe incluir Python.h antes de incluir encabezados estándar.
Se recomienda definir siempre PY_SSIZE_T_CLEAN antes de incluir Python.h. Consulte Analizando argumen-
tos y construyendo valores para obtener una descripción de este macro.

Todos los nombres visibles del usuario definidos por Python.h (excepto los definidos por los encabezados estándar
incluidos) tienen uno de los prefijos Py o _Py. Los nombres que comienzan con _Py son para uso interno de la
implementación de Python y no deben ser utilizados por escritores de extensiones. Los nombres de miembros de
estructura no tienen un prefijo reservado.

Nota: El código de usuario nunca debe definir nombres que comiencen con Py o _Py. Esto confunde al lector y
pone en peligro la portabilidad del código de usuario para futuras versiones de Python, que pueden definir nombres
adicionales que comienzan con uno de estos prefijos.

The header files are typically installed with Python. On Unix, these are located in the directories prefix/
include/pythonversion/ and exec_prefix/include/pythonversion/, where prefix and
exec_prefix are defined by the corresponding parameters to Python’s configure script and version is '%d.
%d' % sys.version_info[:2]. On Windows, the headers are installed in prefix/include, where
prefix is the installation directory specified to the installer.
To include the headers, place both directories (if different) on your compiler’s search path for includes. Do not place
the parent directories on the search path and then use #include <pythonX.Y/Python.h>; this will break on
multi-platform builds since the platform independent headers under prefix include the platform specific headers
from exec_prefix.
Los usuarios de C++ deben tener en cuenta que aunque la API se define completamente usando C, los archivos de
encabezado declaran correctamente que los puntos de entrada son extern "C". Como resultado, no es necesario
hacer nada especial para usar la API desde C++.

1.3 Macros útiles

Varias macros útiles se definen en los archivos de encabezado de Python. Muchos se definen más cerca de donde son
útiles (por ejemplo Py_RETURN_NONE). Otros de una utilidad más general se definen aquí. Esto no es necesaria-
mente una lista completa.
PyMODINIT_FUNC
Declare an extension module PyInit initialization function. The function return type is PyObject*. The
macro declares any special linkage declarations required by the platform, and for C++ declares the function as
extern "C".
The initialization function must be named PyInit_name, where name is the name of the module, and should
be the only non-static item defined in the module file. Example:

4 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4

static struct PyModuleDef spam_module = {


PyModuleDef_HEAD_INIT,
.m_name = "spam",
...
};

PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModule_Create(&spam_module);
}

Py_ABS(x)
Retorna el valor absoluto de x.
Added in version 3.3.
Py_ALWAYS_INLINE
Ordena al compilador a siempre usar inline en una función estática inline. El compilador puede ignorarlo y
decidir no usar inline en la función.
Puede ser usado para usar inline en funciones estáticas inline de rendimiento crítico cuando se corre Python en
modo de depuración con inline de funciones deshabilitado. Por ejemplo, MSC deshabilita el inline de funciones
cuando se configura en modo de depuración.
Marcar ciegamente una función estática inline con Py_ALWAYS_INLINE puede resultar en peor rendimientos
(debido a un aumento del tamaño del código, por ejemplo). El compilador es generalmente más inteligente que
el desarrollador para el análisis costo/beneficio.
If Python is built in debug mode (if the Py_DEBUG macro is defined), the Py_ALWAYS_INLINE macro
does nothing.
Debe ser especificado antes del tipo de retorno de la función. Uso:

static inline Py_ALWAYS_INLINE int random(void) { return 4; }

Added in version 3.11.


Py_CHARMASK(c)
El argumento debe ser un carácter o un número entero en el rango [-128, 127] o [0, 255]. Este macro retorna
la conversión c a un unsigned char.
Py_DEPRECATED(version)
Use esto para declaraciones obsoletas. El macro debe colocarse antes del nombre del símbolo.
Ejemplo:

Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);

Distinto en la versión 3.8: Soporte para MSVC fue agregado.


Py_GETENV(s)
Like getenv(s), but returns NULL if -E was passed on the command line (see PyConfig.
use_environment).
Py_MAX(x, y)
Retorna el valor máximo entre x e y.
Added in version 3.3.
Py_MEMBER_SIZE(type, member)
Retorna el tamaño de una estructura (type) member en bytes.
Added in version 3.6.

1.3. Macros útiles 5


The Python/C API, Versión 3.12.4

Py_MIN(x, y)
Retorna el valor mínimo entre x e y.
Added in version 3.3.
Py_NO_INLINE
Deshabilita el uso de inline en una función. Por ejemplo, reduce el consumo de la pila C: útil en compilaciones
LTO+PGO que usan mucho inline (ver bpo-33720).
Uso:

Py_NO_INLINE static int random(void) { return 4; }

Added in version 3.11.


Py_STRINGIFY(x)
Convierte x en una cadena de caracteres C. Por ejemplo, Py_STRINGIFY(123) retorna "123".
Added in version 3.4.
Py_UNREACHABLE()
Use esto cuando tenga una ruta de código a la que no se pueda acceder por diseño. Por ejemplo, en la cláusula
default: en una declaración switch para la cual todos los valores posibles están cubiertos en declaraciones
case. Use esto en lugares donde podría tener la tentación de poner una llamada assert(0) o abort().
En el modo de lanzamiento, la macro ayuda al compilador a optimizar el código y evita una advertencia sobre
el código inalcanzable. Por ejemplo, la macro se implementa con __builtin_unreachable() en GCC
en modo de lanzamiento.
Un uso de Py_UNREACHABLE() es seguir una llamada a una función que nunca retorna pero que no está
declarada _Py_NO_RETURN.
Si una ruta de código es un código muy poco probable pero se puede acceder en casos excepcionales, esta
macro no debe utilizarse. Por ejemplo, en condiciones de poca memoria o si una llamada al sistema retorna un
valor fuera del rango esperado. En este caso, es mejor informar el error a la persona que llama. Si no se puede
informar del error a la persona que llama, se puede utilizar Py_FatalError().
Added in version 3.7.
Py_UNUSED(arg)
Use esto para argumentos no utilizados en una definición de función para silenciar las advertencias del com-
pilador. Ejemplo: int func(int a, int Py_UNUSED(b)) {return a; }.
Added in version 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
especifica en PEP 7.
Ejemplo:

PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");

static PyMethodDef deque_methods[] = {


// ...
{"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
// ...
}

PyDoc_STR(str)
Crea un docstring para la cadena de caracteres de entrada dada o una cadena vacía si los docstrings están
deshabilitados.

6 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4

Utilice PyDoc_STR al especificar docstrings para admitir la construcción de Python sin docstrings, como se
especifica en PEP 7.
Ejemplo:

static PyMethodDef pysqlite_row_methods[] = {


{"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
PyDoc_STR("Returns the keys of the row.")},
{NULL, NULL}
};

1.4 Objetos, tipos y conteos de referencias

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.

1.4.1 Conteo de Referencias

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.

1.4. Objetos, tipos y conteos de referencias 7


The Python/C API, Versión 3.12.4

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.

Detalles del conteo de referencia

The reference count behavior of functions in the Python/C API is best explained in terms of ownership of references.
Ownership pertains to references, never to objects (objects are not owned: they are always shared). «Owning a re-
ference» means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership
can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for
eventually releasing it by calling Py_DECREF() or Py_XDECREF() when it’s no longer needed—or passing on
this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is
said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing
needs to be done for a borrowed reference.
Por el contrario, cuando una función de llamada pasa una referencia a un objeto, hay dos posibilidades: la función roba
una referencia al objeto, o no lo hace. Robar una referencia significa que cuando pasa una referencia a una función,
esa función asume que ahora posee esa referencia, y usted ya no es responsable de ella.
Pocas funciones roban referencias; las dos excepciones notables son PyList_SetItem() y
PyTuple_SetItem(), que roban una referencia al elemento (¡pero no a la tupla o lista en la que se colo-
ca el elemento!). Estas funciones fueron diseñadas para robar una referencia debido a un idioma común para
poblar una tupla o lista con objetos recién creados; por ejemplo, el código para crear la tupla (1, 2, "tres")
podría verse así (olvidando el manejo de errores por el momento; una mejor manera de codificar esto se muestra a
continuación):
PyObject *t;

t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));

Aquí PyLong_FromLong() retorna una nueva referencia que es inmediatamente robada por
PyTuple_SetItem(). Cuando quiera seguir usando un objeto aunque se le robe la referencia, use
Py_INCREF() para tomar otra referencia antes de llamar a la función de robo de referencias.
Por cierto, PyTuple_SetItem() es la única forma de establecer elementos de tupla;
PySequence_SetItem() y PyObject_SetItem() se niegan a hacer esto ya que las tuplas son un
tipo de datos inmutable. Solo debe usar PyTuple_SetItem() para las tuplas que está creando usted mismo.
El código equivalente para llenar una lista se puede escribir usando PyList_New() y PyList_SetItem().
Sin embargo, en la práctica, rara vez utilizará estas formas de crear y completar una tupla o lista. Hay una función
genérica, Py_BuildValue(), que puede crear los objetos más comunes a partir de valores C, dirigidos por un
una cadena de caracteres de formato (format string). Por ejemplo, los dos bloques de código anteriores podrían
reemplazarse por lo siguiente (que también se ocupa de la comprobación de errores):
PyObject *tuple, *list;

tuple = Py_BuildValue("(iis)", 1, 2, "three");


list = Py_BuildValue("[iis]", 1, 2, "three");

It is much more common to use PyObject_SetItem() and friends with items whose references you are only
borrowing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding

8 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4

references is much saner, since you don’t have to take a new reference just so you can give that reference away («have
it be stolen»). For example, this function sets all items of a list (actually, any mutable sequence) to a given item:

int
set_all(PyObject *target, PyObject *item)
{
Py_ssize_t i, n;

n = PyObject_Length(target);
if (n < 0)
return -1;
for (i = 0; i < n; i++) {
PyObject *index = PyLong_FromSsize_t(i);
if (!index)
return -1;
if (PyObject_SetItem(target, index, item) < 0) {
Py_DECREF(index);
return -1;
}
Py_DECREF(index);
}
return 0;
}

La situación es ligeramente diferente para los valores de retorno de la función. Si bien pasar una referencia a la mayo-
ría de las funciones no cambia sus responsabilidades de propiedad para esa referencia, muchas funciones que retornan
una referencia a un objeto le otorgan la propiedad de la referencia. La razón es simple: en muchos casos, el objeto
retornado se crea sobre la marcha, y la referencia que obtiene es la única referencia al objeto. Por lo tanto, las funcio-
nes genéricas que retornan referencias de objeto, como PyObject_GetItem() y PySequence_GetItem(),
siempre retornan una nueva referencia (la entidad que llama se convierte en el propietario de la referencia).
Es importante darse cuenta de que si posee una referencia retornada por una función depende de a qué función llame
únicamente — el plumaje (el tipo del objeto pasado como argumento a la función) no entra en él! Por lo tanto, si
extrae un elemento de una lista usando PyList_GetItem(), no posee la referencia — pero si obtiene el mismo
elemento de la misma lista usando PySequence_GetItem() (que toma exactamente los mismos argumentos),
usted posee una referencia al objeto retornado.
Aquí hay un ejemplo de cómo podría escribir una función que calcule la suma de los elementos en una lista de enteros;
una vez usando PyList_GetItem(), y una vez usando PySequence_GetItem().

long
sum_list(PyObject *list)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;

n = PyList_Size(list);
if (n < 0)
return -1; /* Not a list */
for (i = 0; i < n; i++) {
item = PyList_GetItem(list, i); /* Can't fail */
if (!PyLong_Check(item)) continue; /* Skip non-integers */
value = PyLong_AsLong(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
return total;
}

1.4. Objetos, tipos y conteos de referencias 9


The Python/C API, Versión 3.12.4

long
sum_sequence(PyObject *sequence)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
n = PySequence_Length(sequence);
if (n < 0)
return -1; /* Has no length */
for (i = 0; i < n; i++) {
item = PySequence_GetItem(sequence, i);
if (item == NULL)
return -1; /* Not a sequence, or other failure */
if (PyLong_Check(item)) {
value = PyLong_AsLong(item);
Py_DECREF(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
else {
Py_DECREF(item); /* Discard reference ownership */
}
}
return total;
}

1.4.2 Tipos

There are few other data types that play a significant role in the Python/C API; most are simple C types such as
int, long, double and char*. A few structure types are used to describe static tables used to list the functions
exported by a module or the data attributes of a new object type, and another is used to describe the value of a
complex number. These will be discussed together with the functions that use them.
type Py_ssize_t
Part of the Stable ABI. Un tipo integral con signo tal que sizeof(Py_ssize_t) ==
sizeof(size_t). C99 no define directamente tal cosa (size_t es un tipo integral sin signo). Vea
PEP 353 para más detalles. PY_SSIZE_T_MAX es el valor positivo más grande del tipo Py_ssize_t.

1.5 Excepciones

El programador de Python solo necesita lidiar con excepciones si se requiere un manejo específico de errores; las
excepciones no manejadas se propagan automáticamente a la persona que llama, luego a la persona que llama, y
así sucesivamente, hasta que llegan al intérprete de nivel superior, donde se informan al usuario acompañado de un
seguimiento de pila (stack traceback).
Para los programadores de C, sin embargo, la comprobación de errores siempre tiene que ser explícita. Todas las
funciones en la API Python/C pueden generar excepciones, a menos que se señale explícitamente en la documentación
de una función. En general, cuando una función encuentra un error, establece una excepción, descarta cualquier
referencia de objeto que posea y retorna un indicador de error. Si no se documenta lo contrario, este indicador
es NULL o -1, dependiendo del tipo de retorno de la función. Algunas funciones retornan un resultado booleano
verdadero/falso, con falso que indica un error. Muy pocas funciones no retornan ningún indicador de error explícito
o tienen un valor de retorno ambiguo, y requieren pruebas explícitas de errores con PyErr_Occurred(). Estas
excepciones siempre se documentan explícitamente.
El estado de excepción se mantiene en el almacenamiento por subproceso (esto es equivalente a usar el almacena-
miento global en una aplicación sin subprocesos). Un subproceso puede estar en uno de dos estados: se ha producido

10 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4

una excepción o no. La función PyErr_Occurred() puede usarse para verificar esto: retorna una referencia
prestada al objeto de tipo de excepción cuando se produce una excepción, y NULL de lo contrario. Hay una serie de
funciones para establecer el estado de excepción: PyErr_SetString() es la función más común (aunque no la
más general) para establecer el estado de excepción, y PyErr_Clear() borra la excepción estado.
El estado de excepción completo consta de tres objetos (todos los cuales pueden ser NULL): el tipo de excepción, el
valor de excepción correspondiente y el rastreo. Estos tienen los mismos significados que el resultado de Python de
sys.exc_info(); sin embargo, no son lo mismo: los objetos Python representan la última excepción manejada
por una declaración de Python try … except, mientras que el estado de excepción de nivel C solo existe mientras
se está pasando una excepción entre las funciones de C hasta que llega al bucle principal del intérprete de código de
bytes (bytecode) de Python, que se encarga de transferirlo a sys.exc_info() y amigos.
Tenga en cuenta que a partir de Python 1.5, la forma preferida y segura de subprocesos para acceder al estado de
excepción desde el código de Python es llamar a la función sys.exc_info(), que retorna el estado de excepción
por subproceso para el código de Python. Además, la semántica de ambas formas de acceder al estado de excepción
ha cambiado de modo que una función que detecta una excepción guardará y restaurará el estado de excepción de
su hilo para preservar el estado de excepción de su llamador. Esto evita errores comunes en el código de manejo
de excepciones causado por una función de aspecto inocente que sobrescribe la excepción que se maneja; También
reduce la extensión de vida útil a menudo no deseada para los objetos a los que hacen referencia los marcos de pila
en el rastreo.
Como principio general, una función que llama a otra función para realizar alguna tarea debe verificar si la función
llamada generó una excepción y, de ser así, pasar el estado de excepción a quien la llama (caller). Debe descartar
cualquier referencia de objeto que posea y retornar un indicador de error, pero no debe establecer otra excepción —
que sobrescribirá la excepción que se acaba de generar y perderá información importante sobre la causa exacta del
error.
A simple example of detecting exceptions and passing them on is shown in the sum_sequence() example above.
It so happens that this example doesn’t need to clean up any owned references when it detects an error. The following
example function shows some error cleanup. First, to remind you why you like Python, we show the equivalent Python
code:

def incr_item(dict, key):


try:
item = dict[key]
except KeyError:
item = 0
dict[key] = item + 1

Aquí está el código C correspondiente, en todo su esplendor:

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) */

item = PyObject_GetItem(dict, key);


if (item == NULL) {
/* Handle KeyError only: */
if (!PyErr_ExceptionMatches(PyExc_KeyError))
goto error;

/* Clear the error and use zero: */


PyErr_Clear();
item = PyLong_FromLong(0L);
if (item == NULL)
goto error;
}
const_one = PyLong_FromLong(1L);
if (const_one == NULL)
(continúe en la próxima página)

1.5. Excepciones 11
The Python/C API, Versión 3.12.4

(proviene de la página anterior)


goto error;

incremented_item = PyNumber_Add(item, const_one);


if (incremented_item == NULL)
goto error;

if (PyObject_SetItem(dict, key, incremented_item) < 0)


goto error;
rv = 0; /* Success */
/* Continue with cleanup code */

error:
/* Cleanup code, shared by success and failure path */

/* Use Py_XDECREF() to ignore NULL references */


Py_XDECREF(item);
Py_XDECREF(const_one);
Py_XDECREF(incremented_item);

return rv; /* -1 for error, 0 for success */


}

Este ejemplo representa un uso aprobado de la declaración goto en C! Ilustra el uso de


PyErr_ExceptionMatches() y PyErr_Clear() para manejar excepciones específicas, y el uso de
Py_XDECREF() para eliminar referencias propias que pueden ser NULL (tenga en cuenta la 'X'” en el nombre;
Py_DECREF() se bloqueará cuando se enfrente con una referencia NULL). Es importante que las variables
utilizadas para contener referencias propias se inicialicen en NULL para que esto funcione; Del mismo modo, el
valor de retorno propuesto se inicializa a -1 (falla) y solo se establece en éxito después de que la última llamada
realizada sea exitosa.

1.6 Integración de Python

La única tarea importante de la que solo tienen que preocuparse los integradores (a diferencia de los escritores de
extensión) del intérprete de Python es la inicialización, y posiblemente la finalización, del intérprete de Python. La
mayor parte de la funcionalidad del intérprete solo se puede usar después de que el intérprete se haya inicializado.
La función básica de inicialización es Py_Initialize(). Esto inicializa la tabla de módulos cargados y crea
los módulos fundamentales builtins, __main__, y sys. También inicializa la ruta de búsqueda del módulo
(sys.path).
Py_Initialize() no establece la «lista de argumentos de script» (sys.argv). Si esta variable es necesaria por
el código Python que se ejecutará más tarde, debe establecerse PyConfig.argv y PyConfig.parse_argv:
consulte Python Initialization Configuration.
En la mayoría de los sistemas (en particular, en Unix y Windows, aunque los detalles son ligeramente diferentes),
Py_Initialize() calcula la ruta de búsqueda del módulo basándose en su mejor estimación de la ubicación del
ejecutable del intérprete de Python estándar, suponiendo que la biblioteca de Python se encuentra en una ubicación fija
en relación con el ejecutable del intérprete de Python. En particular, busca un directorio llamado lib/pythonX.Y
relativo al directorio padre donde se encuentra el ejecutable llamado python en la ruta de búsqueda del comando
shell (la variable de entorno PATH).
Por ejemplo, si el ejecutable de Python se encuentra en /usr/local/bin/python, se supondrá que las biblio-
tecas están en /usr/local/lib/pythonX.Y. (De hecho, esta ruta particular también es la ubicación «alterna-
tiva», utilizada cuando no se encuentra un archivo ejecutable llamado python junto con PATH.) El usuario puede
anular este comportamiento configurando la variable de entorno PYTHONHOME, o inserte directorios adicionales
delante de la ruta estándar estableciendo PYTHONPATH.
La aplicación de integración puede dirigir la búsqueda llamando a Py_SetProgramName(file) antes llamando
Py_Initialize(). Tenga en cuenta que PYTHONHOME todavía anula esto y PYTHONPATH todavía se inserta

12 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4

frente a la ruta estándar. Una aplicación que requiere un control total debe proporcionar su propia implementación de
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), y Py_GetProgramFullPath() (todo
definido en Modules/getpath.c).
A veces, es deseable «no inicializar» Python. Por ejemplo, la aplicación puede querer comenzar de nuevo (hacer otra
llamada a Py_Initialize()) o la aplicación simplemente se hace con el uso de Python y quiere liberar memoria
asignada por Python. Esto se puede lograr llamando a Py_FinalizeEx(). La función Py_IsInitialized()
retorna verdadero si Python se encuentra actualmente en el estado inicializado. Se proporciona más información
sobre estas funciones en un capítulo posterior. Tenga en cuenta que Py_FinalizeEx() no libera toda la memoria
asignada por el intérprete de Python, por ejemplo, la memoria asignada por los módulos de extensión actualmente no
se puede liberar.

1.7 Depuración de compilaciones

Python se puede construir con varios macros para permitir verificaciones adicionales del intérprete y los módulos de
extensión. Estas comprobaciones tienden a agregar una gran cantidad de sobrecarga al tiempo de ejecución, por lo
que no están habilitadas de forma predeterminada.
A full list of the various types of debugging builds is in the file Misc/SpecialBuilds.txt in the Python source
distribution. Builds are available that support tracing of reference counts, debugging the memory allocator, or low-
level profiling of the main interpreter loop. Only the most frequently used builds will be described in the remainder
of this section.
Py_DEBUG

Compiling the interpreter with the Py_DEBUG macro defined produces what is generally meant by a debug build of
Python. Py_DEBUG is enabled in the Unix build by adding --with-pydebug to the ./configure command.
It is also implied by the presence of the not-Python-specific _DEBUG macro. When Py_DEBUG is enabled in the
Unix build, compiler optimization is disabled.
Además de la depuración del recuento de referencia que se describe a continuación, se realizan verificaciones adi-
cionales, véase compilaciones de depuración.
Definiendo Py_TRACE_REFS habilita el rastreo de referencias (véase la opción configure
--with-trace-refs). Cuando se define, se mantiene una lista circular doblemente vinculada de objetos
activos al agregar dos campos adicionales a cada PyObject. También se realiza un seguimiento de las asignaciones
totales. Al salir, se imprimen todas las referencias existentes. (En modo interactivo, esto sucede después de cada
declaración ejecutada por el intérprete).
Consulte Misc/SpecialBuilds.txt en la distribución fuente de Python para obtener información más deta-
llada.

1.7. Depuración de compilaciones 13


The Python/C API, Versión 3.12.4

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.

2.1 Unstable C API

Any API named with the PyUnstable prefix exposes CPython implementation details, and may change in every
minor release (e.g. from 3.9 to 3.10) without any deprecation warnings. However, it will not change in a bugfix release
(e.g. from 3.10.0 to 3.10.1).
It is generally intended for specialized, low-level tools like debuggers.
Projects that use this API are expected to follow CPython development and spend extra effort adjusting to changes.

15
The Python/C API, Versión 3.12.4

2.2 Interfaz binaria de aplicación estable

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.

2.2.1 Limited C API

Python 3.2 introduced the Limited API, a subset of Python’s C API. Extensions that only use the Limited API can be
compiled once and work with multiple versions of Python. Contents of the Limited API are listed below.
Py_LIMITED_API
Se define esta macro antes de incluir Python.h para optar por usar sólo la API limitada y para seleccionar
la versión de la API limitada.
Define Py_LIMITED_API to the value of PY_VERSION_HEX corresponding to the lowest Python version
your extension supports. The extension will work without recompilation with all Python 3 releases from the
specified one onward, and can use Limited API introduced up to that version.
En lugar de utilizar directamente la macro PY_VERSION_HEX, se codifica una versión menor mínima (por
ejemplo, 0x030A0000 para Python 3.10) para tener estabilidad cuando se compila con futuras versiones de
Python.
También se puede definir Py_LIMITED_API con 3. Esto funciona igual que 0x03020000 (Python 3.2, la
función que introdujo la API limitada).

2.2.2 Stable ABI

To enable this, Python provides a Stable ABI: a set of symbols that will remain compatible across Python 3.x versions.
The Stable ABI contains symbols exposed in the Limited API, but also other ones – for example, functions necessary
to support older versions of the Limited API.
En Windows, las extensiones que usan la ABI estable deben estar vinculadas con python3.dll en lugar de una
biblioteca específica de la versión como python39.dll.
En algunas plataformas, Python buscará y cargará archivos de bibliotecas compartidas con el nombre de la etiqueta
abi3 (por ejemplo, mymodule.abi3.so). No comprueba si tales extensiones se ajustan a una ABI estable. El
usuario (o sus herramientas de empaquetado) necesitan asegurarse que, por ejemplo, las extensiones que se crean con
la API limitada 3.10+ no estén instaladas para versiones inferiores de Python.
Todas las funciones de la ABI estable se presentan como funciones en la biblioteca compartida de Python, no sólo
como macros. Esto las hace utilizables desde lenguajes que no usan el preprocesador de C.

2.2.3 Alcance y rendimiento de la API limitada

El objetivo de la API limitada es permitir todo lo que es posible con la API completa en C, pero posiblemente con
una penalización de rendimiento.
Por ejemplo, mientras PyList_GetItem() está disponible, su variante macro “insegura”
PyList_GET_ITEM() no lo está. La macro puede ser más rápida porque puede confiar en los detalles de
implementación específicos de la versión del objeto de lista.
Sin definirse Py_LIMITED_API, algunas funciones de la API en C están integradas o reemplazadas por macros.
Definir Py_LIMITED_API desactiva esta integración, permitiendo estabilidad mientras que se mejoren las estruc-
turas de datos de Python, pero posiblemente reduzca el rendimiento.
Al dejar fuera la definición de Py_LIMITED_API, es posible compilar una extensión de la API limitada con una ABI
específica de la versión. Esto puede mejorar el rendimiento para esa versión de Python, pero limitará la compatibilidad.
Compilar con Py_LIMITED_API producirá una extensión que se puede distribuir donde una versión específica no
esté disponible - por ejemplo, para los prelanzamientos de una versión próxima de Python.

16 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

2.2.4 Advertencias de la API limitada

Note that compiling with Py_LIMITED_API is not a complete guarantee that code conforms to the Limited API or
the Stable ABI. Py_LIMITED_API only covers definitions, but an API also includes other issues, such as expected
semantics.
Un problema contra el que Py_LIMITED_API no protege es llamar una función con argumentos que son inválidos
en una versión inferior de Python. Por ejemplo, se considera una función que empieza a aceptar NULL como un
argumento. Ahora en Python 3.9, NULL selecciona un comportamiento predeterminado, pero en Python 3.8, el
argumento se usará directamente, causando una desreferencia NULL y se detendrá. Un argumento similar funciona
para campos de estructuras.
Otro problema es que algunos campos de estructura no se ocultan actualmente cuando se define Py_LIMITED_API,
aunque son parte de la API limitada.
Por estas razones, recomendamos probar una extensión con todas las versiones menores de Python que soporte, y
preferiblemente compilar con la versión más baja.
También recomendamos revisar la documentación de todas las API usadas para verificar si es parte explícitamente
de la API limitada. Aunque se defina Py_LIMITED_API, algunas declaraciones privadas se exponen por razones
técnicas (o incluso involuntariamente, como errores).
También tome en cuenta que la API limitada no necesariamente es estable: compilar con Py_LIMITED_API con
Python 3.8 significa que la extensión se ejecutará con Python 3.12, pero no necesariamente compilará con Python
3.12. En particular, las partes de la API limitada se pueden quedar obsoletas y eliminarse, siempre que la ABI estable
permanezca estable.

2.3 Consideraciones de la plataforma

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.

2.4 Contenido de la API limitada

Currently, the Limited API includes the following items:

• PY_VECTORCALL_ARGUMENTS_OFFSET
• PyAIter_Check()
• PyArg_Parse()
• PyArg_ParseTuple()
• PyArg_ParseTupleAndKeywords()
• PyArg_UnpackTuple()
• PyArg_VaParse()
• PyArg_VaParseTupleAndKeywords()
• PyArg_ValidateKeywordArguments()
• PyBaseObject_Type

2.3. Consideraciones de la plataforma 17


The Python/C API, Versión 3.12.4

• PyBool_FromLong()
• PyBool_Type
• PyBuffer_FillContiguousStrides()
• PyBuffer_FillInfo()
• PyBuffer_FromContiguous()
• PyBuffer_GetPointer()
• PyBuffer_IsContiguous()
• PyBuffer_Release()
• PyBuffer_SizeFromFormat()
• PyBuffer_ToContiguous()
• PyByteArrayIter_Type
• PyByteArray_AsString()
• PyByteArray_Concat()
• PyByteArray_FromObject()
• PyByteArray_FromStringAndSize()
• PyByteArray_Resize()
• PyByteArray_Size()
• PyByteArray_Type
• PyBytesIter_Type
• PyBytes_AsString()
• PyBytes_AsStringAndSize()
• PyBytes_Concat()
• PyBytes_ConcatAndDel()
• PyBytes_DecodeEscape()
• PyBytes_FromFormat()
• PyBytes_FromFormatV()
• PyBytes_FromObject()
• PyBytes_FromString()
• PyBytes_FromStringAndSize()
• PyBytes_Repr()
• PyBytes_Size()
• PyBytes_Type
• PyCFunction
• PyCFunctionWithKeywords
• PyCFunction_Call()
• PyCFunction_GetFlags()
• PyCFunction_GetFunction()
• PyCFunction_GetSelf()
• PyCFunction_New()

18 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• 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()

2.4. Contenido de la API limitada 19


The Python/C API, Versión 3.12.4

• PyComplex_FromDoubles()
• PyComplex_ImagAsDouble()
• PyComplex_RealAsDouble()
• PyComplex_Type
• PyDescr_NewClassMethod()
• PyDescr_NewGetSet()
• PyDescr_NewMember()
• PyDescr_NewMethod()
• PyDictItems_Type
• PyDictIterItem_Type
• PyDictIterKey_Type
• PyDictIterValue_Type
• PyDictKeys_Type
• PyDictProxy_New()
• PyDictProxy_Type
• PyDictRevIterItem_Type
• PyDictRevIterKey_Type
• PyDictRevIterValue_Type
• PyDictValues_Type
• PyDict_Clear()
• PyDict_Contains()
• PyDict_Copy()
• PyDict_DelItem()
• PyDict_DelItemString()
• PyDict_GetItem()
• PyDict_GetItemString()
• PyDict_GetItemWithError()
• PyDict_Items()
• PyDict_Keys()
• PyDict_Merge()
• PyDict_MergeFromSeq2()
• PyDict_New()
• PyDict_Next()
• PyDict_SetItem()
• PyDict_SetItemString()
• PyDict_Size()
• PyDict_Type
• PyDict_Update()
• PyDict_Values()

20 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• 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()

2.4. Contenido de la API limitada 21


The Python/C API, Versión 3.12.4

• PyErr_SetImportErrorSubclass()
• PyErr_SetInterrupt()
• PyErr_SetInterruptEx()
• PyErr_SetNone()
• PyErr_SetObject()
• PyErr_SetRaisedException()
• PyErr_SetString()
• PyErr_SyntaxLocation()
• PyErr_SyntaxLocationEx()
• PyErr_WarnEx()
• PyErr_WarnExplicit()
• PyErr_WarnFormat()
• PyErr_WriteUnraisable()
• PyEval_AcquireLock()
• PyEval_AcquireThread()
• PyEval_CallFunction()
• PyEval_CallMethod()
• PyEval_CallObjectWithKeywords()
• PyEval_EvalCode()
• PyEval_EvalCodeEx()
• PyEval_EvalFrame()
• PyEval_EvalFrameEx()
• PyEval_GetBuiltins()
• PyEval_GetFrame()
• PyEval_GetFuncDesc()
• PyEval_GetFuncName()
• PyEval_GetGlobals()
• PyEval_GetLocals()
• PyEval_InitThreads()
• PyEval_ReleaseLock()
• PyEval_ReleaseThread()
• PyEval_RestoreThread()
• PyEval_SaveThread()
• PyEval_ThreadsInitialized()
• PyExc_ArithmeticError
• PyExc_AssertionError
• PyExc_AttributeError
• PyExc_BaseException
• PyExc_BaseExceptionGroup

22 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• PyExc_BlockingIOError
• PyExc_BrokenPipeError
• PyExc_BufferError
• PyExc_BytesWarning
• PyExc_ChildProcessError
• PyExc_ConnectionAbortedError
• PyExc_ConnectionError
• PyExc_ConnectionRefusedError
• PyExc_ConnectionResetError
• PyExc_DeprecationWarning
• PyExc_EOFError
• PyExc_EncodingWarning
• PyExc_EnvironmentError
• PyExc_Exception
• PyExc_FileExistsError
• PyExc_FileNotFoundError
• PyExc_FloatingPointError
• PyExc_FutureWarning
• PyExc_GeneratorExit
• PyExc_IOError
• PyExc_ImportError
• PyExc_ImportWarning
• PyExc_IndentationError
• PyExc_IndexError
• PyExc_InterruptedError
• PyExc_IsADirectoryError
• PyExc_KeyError
• PyExc_KeyboardInterrupt
• PyExc_LookupError
• PyExc_MemoryError
• PyExc_ModuleNotFoundError
• PyExc_NameError
• PyExc_NotADirectoryError
• PyExc_NotImplementedError
• PyExc_OSError
• PyExc_OverflowError
• PyExc_PendingDeprecationWarning
• PyExc_PermissionError
• PyExc_ProcessLookupError

2.4. Contenido de la API limitada 23


The Python/C API, Versión 3.12.4

• 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

24 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• PyFloat_AsDouble()
• PyFloat_FromDouble()
• PyFloat_FromString()
• PyFloat_GetInfo()
• PyFloat_GetMax()
• PyFloat_GetMin()
• PyFloat_Type
• PyFrameObject
• PyFrame_GetCode()
• PyFrame_GetLineNumber()
• PyFrozenSet_New()
• PyFrozenSet_Type
• PyGC_Collect()
• PyGC_Disable()
• PyGC_Enable()
• PyGC_IsEnabled()
• PyGILState_Ensure()
• PyGILState_GetThisThreadState()
• PyGILState_Release()
• PyGILState_STATE
• PyGetSetDef
• PyGetSetDescr_Type
• PyImport_AddModule()
• PyImport_AddModuleObject()
• PyImport_AppendInittab()
• PyImport_ExecCodeModule()
• PyImport_ExecCodeModuleEx()
• PyImport_ExecCodeModuleObject()
• PyImport_ExecCodeModuleWithPathnames()
• PyImport_GetImporter()
• PyImport_GetMagicNumber()
• PyImport_GetMagicTag()
• PyImport_GetModule()
• PyImport_GetModuleDict()
• PyImport_Import()
• PyImport_ImportFrozenModule()
• PyImport_ImportFrozenModuleObject()
• PyImport_ImportModule()
• PyImport_ImportModuleLevel()

2.4. Contenido de la API limitada 25


The Python/C API, Versión 3.12.4

• PyImport_ImportModuleLevelObject()
• PyImport_ImportModuleNoBlock()
• PyImport_ReloadModule()
• PyIndex_Check()
• PyInterpreterState
• PyInterpreterState_Clear()
• PyInterpreterState_Delete()
• PyInterpreterState_Get()
• PyInterpreterState_GetDict()
• PyInterpreterState_GetID()
• PyInterpreterState_New()
• PyIter_Check()
• PyIter_Next()
• PyIter_Send()
• PyListIter_Type
• PyListRevIter_Type
• PyList_Append()
• PyList_AsTuple()
• PyList_GetItem()
• PyList_GetSlice()
• PyList_Insert()
• PyList_New()
• PyList_Reverse()
• PyList_SetItem()
• PyList_SetSlice()
• PyList_Size()
• PyList_Sort()
• PyList_Type
• PyLongObject
• PyLongRangeIter_Type
• PyLong_AsDouble()
• PyLong_AsLong()
• PyLong_AsLongAndOverflow()
• PyLong_AsLongLong()
• PyLong_AsLongLongAndOverflow()
• PyLong_AsSize_t()
• PyLong_AsSsize_t()
• PyLong_AsUnsignedLong()
• PyLong_AsUnsignedLongLong()

26 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• PyLong_AsUnsignedLongLongMask()
• PyLong_AsUnsignedLongMask()
• PyLong_AsVoidPtr()
• PyLong_FromDouble()
• PyLong_FromLong()
• PyLong_FromLongLong()
• PyLong_FromSize_t()
• PyLong_FromSsize_t()
• PyLong_FromString()
• PyLong_FromUnsignedLong()
• PyLong_FromUnsignedLongLong()
• PyLong_FromVoidPtr()
• PyLong_GetInfo()
• PyLong_Type
• PyMap_Type
• PyMapping_Check()
• PyMapping_GetItemString()
• PyMapping_HasKey()
• PyMapping_HasKeyString()
• PyMapping_Items()
• PyMapping_Keys()
• PyMapping_Length()
• PyMapping_SetItemString()
• PyMapping_Size()
• PyMapping_Values()
• PyMem_Calloc()
• PyMem_Free()
• PyMem_Malloc()
• PyMem_Realloc()
• PyMemberDef
• PyMemberDescr_Type
• PyMember_GetOne()
• PyMember_SetOne()
• PyMemoryView_FromBuffer()
• PyMemoryView_FromMemory()
• PyMemoryView_FromObject()
• PyMemoryView_GetContiguous()
• PyMemoryView_Type
• PyMethodDef

2.4. Contenido de la API limitada 27


The Python/C API, Versión 3.12.4

• PyMethodDescr_Type
• PyModuleDef
• PyModuleDef_Base
• PyModuleDef_Init()
• PyModuleDef_Type
• PyModule_AddFunctions()
• PyModule_AddIntConstant()
• PyModule_AddObject()
• PyModule_AddObjectRef()
• PyModule_AddStringConstant()
• PyModule_AddType()
• PyModule_Create2()
• PyModule_ExecDef()
• PyModule_FromDefAndSpec2()
• PyModule_GetDef()
• PyModule_GetDict()
• PyModule_GetFilename()
• PyModule_GetFilenameObject()
• PyModule_GetName()
• PyModule_GetNameObject()
• PyModule_GetState()
• PyModule_New()
• PyModule_NewObject()
• PyModule_SetDocString()
• PyModule_Type
• PyNumber_Absolute()
• PyNumber_Add()
• PyNumber_And()
• PyNumber_AsSsize_t()
• PyNumber_Check()
• PyNumber_Divmod()
• PyNumber_Float()
• PyNumber_FloorDivide()
• PyNumber_InPlaceAdd()
• PyNumber_InPlaceAnd()
• PyNumber_InPlaceFloorDivide()
• PyNumber_InPlaceLshift()
• PyNumber_InPlaceMatrixMultiply()
• PyNumber_InPlaceMultiply()

28 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• 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()

2.4. Contenido de la API limitada 29


The Python/C API, Versión 3.12.4

• PyOS_strtol()
• PyOS_strtoul()
• PyOS_vsnprintf()
• PyObject
• PyObject.ob_refcnt
• PyObject.ob_type
• PyObject_ASCII()
• PyObject_AsCharBuffer()
• PyObject_AsFileDescriptor()
• PyObject_AsReadBuffer()
• PyObject_AsWriteBuffer()
• PyObject_Bytes()
• PyObject_Call()
• PyObject_CallFunction()
• PyObject_CallFunctionObjArgs()
• PyObject_CallMethod()
• PyObject_CallMethodObjArgs()
• PyObject_CallNoArgs()
• PyObject_CallObject()
• PyObject_Calloc()
• PyObject_CheckBuffer()
• PyObject_CheckReadBuffer()
• PyObject_ClearWeakRefs()
• PyObject_CopyData()
• PyObject_DelItem()
• PyObject_DelItemString()
• PyObject_Dir()
• PyObject_Format()
• PyObject_Free()
• PyObject_GC_Del()
• PyObject_GC_IsFinalized()
• PyObject_GC_IsTracked()
• PyObject_GC_Track()
• PyObject_GC_UnTrack()
• PyObject_GenericGetAttr()
• PyObject_GenericGetDict()
• PyObject_GenericSetAttr()
• PyObject_GenericSetDict()
• PyObject_GetAIter()

30 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• PyObject_GetAttr()
• PyObject_GetAttrString()
• PyObject_GetBuffer()
• PyObject_GetItem()
• PyObject_GetIter()
• PyObject_GetTypeData()
• PyObject_HasAttr()
• PyObject_HasAttrString()
• PyObject_Hash()
• PyObject_HashNotImplemented()
• PyObject_Init()
• PyObject_InitVar()
• PyObject_IsInstance()
• PyObject_IsSubclass()
• PyObject_IsTrue()
• PyObject_Length()
• PyObject_Malloc()
• PyObject_Not()
• PyObject_Realloc()
• PyObject_Repr()
• PyObject_RichCompare()
• PyObject_RichCompareBool()
• PyObject_SelfIter()
• PyObject_SetAttr()
• PyObject_SetAttrString()
• PyObject_SetItem()
• PyObject_Size()
• PyObject_Str()
• PyObject_Type()
• PyObject_Vectorcall()
• PyObject_VectorcallMethod()
• PyProperty_Type
• PyRangeIter_Type
• PyRange_Type
• PyReversed_Type
• PySeqIter_New()
• PySeqIter_Type
• PySequence_Check()
• PySequence_Concat()

2.4. Contenido de la API limitada 31


The Python/C API, Versión 3.12.4

• 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()

32 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• PyStructSequence_New()
• PyStructSequence_NewType()
• PyStructSequence_SetItem()
• PyStructSequence_UnnamedField
• PySuper_Type
• PySys_AddWarnOption()
• PySys_AddWarnOptionUnicode()
• PySys_AddXOption()
• PySys_FormatStderr()
• PySys_FormatStdout()
• PySys_GetObject()
• PySys_GetXOptions()
• PySys_HasWarnOptions()
• PySys_ResetWarnOptions()
• PySys_SetArgv()
• PySys_SetArgvEx()
• PySys_SetObject()
• PySys_SetPath()
• PySys_WriteStderr()
• PySys_WriteStdout()
• PyThreadState
• PyThreadState_Clear()
• PyThreadState_Delete()
• PyThreadState_Get()
• PyThreadState_GetDict()
• PyThreadState_GetFrame()
• PyThreadState_GetID()
• PyThreadState_GetInterpreter()
• PyThreadState_New()
• PyThreadState_SetAsyncExc()
• PyThreadState_Swap()
• PyThread_GetInfo()
• PyThread_ReInitTLS()
• PyThread_acquire_lock()
• PyThread_acquire_lock_timed()
• PyThread_allocate_lock()
• PyThread_create_key()
• PyThread_delete_key()
• PyThread_delete_key_value()

2.4. Contenido de la API limitada 33


The Python/C API, Versión 3.12.4

• PyThread_exit_thread()
• PyThread_free_lock()
• PyThread_get_key_value()
• PyThread_get_stacksize()
• PyThread_get_thread_ident()
• PyThread_get_thread_native_id()
• PyThread_init_thread()
• PyThread_release_lock()
• PyThread_set_key_value()
• PyThread_set_stacksize()
• PyThread_start_new_thread()
• PyThread_tss_alloc()
• PyThread_tss_create()
• PyThread_tss_delete()
• PyThread_tss_free()
• PyThread_tss_get()
• PyThread_tss_is_created()
• PyThread_tss_set()
• PyTraceBack_Here()
• PyTraceBack_Print()
• PyTraceBack_Type
• PyTupleIter_Type
• PyTuple_GetItem()
• PyTuple_GetSlice()
• PyTuple_New()
• PyTuple_Pack()
• PyTuple_SetItem()
• PyTuple_Size()
• PyTuple_Type
• PyTypeObject
• PyType_ClearCache()
• PyType_FromMetaclass()
• PyType_FromModuleAndSpec()
• PyType_FromSpec()
• PyType_FromSpecWithBases()
• PyType_GenericAlloc()
• PyType_GenericNew()
• PyType_GetFlags()
• PyType_GetModule()

34 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• 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()

2.4. Contenido de la API limitada 35


The Python/C API, Versión 3.12.4

• 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()

36 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• PyUnicode_DecodeUTF32Stateful()
• PyUnicode_DecodeUTF7()
• PyUnicode_DecodeUTF7Stateful()
• PyUnicode_DecodeUTF8()
• PyUnicode_DecodeUTF8Stateful()
• PyUnicode_DecodeUnicodeEscape()
• PyUnicode_EncodeCodePage()
• PyUnicode_EncodeFSDefault()
• PyUnicode_EncodeLocale()
• PyUnicode_FSConverter()
• PyUnicode_FSDecoder()
• PyUnicode_Find()
• PyUnicode_FindChar()
• PyUnicode_Format()
• PyUnicode_FromEncodedObject()
• PyUnicode_FromFormat()
• PyUnicode_FromFormatV()
• PyUnicode_FromObject()
• PyUnicode_FromOrdinal()
• PyUnicode_FromString()
• PyUnicode_FromStringAndSize()
• PyUnicode_FromWideChar()
• PyUnicode_GetDefaultEncoding()
• PyUnicode_GetLength()
• PyUnicode_InternFromString()
• PyUnicode_InternInPlace()
• PyUnicode_IsIdentifier()
• PyUnicode_Join()
• PyUnicode_Partition()
• PyUnicode_RPartition()
• PyUnicode_RSplit()
• PyUnicode_ReadChar()
• PyUnicode_Replace()
• PyUnicode_Resize()
• PyUnicode_RichCompare()
• PyUnicode_Split()
• PyUnicode_Splitlines()
• PyUnicode_Substring()
• PyUnicode_Tailmatch()

2.4. Contenido de la API limitada 37


The Python/C API, Versión 3.12.4

• PyUnicode_Translate()
• PyUnicode_Type
• PyUnicode_WriteChar()
• PyVarObject
• PyVarObject.ob_base
• PyVarObject.ob_size
• PyVectorcall_Call()
• PyVectorcall_NARGS()
• PyWeakReference
• PyWeakref_GetObject()
• PyWeakref_NewProxy()
• PyWeakref_NewRef()
• PyWrapperDescr_Type
• PyWrapper_New()
• PyZip_Type
• Py_AddPendingCall()
• Py_AtExit()
• Py_BEGIN_ALLOW_THREADS
• Py_BLOCK_THREADS
• Py_BuildValue()
• Py_BytesMain()
• Py_CompileString()
• Py_DecRef()
• Py_DecodeLocale()
• Py_END_ALLOW_THREADS
• Py_EncodeLocale()
• Py_EndInterpreter()
• Py_EnterRecursiveCall()
• Py_Exit()
• Py_FatalError()
• Py_FileSystemDefaultEncodeErrors
• Py_FileSystemDefaultEncoding
• Py_Finalize()
• Py_FinalizeEx()
• Py_GenericAlias()
• Py_GenericAliasType
• Py_GetBuildInfo()
• Py_GetCompiler()
• Py_GetCopyright()

38 Capítulo 2. Estabilidad de la API en C


The Python/C API, Versión 3.12.4

• Py_GetExecPrefix()
• Py_GetPath()
• Py_GetPlatform()
• Py_GetPrefix()
• Py_GetProgramFullPath()
• Py_GetProgramName()
• Py_GetPythonHome()
• Py_GetRecursionLimit()
• Py_GetVersion()
• Py_HasFileSystemDefaultEncoding
• Py_IncRef()
• Py_Initialize()
• Py_InitializeEx()
• Py_Is()
• Py_IsFalse()
• Py_IsInitialized()
• Py_IsNone()
• Py_IsTrue()
• Py_LeaveRecursiveCall()
• Py_Main()
• Py_MakePendingCalls()
• Py_NewInterpreter()
• Py_NewRef()
• Py_ReprEnter()
• Py_ReprLeave()
• Py_SetPath()
• Py_SetProgramName()
• Py_SetPythonHome()
• Py_SetRecursionLimit()
• Py_UCS4
• Py_UNBLOCK_THREADS
• Py_UTF8Mode
• Py_VaBuildValue()
• Py_Version
• Py_XNewRef()
• Py_buffer
• Py_intptr_t
• Py_ssize_t
• Py_uintptr_t

2.4. Contenido de la API limitada 39


The Python/C API, Versión 3.12.4

• 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

40 Capítulo 2. Estabilidad de la API en C


CAPÍTULO 3

La capa de muy alto nivel

Las funciones en este capítulo te permitirán ejecutar código fuente de Python desde un archivo o un búfer, pero no
te permitirán interactuar de una manera detallada con el intérprete.
Several of these functions accept a start symbol from the grammar as a parameter. The available start symbols are
Py_eval_input, Py_file_input, and Py_single_input. These are described following the functions
which accept them as parameters.
Note also that several of these functions take FILE* parameters. One particular issue which needs to be handled
carefully is that the FILE structure for different C libraries can be different and incompatible. Under Windows (at
least), it is possible for dynamically linked extensions to actually use different libraries, so care should be taken that
FILE* parameters are only passed to these functions if it is certain that they were created by the same library that
the Python runtime is using.
int Py_Main(int argc, wchar_t **argv)
Part of the Stable ABI. El programa principal para el intérprete estándar. Está disponible para programas que
incorporan Python. Los parámetros argc y argv deben prepararse exactamente como los que se pasan a la
función main() de un programa en C (convertido a wchar_t de acuerdo con la configuración regional del
usuario). Es importante tener en cuenta que la lista de argumentos puede ser modificada (pero el contenido
de las cadenas de caracteres señaladas por la lista de argumentos no lo es). El valor de retorno será 0 si el
intérprete acaba normalmente (es decir, sin excepción), 1 si el intérprete acaba debido a una excepción, o 2 si
la lista de parámetros no representa una línea de comando Python válida.
Note that if an otherwise unhandled SystemExit is raised, this function will not return 1, but exit the
process, as long as PyConfig.inspect is zero.
int Py_BytesMain(int argc, char **argv)
Part of the Stable ABI since version 3.8. Similar a Py_Main() pero argv es un arreglo de cadenas de caracteres
de bytes.
Added in version 3.8.
int PyRun_AnyFile(FILE *fp, const char *filename)
Esta es una interfaz simplificada para PyRun_AnyFileExFlags() más abajo, dejando closeit establecido
a 0 y flags establecido a NULL.
int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Esta es una interfaz simplificada para PyRun_AnyFileExFlags() más abajo, dejando closeit establecido
a 0.

41
The Python/C API, Versión 3.12.4

int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)


Esta es una interfaz simplificada para PyRun_AnyFileExFlags() más abajo, dejando flags establecido
a NULL.
int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)
If fp refers to a file associated with an interactive device (console or terminal input or Unix
pseudo-terminal), return the value of PyRun_InteractiveLoop(), otherwise return the re-
sult of PyRun_SimpleFile(). filename is decoded from the filesystem encoding (sys.
getfilesystemencoding()). If filename is NULL, this function uses "???" as the filename. If
closeit is true, the file is closed before PyRun_SimpleFileExFlags() returns.
int PyRun_SimpleString(const char *command)
This is a simplified interface to PyRun_SimpleStringFlags() below, leaving the
PyCompilerFlags* argument set to NULL.
int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Ejecuta el código fuente de Python desde command en el módulo __main__ de acuerdo con el argumento
flags. Si __main__ aún no existe, se crea. Retorna 0 en caso de éxito o -1 si se produjo una excepción. Si
hubo un error, no hay forma de obtener la información de excepción. Para el significado de flags, ver abajo.
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 PyRun_SimpleFile(FILE *fp, const char *filename)
Esta es una interfaz simplificada para PyRun_SimpleStringFlags() más abajo, dejando closeit esta-
blecido a 0 y flags establecido a NULL.
int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Esta es una interfaz simplificada para PyRun_SimpleStringFlags() más abajo, dejando flags estable-
cido a NULL.
int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)
Similar a PyRun_SimpleStringFlags(), pero el código fuente de Python se lee desde fp en lu-
gar de una cadena de caracteres en memoria. filename debe ser el nombre del fichero, se decodifica
desde filesystem encoding and error handler. Si closeit es verdadero, el fichero se cierra antes de que
PyRun_SimpleFileExFlags() retorne.

Nota: En Windows, fp debe abrirse en modo binario (por ejemplo, fopen(filename, "rb"). De lo
contrario, Python puede no manejar correctamente el archivo de script con la terminación de línea LF.

int PyRun_InteractiveOne(FILE *fp, const char *filename)


Esta es una interfaz simplificada para PyRun_InteractiveOneFlags() más abajo, dejando flags es-
tablecido a NULL.
int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Lee y ejecuta declaraciones de un archivo asociado con un dispositivo interactivo de acuerdo al argumento
flags. Se le solicitará al usuario usando sys.ps1 y sys.ps2. filename se decodifica a partir del manejador
de codificación y errores del sistema de archivos.
Retorna 0 cuando la entrada se ejecuta con éxito, -1 si hubo una excepción, o un código de error del archivo
errcode.h distribuido como parte de Python si hubo un error de análisis gramatical. (Tenga en cuenta que
errcode.h no está incluido en Python.h, por lo que debe incluirse específicamente si es necesario).
int PyRun_InteractiveLoop(FILE *fp, const char *filename)
Esta es una interfaz simplificada para PyRun_InteractiveLoopFlags() más abajo, dejando flags
establecido a NULL.
int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Lee y ejecuta declaraciones de un archivo asociado con un dispositivo interactivo hasta llegar al EOF. Se
le solicitará al usuario usando sys.ps1 y sys.ps2.*filename* se decodifica a partir del manejador de
codificación y errores del sistema de archivos. Retorna 0 en EOF o un número negativo en caso de falla.

42 Capítulo 3. La capa de muy alto nivel


The Python/C API, Versión 3.12.4

int (*PyOS_InputHook)(void)
Part of the Stable ABI. Se puede configurar para que apunte a una función con el prototipo int
func(void). Se llamará a la función cuando el indicador del intérprete de Python esté a punto de estar
inactivo y espere la entrada del usuario desde el terminal. El valor de retorno es ignorado. Sobrescribiendo este
enlace se puede utilizar para integrar la solicitud del intérprete con otros bucles de eventos, como se hace en
Modules/_tkinter.c en el código fuente de Python.
Distinto en la versión 3.12: This function is only called from the main interpreter.
char *(*PyOS_ReadlineFunctionPointer)(FILE*, FILE*, const char*)
Se puede configurar para que apunte a una función con el prototipo char *func (FILE *stdin,
FILE *stdout, char *prompt), sobrescribiendo la función predeterminada utilizada para leer una
sola línea de entrada desde el intérprete. Se espera que la función genere la cadena de caracteres prompt si
no es NULL, y luego lea una línea de entrada del archivo de entrada estándar proporcionado, retornando la
cadena de caracteres resultante. Por ejemplo, el módulo readline establece este enlace para proporcionar
funciones de edición de línea y finalización de tabulación.
El resultado debe ser una cadena de caracteres alocado por PyMem_RawMalloc() o
PyMem_RawRealloc(), o NULL si ocurre un error.
Distinto en la versión 3.4: El resultado debe ser alocado por PyMem_RawMalloc() o
PyMem_RawRealloc(), en vez de ser alocado por PyMem_Malloc() o PyMem_Realloc().
Distinto en la versión 3.12: This function is only called from the main interpreter.
PyObject *PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Return value: New reference. Esta es una interfaz simplificada para PyRun_StringFlags() más abajo,
dejando flags establecido a NULL.
PyObject *PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
Return value: New reference. Ejecuta el código fuente de Python desde str en el contexto especificado por los
objetos globals y locals con los indicadores del compilador especificados por flags. globals debe ser un diccio-
nario; locals puede ser cualquier objeto que implemente el protocolo de mapeo. El parámetro start especifica
el token de inicio que se debe usar para analizar el código fuente.
Retorna el resultado de ejecutar el código como un objeto Python, o NULL” si se produjo una excepción.
PyObject *PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)
Return value: New reference. Esta es una interfaz simplificada para PyRun_FileExFlags() más abajo,
dejando closeit establecido a 0 y flags establecido a NULL.
PyObject *PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int
closeit)
Return value: New reference. Esta es una interfaz simplificada para PyRun_FileExFlags() más abajo,
dejando flags establecido a NULL.
PyObject *PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
Return value: New reference. Esta es una interfaz simplificada para PyRun_FileExFlags() más abajo,
dejando closeit establecido a 0.
PyObject *PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
int closeit, PyCompilerFlags *flags)
Return value: New reference. Similar a PyRun_StringFlags(), pero el código fuente de Python se lee
de fp en lugar de una cadena de caracteres en memoria. filename debe ser el nombre del fichero, es decodifi-
cado desde el filesystem encoding and error handler. Si closeit es verdadero, el fichero se cierra antes de que
PyRun_FileExFlags() retorne.
PyObject *Py_CompileString(const char *str, const char *filename, int start)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz simplificada para
Py_CompileStringFlags() más abajo, dejando flags establecido a NULL.

43
The Python/C API, Versión 3.12.4

PyObject *Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)
Return value: New reference. Esta es una interfaz simplificada para Py_CompileStringExFlags() más
abajo, con optimize establecido a -1.
PyObject *Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags,
int optimize)
Return value: New reference. Parse and compile the Python source code in str, returning the resulting code
object. The start token is given by start; this can be used to constrain the code which can be compiled and should
be Py_eval_input, Py_file_input, or Py_single_input. The filename specified by filename is
used to construct the code object and may appear in tracebacks or SyntaxError exception messages. This
returns NULL if the code cannot be parsed or compiled.
El número entero optimize especifica el nivel de optimización del compilador; un valor de -1 selecciona el nivel
de optimización del intérprete como se indica en las opciones -O. Los niveles explícitos son 0 (sin optimización;
__debug__ es verdadero), 1 (los asserts se eliminan, __debug__ es falso) o 2 (los docstrings también se
eliminan) )
Added in version 3.4.
PyObject *Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags
*flags, int optimize)
Return value: New reference. Como Py_CompileStringObject(), pero filename es una cadena de bytes
decodificada a partir del manejador de codificación y errores del sistema de archivos.
Added in version 3.2.
PyObject *PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz simplificada para
PyEval_EvalCodeEx(), con solo el objeto de código y las variables globales y locales. Los otros ar-
gumentos están establecidos en NULL.
PyObject *PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int
argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int
defcount, PyObject *kwdefs, PyObject *closure)
Return value: New reference. Part of the Stable ABI. Evaluar un objeto de código precompilado, dado un
entorno particular para su evaluación. Este entorno consta de un diccionario de variables globales, un objeto de
mapeo de variables locales, arreglos de argumentos, palabras clave y valores predeterminados, un diccionario
de valores predeterminados para argumentos keyword-only y una tupla de cierre de células.
PyObject *PyEval_EvalFrame(PyFrameObject *f)
Return value: New reference. Part of the Stable ABI. Evaluar un marco de ejecución. Esta es una interfaz
simplificada para PyEval_EvalFrameEx(), para compatibilidad con versiones anteriores.
PyObject *PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Return value: New reference. Part of the Stable ABI. Esta es la función principal sin barnizar de la interpretación
de Python. El objeto de código asociado con el marco de ejecución del marco f se ejecuta, interpretando el
código de bytes y ejecutando llamadas según sea necesario. El parámetro adicional throwflag se puede ignorar
por lo general; si es verdadero, entonces se lanza una excepción de inmediato; esto se usa para los métodos
throw() de objetos generadores.
Distinto en la versión 3.4: Esta función ahora incluye una afirmación de depuración para ayudar a garantizar
que no descarte silenciosamente una excepción activa.
int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Esta función cambia los flags del marco de evaluación actual, y retorna verdad (true) en caso de éxito, falso
(false) en caso de fallo.
int Py_eval_input
El símbolo de inicio de la gramática de Python para expresiones aisladas; para usar con
Py_CompileString().

44 Capítulo 3. La capa de muy alto nivel


The Python/C API, Versión 3.12.4

int Py_file_input
El símbolo de inicio de la gramática de Python para secuencias de declaración leídos desde un archivo u otra
fuente; para usar con Py_CompileString(). Este es el símbolo usado cuando se compile un código fuente
en Python arbitrariamente largo.
int Py_single_input
El símbolo de inicio de la gramática de Python para una declaración única; para usar con
Py_CompileString(). Este es el símbolo usado para el bucle interactivo del intérprete.
struct PyCompilerFlags
Esta es la estructura usada para contener los flags del compilador. En casos donde el código es sólo compilado,
es pasado como int flags, y en casos donde el código es ejecutado, es pasado como PyCompilerFlags
*flags. En este caso, from __future__ import puede modificar los flags.
Whenever PyCompilerFlags *flags is NULL, cf_flags is treated as equal to 0, and any modifica-
tion due to from __future__ import is discarded.
int cf_flags
Flags del compilador.
int cf_feature_version
cf_feature_version es la versión menor de Python. Debe ser inicializado a PY_MINOR_VERSION.
The field is ignored by default, it is used if and only if PyCF_ONLY_AST flag is set in cf_flags.
Distinto en la versión 3.8: Agregado el campo cf_feature_version.
int CO_FUTURE_DIVISION
Este bit puede ser configurado en flags para causar que un operador de división / sea interpretado como una
«división real» de acuerdo a PEP 238.

45
The Python/C API, Versión 3.12.4

46 Capítulo 3. La capa de muy alto nivel


CAPÍTULO 4

Conteo de referencias

The functions and macros in this section are used for managing reference counts of Python objects.
Py_ssize_t Py_REFCNT(PyObject *o)
Get the reference count of the Python object o.
Note that the returned value may not actually reflect how many references to the object are actually held. For
example, some objects are «immortal» and have a very high refcount that does not reflect the actual number of
references. Consequently, do not rely on the returned value to be accurate, other than a value of 0 or 1.
Use the Py_SET_REFCNT() function to set an object reference count.
Distinto en la versión 3.10: Py_REFCNT() is changed to the inline static function.
Distinto en la versión 3.11: The parameter type is no longer const PyObject*.
void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)
Set the object o reference counter to refcnt.
Note that this function has no effect on immortal objects.
Added in version 3.9.
Distinto en la versión 3.12: Immortal objects are not modified.
void Py_INCREF(PyObject *o)
Indicate taking a new strong reference to object o, indicating it is in use and should not be destroyed.
Esta función se usa generalmente para convertir un borrowed reference en un strong reference en su lugar. La
función Py_NewRef() se puede utilizar para crear un nuevo strong reference.
When done using the object, release it by calling Py_DECREF().
El objeto no debe ser NULL; si no está seguro de que no sea NULL, use Py_XINCREF().
Do not expect this function to actually modify o in any way. For at least some objects, this function has no
effect.
Distinto en la versión 3.12: Immortal objects are not modified.
void Py_XINCREF(PyObject *o)
Similar to Py_INCREF(), but the object o can be NULL, in which case this has no effect.
Ver también Py_XNewRef().

47
The Python/C API, Versión 3.12.4

PyObject *Py_NewRef(PyObject *o)


Part of the Stable ABI since version 3.10. Create a new strong reference to an object: call Py_INCREF() on
o and return the object o.
When the strong reference is no longer needed, Py_DECREF() should be called on it to release the reference.
El objeto o no debe ser NULL; use Py_XNewRef() si o puede ser NULL.
Por ejemplo:
Py_INCREF(obj);
self->attr = obj;

puede ser escrito como:


self->attr = Py_NewRef(obj);

Ver también Py_INCREF().


Added in version 3.10.
PyObject *Py_XNewRef(PyObject *o)
Part of the Stable ABI since version 3.10. Similar a Py_NewRef(), pero el objeto o puede ser NULL.
Si el objeto o es NULL, la función solo retorna NULL.
Added in version 3.10.
void Py_DECREF(PyObject *o)
Release a strong reference to object o, indicating the reference is no longer used.
Once the last strong reference is released (i.e. the object’s reference count reaches 0), the object’s type’s dea-
llocation function (which must not be NULL) is invoked.
Esta función se usa generalmente para eliminar un strong reference antes de salir de su alcance.
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.

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.

Distinto en la versión 3.12: Immortal objects are not modified.


void Py_XDECREF(PyObject *o)
Similar to Py_DECREF(), but the object o can be NULL, in which case this has no effect. The same warning
from Py_DECREF() applies here as well.
void Py_CLEAR(PyObject *o)
Release a strong reference for object o. The object may be NULL, in which case the macro has no effect;
otherwise the effect is the same as for Py_DECREF(), except that the argument is also set to NULL. The
warning for Py_DECREF() does not apply with respect to the object passed because the macro carefully uses
a temporary variable and sets the argument to NULL before releasing the reference.
It is a good idea to use this macro whenever releasing a reference to an object that might be traversed during
garbage collection.
Distinto en la versión 3.12: The macro argument is now only evaluated once. If the argument has side effects,
these are no longer duplicated.

48 Capítulo 4. Conteo de referencias


The Python/C API, Versión 3.12.4

void Py_IncRef(PyObject *o)


Part of the Stable ABI. Indicate taking a new strong reference to object o. A function version of
Py_XINCREF(). It can be used for runtime dynamic embedding of Python.
void Py_DecRef(PyObject *o)
Part of the Stable ABI. Release a strong reference to object o. A function version of Py_XDECREF(). It can
be used for runtime dynamic embedding of Python.
Py_SETREF(dst, src)
Macro safely releasing a strong reference to object dst and setting dst to src.
As in case of Py_CLEAR(), «the obvious» code can be deadly:

Py_DECREF(dst);
dst = src;

The safe way is:

Py_SETREF(dst, src);

That arranges to set dst to src _before_ releasing the reference to the old value of dst, so that any code triggered
as a side-effect of dst getting torn down no longer believes dst points to a valid object.
Added in version 3.6.
Distinto en la versión 3.12: The macro arguments are now only evaluated once. If an argument has side effects,
these are no longer duplicated.
Py_XSETREF(dst, src)
Variant of Py_SETREF macro that uses Py_XDECREF() instead of Py_DECREF().
Added in version 3.6.
Distinto en la versión 3.12: The macro arguments are now only evaluated once. If an argument has side effects,
these are no longer duplicated.

49
The Python/C API, Versión 3.12.4

50 Capítulo 4. Conteo de referencias


CAPÍTULO 5

Manejo de excepciones

Las funciones descritas en este capítulo le permitirán manejar y lanzar excepciones de Python. Es importante com-
prender algunos de los conceptos básicos del manejo de excepciones de Python. Funciona de manera similar a la
variable POSIX errno: hay un indicador global (por hilo) del último error que ocurrió. La mayoría de las funciones
de C API no borran esto en caso de éxito, pero lo configurarán para indicar la causa del error en caso de falla. La
mayoría de las funciones de C API también retornan un indicador de error, generalmente NULL si se supone que
retornan un puntero, o -1 si retornan un número entero (excepción: las funciones PyArg_* retornan 1 para el éxito
y 0 para el fracaso).
Concretamente, el indicador de error consta de tres punteros de objeto: el tipo de excepción, el valor de la excep-
ción y el objeto de rastreo. Cualquiera de esos punteros puede ser NULL si no está configurado (aunque algunas
combinaciones están prohibidas, por ejemplo, no puede tener un rastreo no NULL si el tipo de excepción es NULL).
Cuando una función debe fallar porque alguna función que llamó falló, generalmente no establece el indicador de
error; la función que llamó ya lo configuró. Es responsable de manejar el error y borrar la excepción o regresar
después de limpiar cualquier recurso que tenga (como referencias de objetos o asignaciones de memoria); debería
no continuar normalmente si no está preparado para manejar el error. Si regresa debido a un error, es importante
indicarle a la persona que llama que se ha establecido un error. Si el error no se maneja o se propaga cuidadosamente,
es posible que las llamadas adicionales a la API de Python/C no se comporten como se espera y pueden fallar de
manera misteriosa.

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).

5.1 Impresión y limpieza

void PyErr_Clear()
Part of the Stable ABI. Borra el indicador de error. Si el indicador de error no está configurado, no hay efecto.
void PyErr_PrintEx(int set_sys_last_vars)
Part of the Stable ABI. Imprime un rastreo estándar en sys.stderr y borra el indicador de error. A menos
que el error sea un Salida del sistema, en ese caso no se imprime ningún rastreo y el proceso de
Python se cerrará con el código de error especificado por la instancia de Salida del sistema.

51
The Python/C API, Versión 3.12.4

Llame a esta función solo cuando el indicador de error está configurado. De lo contrario, provocará un error
fatal!
If set_sys_last_vars is nonzero, the variable sys.last_exc is set to the printed exception. For
backwards compatibility, the deprecated variables sys.last_type, sys.last_value and sys.
last_traceback are also set to the type, value and traceback of this exception, respectively.
Distinto en la versión 3.12: The setting of sys.last_exc was added.
void PyErr_Print()
Part of the Stable ABI. Alias para PyErr_PrintEx(1).
void PyErr_WriteUnraisable(PyObject *obj)
Part of the Stable ABI. Llama sys.unraisablehook() utilizando la excepción actual y el argumento
obj.
This utility function prints a warning message to sys.stderr when an exception has been set but it is
impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs
in an __del__() method.
The function is called with a single argument obj that identifies the context in which the unraisable exception
occurred. If possible, the repr of obj will be printed in the warning message. If obj is NULL, only the traceback
is printed.
Se debe establecer una excepción al llamar a esta función.
Distinto en la versión 3.4: Print a traceback. Print only traceback if obj is NULL.
Distinto en la versión 3.8: Use sys.unraisablehook().
void PyErr_DisplayException(PyObject *exc)
Part of the Stable ABI since version 3.12. Print the standard traceback display of exc to sys.stderr,
including chained exceptions and notes.
Added in version 3.12.

5.2 Lanzando excepciones

Estas funciones lo ayudan a configurar el indicador de error del hilo actual. Por conveniencia, algunas de estas fun-
ciones siempre retornarán un puntero NULL para usar en una declaración return.
void PyErr_SetString(PyObject *type, const char *message)
Part of the Stable ABI. This is the most common way to set the error indicator. The first argument specifies the
exception type; it is normally one of the standard exceptions, e.g. PyExc_RuntimeError. You need not
create a new strong reference to it (e.g. with Py_INCREF()). The second argument is an error message; it is
decoded from 'utf-8'.
void PyErr_SetObject(PyObject *type, PyObject *value)
Part of the Stable ABI. Esta función es similar a PyErr_SetString() pero le permite especificar un objeto
Python arbitrario para el «valor» de la excepción.
PyObject *PyErr_Format(PyObject *exception, const char *format, ...)
Return value: Always NULL. Part of the Stable ABI. Esta función establece el indicador de error y retorna
NULL. exception debe ser una clase de excepción Python. El format y los parámetros posteriores ayudan a
formatear el mensaje de error; tienen el mismo significado y valores que en PyUnicode_FromFormat().
format es una cadena de caracteres codificada en ASCII.
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Return value: Always NULL. Part of the Stable ABI since version 3.5. Igual que PyErr_Format(), pero
tomando un argumento va_list en lugar de un número variable de argumentos.
Added in version 3.5.

52 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.12.4

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
objetos 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 addi-
tional 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
archivo, para lanzar errores cuando falla una función que toma dos nombres de archivo.
Added in version 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 fun-
ction to raise OSError. 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 OSError object with the winerror at-
tribute set to the error code, the strerror attribute set to the corresponding error message (gotten from
FormatMessage()), and then calls PyErr_SetObject(PyExc_OSError, object). This fun-
ction 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

5.2. Lanzando excepciones 53


The Python/C API, Versión 3.12.4

PyErr_SetFromWindowsErr(), with the additional behavior that if filename is not NULL, it is deco-
ded from the filesystem encoding (os.fsdecode()) and passed to the constructor of OSError as a third
parameter to be used to define the filename attribute of the exception instance.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject
*filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar to
PyErr_SetExcFromWindowsErr(), with the additional behavior that if filename is not NULL, it is
passed to the constructor of OSError as a third parameter to be used to define the filename attribute of
the exception instance.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject
*filename, PyObject *filename2)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a
PyErr_SetExcFromWindowsErrWithFilenameObject(), pero acepta un segundo objeto de
nombre de archivo.
Disponibilidad: Windows.
Added in version 3.4.
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char
*filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a
PyErr_SetFromWindowsErrWithFilename(), con un parámetro adicional que especifica el tipo
de excepción que se lanzará.
Disponibilidad: Windows.
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.7. Esta es una función conveniente para subir
ImportError. msg se establecerá como la cadena de mensaje de la excepción. name y path, que pueden ser
NULL, se establecerán como atributos respectivos name y path de ImportError.
Added in version 3.3.
PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name,
PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.6. Al igual que
PyErr_SetImportError() pero esta función permite especificar una subclase de ImportError para
aumentar.
Added in version 3.6.
void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Establece información de archivo, línea y desplazamiento para la excepción actual. Si la excepción actual no es
un SyntaxError, establece atributos adicionales, lo que hace que el sub sistema de impresión de excepciones
piense que la excepción es SyntaxError.
Added in version 3.4.
void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Part of the Stable ABI since version 3.7. Como PyErr_SyntaxLocationObject(), pero filename es
una cadena de bytes decodificada a partir de filesystem encoding and error handler.
Added in version 3.2.
void PyErr_SyntaxLocation(const char *filename, int lineno)
Part of the Stable ABI. Como PyErr_SyntaxLocationEx(), pero se omite el parámetro col_offset.

54 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.12.4

void PyErr_BadInternalCall()
Part of the Stable ABI. Esta es una abreviatura de PyErr_SetString(PyExc_SystemError,
message), donde message indica que se invocó una operación interna (por ejemplo, una función de Pyt-
hon/C API) con un argumento ilegal. Es principalmente para uso interno.

5.3 Emitir advertencias

Use estas funciones para emitir advertencias desde el código C. Reflejan funciones similares exportadas por el módulo
Python warnings. Normalmente imprimen un mensaje de advertencia a sys.stderr; sin embargo, también es posible
que el usuario haya especificado que las advertencias se conviertan en errores, y en ese caso lanzarán una excepción.
También es posible que las funciones generen una excepción debido a un problema con la maquinaria de advertencia.
El valor de retorno es 0 si no se lanza una excepción, o -1 si se lanza una excepción. (No es posible determinar
si realmente se imprime un mensaje de advertencia, ni cuál es el motivo de la excepción; esto es intencional). Si se
produce una excepción, la persona que llama debe hacer su manejo normal de excepciones (por ejemplo, referencias
propiedad de Py_DECREF() y retornan un valor de error).
int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Part of the Stable ABI. Emite un mensaje de advertencia. El argumento category es una categoría de advertencia
(ver más abajo) o NULL; el argumento message es una cadena de caracteres codificada en UTF-8. stack_level
es un número positivo que proporciona una cantidad de marcos de pila; la advertencia se emitirá desde la línea
de código que se está ejecutando actualmente en ese marco de pila. Un stack_level de 1 es la función que llama
PyErr_WarnEx(), 2 es la función por encima de eso, y así sucesivamente.
Las categorías de advertencia deben ser subclases de PyExc_Warning; PyExc_Warning es una subcla-
se de PyExc_Exception; la categoría de advertencia predeterminada es PyExc_RuntimeWarning.
Las categorías de advertencia estándar de Python están disponibles como variables globales cuyos nombres se
enumeran en Categorías de advertencia estándar.
Para obtener información sobre el control de advertencia, consulte la documentación del módulo warnings
y la opción -W en la documentación de la línea de comandos. No hay API de C para el control de advertencia.
int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno,
PyObject *module, PyObject *registry)
Emite un mensaje de advertencia con control explícito sobre todos los atributos de advertencia. Este es un
contenedor sencillo alrededor de la función Python warnings.warn_explicit(); consulte allí para
obtener más información. Los argumentos module y registry pueden establecerse en NULL para obtener el
efecto predeterminado que se describe allí.
Added in version 3.4.
int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const
char *module, PyObject *registry)
Part of the Stable ABI. Similar a PyErr_WarnExplicitObject() excepto que message y module son
cadenas codificadas UTF-8, y filename se decodifica de filesystem encoding and error handler.
int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI. Función similar a PyErr_WarnEx(), pero usa PyUnicode_FromFormat()
para formatear el mensaje de advertencia. format es una cadena de caracteres codificada en ASCII.
Added in version 3.2.
int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI since version 3.6. Function similar to PyErr_WarnFormat(), but category is
ResourceWarning and it passes source to warnings.WarningMessage.
Added in version 3.6.

5.3. Emitir advertencias 55


The Python/C API, Versión 3.12.4

5.4 Consultando el indicador de error

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).

int PyErr_ExceptionMatches(PyObject *exc)


Part of the Stable ABI. Equivalente a PyErr_GivenExceptionMatches(PyErr_Occurred(),
exc). Esto solo debería llamarse cuando se establece una excepción; se producirá una infracción de acce-
so a la memoria si no se ha producido ninguna excepción.
int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
Part of the Stable ABI. Retorna verdadero si la excepción dada coincide con el tipo de excepción en exc. Si
exc es un objeto de clase, esto también retorna verdadero cuando dado es una instancia de una subclase. Si exc
es una tupla, se busca una coincidencia en todos los tipos de excepción en la tupla (y recursivamente en sub
tuplas).
PyObject *PyErr_GetRaisedException(void)
Return value: New reference. Part of the Stable ABI since version 3.12. Return the exception currently being
raised, clearing the error indicator at the same time. Return NULL if the error indicator is not set.
This function is used by code that needs to catch exceptions, or code that needs to save and restore the error
indicator temporarily.
For example:

{
PyObject *exc = PyErr_GetRaisedException();

/* ... code that might produce other errors ... */

PyErr_SetRaisedException(exc);
}

Ver también:
PyErr_GetHandledException(), to save the exception currently being handled.
Added in version 3.12.
void PyErr_SetRaisedException(PyObject *exc)
Part of the Stable ABI since version 3.12. Set exc as the exception currently being raised, clearing the existing
exception if one is set.

Advertencia: This call steals a reference to exc, which must be a valid exception.

Added in version 3.12.

56 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.12.4

void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)


Part of the Stable ABI. Obsoleto desde la versión 3.12: Use PyErr_GetRaisedException() instead.
Recupera el indicador de error en tres variables cuyas direcciones se pasan. Si el indicador de error no está
configurado, configure las tres variables en NULL. Si está configurado, se borrará y usted tendrá una referencia
a cada objeto recuperado. El objeto de valor y rastreo puede ser NULL incluso cuando el objeto de tipo no lo
es.

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);

/* ... code that might produce other errors ... */

PyErr_Restore(type, value, traceback);


}

void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)


Part of the Stable ABI. Obsoleto desde la versión 3.12: Use PyErr_SetRaisedException() instead.
Set the error indicator from the three objects, type, value, and traceback, clearing the existing exception if one
is set. If the objects are NULL, the error indicator is cleared. Do not pass a NULL type and non-NULL value
or traceback. The exception type should be a class. Do not pass an invalid exception type or value. (Violating
these rules will cause subtle problems later.) This call takes away a reference to each object: you must own
a reference to each object before the call and after the call you no longer own these references. (If you don’t
understand this, don’t use this function. I warned you.)

Nota: This function is normally only used by legacy code that needs to save and restore the error indicator
temporarily. Use PyErr_Fetch() to save the current error indicator.

void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)


Part of the Stable ABI. Obsoleto desde la versión 3.12: Use PyErr_GetRaisedException() instead,
to avoid any possible de-normalization.
Bajo ciertas circunstancias, los valores retornados por PyErr_Fetch() a continuación pueden ser «no nor-
malizados», lo que significa que *exc es un objeto de clase pero *val no es una instancia de la misma clase .
Esta función se puede utilizar para crear instancias de la clase en ese caso. Si los valores ya están normalizados,
no pasa nada. La normalización retrasada se implementa para mejorar el rendimiento.

Nota: This function does not implicitly set the __traceback__ attribute on the exception value. If setting
the traceback appropriately is desired, the following additional snippet is needed:

if (tb != NULL) {
PyException_SetTraceback(val, tb);
}

PyObject *PyErr_GetHandledException(void)
Part of the Stable ABI since version 3.11. Recupera la instancia de excepción activa, como la que devolvería
sys.exception(). Esto se refiere a una excepción que ya fue capturada, no a una excepción recién lan-
zada. Retorna una nueva referencia a la excepción o NULL. No modifica el estado de excepción del intérprete.

5.4. Consultando el indicador de error 57


The Python/C API, Versión 3.12.4

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.

Added in version 3.11.


void PyErr_SetHandledException(PyObject *exc)
Part of the Stable ABI since version 3.11. Establece la excepción activa, como se conoce de sys.
exception(). Esto se refiere a la excepción que ya fue capturada, no a una excepción que fue lanzada
recientemente. Para borrar el estado de la excepción, pasa NULL.

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.

Added in version 3.11.


void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
Part of the Stable ABI since version 3.7. Recupera la información de excepción, como se conoce de sys.
exc_info(). Esto se refiere a una excepción que ya fue capturada, no a una excepción que fue lanzada
recientemente. Retorna nuevas referencias para los tres objetos, cualquiera de los cuales puede ser NULL.
No modifica el estado de información de excepción. Esta función se mantiene por retro-compatibilidad. Es
preferible usar PyErr_GetHandledException().

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.

Added in version 3.3.


void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
Part of the Stable ABI since version 3.7. Establece la información de excepción, como se conoce de sys.
exc_info(). Esto se refiere a una excepción que ya fue capturada, no a una excepción que fue lan-
zada recientemente. Esta función roba las referencias de los argumentos. Para borrar el estado de excep-
ción, pase NULL para los tres argumentos. Para ver las reglas generales sobre los tres argumentos, consulte
PyErr_SetHandledException().

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.

Added in version 3.3.


Distinto en la versión 3.11: Los argumentos type y traceback ya no se utilizan y pueden ser NULL. El
intérprete los deriva ahora de la instancia de la excepción (el argumento value). La función sigue robando
referencias de los tres argumentos.

58 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.12.4

5.5 Manejo de señal

int PyErr_CheckSignals()
Part of the Stable ABI. Esta función interactúa con el manejo de señales de Python.
Si la función se llama desde el hilo principal y bajo el intérprete principal de Python, verifica si se ha enviado
una señal a los procesos y, de ser así, invoca el manejador de señales correspondiente. Si el módulo signal
es compatible, esto puede invocar un manejador de señales escrito en Python.
La función intenta manejar todas las señales pendientes y luego devuelve 0. Sin embargo, si un manejador de
señales de Python lanza una excepción, el indicador de error se establece y la función devuelve -1 inmedia-
tamente (de modo que es posible que otras señales pendientes no se hayan manejado todavía: estarán en la
siguiente invocación de PyErr_CheckSignals()).
Si la función se llama desde un hilo no principal, o bajo un intérprete de Python no principal, no hace nada y
devuelve 0.
Esta función se puede llamar mediante un código C de ejecución prolongada que quiere ser interrumpible por
las peticiones del usuario (como presionar Ctrl-C).

Nota: The default Python signal handler for SIGINT raises the KeyboardInterrupt exception.

void PyErr_SetInterrupt()
Part of the Stable ABI. Simulate the effect of a SIGINT signal arriving. This is equivalent to
PyErr_SetInterruptEx(SIGINT).

Nota: Esta función es segura para señales asíncronas. Se puede llamar sin el GIL y desde un manejador de
señales de C.

int PyErr_SetInterruptEx(int signum)


Part of the Stable ABI since version 3.10. Simula el efecto de la llegada de una señal. La próxima vez que sea
llamado PyErr_CheckSignals(), se llamará al manejador de señal de Python para el número de señal
dado.
Esta función puede ser llamada por código C que configura su propio manejo de señales y quiere que los
manejadores de señales de Python sean invocados como se espera cuando se solicita una interrupción (por
ejemplo, cuando el usuario presiona Ctrl-C para interrumpir una operación).
If the given signal isn’t handled by Python (it was set to signal.SIG_DFL or signal.SIG_IGN), it will
be ignored.
Si signum está fuera del rango permitido de números de señal, se devuelve -1. De lo contrario, se devuelve 0.
Esta función nunca cambia el indicador de error.

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.

Added in version 3.10.


int PySignal_SetWakeupFd(int fd)
Esta función de utilidad especifica un descriptor de archivo en el que el número de señal se escribe como un
solo byte cada vez que se recibe una señal. fd debe ser sin bloqueo. retorna el descriptor de archivo anterior.
El valor -1 desactiva la función; Este es el estado inicial. Esto es equivalente a signal.
set_wakeup_fd() en Python, pero sin verificación de errores. fd debe ser un descriptor de archivo válido.
La función solo debe llamarse desde el hilo principal.
Distinto en la versión 3.5: En Windows, la función ahora también admite controladores de socket.

5.5. Manejo de señal 59


The Python/C API, Versión 3.12.4

5.6 Clases de excepción

PyObject *PyErr_NewException(const char *name, PyObject *base, PyObject *dict)


Return value: New reference. Part of the Stable ABI. Esta función de utilidad crea y retorna una nueva clase de
excepción. El argumento name debe ser el nombre de la nueva excepción, una cadena de caracteres en C de la
forma module.classname. Los argumentos base y dict son normalmente NULL. Esto crea un objeto de
clase derivado de Exception (accesible en C como PyExc_Exception).
The __module__ attribute of the new class is set to the first part (up to the last dot) of the name argument,
and the class name is set to the last part (after the last dot). The base argument can be used to specify alternate
base classes; it can either be only one class or a tuple of classes. The dict argument can be used to specify a
dictionary of class variables and methods.
PyObject *PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject
*dict)
Return value: New reference. Part of the Stable ABI. Igual que PyErr_NewException(), excepto que
la nueva clase de excepción puede recibir fácilmente una cadena de documentación: si doc no es NULL, se
utilizará como la cadena de documentación para la clase de excepción.
Added in version 3.2.

5.7 Objetos excepción

PyObject *PyException_GetTraceback(PyObject *ex)


Return value: New reference. Part of the Stable ABI. Return the traceback associated with the exception as a
new reference, as accessible from Python through the __traceback__ attribute. If there is no traceback
associated, this returns NULL.
int PyException_SetTraceback(PyObject *ex, PyObject *tb)
Part of the Stable ABI. Establezca el rastreo asociado con la excepción a tb. Use Py_None para borrarlo.
PyObject *PyException_GetContext(PyObject *ex)
Return value: New reference. Part of the Stable ABI. Return the context (another exception instance during
whose handling ex was raised) associated with the exception as a new reference, as accessible from Python
through the __context__ attribute. If there is no context associated, this returns NULL.
void PyException_SetContext(PyObject *ex, PyObject *ctx)
Part of the Stable ABI. Establece el contexto asociado con la excepción a ctx. Use NULL para borrarlo. No hay
verificación de tipo para asegurarse de que ctx es una instancia de excepción. Esto roba una referencia a ctx.
PyObject *PyException_GetCause(PyObject *ex)
Return value: New reference. Part of the Stable ABI. Return the cause (either an exception instance, or None,
set by raise ... from ...) associated with the exception as a new reference, as accessible from Python
through the __cause__ attribute.
void PyException_SetCause(PyObject *ex, PyObject *cause)
Part of the Stable ABI. Set the cause associated with the exception to cause. Use NULL to clear it. There is no
type check to make sure that cause is either an exception instance or None. This steals a reference to cause.
The __suppress_context__ attribute is implicitly set to True by this function.
PyObject *PyException_GetArgs(PyObject *ex)
Return value: New reference. Part of the Stable ABI since version 3.12. Return args of exception ex.
void PyException_SetArgs(PyObject *ex, PyObject *args)
Part of the Stable ABI since version 3.12. Set args of exception ex to args.

60 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.12.4

PyObject *PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs)

This is Unstable API. It may change without warning in minor releases.

Implement part of the interpreter’s implementation of except*. orig is the original exception that was caught,
and excs is the list of the exceptions that need to be raised. This list contains the unhandled part of orig, if any,
as well as the exceptions that were raised from the except* clauses (so they have a different traceback from
orig) and those that were reraised (and have the same traceback as orig). Return the ExceptionGroup that
needs to be reraised in the end, or None if there is nothing to reraise.
Added in version 3.12.

5.8 Objetos unicode de excepción

Las siguientes funciones se utilizan para crear y modificar excepciones Unicode de C.


PyObject *PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length,
Py_ssize_t start, Py_ssize_t end, const char *reason)
Return value: New reference. Part of the Stable ABI. Crea un objeto UnicodeDecodeError con los atri-
butos encoding, object, length, start, end y reason. encoding y reason son cadenas codificadas UTF-8.
PyObject *PyUnicodeDecodeError_GetEncoding(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetEncoding(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Retorna el atributo encoding del objeto de excepción dado.
PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Retorna el atributo object del objeto de excepción dado.
int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
Part of the Stable ABI. Obtiene el atributo start del objeto de excepción dado y lo coloca en *start. start no
debe ser NULL. retorna 0 en caso de éxito, -1 en caso de error.
int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
Part of the Stable ABI. Establece el atributo start del objeto de excepción dado en start. Retorna 0 en caso de
éxito, -1 en caso de error.
int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
Part of the Stable ABI. Obtiene el atributo end del objeto de excepción dado y lo coloca en *end. end no debe
ser NULL. retorna 0 en caso de éxito, -1 en caso de error.
int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
Part of the Stable ABI. Establece el atributo end del objeto de excepción dado en end. Retorna 0 en caso de
éxito, -1 en caso de error.
PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc)

5.8. Objetos unicode de excepción 61


The Python/C API, Versión 3.12.4

PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc)


Return value: New reference. Part of the Stable ABI. Retorna el atributo reason del objeto de excepción dado.
int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
Part of the Stable ABI. Establece el atributo reason del objeto de excepción dado en reason. Retorna 0 en caso
de éxito, -1 en caso de error.

5.9 Control de recursión

Estas dos funciones proporcionan una forma de realizar llamadas recursivas seguras en el nivel C, tanto en el núcleo
como en los módulos de extensión. Son necesarios si el código recursivo no invoca necesariamente el código Python
(que rastrea su profundidad de recursión automáticamente). Tampoco son necesarios para las implementaciones de
tp_call porque call protocol se encarga del manejo de la recursividad.
int Py_EnterRecursiveCall(const char *where)
Part of the Stable ABI since version 3.9. Marca un punto donde una llamada recursiva de nivel C está a punto
de realizarse.
If USE_STACKCHECK is defined, this function checks if the OS stack overflowed using
PyOS_CheckStack(). If this is the case, it sets a MemoryError and returns a nonzero value.
La función verifica si se alcanza el límite de recursión. Si este es el caso, se establece a RecursionError
y se retorna un valor distinto de cero. De lo contrario, se retorna cero.
where debería ser una cadena de caracteres codificada en UTF-8 como "en la comprobación de
instancia" para concatenarse con el mensaje RecursionError causado por el límite de profundidad
de recursión.
Distinto en la versión 3.9: This function is now also available in the limited API.
void Py_LeaveRecursiveCall(void)
Part of the Stable ABI since version 3.9. Termina una Py_EnterRecursiveCall(). Se debe llamar una
vez por cada invocación exitosa de Py_EnterRecursiveCall().
Distinto en la versión 3.9: This function is now also available in the limited API.
La implementación adecuada de tp_repr para los tipos de contenedor requiere un manejo de recursión especial.
Además de proteger la pila, tp_repr también necesita rastrear objetos para evitar ciclos. Las siguientes dos funcio-
nes facilitan esta funcionalidad. Efectivamente, estos son los C equivalentes a reprlib.recursive_repr().

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.

62 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.12.4

5.10 Excepciones estándar

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 Nombre en Python Notas


1
PyExc_BaseException BaseException
Página 64, 1
PyExc_Exception Exception
Página 64, 1
PyExc_ArithmeticError ArithmeticError
PyExc_AssertionError AssertionError
PyExc_AttributeError AttributeError
PyExc_BlockingIOError BlockingIOError
PyExc_BrokenPipeError BrokenPipeError
PyExc_BufferError BufferError
PyExc_ChildProcessError ChildProcessError
PyExc_ConnectionAbortedError
ConnectionAbortedError
PyExc_ConnectionError ConnectionError
PyExc_ConnectionRefusedError
ConnectionRefusedError
PyExc_ConnectionResetError
ConnectionResetError
PyExc_EOFError EOFError
PyExc_FileExistsError FileExistsError
PyExc_FileNotFoundError FileNotFoundError
PyExc_FloatingPointError FloatingPointError
PyExc_GeneratorExit GeneratorExit
PyExc_ImportError ImportError
PyExc_IndentationError IndentationError
PyExc_IndexError IndexError
PyExc_InterruptedError InterruptedError
PyExc_IsADirectoryError IsADirectoryError
PyExc_KeyError KeyError
PyExc_KeyboardInterrupt KeyboardInterrupt
Página 64, 1
PyExc_LookupError LookupError
PyExc_MemoryError MemoryError
PyExc_ModuleNotFoundErrorModuleNotFoundError
PyExc_NameError NameError
PyExc_NotADirectoryError NotADirectoryError
PyExc_NotImplementedErrorNotImplementedError
Página 64, 1
PyExc_OSError OSError
PyExc_OverflowError OverflowError
PyExc_PermissionError PermissionError
PyExc_ProcessLookupError ProcessLookupError
PyExc_RecursionError RecursionError
PyExc_ReferenceError ReferenceError
PyExc_RuntimeError RuntimeError
PyExc_StopAsyncIteration StopAsyncIteration
PyExc_StopIteration StopIteration
PyExc_SyntaxError SyntaxError
PyExc_SystemError SystemError
PyExc_SystemExit SystemExit
PyExc_TabError TabError
PyExc_TimeoutError TimeoutError
PyExc_TypeError TypeError
PyExc_UnboundLocalError UnboundLocalError
PyExc_UnicodeDecodeError UnicodeDecodeError
continúe en la próxima página

5.10. Excepciones estándar 63


The Python/C API, Versión 3.12.4

Tabla 1 – proviene de la página anterior


Nombre en C Nombre en Python Notas
PyExc_UnicodeEncodeError UnicodeEncodeError
PyExc_UnicodeError UnicodeError
PyExc_UnicodeTranslateError
UnicodeTranslateError
PyExc_ValueError ValueError
PyExc_ZeroDivisionError ZeroDivisionError

Added in version 3.3: PyExc_BlockingIOError, PyExc_BrokenPipeError,


PyExc_ChildProcessError, PyExc_ConnectionError, PyExc_ConnectionAbortedError,
PyExc_ConnectionRefusedError, PyExc_ConnectionResetError,
PyExc_FileExistsError, PyExc_FileNotFoundError, PyExc_InterruptedError,
PyExc_IsADirectoryError, PyExc_NotADirectoryError, PyExc_PermissionError,
PyExc_ProcessLookupError y PyExc_TimeoutError fueron introducidos luego de PEP 3151.
Added in version 3.5: PyExc_StopAsyncIteration y PyExc_RecursionError.
Added in version 3.6: PyExc_ModuleNotFoundError.
Estos son alias de compatibilidad para PyExc_OSError:

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:

5.11 Categorías de advertencia estándar

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:

Nombre en C Nombre en Python Notas


3
PyExc_Warning Warning
PyExc_BytesWarning BytesWarning
PyExc_DeprecationWarning DeprecationWarning
PyExc_FutureWarning FutureWarning
PyExc_ImportWarning ImportWarning
PyExc_PendingDeprecationWarning PendingDeprecationWarning
PyExc_ResourceWarning ResourceWarning
PyExc_RuntimeWarning RuntimeWarning
PyExc_SyntaxWarning SyntaxWarning
PyExc_UnicodeWarning UnicodeWarning
PyExc_UserWarning UserWarning

Added in version 3.2: PyExc_ResourceWarning.


Notas:
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.
3 Esta es una clase base para otras categorías de advertencia estándar.

64 Capítulo 5. Manejo de excepciones


CAPÍTULO 6

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.

6.1 Utilidades del sistema operativo

PyObject *PyOS_FSPath(PyObject *path)


Return value: New reference. Part of the Stable ABI since version 3.6. Return the file system representation for
path. If the object is a str or bytes object, then a new strong reference is returned. If the object implements
the os.PathLike interface, then __fspath__() is returned as long as it is a str or bytes object.
Otherwise TypeError is raised and NULL is returned.
Added in version 3.6.
int Py_FdIsInteractive(FILE *fp, const char *filename)
Return true (nonzero) if the standard I/O file fp with name filename is deemed interactive. This is the case for
files for which isatty(fileno(fp)) is true. If the PyConfig.interactive is non-zero, this fun-
ction also returns true if the filename pointer is NULL or if the name is equal to one of the strings '<stdin>'
or '???'.
This function must not be called before Python is initialized.
void PyOS_BeforeFork()
Part of the Stable ABI on platforms with fork() since version 3.7. Función para preparar algún estado interno
antes de una bifurcación de proceso (process fork). Esto debería llamarse antes de llamar a fork() o cualquier
función similar que clone el proceso actual. 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_BeforeFork().

Added in version 3.7.


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()

65
The Python/C API, Versión 3.12.4

o cualquier función similar que clone el proceso actual, independientemente de si la clonación del proceso fue
exitosa. Solo disponible en sistemas donde fork() está definido.

Advertencia: La llamada C fork() solo debe hacerse desde hilo «principal» (del intérprete «principal»).
Lo mismo es cierto para PyOS_AfterFork_Parent().

Added in version 3.7.


void PyOS_AfterFork_Child()
Part of the Stable ABI on platforms with fork() since version 3.7. Función para actualizar el estado del intér-
prete interno después de una bifurcación de proceso (process fork). Debe llamarse desde el proceso secundario
después de llamar a fork(), o cualquier función similar que clone el proceso actual, si existe alguna posibi-
lidad de que el proceso vuelva a llamar al intérprete de Python. 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_Child().

Added in version 3.7.


Ver también:
os.register_at_fork() permite registrar funciones personalizadas de Python a las que puede llamar
PyOS_BeforeFork(), PyOS_AfterFork_Parent() y PyOS_AfterFork_Child().
void PyOS_AfterFork()
Part of the Stable ABI on platforms with fork(). Función para actualizar algún estado interno después de una
bifurcación de proceso (process fork); Esto debería llamarse en el nuevo proceso si el intérprete de Python
continuará siendo utilizado. Si se carga un nuevo ejecutable en el nuevo proceso, no es necesario llamar a esta
función.
Obsoleto desde la versión 3.7: Esta función es reemplazada por PyOS_AfterFork_Child().
int PyOS_CheckStack()
Part of the Stable ABI on platforms with USE_STACKCHECK since version 3.7. Return true when the interpreter
runs out of stack space. This is a reliable check, but is only available when USE_STACKCHECK is defined
(currently on certain versions of Windows using the Microsoft Visual C++ compiler). USE_STACKCHECK
will be defined automatically; you should never change the definition in your own code.
typedef void (*PyOS_sighandler_t)(int)
Part of the Stable ABI.
PyOS_sighandler_t PyOS_getsig(int i)
Part of the Stable ABI. Return the current signal handler for signal i. This is a thin wrapper around either
sigaction() or signal(). Do not call those functions directly!
PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)
Part of the Stable ABI. Set the signal handler for signal i to be h; return the old signal handler. This is a thin
wrapper around either sigaction() or signal(). Do not call those functions directly!
wchar_t *Py_DecodeLocale(const char *arg, size_t *size)
Part of the Stable ABI since version 3.7.

Advertencia: Esta función no debe llamarse directamente: utilice la API PyConfig con la función
PyConfig_SetBytesString() que asegura que Python está preinicializado.
Esta función no debe llamarse antes de que Python esté preinicializado y para que la configuración local
LC_CTYPE esté correctamente configurada: véase la función Py_PreInitialize().

66 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

Decodifica una cadena de bytes a partir del manejador de codificación y errores del sistema de archivos. Si el
controlador de error es el controlador de error surrogateescape, los bytes no codificables se decodifican como
caracteres en el rango U+DC80..U+DCFF; y si una secuencia de bytes se puede decodificar como un carácter
sustituto, escape los bytes usando el controlador de error surrogateescape en lugar de decodificarlos.
Retorna un puntero a una cadena de caracteres anchos recientemente asignada, use PyMem_RawFree() para
liberar la memoria. Si el tamaño no es NULL, escribe el número de caracteres anchos excluyendo el carácter
nulo en *size
Retorna NULL en caso de error de decodificación o error de asignación de memoria. Si size no es NULL,
*size se establece en (size_t) -1 en caso de error de memoria o en (size_t) -2 en caso de error
de decodificación.
El filesystem encoding and error handler son seleccionados por PyConfig_Read(): ver
filesystem_encoding y filesystem_errors que pertenecen a PyConfig.
Los errores de decodificación nunca deberían ocurrir, a menos que haya un error en la biblioteca C.
Utilice la función Py_EncodeLocale() para codificar la cadena de caracteres en una cadena de bytes.
Ver también:
Las funciones PyUnicode_DecodeFSDefaultAndSize() y PyUnicode_DecodeLocaleAndSize().
Added in version 3.5.
Distinto en la versión 3.7: La función ahora utiliza la codificación UTF-8 en el Modo Python UTF-8.
Distinto en la versión 3.8: The function now uses the UTF-8 encoding on Windows if PyPreConfig.
legacy_windows_fs_encoding is zero;
char *Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
Part of the Stable ABI since version 3.7. Codifica una cadena de caracteres amplios según el término filesystem
encoding and error handler. Si el gestor de errores es surrogateescape error handler, los caracteres sustituidos
en el rango U+DC80..U+DCFF se convierten en bytes 0x80..0xFF.
Retorna un puntero a una cadena de bytes recién asignada, usa PyMem_Free() para liberar la memoria.
Retorna NULL si se genera un error de codificación o error de asignación de memoria.
Si error_pos no es NULL, *error_pos se establece en (size_t)-1 en caso de éxito, o se establece en el
índice del carácter no válido en el error de codificación.
El filesystem encoding and error handler son seleccionados por PyConfig_Read(): ver
filesystem_encoding y filesystem_errors que pertenecen a PyConfig.
Use la función Py_DecodeLocale() para decodificar la cadena de bytes en una cadena de caracteres
anchos.

Advertencia: Esta función no debe llamarse antes de que Python esté preinicializado y para que la confi-
guración local LC_CTYPE esté correctamente configurada: véase la función Py_PreInitialize().

Ver también:
Las funciones PyUnicode_EncodeFSDefault() y PyUnicode_EncodeLocale().
Added in version 3.5.
Distinto en la versión 3.7: La función ahora utiliza la codificación UTF-8 en el Modo Python UTF-8.
Distinto en la versión 3.8: The function now uses the UTF-8 encoding on Windows if PyPreConfig.
legacy_windows_fs_encoding is zero.

6.1. Utilidades del sistema operativo 67


The Python/C API, Versión 3.12.4

6.2 Funciones del Sistema

Estas son funciones de utilidad que hacen que la funcionalidad del módulo sys sea accesible para el código C. Todos
funcionan con el diccionario del módulo sys del subproceso actual del intérprete, que está contenido en la estructura
interna del estado del subproceso.
PyObject *PySys_GetObject(const char *name)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto name del módulo sys o NULL si
no existe, sin establecer una excepción.
int PySys_SetObject(const char *name, PyObject *v)
Part of the Stable ABI. Establece name en el módulo sys en v a menos que v sea NULL, en cuyo caso name
se elimina del módulo sys. Retorna 0 en caso de éxito, -1 en caso de error.
void PySys_ResetWarnOptions()
Part of the Stable ABI. Restablece sys.warnoptions a una lista vacía. Esta función puede llamarse antes
de Py_Initialize().
void PySys_AddWarnOption(const wchar_t *s)
Part of the Stable ABI. Esta API se mantiene para conservar compatibilidad con versiones anteriores, en su
lugar se debe usar: PyConfig.warnoptions, ver Configuración de inicialización de Python.
Agrega s a sys.warnoptions. Esta función debe llamarse antes de Py_Initialize() para afectar la
lista de filtros de advertencias.
Obsoleto desde la versión 3.11.
void PySys_AddWarnOptionUnicode(PyObject *unicode)
Part of the Stable ABI. Esta API se mantiene para conservar compatibilidad con versiones anteriores, en su
lugar se debe usar: PyConfig.warnoptions, ver Configuración de inicialización de Python.
Agrega unicode a sys.warnoptions.
Nota: esta función no se puede utilizar actualmente desde fuera de la implementación de CPython, ya que debe
llamarse antes de la importación implícita de warnings en Py_Initialize() para que sea efectiva,
pero no se puede llamar hasta que se haya inicializado suficiente tiempo de ejecución para permitir la creación
de objetos Unicode.
Obsoleto desde la versión 3.11.
void PySys_SetPath(const wchar_t *path)
Part of the Stable ABI. Esta API se mantiene para conservar compatibilidad con versiones anteriores, en su lugar
se debe usar: PyConfig.module_search_paths y PyConfig.module_search_paths_set,
ver Python Initialization Configuration.
Establece sys.path en un objeto lista de rutas que se encuentra en path, que debería ser una lista de rutas
separadas con el delimitador de ruta de búsqueda de la plataforma (: en Unix, ; en Windows )
Obsoleto desde la versión 3.11.
void PySys_WriteStdout(const char *format, ...)
Part of the Stable ABI. Escribe la cadena de caracteres de salida descrita por format en sys.stdout. No se
lanzan excepciones, incluso si se produce el truncamiento (ver más abajo).
format debe limitar el tamaño total de la cadena de caracteres de salida formateada a 1000 bytes o menos;
después de 1000 bytes, la cadena de caracteres de salida se trunca. En particular, esto significa que no deben
existir formatos «%s» sin restricciones; estos deben limitarse usando «%.<N>s» donde <N> es un número
decimal calculado de modo que <N> más el tamaño máximo de otro texto formateado no exceda los 1000
bytes. También tenga cuidado con «%f», que puede imprimir cientos de dígitos para números muy grandes.
Si ocurre un problema, o sys.stdout no está configurado, el mensaje formateado se escribe en el real (nivel
C) stdout.

68 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

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.
Added in version 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.
Added in version 3.2.
void PySys_AddXOption(const wchar_t *s)
Part of the Stable ABI since version 3.7. Esta API se mantiene para conservar compatibilidad con versiones
anteriores, en su lugar se debe usar: PyConfig.xoptions, ver Configuración de inicialización de Python.
Analiza (parse) s como un conjunto de opciones -X y los agrega a la asignación de opciones actual tal como lo
retorna PySys_GetXOptions(). Esta función puede llamarse antes de Py_Initialize().
Added in version 3.2.
Obsoleto desde la versión 3.11.
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.
Added in version 3.2.
int PySys_Audit(const char *event, const char *format, ...)
Lanza un evento de auditoría con cualquier gancho activo. Retorna cero para el éxito y no cero con una excep-
ción establecida en caso de error.
Si se han agregado ganchos, format y otros argumentos se utilizarán para construir una tupla para pasar. Además
de N, están disponibles los mismos caracteres de formato que los utilizados en Py_BuildValue(). Si el
valor generado no es una tupla, se agregará a una tupla de un solo elemento. (La opción de formato N consume
una referencia, pero dado que no hay forma de saber si se consumirán argumentos para esta función, su uso
puede causar fugas de referencia).
Tenga en cuenta que los caracteres de formato # deben tratarse como Py_ssize_t, independientemente de
si se definió PY_SSIZE_T_CLEAN.
sys.audit() realiza la misma función del código Python.
Added in version 3.8.
Distinto en la versión 3.8.2: Requiere Py_ssize_t para los caracteres de formato #. Anteriormente, se
lanzaba una advertencia de deprecación inevitable.
int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
Agrega el hook invocable a la lista de hooks de auditoría activos. Retorna cero para el éxito y no cero en caso
de error. Si el tiempo de ejecución se ha inicializado, también configura un error en caso de fallo. Los hooks
agregados a través de esta API se llaman para todos los intérpretes creados por el tiempo de ejecución.
El puntero userData se pasa a la función gancho. Dado que las funciones de enlace pueden llamarse desde
diferentes tiempos de ejecución, este puntero no debe referirse directamente al estado de Python.
Es seguro llamar a esta función antes de Py_Initialize(). Cuando se llama después de la inicialización
del tiempo de ejecución, se notifican los enlaces de auditoría existentes y pueden anular silenciosamente la
operación al generar un error subclasificado de Excepción (otros errores no se silenciarán).
The hook function is always called with the GIL held by the Python interpreter that raised the event.

6.2. Funciones del Sistema 69


The Python/C API, Versión 3.12.4

Ver PEP 578 para una descripción detallada de la auditoría. Las funciones en el tiempo de ejecución y la
biblioteca estándar que generan eventos se enumeran en table de eventos de auditoria. Los detalles se encuentran
en la documentación de cada función.
Lanza un evento de auditoria sys.addaudithook sin argumentos.
typedef int (*Py_AuditHookFunction)(const char *event, PyObject *args, void *userData)
The type of the hook function. event is the C string event argument passed to PySys_Audit(). args
is guaranteed to be a PyTupleObject. userData is the argument passed to PySys_AddAuditHook().
Added in version 3.8.

6.3 Control de procesos

void Py_FatalError(const char *message)


Part of the Stable ABI. Print a fatal error message and kill the process. No cleanup is performed. This function
should only be invoked when a condition is detected that would make it dangerous to continue using the Python
interpreter; e.g., when the object administration appears to be corrupted. On Unix, the standard C library
function abort() is called which will attempt to produce a core file.
La función Py_FatalError() se reemplaza con una macro que registra automáticamente el nombre de la
función actual, a menos que se defina la macro Py_LIMITED_API.
Distinto en la versión 3.9: Registra el nombre de la función automáticamente.
void Py_Exit(int status)
Part of the Stable ABI. Sale del proceso actual. Esto llama Py_FinalizeEx() y luego llama a la función
estándar de la biblioteca C exit(status). Si Py_FinalizeEx() indica un error, el estado de salida se
establece en 120.
Distinto en la versión 3.6: Los errores de finalización ya no se ignoran.
int Py_AtExit(void (*func)())
Part of the Stable ABI. Registra una función de limpieza a la que llamará Py_FinalizeEx(). Se llamará a
la función de limpieza sin argumentos y no debería retornar ningún valor. Como máximo se pueden registrar 32
funciones de limpieza. Cuando el registro es exitoso, Py_AtExit() retorna 0; en caso de error, retorna -1.
La última función de limpieza registrada se llama primero. Cada función de limpieza se llamará como máximo
una vez. Dado que la finalización interna de Python se habrá completado antes de la función de limpieza, func
no debería llamar a las API de Python.

6.4 Importando módulos

PyObject *PyImport_ImportModule(const char *name)


Return value: New reference. Part of the Stable ABI. This is a wrapper around PyImport_Import() which
takes a const char* as an argument instead of a PyObject*.
PyObject *PyImport_ImportModuleNoBlock(const char *name)
Return value: New reference. Part of the Stable ABI. Esta función es un alias obsoleto de
PyImport_ImportModule().
Distinto en la versión 3.3: Esta función solía fallar inmediatamente cuando el bloqueo de importación era
retenido por otro hilo. Sin embargo, en Python 3.3, el esquema de bloqueo cambió a bloqueos por módulo para
la mayoría de los propósitos, por lo que el comportamiento especial de esta función ya no es necesario.
PyObject *PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals, PyObject
*fromlist)
Return value: New reference. Importa un módulo. Esto se describe mejor haciendo referencia a la función
Python incorporada __import__().

70 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

El valor de retorno es una nueva referencia al módulo importado o paquete de nivel superior, o NULL con una
excepción establecida en caso de error. Al igual que para __import__(), el valor de retorno cuando se
solicitó un submódulo de un paquete normalmente es el paquete de nivel superior, a menos que se proporcione
un fromlist no vacío.
Las importaciones que fallan eliminan objetos de módulo incompletos, como con
PyImport_ImportModule().
PyObject *PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI since version 3.7. Importa un módulo. Esto se descri-
be mejor haciendo referencia a la función Python incorporada __import__(), ya que la función estándar
__import__() llama a esta función directamente.
El valor de retorno es una nueva referencia al módulo importado o paquete de nivel superior, o NULL con una
excepción establecida en caso de error. Al igual que para __import__(), el valor de retorno cuando se
solicitó un submódulo de un paquete normalmente es el paquete de nivel superior, a menos que se proporcione
un fromlist no vacío.
Added in version 3.3.
PyObject *PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI. Similar a PyImport_ImportModuleLevelObject(),
pero el nombre es una cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
Distinto en la versión 3.3: Los valores negativos para level ya no se aceptan.
PyObject *PyImport_Import(PyObject *name)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz de nivel superior que llama a la
«función de enlace de importación» actual (con un nivel explícito de 0, que significa importación absoluta).
Invoca la función __import__() de las __builtins__ de los globales (globals) actuales. Esto significa
que la importación se realiza utilizando los ganchos de importación instalados en el entorno actual.
Esta función siempre usa importaciones absolutas.
PyObject *PyImport_ReloadModule(PyObject *m)
Return value: New reference. Part of the Stable ABI. Recarga un módulo. Retorna una nueva referencia al
módulo recargado, o NULL con una excepción establecida en caso de error (el módulo todavía existe en este
caso).
PyObject *PyImport_AddModuleObject(PyObject *name)
Return value: Borrowed reference. Part of the Stable ABI since version 3.7. Retorna el objeto módulo corres-
pondiente a un nombre de módulo. El argumento name puede tener la forma package.module. Primero
revise el diccionario de módulos si hay uno allí, y si no, crea uno nuevo y lo agrega al diccionario de módulos.
Retorna NULL con una excepción establecida en caso de error.

Nota: Esta función no carga ni importa el módulo; si el módulo no estaba cargado, obtendrá un objeto de
módulo vacío. Utilice PyImport_ImportModule() o una de sus variantes para importar un módulo. Las
estructuras de paquete implicadas por un nombre punteado para name no se crean si aún no están presentes.

Added in version 3.3.


PyObject *PyImport_AddModule(const char *name)
Return value: Borrowed reference. Part of the Stable ABI. Similar a PyImport_AddModuleObject(),
pero el nombre es una cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
PyObject *PyImport_ExecCodeModule(const char *name, PyObject *co)
Return value: New reference. Part of the Stable ABI. Given a module name (possibly of the form package.
module) and a code object read from a Python bytecode file or obtained from the built-in function
compile(), load the module. Return a new reference to the module object, or NULL with an exception

6.4. Importando módulos 71


The Python/C API, Versión 3.12.4

set if an error occurred. name is removed from sys.modules in error cases, even if name was already in
sys.modules on entry to PyImport_ExecCodeModule(). Leaving incompletely initialized modules
in sys.modules is dangerous, as imports of such modules have no way to know that the module object is
an unknown (and probably damaged with respect to the module author’s intents) state.
The module’s __spec__ and __loader__ will be set, if not set already, with the appropriate values. The
spec’s loader will be set to the module’s __loader__ (if set) and to an instance of SourceFileLoader
otherwise.
The module’s __file__ attribute will be set to the code object’s co_filename. If applicable,
__cached__ will also be set.
Esta función volverá a cargar el módulo si ya se importó. Consulte PyImport_ReloadModule() para
conocer la forma prevista de volver a cargar un módulo.
Si name apunta a un nombre punteado de la forma package.module, cualquier estructura de paquete que
no se haya creado aún no se creará.
Ver también PyImport_ExecCodeModuleEx() y PyImport_ExecCodeModuleWithPathnames().
Distinto en la versión 3.12: The setting of __cached__ and __loader__ is deprecated. See
ModuleSpec for alternatives.
PyObject *PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Return value: New reference. Part of the Stable ABI. Como PyImport_ExecCodeModule(), pero el
atributo __file__ del objeto del módulo se establece en pathname si no es NULL.
Ver también PyImport_ExecCodeModuleWithPathnames().
PyObject *PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
PyObject *cpathname)
Return value: New reference. Part of the Stable ABI since version 3.7. Como
PyImport_ExecCodeModuleEx(), pero el atributo __cached__ del objeto módulo se establece en
cpathname si no es NULL. De las tres funciones, esta es la recomendada para usar.
Added in version 3.3.
Distinto en la versión 3.12: Setting __cached__ is deprecated. See ModuleSpec for alternatives.
PyObject *PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char
*pathname, const char *cpathname)
Return value: New reference. Part of the Stable ABI. Como PyImport_ExecCodeModuleObject(),
pero name, pathname y cpathname son cadenas de caracteres codificadas UTF-8. También se intenta averiguar
cuál debe ser el valor de pathname de cpathname si el primero se establece en NULL.
Added in version 3.2.
Distinto en la versión 3.3: Uses imp.source_from_cache() in calculating the source path if only the
bytecode path is provided.
Distinto en la versión 3.12: No longer uses the removed imp module.
long PyImport_GetMagicNumber()
Part of the Stable ABI. Retorna el número mágico para los archivos de bytecode de Python (también conocido
como archivos .pyc). El número mágico debe estar presente en los primeros cuatro bytes del archivo de código
de bytes, en orden de bytes little-endian. Retorna -1 en caso de error.
Distinto en la versión 3.3: Retorna un valor de -1 en caso de error.
const char *PyImport_GetMagicTag()
Part of the Stable ABI. Retorna la cadena de caracteres de etiqueta mágica para nombres de archivo de có-
digo de bytes Python en formato PEP 3147. Tenga en cuenta que el valor en sys.implementation.
cache_tag es autoritario y debe usarse en lugar de esta función.
Added in version 3.2.

72 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

PyObject *PyImport_GetModuleDict()
Return value: Borrowed reference. Part of the Stable ABI. Retorna el diccionario utilizado para la administración
del módulo (también conocido como sys.modules). Tenga en cuenta que esta es una variable por intérprete.
PyObject *PyImport_GetModule(PyObject *name)
Return value: New reference. Part of the Stable ABI since version 3.8. Retorna el módulo ya importado con el
nombre dado. Si el módulo aún no se ha importado, retorna NULL pero no establece un error. Retorna NULL
y establece un error si falla la búsqueda.
Added in version 3.7.
PyObject *PyImport_GetImporter(PyObject *path)
Return value: New reference. Part of the Stable ABI. Return a finder object for a sys.path/pkg.__path__
item path, possibly by fetching it from the sys.path_importer_cache dict. If it wasn’t yet cached,
traverse sys.path_hooks until a hook is found that can handle the path item. Return None if no hook
could; this tells our caller that the path based finder could not find a finder for this path item. Cache the result
in sys.path_importer_cache. Return a new reference to the finder object.
int PyImport_ImportFrozenModuleObject(PyObject *name)
Part of the Stable ABI since version 3.7. Carga un módulo congelado llamado name. Retorna 1 para el éxito,
0 si no se encuentra el módulo y -1 con una excepción establecida si falla la inicialización. Para acceder al
módulo importado con una carga exitosa, use PyImport_ImportModule(). (Tenga en cuenta el nombre
inapropiado — esta función volvería a cargar el módulo si ya se importó).
Added in version 3.3.
Distinto en la versión 3.4: El atributo __file__ ya no está establecido en el módulo.
int PyImport_ImportFrozenModule(const char *name)
Part of the Stable ABI. Similar a PyImport_ImportFrozenModuleObject(), pero el nombre es una
cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
struct _frozen
Esta es la definición del tipo de estructura para los descriptores de módulos congelados, según lo generado con
la herramienta freeze (ver Tools/freeze en la distribución de código fuente de Python). Su definición,
que se encuentra en Include/import.h, es:

struct _frozen {
const char *name;
const unsigned char *code;
int size;
bool is_package;
};

Distinto en la versión 3.11: El nuevo campo is_package indica si el módulo es un paquete o no. Esto
sustituye a la configuración del campo size con un valor negativo.
const struct _frozen *PyImport_FrozenModules
Este puntero se inicializa para apuntar a un arreglo de registros _frozen, terminado por uno cuyos registros
son todos NULL o cero. Cuando se importa un módulo congelado, se busca en esta tabla. El código de terceros
podría jugar con esto para proporcionar una colección de módulos congelados creada dinámicamente.
int PyImport_AppendInittab(const char *name, PyObject *(*initfunc)(void))
Part of the Stable ABI. Agrega un solo módulo a la tabla existente de módulos incorporados. Este es un con-
tenedor conveniente PyImport_ExtendInittab(), que retorna -1 si la tabla no se puede extender. El
nuevo módulo se puede importar con el nombre name, y utiliza la función initfunc como la función de inicia-
lización llamada en el primer intento de importación. Esto debería llamarse antes de Py_Initialize().
struct _inittab
Structure describing a single entry in the list of built-in modules. Programs which embed Python may use an
array of these structures in conjunction with PyImport_ExtendInittab() to provide additional built-in
modules. The structure consists of two members:

6.4. Importando módulos 73


The Python/C API, Versión 3.12.4

const char *name


The module name, as an ASCII encoded string.
PyObject *(*initfunc)(void)
Initialization function for a module built into the interpreter.
int PyImport_ExtendInittab(struct _inittab *newtab)
Add a collection of modules to the table of built-in modules. The newtab array must end with a sentinel entry
which contains NULL for the name field; failure to provide the sentinel value can result in a memory fault.
Returns 0 on success or -1 if insufficient memory could be allocated to extend the internal table. In the event
of failure, no modules are added to the internal table. This must be called before Py_Initialize().
Si Python es inicializado múltiples veces, se debe llamar PyImport_AppendInittab() o
PyImport_ExtendInittab() antes de cada inicialización de Python.

6.5 Soporte de empaquetado (marshalling) de datos

Estas rutinas permiten que el código C funcione con objetos serializados utilizando el mismo formato de datos que
el módulo marshal. Hay funciones para escribir datos en el formato de serialización y funciones adicionales que
se pueden usar para volver a leer los datos. Los archivos utilizados para almacenar datos ordenados deben abrirse en
modo binario.
Los valores numéricos se almacenan con el byte menos significativo primero.
El módulo admite dos versiones del formato de datos: la versión 0 es la versión histórica, la versión 1 comparte
cadenas de caracteres internas en el archivo y al desempaquetar (unmarshalling). La versión 2 usa un formato binario
para números de punto flotante. Py_MARSHAL_VERSION indica el formato de archivo actual (actualmente 2).
void PyMarshal_WriteLongToFile(long value, FILE *file, int version)
Empaqueta (marshal) un entero value long a un archivo file. Esto solo escribirá los 32 bits menos significativos
de value; sin importar el tamaño del tipo long nativo. version indica el formato del archivo.
This function can fail, in which case it sets the error indicator. Use PyErr_Occurred() to check for that.
void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)
Empaqueta (marshal) un objeto Python, value, a un archivo file. version indica el formato del archivo.
This function can fail, in which case it sets the error indicator. Use PyErr_Occurred() to check for that.
PyObject *PyMarshal_WriteObjectToString(PyObject *value, int version)
Return value: New reference. Retorna un objeto de bytes que contiene la representación empaquetada (mars-
halled) de value. version indica el formato del archivo.
Las siguientes funciones permiten volver a leer los valores empaquetados (marshalled).
long PyMarshal_ReadLongFromFile(FILE *file)
Retorna un entero long de C desde el flujo de datos FILE* abierto para lectura. Solo se puede leer un valor
de 32 bits con esta función, independientemente del tamaño nativo del tipo long.
En caso de error, establece la excepción apropiada (EOFError) y retorna -1.
int PyMarshal_ReadShortFromFile(FILE *file)
Retorna un entero short de C desde el flujo de datos FILE* abierto para lectura. Solo se puede leer un valor
de 16 bits con esta función, independientemente del tamaño nativo del tipo short.
En caso de error, establece la excepción apropiada (EOFError) y retorna -1.
PyObject *PyMarshal_ReadObjectFromFile(FILE *file)
Return value: New reference. Retorna un objeto Python del flujo de datos FILE* abierto para lectura.
En caso de error, establece la excepción apropiada (EOFError, ValueError o TypeError) y retorna
NULL.

74 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

PyObject *PyMarshal_ReadLastObjectFromFile(FILE *file)


Return value: New reference. Retorna un objeto Python del flujo de datos FILE* abierto para lectura. A dife-
rencia de PyMarshal_ReadObjectFromFile(), esta función asume que no se leerán más objetos del
archivo, lo que le permite cargar agresivamente los datos del archivo en la memoria para que la deserialización
pueda operar desde dichos datos en lugar de leer un byte a la vez desde el archivo. Solo use esta variante si
está seguro de que no leerá nada más del archivo.
En caso de error, establece la excepción apropiada (EOFError, ValueError o TypeError) y retorna
NULL.
PyObject *PyMarshal_ReadObjectFromString(const char *data, Py_ssize_t len)
Return value: New reference. Retorna un objeto Python del flujo de datos en un búfer de bytes que contiene len
bytes a los que apunta data.
En caso de error, establece la excepción apropiada (EOFError, ValueError o TypeError) y retorna
NULL.

6.6 Analizando argumentos y construyendo valores

Estas funciones son útiles al crear sus propias funciones y métodos de extensiones. Información y ejemplos adicionales
están disponibles en extending-index.
Las tres primeras de estas funciones descritas, PyArg_ParseTuple(),
PyArg_ParseTupleAndKeywords(), y PyArg_Parse(), todas usan cadenas de caracteres de for-
mato que se utilizan para contarle a la función sobre los argumentos esperados. Las cadenas de caracteres de formato
utilizan la misma sintaxis para cada una de estas funciones.

6.6.1 Analizando argumentos

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.

Cadena de caracteres y búferes

Estos formatos permiten acceder a un objeto como un bloque contiguo de memoria. Usted no tiene que proporcionar
almacenamiento en bruto para el Unicode o área de bytes retornada.
A menos que se indique lo contrario, los búferes no son terminados en NULL (NUL-terminated).
There are three ways strings and buffers can be converted to C:
• Formats such as y* and s* fill a Py_buffer structure. This locks the underlying buffer so that the caller can
subsequently use the buffer even inside a Py_BEGIN_ALLOW_THREADS block without the risk of mutable
data being resized or destroyed. As a result, you have to call PyBuffer_Release() after you have finished
processing the data (or in any early abort case).
• The es, es#, et and et# formats allocate the result buffer. You have to call PyMem_Free() after you
have finished processing the data (or in any early abort case).
• Other formats take a str or a read-only bytes-like object, such as bytes, and provide a const char *
pointer to its buffer. In this case the buffer is «borrowed»: it is managed by the corresponding Python object,
and shares the lifetime of this object. You won’t have to release any memory yourself.

6.6. Analizando argumentos y construyendo valores 75


The Python/C API, Versión 3.12.4

To ensure that the underlying buffer may be safely borrowed, the object’s PyBufferProcs.
bf_releasebuffer field must be NULL. This disallows common mutable objects such as bytearray,
but also some read-only objects such as memoryview of bytes.
Besides this bf_releasebuffer requirement, there is no check to verify whether the input object is im-
mutable (e.g. whether it would honor a request for a writable buffer, or whether another thread can mutate the
data).

Nota: Para todas las variantes de formatos # (s#, y#, etc.), la macro PY_SSIZE_T_CLEAN tiene que estar definida
antes de incluir Python.h. En Python 3.9 y versiones anteriores, el tipo del argumento length es Py_ssize_t si
la macro PY_SSIZE_T_CLEAN está definida, o int si no lo está.

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 convertirlos en cadenas de caracteres C, es preferible utilizar el formato O& con
PyUnicode_FSConverter() como convertidor.

Distinto en la versión 3.5: Anteriormente, TypeError se lanzó cuando se encontraron puntos de código nulos
incrustados en la cadena de caracteres de Python.
s* (str o bytes-like object) [Py_buffer]
Este formato acepta objetos Unicode, así como objetos de tipo bytes. Llena una estructura Py_buffer pro-
porcionada por la persona que llama. En este caso la cadena de caracteres de C resultante puede contener
bytes NUL embebidos. Los objetos Unicode se convierten en cadenas de caracteres C utilizando codificación
'utf-8'.
s# (str, bytes-like object de sólo lectura) [const char *, Py_ssize_t]
Like s*, except that it provides a borrowed buffer. The result is stored into two C variables, the first one a
pointer to a C string, the second one its length. The string may contain embedded null bytes. Unicode objects
are converted to C strings using 'utf-8' encoding.
z (str o None) [const char *]
Como s, pero el objeto Python también puede ser None, en cuyo caso el puntero C se establece en NULL.
z* (str, bytes-like object o None) [Py_buffer]
Como s*, pero el objeto Python también puede ser None, en cuyo caso el miembro de buf de la estructura
Py_buffer se establece en NULL.
z# (str, bytes-like object de sólo lectura o None) [const char *, Py_ssize_t]
Como s#, pero el objeto Python también puede ser None, en cuyo caso el puntero C se establece en NULL.
y (bytes-like object de sólo lectura) [const char *]
This format converts a bytes-like object to a C pointer to a borrowed character string; it does not accept Unicode
objects. The bytes buffer must not contain embedded null bytes; if it does, a ValueError exception is raised.
Distinto en la versión 3.5: Anteriormente, TypeError se lanzó cuando bytes nulos incrustados se encontraron
en el buffer de bytes.
y* (bytes-like object) [Py_buffer]
Esta variante de s* no acepta objetos Unicode, solamente los objetos de tipo bytes. Esta es la forma reco-
mendada para aceptar datos binarios.
y# (bytes-like object de sólo lectura) [const char *, Py_ssize_t]
Esta variante en s# no acepta objetos Unicode, solo objetos similares a bytes.

76 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

S (bytes) [PyBytesObject *]
Requires that the Python object is a bytes object, without attempting any conversion. Raises TypeError
if the object is not a bytes object. The C variable may also be declared as PyObject*.
Y (bytearray) [PyByteArrayObject *]
Requires that the Python object is a bytearray object, without attempting any conversion. Raises
TypeError if the object is not a bytearray object. The C variable may also be declared as PyObject*.
U (str) [PyObject *]
Requires that the Python object is a Unicode object, without attempting any conversion. Raises TypeError
if the object is not a Unicode object. The C variable may also be declared as PyObject*.
w* (bytes-like object de lectura y escritura) [Py_buffer]
Este formato acepta cualquier objeto que implemente la interfaz del búfer de lectura-escritura. Llena la es-
tructura Py_buffer proporcionada por quien llama. El búfer puede contener bytes nulos incrustados. Quien
llama tiene que llamar PyBuffer_Release() cuando termina con el búfer.
es (str) [const char *encoding, char **buffer]
Esta variante en s se usa para codificar Unicode en un búfer de caracteres. Solo funciona para datos codificados
sin bytes NUL integrados.
This format requires two arguments. The first is only used as input, and must be a const char* which
points to the name of an encoding as a NUL-terminated string, or NULL, in which case 'utf-8' encoding
is used. An exception is raised if the named encoding is not known to Python. The second argument must be
a char**; the value of the pointer it references will be set to a buffer with the contents of the argument text.
The text will be encoded in the encoding specified by the first argument.
PyArg_ParseTuple() asignará un búfer del tamaño necesitado, copiará los datos codificados en este búfer
y ajustará *buffer para referenciar el nuevo almacenamiento asignado. Quien llama es responsable para llamar
PyMem_Free() para liberar el búfer asignado después de su uso.
et (str, bytes o bytearray) [const char *encoding, char **buffer]
Igual que es, excepto que los objetos de cadena de caracteres de bytes se pasan sin recodificarlos. En cambio,
la implementación supone que el objeto de cadena de caracteres de bytes utiliza la codificación que se pasa
como parámetro.
es# (str) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
Esta variante en s# se usa para codificar Unicode en un búfer de caracteres. A diferencia del formato es, esta
variante permite datos de entrada que contienen caracteres NUL.
It requires three arguments. The first is only used as input, and must be a const char* which points to the
name of an encoding as a NUL-terminated string, or NULL, in which case 'utf-8' encoding is used. An
exception is raised if the named encoding is not known to Python. The second argument must be a char**;
the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will
be encoded in the encoding specified by the first argument. The third argument must be a pointer to an integer;
the referenced integer will be set to the number of bytes in the output buffer.
Hay dos modos de operación:
Si *buffer señala un puntero NULL, la función asignará un búfer del tamaño necesario, copiará los datos co-
dificados en este búfer y configurará *buffer para hacer referencia al almacenamiento recién asignado. Quien
llama es responsable de llamar a PyMem_Free() para liberar el búfer asignado después del uso.
Si *buffer apunta a un puntero no NULL (un búfer ya asignado), PyArg_ParseTuple() usará esta ubica-
ción como el búfer e interpretará el valor inicial de *buffer_length como el tamaño del búfer. Luego copiará los
datos codificados en el búfer y los terminará en NUL. Si el búfer no es lo suficientemente grande, se establecerá
a ValueError.
En ambos casos, *buffer_length se establece a la longitud de los datos codificados sin el byte NUL final.
et# (str, bytes o bytearray) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
Igual que es#, excepto que los objetos de cadena de caracteres de bytes se pasan sin recodificarlos. En cambio,
la implementación supone que el objeto de cadena de caracteres de bytes utiliza la codificación que se pasa
como parámetro.
Distinto en la versión 3.12: u, u#, Z, and Z# are removed because they used a legacy Py_UNICODE* representation.

6.6. Analizando argumentos y construyendo valores 77


The Python/C API, Versión 3.12.4

Números

b (int) [unsigned char]


Convert a nonnegative Python integer to an unsigned tiny int, stored in a C unsigned char.
B (int) [unsigned char]
Convert a Python integer to a tiny int without overflow checking, stored in a C unsigned char.
h (int) [short int]
Convert a Python integer to a C short int.
H (int) [unsigned short int]
Convert a Python integer to a C unsigned short int, without overflow checking.
i (int) [int]
Convert a Python integer to a plain C int.
I (int) [unsigned int]
Convert a Python integer to a C unsigned int, without overflow checking.
l (int) [long int]
Convert a Python integer to a C long int.
k (int) [unsigned long]
Convert a Python integer to a C unsigned long without overflow checking.
L (int) [long long]
Convert a Python integer to a C long long.
K (int) [unsigned long long]
Convert a Python integer to a C unsigned long long without overflow checking.
n (int) [Py_ssize_t]
Convierte un entero de Python a un Py_ssize_t de C.
c (bytes o bytearray de largo 1) [char]
Convert a Python byte, represented as a bytes or bytearray object of length 1, to a C char.
Distinto en la versión 3.3: Permite objetos bytearray.
C (str de largo 1) [int]
Convert a Python character, represented as a str object of length 1, to a C int.
f (float) [float]
Convert a Python floating point number to a C float.
d (float) [double]
Convert a Python floating point number to a C double.
D (complex) [Py_complex]
Convierte un número complejo de Python en una estructura Py_complex de C.

Otros objetos

O (object) [PyObject *]
Store a Python object (without any conversion) in a C object pointer. The C program thus receives the ac-
tual object that was passed. A new strong reference to the object is not created (i.e. its reference count is not
increased). The pointer stored is not NULL.
O! (object) [typeobject, PyObject *]
Store a Python object in a C object pointer. This is similar to O, but takes two C arguments: the first is the
address of a Python type object, the second is the address of the C variable (of type PyObject*) into which
the object pointer is stored. If the Python object does not have the required type, TypeError is raised.

78 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

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:

status = converter(object, address);

where object is the Python object to be converted and address is the void* argument that was passed to the
PyArg_Parse* function. The returned status should be 1 for a successful conversion and 0 if the conversion
has failed. When the conversion fails, the converter function should raise an exception and leave the content of
address unmodified.
Si el converter retorna Py_CLEANUP_SUPPORTED, se puede llamar por segunda vez si el análisis del argu-
mento finalmente falla, dando al convertidor la oportunidad de liberar cualquier memoria que ya haya asignado.
En esta segunda llamada, el parámetro object será NULL; address tendrá el mismo valor que en la llamada ori-
ginal.
Distinto en la versión 3.1: Py_CLEANUP_SUPPORTED fue agregada.
p (bool) [int]
Prueba el valor pasado por verdad (un booleano predicado p) y convierte el resultado a su valor entero C
verdadero/falso entero equivalente. Establece int en 1 si la expresión era verdadera y 0 si era falsa. Esto acepta
cualquier valor válido de Python. Consulte truth para obtener más información sobre cómo Python prueba los
valores por verdad.
Added in version 3.3.
(items) (tuple) [matching-items]
El objeto debe ser una secuencia de Python cuya longitud es el número de unidades de formato en items. Los
argumentos C deben corresponder a las unidades de formato individuales en items. Las unidades de formato
para secuencias pueden estar anidadas.
It is possible to pass «long» integers (integers whose value exceeds the platform’s LONG_MAX) however no proper
range checking is done — the most significant bits are silently truncated when the receiving field is too small to receive
the value (actually, the semantics are inherited from downcasts in C — your mileage may vary).
Algunos otros caracteres tienen un significado en una cadena de formato. Esto puede no ocurrir dentro de paréntesis
anidados. Son:
|
Indica que los argumentos restantes en la lista de argumentos de Python son opcionales. Las variables C corres-
pondientes a argumentos opcionales deben inicializarse a su valor predeterminado — cuando no se especifica
un argumento opcional, PyArg_ParseTuple() no toca el contenido de las variables C correspondientes.
$
PyArg_ParseTupleAndKeywords() solamente: indica que los argumentos restantes en la lista de ar-
gumentos de Python son solo palabras clave. Actualmente, todos los argumentos de solo palabras clave también
deben ser argumentos opcionales, por lo que | siempre debe especificarse antes de $ en la cadena de formato.
Added in version 3.3.
:
La lista de unidades de formato termina aquí; la cadena después de los dos puntos se usa como el nombre de la
función en los mensajes de error (el «valor asociado» de la excepción que PyArg_ParseTuple() lanza).
;
La lista de unidades de formato termina aquí; la cadena después del punto y coma se usa como mensaje de
error en lugar de del mensaje de error predeterminado. : y ; se excluyen mutuamente.
Note that any Python object references which are provided to the caller are borrowed references; do not release them
(i.e. do not decrement their reference count)!
Los argumentos adicionales pasados a estas funciones deben ser direcciones de variables cuyo tipo está determinado
por la cadena de formato; Estos se utilizan para almacenar valores de la tupla de entrada. Hay algunos casos, como

6.6. Analizando argumentos y construyendo valores 79


The Python/C API, Versión 3.12.4

se describe en la lista de unidades de formato anterior, donde estos parámetros se utilizan como valores de entrada;
deben coincidir con lo especificado para la unidad de formato correspondiente en ese caso.
For the conversion to succeed, the arg object must match the format and the format must be exhausted. On success,
the PyArg_Parse* functions return true, otherwise they return false and raise an appropriate exception. When the
PyArg_Parse* functions fail due to conversion failure in one of the format units, the variables at the addresses
corresponding to that and the following format units are left untouched.

Funciones API

int PyArg_ParseTuple(PyObject *args, const char *format, ...)


Part of the Stable ABI. Analiza los parámetros de una función que solo toma parámetros posicionales en
variables locales. Retorna verdadero en el éxito; en caso de fallo, retorna falso y lanza la excepción apropiada.
int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
Part of the Stable ABI. Idéntico a PyArg_ParseTuple(), excepto que acepta una va_list en lugar de un
número variable de argumentos .
int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[],
...)
Part of the Stable ABI. Analiza los parámetros de una función que toma parámetros posicionales y de palabras
clave en variables locales. El argumento keywords es un arreglo terminado en NULL de nombres de parámetros
de palabras clave. Los nombres vacíos denotan parámetros solo posicionales. Retorna verdadero cuando hay
éxito; en caso de fallo, retorna falso y lanza la excepción apropiada.
Distinto en la versión 3.6: Soporte agregado para sólo parámetros posicionales.
int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char
*keywords[], va_list vargs)
Part of the Stable ABI. Idéntico a PyArg_ParseTupleAndKeywords(), excepto que acepta una va_list
en lugar de un número variable de argumentos.
int PyArg_ValidateKeywordArguments(PyObject*)
Part of the Stable ABI. Asegúrese de que las claves en el diccionario de argumentos de palabras clave son
cadenas. Esto solo es necesario si PyArg_ParseTupleAndKeywords() no se utiliza, ya que este último
ya hace esta comprobación.
Added in version 3.2.
int PyArg_Parse(PyObject *args, const char *format, ...)
Part of the Stable ABI. Función utilizada para deconstruir las listas de argumentos de las funciones de «estilo
antiguo» — estas son funciones que usan el método de análisis de parámetros METH_OLDARGS, que se ha
eliminado en Python 3. No se recomienda su uso en el análisis de parámetros en código nuevo, y la mayoría del
código en el intérprete estándar se ha modificado para que ya no se use para ese propósito. Sin embargo, sigue
siendo una forma conveniente de descomponer otras tuplas, y puede continuar usándose para ese propósito.
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:

80 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
PyObject *result = NULL;

if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {


result = PyWeakref_NewRef(object, callback);
}
return result;
}

La llamada a PyArg_UnpackTuple() en este ejemplo es completamente equivalente a esta llamada a


PyArg_ParseTuple():
PyArg_ParseTuple(args, "O|O:ref", &object, &callback)

6.6.2 Construyendo valores

PyObject *Py_BuildValue(const char *format, ...)


Return value: New reference. Part of the Stable ABI. Create a new value based on a format string similar to
those accepted by the PyArg_Parse* family of functions and a sequence of values. Returns the value or
NULL in the case of an error; an exception will be raised if NULL is returned.
Py_BuildValue() no siempre genera una tupla. Construye una tupla solo si su cadena de formato contiene
dos o más unidades de formato. Si la cadena de formato está vacía, retorna None; si contiene exactamente una
unidad de formato, retorna el objeto que describa esa unidad de formato. Para forzarlo a retornar una tupla de
tamaño 0 o uno, paréntesis la cadena de formato.
Cuando los búfer de memoria se pasan como parámetros para suministrar datos para construir objetos, como
para los formatos s y s#, los datos requeridos se copian. Las memorias intermedias proporcionadas por quien
llama nunca son referenciadas por los objetos creados por Py_BuildValue(). En otras palabras, si su
código invoca malloc() y pasa la memoria asignada a Py_BuildValue(), su código es responsable de
llamar a free() para esa memoria una vez retorna Py_BuildValue().
En la siguiente descripción, la cadena de caracteres entre comillas, así, es la unidad de formato; la entrada
entre paréntesis (redondos) es el tipo de objeto Python que retornará la unidad de formato; y la entrada entre
corchetes [cuadrados] es el tipo de los valores C que se pasarán.
Los caracteres espacio, tabulación, dos puntos y coma se ignoran en las cadenas de formato (pero no dentro
de las unidades de formato como s#). Esto se puede usar para hacer que las cadenas de formato largo sean un
poco más legibles.
s (str o None) [const char *]
Convierte una cadena de caracteres C terminada en nulo en un objeto Python str usando la codificación
'utf-8'. Si el puntero de la cadena de caracteres C es NULL, se usa None.
s# (str o None) [const char *, Py_ssize_t]
Convierte una cadena de caracteres de C y su longitud en un objeto Python str utilizando la codificación
'utf-8'. Si el puntero de la cadena de caracteres de C es NULL, la longitud se ignora y se retorna None.
y (bytes) [const char *]
Esto convierte una cadena de caracteres de C en un objeto Python bytes. Si el puntero de la cadena de
caracteres de C es NULL, se retorna None.
y# (bytes) [const char *, Py_ssize_t]
Esto convierte una cadena de caracteres de C y sus longitudes en un objeto Python. Si el puntero de la
cadena de caracteres de C es NULL, se retorna None.
z (str o None) [const char *]
Igual que s.

6.6. Analizando argumentos y construyendo valores 81


The Python/C API, Versión 3.12.4

z# (str o None) [const char *, Py_ssize_t]


Igual que s#.
u (str) [const wchar_t *]
Convert a null-terminated wchar_t buffer of Unicode (UTF-16 or UCS-4) data to a Python Unicode
object. If the Unicode buffer pointer is NULL, None is returned.
u# (str) [const wchar_t *, Py_ssize_t]
Convierte un búfer de datos Unicode (UTF-16 o UCS-4) y su longitud en un objeto Python Unicode. Si
el puntero del búfer Unicode es NULL, la longitud se ignora y se retorna None.
U (str o None) [const char *]
Igual que s.
z# (str o None) [const char *, Py_ssize_t]
Igual que s#.
i (int) [int]
Convert a plain C int to a Python integer object.
b (int) [char]
Convert a plain C char to a Python integer object.
h (int) [short int]
Convert a plain C short int to a Python integer object.
l (int) [long int]
Convert a C long int to a Python integer object.
B (int) [unsigned char]
Convert a C unsigned char to a Python integer object.
H (int) [unsigned short int]
Convert a C unsigned short int to a Python integer object.
I (int) [unsigned int]
Convert a C unsigned int to a Python integer object.
k (int) [unsigned long]
Convert a C unsigned long to a Python integer object.
L (int) [long long]
Convert a C long long to a Python integer object.
K (int) [unsigned long long]
Convert a C unsigned long long to a Python integer object.
n (int) [Py_ssize_t]
Convierte un Py_ssize_t de C a un entero de Python.
c (bytes de largo 1) [char]
Convert a C int representing a byte to a Python bytes object of length 1.
C (str de largo 1) [int]
Convert a C int representing a character to Python str object of length 1.
d (float) [double]
Convert a C double to a Python floating point number.
f (float) [float]
Convert a C float to a Python floating point number.
D (complex) [Py_complex *]
Convierte una estructura Py_complex de C en un número complejo de Python.
O (object) [PyObject *]
Pass a Python object untouched but create a new strong reference to it (i.e. its reference count is incre-
mented by one). If the object passed in is a NULL pointer, it is assumed that this was caused because the

82 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

call producing the argument found an error and set an exception. Therefore, Py_BuildValue() will
return NULL but won’t raise an exception. If no exception has been raised yet, SystemError is set.
S (object) [PyObject *]
Igual que O.
N (object) [PyObject *]
Same as O, except it doesn’t create a new strong reference. Useful when the object is created by a call to
an object constructor in the argument list.
O& (object) [converter, anything]
Convert anything to a Python object through a converter function. The function is called with anything
(which should be compatible with void*) as its argument and should return a «new» Python object, or
NULL if an error occurred.
(items) (tuple) [matching-items]
Convierta una secuencia de valores C en una tupla de Python con el mismo número de elementos.
[items] (list) [matching-items]
Convierte una secuencia de valores C en una lista de Python con el mismo número de elementos.
{items} (dict) [matching-items]
Convierte una secuencia de valores C en un diccionario Python. Cada par de valores C consecutivos
agrega un elemento al diccionario, que sirve como clave y valor, respectivamente.
Si hay un error en la cadena de formato, se establece la excepción SystemError y se retorna NULL.
PyObject *Py_VaBuildValue(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Idéntico a Py_BuildValue(), excepto que acepta una
va_list en lugar de un número variable de argumentos.

6.7 Conversión y formato de cadenas de caracteres

Funciones para conversión de números y salida de cadena de caracteres formateadas.


int PyOS_snprintf(char *str, size_t size, const char *format, ...)
Part of the Stable ABI. Salida de no más de size bytes a str según la cadena de caracteres de formato format y
los argumentos adicionales. Consulte la página de manual de Unix snprintf(3).
int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
Part of the Stable ABI. Salida de no más de size bytes a str según la cadena de caracteres de formato format y
la lista de argumentos variables va. Página de manual de Unix vsnprintf(3).
PyOS_snprintf() y PyOS_vsnprintf() envuelven las funciones estándar de la biblioteca C snprintf()
y vsnprintf(). Su propósito es garantizar un comportamiento consistente en casos de esquina (corner cases), que
las funciones del Estándar C no hacen.
The wrappers ensure that str[size-1] is always '\0' upon return. They never write more than size bytes (in-
cluding the trailing '\0') into str. Both functions require that str != NULL, size > 0, format != NULL
and size < INT_MAX. Note that this means there is no equivalent to the C99 n = snprintf(NULL, 0,
...) which would determine the necessary buffer size.
El valor de retorno (rv) para estas funciones debe interpretarse de la siguiente manera:
• Cuando 0 <= rv < size, la conversión de salida fue exitosa y los caracteres rv se escribieron en str (ex-
cluyendo el byte '\0' final en str[rv]).
• Cuando rv >= size, la conversión de salida se truncó y se habría necesitado un búfer con rv + 1 bytes
para tener éxito. str[size-1] es '\0' en este caso.
• Cuando rv < 0, «sucedió algo malo». str[size-1] es '\0' en este caso también, pero el resto de str
no está definido. La causa exacta del error depende de la plataforma subyacente.

6.7. Conversión y formato de cadenas de caracteres 83


The Python/C API, Versión 3.12.4

Las siguientes funciones proporcionan cadenas de caracteres independientes de la configuración regional para numerar
las conversiones.
unsigned long PyOS_strtoul(const char *str, char **ptr, int base)
Part of the Stable ABI. Convert the initial part of the string in str to an unsigned long value according
to the given base, which must be between 2 and 36 inclusive, or be the special value 0.
Leading white space and case of characters are ignored. If base is zero it looks for a leading 0b, 0o or 0x to
tell which base. If these are absent it defaults to 10. Base must be 0 or between 2 and 36 (inclusive). If ptr is
non-NULL it will contain a pointer to the end of the scan.
If the converted value falls out of range of corresponding return type, range error occurs (errno is set to
ERANGE) and ULONG_MAX is returned. If no conversion can be performed, 0 is returned.
See also the Unix man page strtoul(3).
Added in version 3.2.
long PyOS_strtol(const char *str, char **ptr, int base)
Part of the Stable ABI. Convert the initial part of the string in str to an long value according to the given
base, which must be between 2 and 36 inclusive, or be the special value 0.
Same as PyOS_strtoul(), but return a long value instead and LONG_MAX on overflows.
See also the Unix man page strtol(3).
Added in version 3.2.
double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)
Part of the Stable ABI. Convert a string s to a double, raising a Python exception on failure. The set of
accepted strings corresponds to the set of strings accepted by Python’s float() constructor, except that s
must not have leading or trailing whitespace. The conversion is independent of the current locale.
Si endptr es NULL, convierte toda la cadena de caracteres. Lanza ValueError y retorna -1.0 si la cadena
de caracteres no es una representación válida de un número de punto flotante.
Si endptr no es NULL, convierte la mayor cantidad posible de la cadena de caracteres y configura *endptr
para que apunte al primer carácter no convertido. Si ningún segmento inicial de la cadena de caracteres es la
representación válida de un número de punto flotante, configura *endptr para que apunte al comienzo de la
cadena de caracteres, lanza ValueError y retorna -1.0.
Si s representa un valor que es demasiado grande para almacenar en un flotante (por ejemplo, "1e500"
es una cadena de caracteres de este tipo en muchas plataformas), entonces si overflow_exception es
NULL retorna Py_HUGE_VAL (con un signo apropiado) y no establece ninguna excepción. De lo contrario,
overflow_exception debe apuntar a un objeto excepción de Python; lanza esa excepción y retorna -1.
0. En ambos casos, configura *endptr para que apunte al primer carácter después del valor convertido.
Si se produce algún otro error durante la conversión (por ejemplo, un error de falta de memoria), establece la
excepción Python adecuada y retorna -1.0.
Added in version 3.1.
char *PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)
Part of the Stable ABI. Convert a double val to a string using supplied format_code, precision, and flags.
format_code debe ser uno de 'e', 'E', 'f', 'F', 'g', 'G' or 'r'. Para 'r', la precision suministrada
debe ser 0 y se ignora. El código de formato 'r' especifica el formato estándar repr().
flags puede ser cero o más de los valores Py_DTSF_SIGN, Py_DTSF_ADD_DOT_0, o Py_DTSF_ALT,
unidos por or (or-ed) juntos:
• Py_DTSF_SIGN significa preceder siempre a la cadena de caracteres retornada con un carácter de signo,
incluso si val no es negativo.
• Py_DTSF_ADD_DOT_0 significa asegurarse de que la cadena de caracteres retornada no se verá como
un número entero.

84 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

• Py_DTSF_ALT significa aplicar reglas de formato «alternativas». Consulte la documentación del espe-
cificador PyOS_snprintf() '#' para obtener más detalles.
Si ptype no es NULL, el valor al que apunta se establecerá en uno de Py_DTST_FINITE,
Py_DTST_INFINITE o Py_DTST_NAN, lo que significa que val es un número finito, un número infinito
o no es un número, respectivamente.
El valor de retorno es un puntero a buffer con la cadena de caracteres convertida o NULL si la conversión falla.
La persona que llama es responsable de liberar la cadena de caracteres retornada llamando a PyMem_Free().
Added in version 3.1.
int PyOS_stricmp(const char *s1, const char *s2)
Case insensitive comparison of strings. The function works almost identically to strcmp() except that it
ignores the case.
int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size)
Case insensitive comparison of strings. The function works almost identically to strncmp() except that it
ignores the case.

6.8 PyHash API

See also the PyTypeObject.tp_hash member.


type Py_hash_t
Hash value type: signed integer.
Added in version 3.2.
type Py_uhash_t
Hash value type: unsigned integer.
Added in version 3.2.
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.
Added in version 3.4.
PyHash_FuncDef *PyHash_GetFuncDef(void)
Get the hash function definition.
Ver también:
PEP 456 «Secure and interchangeable hash algorithm».
Added in version 3.4.

6.8. PyHash API 85


The Python/C API, Versión 3.12.4

6.9 Reflexión

PyObject *PyEval_GetBuiltins(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las construcciones en el
marco de ejecución actual, o el intérprete del estado del hilo si no se está ejecutando ningún marco actualmente.
PyObject *PyEval_GetLocals(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las variables locales en el
marco de ejecución actual, o NULL si actualmente no se está ejecutando ningún marco.
PyObject *PyEval_GetGlobals(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las variables globales en
el marco de ejecución actual, o NULL si actualmente no se está ejecutando ningún marco.
PyFrameObject *PyEval_GetFrame(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el marco del estado del hilo actual, que es
NULL si actualmente no se está ejecutando ningún marco.
Vea también PyThreadState_GetFrame().
const char *PyEval_GetFuncName(PyObject *func)
Part of the Stable ABI. Retorna el nombre de func si es una función, clase u objeto de instancia; de lo contrario,
el nombre del tipo funcs.
const char *PyEval_GetFuncDesc(PyObject *func)
Part of the Stable ABI. Retorna una cadena de caracteres de descripción, según el tipo de func. Los valores
de retorno incluyen «()» para funciones y métodos, «constructor», «instancia» y «objeto». Concatenado con el
resultado de PyEval_GetFuncName(), el resultado será una descripción de func.

6.10 Registro de códec y funciones de soporte

int PyCodec_Register(PyObject *search_function)


Part of the Stable ABI. Registra una nueva función de búsqueda de códec.
As side effect, this tries to load the encodings package, if not yet done, to make sure that it is always first
in the list of search functions.
int PyCodec_Unregister(PyObject *search_function)
Part of the Stable ABI since version 3.10. Anula el registro de una función de búsqueda de códecs y borra el
caché del registro. Si la función de búsqueda no está registrada, no hace nada. Retorna 0 en caso de éxito.
Lanza una excepción y devuelva -1 en caso de error.
Added in version 3.10.
int PyCodec_KnownEncoding(const char *encoding)
Part of the Stable ABI. Retorna 1 o 0 dependiendo de si hay un códec registrado para el encoding dado. Esta
función siempre finaliza con éxito.
PyObject *PyCodec_Encode(PyObject *object, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. API de codificación genérica basada en códec.
object se pasa a través de la función de codificador encontrada por el encoding dado usando el método de manejo
de errores definido por errors. errors pueden ser NULL para usar el método predeterminado definido para el
códec. Lanza un LookupError si no se puede encontrar el codificador.
PyObject *PyCodec_Decode(PyObject *object, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. API de decodificación basada en códec genérico.

86 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

object se pasa a través de la función de decodificador encontrada por el encoding dado usando el método de
manejo de errores definido por errors. errors puede ser NULL para usar el método predeterminado definido
para el códec. Lanza un LookupError si no se puede encontrar el codificador.

6.10.1 API de búsqueda de códec

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.10.2 API de registro para controladores de errores de codificación Unicode

int PyCodec_RegisterError(const char *name, PyObject *error)


Part of the Stable ABI. Registra la función de devolución de llamada de manejo de errores error bajo el nombre
name dado. Esta función de devolución de llamada será llamada por un códec cuando encuentre caracteres no
codificables / bytes no codificables y name se especifica como parámetro de error en la llamada a la función de
codificación / decodificación.
La devolución de llamada obtiene un único argumento, una instancia de UnicodeEncodeError,
UnicodeDecodeError o UnicodeTranslateError que contiene información sobre la secuencia
problemática de caracteres o bytes y su desplazamiento en la cadena original (consulte Objetos unicode de ex-
cepción para funciones para extraer esta información). La devolución de llamada debe lanzar la excepción dada
o retornar una tupla de dos elementos que contiene el reemplazo de la secuencia problemática, y un número
entero que proporciona el desplazamiento en la cadena original en la que se debe reanudar la codificación /
decodificación.
Retorna 0 en caso de éxito, -1 en caso de error.
PyObject *PyCodec_LookupError(const char *name)
Return value: New reference. Part of the Stable ABI. Busca la función de devolución de llamada de manejo de
errores registrada con name. Como caso especial se puede pasar NULL, en cuyo caso se retornará la devolución
de llamada de manejo de errores para «estricto».
PyObject *PyCodec_StrictErrors(PyObject *exc)
Return value: Always NULL. Part of the Stable ABI. Lanza exc como una excepción.

6.10. Registro de códec y funciones de soporte 87


The Python/C API, Versión 3.12.4

PyObject *PyCodec_IgnoreErrors(PyObject *exc)


Return value: New reference. Part of the Stable ABI. Ignora el error Unicode, omitiendo la entrada defectuosa.
PyObject *PyCodec_ReplaceErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Reemplaza el error de codificación Unicode con ? o
U+FFFD.
PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Reemplaza el error de codificación Unicode con referencias
de caracteres XML.
PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Reemplaza el error de codificación Unicode con escapes
de barra invertida (\x, \u y \U).
PyObject *PyCodec_NameReplaceErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI since version 3.7. Reemplaza el error de codificación
Unicode con escapes \N{...}.
Added in version 3.5.

6.11 Support for Perf Maps

On supported platforms (as of this writing, only Linux), the runtime can take advantage of perf map files to make
Python functions visible to an external profiling tool (such as perf). A running process may create a file in the /tmp
directory, which contains entries that can map a section of executable code to a name. This interface is described in
the documentation of the Linux Perf tool.
In Python, these helper APIs can be used by libraries and features that rely on generating machine code on the fly.
Note that holding the Global Interpreter Lock (GIL) is not required for these APIs.
int PyUnstable_PerfMapState_Init(void)

This is Unstable API. It may change without warning in minor releases.

Open the /tmp/perf-$pid.map file, unless it’s already opened, and create a lock to ensure thread-safe
writes to the file (provided the writes are done through PyUnstable_WritePerfMapEntry()). Nor-
mally, there’s no need to call this explicitly; just use PyUnstable_WritePerfMapEntry() and it will
initialize the state on first call.
Returns 0 on success, -1 on failure to create/open the perf map file, or -2 on failure to create a lock. Check
errno for more information about the cause of a failure.
int PyUnstable_WritePerfMapEntry(const void *code_addr, unsigned int code_size, const char
*entry_name)

This is Unstable API. It may change without warning in minor releases.

Write one single entry to the /tmp/perf-$pid.map file. This function is thread safe. Here is what an
example entry looks like:
# address size name
7f3529fcf759 b py::bar:/run/t.py

Will call PyUnstable_PerfMapState_Init() before writing the entry, if the perf map file is not
already opened. Returns 0 on success, or the same error codes as PyUnstable_PerfMapState_Init()
on failure.

88 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4

void PyUnstable_PerfMapState_Fini(void)

This is Unstable API. It may change without warning in minor releases.

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.

6.11. Support for Perf Maps 89


The Python/C API, Versión 3.12.4

90 Capítulo 6. Utilidades
CAPÍTULO 7

Capa de objetos abstractos

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.

7.1 Protocolo de objeto

PyObject *Py_NotImplemented
El singleton NotImplemented, se usa para indicar que una operación no está implementada para la com-
binación de tipos dada.
Py_RETURN_NOTIMPLEMENTED
Properly handle returning Py_NotImplemented from within a C function (that is, create a new strong
reference to NotImplemented and return it).
Py_PRINT_RAW
Flag to be used with multiple functions that print the object (like PyObject_Print() and
PyFile_WriteObject()). If passed, these function would use the str() of the object instead of the
repr().
int PyObject_Print(PyObject *o, FILE *fp, int flags)
Print an object o, on file fp. Returns -1 on error. The flags argument is used to enable certain printing options.
The only option currently supported is Py_PRINT_RAW; if given, the str() of the object is written instead
of the repr().
int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
Part of the Stable ABI. Retorna 1 si o tiene el atributo attr_name, y 0 en caso contrario. Esto es equivalente a
la expresión de Python hasattr(o, attr_name). Esta función siempre finaliza exitosamente.

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

91
The Python/C API, Versión 3.12.4

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


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

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

PyObject *PyObject_GetAttr(PyObject *o, PyObject *attr_name)


Return value: New reference. Part of the Stable ABI. Recupera un atributo llamado attr_name del objeto o.
Retorna el valor del atributo en caso de éxito o NULL en caso de error. Este es el equivalente de la expresión
de Python o.attr_name.
PyObject *PyObject_GetAttrString(PyObject *o, const char *attr_name)
Return value: New reference. Part of the Stable ABI. This is the same as PyObject_GetAttr(), but
attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
PyObject *PyObject_GenericGetAttr(PyObject *o, PyObject *name)
Return value: New reference. Part of the Stable ABI. Función getter de atributo genérico que debe colocarse en
la ranura tp_getattro de un objeto tipo. Busca un descriptor en el diccionario de clases en el MRO del
objeto, 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)
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)
This is the same as PyObject_DelAttr(), but attr_name is specified as a const char* UTF-8 enco-
ded 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.

92 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

Esta función también puede ser llamada para obtener el __dict__ del objeto o. Se pasa context igual a NULL
cuando se lo llama. Dado que esta función puede necesitar asignar memoria para el diccionario, puede ser más
eficiente llamar a PyObject_GetAttr() para acceder a un atributo del objeto.
En caso de fallo, retorna NULL con una excepción establecida.
Added in version 3.3.
int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
Part of the Stable ABI since version 3.7. Una implementación genérica para el creador de un descriptor
__dict__. Esta implementación no permite que se elimine el diccionario.
Added in version 3.3.
PyObject **_PyObject_GetDictPtr(PyObject *obj)
Retorna un puntero al __dict__ del objeto obj. Si no hay __dict__, retorna NULL sin establecer una
excepción.
Esta función puede necesitar asignar memoria para el diccionario, por lo que puede ser más eficiente llamar a
PyObject_GetAttr() para acceder a un atributo del objeto.
PyObject *PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)
Return value: New reference. Part of the Stable ABI. Compare the values of o1 and o2 using the operation
specified by opid, which must be one of Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, or Py_GE, corresponding
to <, <=, ==, !=, >, or >= respectively. This is the equivalent of the Python expression o1 op o2, where
op is the operator corresponding to opid. Returns the value of the comparison on success, or NULL on failure.
int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)
Part of the Stable ABI. Compare the values of o1 and o2 using the operation specified by opid, like
PyObject_RichCompare(), but returns -1 on error, 0 if the result is false, 1 otherwise.

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

PyObject *PyObject_Format(PyObject *obj, PyObject *format_spec)


Part of the Stable ABI. Format obj using format_spec. This is equivalent to the Python expression
format(obj, format_spec).
format_spec may be NULL. In this case the call is equivalent to format(obj). Returns the formatted string
on success, NULL on failure.
PyObject *PyObject_Repr(PyObject *o)
Return value: New reference. Part of the Stable ABI. Calcula una representación de cadena de caracteres del
objeto o. Retorna la representación de cadena de caracteres en caso de éxito, NULL en caso de error. Este es
el equivalente de la expresión de Python repr(o). Llamado por la función incorporada repr().
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.
PyObject *PyObject_ASCII(PyObject *o)
Return value: New reference. Part of the Stable ABI. Como PyObject_Repr(), calcula una representación
de cadena de caracteres del objeto o, pero escapa los caracteres no ASCII en la cadena de caracteres retornada
por PyObject_Repr() con \x, \u o \U escapa. Esto genera una cadena de caracteres similar a la que
retorna PyObject_Repr() en Python 2. Llamado por la función incorporada ascii().
PyObject *PyObject_Str(PyObject *o)
Return value: New reference. Part of the Stable ABI. Calcula una representación de cadena de caracteres del
objeto o. Retorna la representación de cadena de caracteres en caso de éxito, NULL en caso de error. Llamado
por la función incorporada str() y, por lo tanto, por la función print().
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.

7.1. Protocolo de objeto 93


The Python/C API, Versión 3.12.4

PyObject *PyObject_Bytes(PyObject *o)


Return value: New reference. Part of the Stable ABI. Calcula una representación de bytes del objeto o. NULL
se retorna en caso de error y un objeto de bytes en caso de éxito. Esto es equivalente a la expresión de Python
bytes(o), cuando o no es un número entero. A diferencia de bytes(o), se lanza un TypeError cuando o
es un entero en lugar de un objeto de bytes con inicialización cero.
int PyObject_IsSubclass(PyObject *derived, PyObject *cls)
Part of the Stable ABI. Retorna 1 si la clase derived es idéntica o derivada de la clase cls; de lo contrario,
retorna 0. En caso de error, retorna -1.
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 __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.

94 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

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).
Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
Retorna una longitud estimada para el objeto o. Primero intenta retornar su longitud real, luego una estimación
usando __length_hint__(), y finalmente retorna el valor predeterminado. En caso de error, retorna -1.
Este es el equivalente a la expresión de Python operator.length_hint(o, defaultvalue).
Added in version 3.4.
PyObject *PyObject_GetItem(PyObject *o, PyObject *key)
Return value: New reference. Part of the Stable ABI. Retorna el elemento de o correspondiente a la clave key
del objeto o NULL en caso de error. Este es el equivalente de la expresión de Python o[key].
int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)
Part of the Stable ABI. Asigna el objeto key al valor v. Lanza una excepción y retorna -1 en caso de error;
retorna 0 en caso de éxito. Este es el equivalente de la declaración de Python o[key] = v. Esta función no
roba una referencia a v.
int PyObject_DelItem(PyObject *o, PyObject *key)
Part of the Stable ABI. Elimina la asignación para el objeto key del objeto o. Retorna -1 en caso de falla. Esto
es equivalente a la declaración de Python del o[key].
PyObject *PyObject_Dir(PyObject *o)
Return value: New reference. Part of the Stable ABI. Esto es equivalente a la expresión de Python dir(o), que
retorna una lista (posiblemente vacía) de cadenas de caracteres apropiadas para el argumento del objeto, o NULL
si hubo un error. Si el argumento es NULL, es como el Python dir(), que retorna los nombres de los locales
actuales; en este caso, si no hay un marco de ejecución activo, se retorna NULL pero PyErr_Occurred()
retornará falso.
PyObject *PyObject_GetIter(PyObject *o)
Return value: New reference. Part of the Stable ABI. Esto es equivalente a la expresión de Python iter(o).
Retorna un nuevo iterador para el argumento del objeto, o el propio objeto si el objeto ya es un iterador. Lanza
TypeError y retorna NULL si el objeto no puede iterarse.
PyObject *PyObject_GetAIter(PyObject *o)
Return value: New reference. Part of the Stable ABI since version 3.10. Esto es equivalente a la expresión de
Python aiter(o). Toma un objeto AsyncIterable y retorna AsyncIterator. Este es típicamente
un nuevo iterador, pero si el argumento es AsyncIterator, se retornará a sí mismo. Lanza TypeError
y retorna NULL si el objeto no puede ser iterado.
Added in version 3.10.
void *PyObject_GetTypeData(PyObject *o, PyTypeObject *cls)
Part of the Stable ABI since version 3.12. Get a pointer to subclass-specific data reserved for cls.
The object o must be an instance of cls, and cls must have been created using negative PyType_Spec.
basicsize. Python does not check this.
On error, set an exception and return NULL.
Added in version 3.12.

7.1. Protocolo de objeto 95


The Python/C API, Versión 3.12.4

Py_ssize_t PyType_GetTypeDataSize(PyTypeObject *cls)


Part of the Stable ABI since version 3.12. Return the size of the instance memory space reserved for cls, i.e.
the size of the memory PyObject_GetTypeData() returns.
This may be larger than requested using -PyType_Spec.basicsize; it is safe to use this larger size (e.g.
with memset()).
The type cls must have been created using negative PyType_Spec.basicsize. Python does not check
this.
On error, set an exception and return a negative value.
Added in version 3.12.
void *PyObject_GetItemData(PyObject *o)
Get a pointer to per-item data for a class with Py_TPFLAGS_ITEMS_AT_END.
On error, set an exception and return NULL. TypeError is raised if o does not have
Py_TPFLAGS_ITEMS_AT_END set.
Added in version 3.12.

7.2 Protocolo de llamada

CPython admite dos protocolos de llamada diferentes: tp_call y vectorcall.

7.2.1 El protocolo tp_call

Las instancias de clases que establecen tp_call son invocables. La firma del slot es:

PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);

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.

7.2.2 El protocolo vectorcall

Added in version 3.9.


El protocolo vectorcall se introdujo en PEP 590 como un protocolo adicional para hacer que las llamadas sean más
eficientes.
Como regla general, CPython preferirá el vectorcall para llamadas internas si el invocable lo admite. Sin embargo,
esta no es una regla estricta. Además, algunas extensiones de terceros usan tp_call directamente (en lugar de usar
PyObject_Call()). Por lo tanto, una clase que admita vectorcall también debe implementar tp_call. Ade-
más, el invocable debe comportarse de la misma manera independientemente del protocolo que se utilice. La forma
recomendada de lograr esto es configurando tp_call en PyVectorcall_Call(). Vale la pena repetirlo:

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

96 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

differently than the vectorcall function.) In earlier Python versions, vectorcall should only be used with immutable
or static types.
Una clase no debería implementar vectorcall si eso fuera más lento que tp_call. Por ejemplo, si el destinatario de la
llamada necesita convertir los argumentos a una tupla args y un dict kwargs de todos modos, entonces no tiene sentido
implementar vectorcall.
Classes can implement the vectorcall protocol by enabling the Py_TPFLAGS_HAVE_VECTORCALL flag and setting
tp_vectorcall_offset to the offset inside the object structure where a vectorcallfunc appears. This is a pointer
to a function with the following signature:
typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Part of the Stable ABI since version 3.12.
• callable es el objeto siendo invocado.
• args es un arreglo en C que consta de los argumentos posicionales seguidos por el
valores de los argumentos de la palabra clave. Puede ser NULL si no hay argumentos.
• nargsf es el número de argumentos posicionales más posiblemente el
PY_VECTORCALL_ARGUMENTS_OFFSET flag. To get the actual number of positional arguments
from nargsf, use PyVectorcall_NARGS().
• kwnames es una tupla que contiene los nombres de los argumentos de la palabra clave;
en otras palabras, las claves del diccionario kwargs. Estos nombres deben ser cadenas (instancias de str
o una subclase) y deben ser únicos. Si no hay argumentos de palabras clave, entonces kwnames puede ser
NULL.
PY_VECTORCALL_ARGUMENTS_OFFSET
Part of the Stable ABI since version 3.12. Si este flag se establece en un argumento vectorcall nargsf, el desti-
natario de la llamada puede cambiar temporalmente args[-1]. En otras palabras, args apunta al argumento
1 (no 0) en el vector asignado. El destinatario de la llamada debe restaurar el valor de args[-1] antes de
regresar.
Para PyObject_VectorcallMethod(), este flag significa en cambio que args[0] puede cambiarse.
Whenever they can do so cheaply (without additional allocation), callers are encouraged to use
PY_VECTORCALL_ARGUMENTS_OFFSET. Doing so will allow callables such as bound methods to ma-
ke their onward calls (which include a prepended self argument) very efficiently.
Added in version 3.8.
Para llamar a un objeto que implementa vectorcall, use una función call API como con cualquier otro invocable.
PyObject_Vectorcall() normalmente será más eficiente.

Nota: En CPython 3.8, la API de vectorcall y las funciones relacionadas es-


taban disponibles provisionalmente bajo nombres con un guión bajo inicial:
_PyObject_Vectorcall, _Py_TPFLAGS_HAVE_VECTORCALL, _PyObject_VectorcallMethod,
_PyVectorcall_Function, _PyObject_CallMethodNoArgs, _PyObject_CallMethodOneArg.
Además, PyObject_VectorcallDict estaba disponible como _PyObject_FastCallDict. Los nom-
bres antiguos todavía se definen como alias de los nuevos nombres no subrayados.

7.2. Protocolo de llamada 97


The Python/C API, Versión 3.12.4

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.

API de soporte para vectorcall

Py_ssize_t PyVectorcall_NARGS(size_t nargsf)


Part of the Stable ABI since version 3.12. Dado un argumento vectorcall nargsf, retorna el número real de
argumentos. Actualmente equivalente a:

(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)

Sin embargo, la función PyVectorcall_NARGS debe usarse para permitir futuras extensiones.
Added in version 3.8.
vectorcallfunc PyVectorcall_Function(PyObject *op)
Si op no admite el protocolo vectorcall (ya sea porque el tipo no lo hace o porque la instancia específica no
lo hace), retorna NULL. De lo contrario, retorna el puntero de la función vectorcall almacenado en op. Esta
función nunca lanza una excepción.
Esto es principalmente útil para verificar si op admite vectorcall, lo cual se puede hacer marcando
PyVectorcall_Function(op) != NULL.
Added in version 3.9.
PyObject *PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict)
Part of the Stable ABI since version 3.12. Llama a la vectorcallfunc de callable con argumentos posi-
cionales y de palabras clave dados en una tupla y dict, respectivamente.
This is a specialized function, intended to be put in the tp_call slot or be used in an implementation of
tp_call. It does not check the Py_TPFLAGS_HAVE_VECTORCALL flag and it does not fall back to
tp_call.
Added in version 3.8.

7.2.3 API para invocar objetos

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.

98 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

Función invocable args kwargs


PyObject_Call() PyObject * tupla dict/NULL
PyObject_CallNoArgs() PyObject * — —
PyObject_CallOneArg() PyObject * 1 objeto —
PyObject_CallObject() PyObject * tuple/NULL —
PyObject_CallFunction() PyObject * formato —
PyObject_CallMethod() obj + char* formato —
PyObject_CallFunctionObjArgs() PyObject * variadica —
PyObject_CallMethodObjArgs() obj + nombre variadica —
PyObject_CallMethodNoArgs() obj + nombre — —
PyObject_CallMethodOneArg() obj + nombre 1 objeto —
PyObject_Vectorcall() PyObject * vectorcall vectorcall
PyObject_VectorcallDict() PyObject * vectorcall dict/NULL
PyObject_VectorcallMethod() arg + nombre vectorcall vectorcall

PyObject *PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)


Return value: New reference. Part of the Stable ABI. Llama a un objeto de Python invocable callable, con
argumentos dados por la tupla args, y argumentos con nombre dados por el diccionario kwargs.
args no debe ser NULL; use una tupla vacía si no se necesitan argumentos. Si no se necesitan argumentos con
nombre, kwargs puede ser NULL.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Este es el equivalente de la expresión de Python: callable(*args, **kwargs).
PyObject *PyObject_CallNoArgs(PyObject *callable)
Return value: New reference. Part of the Stable ABI since version 3.10. Llama a un objeto de Python invocable
callable sin ningún argumento. Es la forma más eficiente de llamar a un objeto Python invocable sin ningún
argumento.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Added in version 3.9.
PyObject *PyObject_CallOneArg(PyObject *callable, PyObject *arg)
Return value: New reference. Llama a un objeto de Python invocable callable con exactamente 1 argumento
posicional arg y sin argumentos de palabra clave.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Added in version 3.9.
PyObject *PyObject_CallObject(PyObject *callable, PyObject *args)
Return value: New reference. Part of the Stable ABI. Llama a un objeto de Python invocable callable, con
argumentos dados por la tupla args. Si no se necesitan argumentos, entonces args puede ser NULL.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Este es el equivalente de la expresión de Python: callable(*args).
PyObject *PyObject_CallFunction(PyObject *callable, const char *format, ...)
Return value: New reference. Part of the Stable ABI. Llama a un objeto de Python invocable callable, con un
número variable de argumentos C. Los argumentos de C se describen usando una cadena de caracteres de
formato de estilo Py_BuildValue(). El formato puede ser NULL, lo que indica que no se proporcionan
argumentos.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Este es el equivalente de la expresión de Python: callable(*args).
Note that if you only pass PyObject* args, PyObject_CallFunctionObjArgs() is a faster alter-
native.

7.2. Protocolo de llamada 99


The Python/C API, Versión 3.12.4

Distinto en la versión 3.4: El tipo de format se cambió desde char *.


PyObject *PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
Return value: New reference. Part of the Stable ABI. Llama al método llamado name del objeto obj con un
número variable de argumentos en C. Los argumentos de C se describen mediante una cadena de formato
Py_BuildValue() que debería producir una tupla.
El formato puede ser NULL, lo que indica que no se proporcionan argumentos.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Este es el equivalente de la expresión de Python: obj.name(arg1, arg2, ...).
Note that if you only pass PyObject* args, PyObject_CallMethodObjArgs() is a faster alternative.
Distinto en la versión 3.4: Los tipos de name y format se cambiaron desde char *.
PyObject *PyObject_CallFunctionObjArgs(PyObject *callable, ...)
Return value: New reference. Part of the Stable ABI. Call a callable Python object callable, with a variable
number of PyObject* arguments. The arguments are provided as a variable number of parameters followed
by NULL.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Este es el equivalente de la expresión de Python: callable(arg1, arg2, ...).
PyObject *PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ...)
Return value: New reference. Part of the Stable ABI. Call a method of the Python object obj, where the name
of the method is given as a Python string object in name. It is called with a variable number of PyObject*
arguments. The arguments are provided as a variable number of parameters followed by NULL.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
PyObject *PyObject_CallMethodNoArgs(PyObject *obj, PyObject *name)
Llama a un método del objeto de Python obj sin argumentos, donde el nombre del método se da como un objeto
de cadena de caracteres de Python en name.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Added in version 3.9.
PyObject *PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObject *arg)
Llame a un método del objeto de Python obj con un único argumento posicional arg, donde el nombre del
método se proporciona como un objeto de cadena de caracteres de Python en name.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Added in version 3.9.
PyObject *PyObject_Vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Part of the Stable ABI since version 3.12. Llama a un objeto de Python invocable callable. Los argumentos son
los mismos que para vectorcallfunc. Si callable admite vectorcall, esto llama directamente a la función
vectorcall almacenada en callable.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Added in version 3.9.
PyObject *PyObject_VectorcallDict(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwdict)
Llamada invocable con argumentos posicionales pasados exactamente como en el protocolo vectorcall, pero con
argumentos de palabras clave pasados como un diccionario kwdict. El arreglo args contiene solo los argumentos
posicionales.
Independientemente del protocolo que se utilice internamente, es necesario realizar una conversión de argu-
mentos. Por lo tanto, esta función solo debe usarse si la persona que llama ya tiene un diccionario listo para
usar para los argumentos de palabras clave, pero no una tupla para los argumentos posicionales.

100 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

Added in version 3.9.


PyObject *PyObject_VectorcallMethod(PyObject *name, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Part of the Stable ABI since version 3.12. Call a method using the vectorcall calling convention. The name of
the method is given as a Python string name. The object whose method is called is args[0], and the args array
starting at args[1] represents the arguments of the call. There must be at least one positional argument. nargsf
is the number of positional arguments including args[0], plus PY_VECTORCALL_ARGUMENTS_OFFSET
if the value of args[0] may temporarily be changed. Keyword arguments can be passed just like in
PyObject_Vectorcall().
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.
Added in version 3.9.

7.2.4 API de soporte de llamadas

int PyCallable_Check(PyObject *o)


Part of the Stable ABI. Determina si el objeto o es invocable. Retorna 1 si el objeto es invocable y 0 en caso
contrario. Esta función siempre finaliza con éxito.

7.3 Protocolo de números

int PyNumber_Check(PyObject *o)


Part of the Stable ABI. Retorna 1 si el objeto o proporciona protocolos numéricos, y falso en caso contrario.
Esta función siempre finaliza con éxito.
Distinto en la versión 3.8: Retorna 1 si o es un índice entero.
PyObject *PyNumber_Add(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de agregar o1 y o2, o NULL en caso
de falla. Este es el equivalente de la expresión de Python o1 + o2.
PyObject *PyNumber_Subtract(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de restar o2 de o1, o NULL en caso
de falla. Este es el equivalente de la expresión de Python o1 - o2.
PyObject *PyNumber_Multiply(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de multiplicar o1 y o2, o NULL en
caso de error. Este es el equivalente de la expresión de Python o1 * o2.
PyObject *PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI since version 3.7. Retorna el resultado de la multiplicación
de matrices en o1 y o2, o NULL en caso de falla. Este es el equivalente de la expresión de Python o1 @ o2.
Added in version 3.5.
PyObject *PyNumber_FloorDivide(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el cociente de la división entera a la baja entre o1
y o2, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 // o2.
PyObject *PyNumber_TrueDivide(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna una aproximación razonable para el valor ma-
temático de o1 dividido por o2 o NULL en caso de falla. El valor de retorno es «aproximado» porque los
números binarios de punto flotante son aproximados; No es posible representar todos los números reales en la

7.3. Protocolo de números 101


The Python/C API, Versión 3.12.4

base dos. Esta función puede retornar un valor de punto flotante cuando se pasan dos enteros. Es equivalente
a la expresión de Python o1 / o2.
PyObject *PyNumber_Remainder(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resto de la división entera a la baja entre o1 y
o2, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 % o2.
PyObject *PyNumber_Divmod(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Vea la función incorporada divmod(). Retorna NULL
en caso de falla. Este es el equivalente de la expresión de Python divmod (o1, o2).
PyObject *PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3)
Return value: New reference. Part of the Stable ABI. Consulte la función incorporada pow(). Retorna NULL
en caso de falla. Este es el equivalente de la expresión de Python pow(o1, o2, o3), donde o3 es opcional.
Si se ignora o3, pase Py_None en su lugar (pasar NULL por o3 provocaría un acceso ilegal a la memoria).
PyObject *PyNumber_Negative(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna la negación de o en caso de éxito o NULL en caso
de error. Este es el equivalente de la expresión de Python -o.
PyObject *PyNumber_Positive(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna o en caso de éxito o NULL en caso de error. Este
es el equivalente de la expresión de Python +o.
PyObject *PyNumber_Absolute(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna el valor absoluto de o o NULL en caso de error.
Este es el equivalente de la expresión de Python abs(o).
PyObject *PyNumber_Invert(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna la negación bit a bit de o en caso de éxito o NULL
en caso de error. Este es el equivalente de la expresión de Python ~o.
PyObject *PyNumber_Lshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado del desplazamiento a la izquierda o1
por o2 en caso de éxito o NULL en caso de error. Este es el equivalente de la expresión de Python o1 << o2.
PyObject *PyNumber_Rshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado del desplazamiento a la derecha o1
por o2 en caso de éxito o NULL en caso de error. Este es el equivalente de la expresión de Python o1 >> o2.
PyObject *PyNumber_And(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit y» (bitwise and) de o1 y o2 en caso
de éxito y NULL en caso de error. Este es el equivalente de la expresión de Python o1 & o2.
PyObject *PyNumber_Xor(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit o exclusivo» (bitwise exclusive or) de
o1 por o2 en caso de éxito, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 ^
o2.
PyObject *PyNumber_Or(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit o» (bitwise or) de o1 y o2 en caso de
éxito, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 | o2.
PyObject *PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de agregar o1 y o2, o NULL en caso de
falla. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es el equivalente de la declaración
de Python o1 += o2.
PyObject *PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de restar o2 de o1, o NULL en caso de
falla. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es el equivalente de la declaración
de Python o1 -= o2.

102 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

PyObject *PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2)


Return value: New reference. Part of the Stable ABI. Retorna el resultado de multiplicar o1 y o2, o NULL en
caso de error. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es el equivalente de la
declaración de Python o1 *= o2.
PyObject *PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI since version 3.7. Retorna el resultado de la multiplicación
de matrices en o1 y o2, o NULL en caso de falla. La operación se realiza en su lugar (in-place) cuando o1 lo
admite. Este es el equivalente de la declaración de Python o1 @= o2.
Added in version 3.5.
PyObject *PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el cociente de la división entera a la baja entre o1
y o2, o NULL en caso de error. La operación se realiza in situ (in-place) cuando o1 lo admite. Es el equivalente
de la sentencia de Python o1 //= o2.
PyObject *PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Return a reasonable approximation for the mathematical
value of o1 divided by o2, or NULL on failure. The return value is «approximate» because binary floating point
numbers are approximate; it is not possible to represent all real numbers in base two. This function can return
a floating point value when passed two integers. The operation is done in-place when o1 supports it. This is the
equivalent of the Python statement o1 /= o2.
PyObject *PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resto de dividir o1 entre o2 o NULL en caso de
error. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es el equivalente de la declaración
de Python o1%= o2.
PyObject *PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3)
Return value: New reference. Part of the Stable ABI. Consulte la función incorporada pow(). Retorna NULL
en caso de falla. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es el equivalente de
la declaración de Python o1 **= o2 cuando o3 es Py_None, o una variante en su lugar (in-place) de pow
(o1, o2, o3) de lo contrario. Si se ignora o3, pase Py_None en su lugar (pasar NULL para o3 provocaría
un acceso ilegal a la memoria).
PyObject *PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado del desplazamiento a la izquierda o1
por o2 en caso de éxito o NULL en caso de error. La operación se realiza en su sitio (in-place) cuando o1 lo
admite. Este es el equivalente de la declaración de Python o1 <<= o2.
PyObject *PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado del desplazamiento a la derecha o1
por o2 en caso de éxito o NULL en caso de error. La operación se realiza en su lugar (in-place) cuando o1 lo
admite. Este es el equivalente de la declaración de Python o1 >>= o2.
PyObject *PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit y» (bitwise and) de o1 y o2 en caso
de éxito y NULL en caso de error. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es
el equivalente de la declaración de Python o1 &= o2.
PyObject *PyNumber_InPlaceXor(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit o exclusivo» (bitwise exclusive or) de
o1 por o2 en caso de éxito, o NULL en caso de error. La operación se realiza en su lugar (in-place) cuando o1
lo admite. Este es el equivalente de la declaración de Python o1 ^= o2.
PyObject *PyNumber_InPlaceOr(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit o» (bitwise or) de o1 y o2 en caso
de éxito, o NULL en caso de error. La operación se realiza en su lugar in-place cuando o1 lo admite. Este es el
equivalente de la declaración de Python o1 |= o2.

7.3. Protocolo de números 103


The Python/C API, Versión 3.12.4

PyObject *PyNumber_Long(PyObject *o)


Return value: New reference. Part of the Stable ABI. Retorna el o convertido a un objeto entero en caso de
éxito, o NULL en caso de error. Este es el equivalente de la expresión de Python int(o).
PyObject *PyNumber_Float(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna el o convertido a un objeto flotante en caso de
éxito o NULL en caso de error. Este es el equivalente de la expresión de Python float(o).
PyObject *PyNumber_Index(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna el o convertido aun entero de Python (int) en caso
de éxito o NULL con una excepción TypeError lanzada en caso de error.
Distinto en la versión 3.10: El resultado siempre tiene el tipo exacto int. Anteriormente, el resultado podía
ser una instancia de una subclase de int.
PyObject *PyNumber_ToBase(PyObject *n, int base)
Return value: New reference. Part of the Stable ABI. Retorna el entero n convertido a base base como una cadena
de caracteres. El argumento base debe ser uno de 2, 8, 10 o 16. Para la base 2, 8 o 16, la cadena retornada está
prefijada con un marcador base de '0b'”, '0o' o '0x', respectivamente. Si n no es un entero (int) Python,
primero se convierte con PyNumber_Index().
Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc)
Part of the Stable ABI. Returns o converted to a Py_ssize_t value if o can be interpreted as an integer. If
the call fails, an exception is raised and -1 is returned.
If o can be converted to a Python int but the attempt to convert to a Py_ssize_t value would rai-
se an OverflowError, then the exc argument is the type of exception that will be raised (usually
IndexError or OverflowError). If exc is NULL, then the exception is cleared and the value is clip-
ped to PY_SSIZE_T_MIN for a negative integer or PY_SSIZE_T_MAX for a positive integer.
int PyIndex_Check(PyObject *o)
Part of the Stable ABI since version 3.8. Returns 1 if o is an index integer (has the nb_index slot of the
tp_as_number structure filled in), and 0 otherwise. This function always succeeds.

7.4 Protocolo de secuencia

int PySequence_Check(PyObject *o)


Part of the Stable ABI. Return 1 if the object provides the sequence protocol, and 0 otherwise. Note that it
returns 1 for Python classes with a __getitem__() method, unless they are dict subclasses, since in
general it is impossible to determine what type of keys the class supports. This function always succeeds.
Py_ssize_t PySequence_Size(PyObject *o)
Py_ssize_t PySequence_Length(PyObject *o)
Part of the Stable ABI. Retorna el número de objetos en secuencia o en caso de éxito y -1 en caso de error.
Esto es equivalente a la expresión de Python len(o).
PyObject *PySequence_Concat(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna la concatenación de o1 y o2 en caso de éxito, y
NULL en caso de error. Este es el equivalente de la expresión de Python o1+o2.
PyObject *PySequence_Repeat(PyObject *o, Py_ssize_t count)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de repetir el objeto de secuencia o
count veces, o NULL en caso de falla. Este es el equivalente de la expresión de Python o*count.
PyObject *PySequence_InPlaceConcat(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna la concatenación de o1 y o2 en caso de éxito, y
NULL en caso de error. La operación se realiza en su lugar in-place cuando o1 lo admite. Este es el equivalente
de la expresión de Python o1+=o2.

104 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

PyObject *PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)


Return value: New reference. Part of the Stable ABI. Retorna el resultado de repetir el objeto de secuencia o
count veces, o NULL en caso de falla. La operación se realiza en su lugar (in-place) cuando o lo admite. Este
es el equivalente de la expresión de Python o*=count.
PyObject *PySequence_GetItem(PyObject *o, Py_ssize_t i)
Return value: New reference. Part of the Stable ABI. Retorna el elemento i-ésimo de o o NULL en caso de error.
Este es el equivalente de la expresión de Python o[i].
PyObject *PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
Return value: New reference. Part of the Stable ABI. Retorna la rebanada del objeto secuencia o entre i1 y i2,
o NULL en caso de error. Este es el equivalente de la expresión de Python o[i1:i2].
int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v)
Part of the Stable ABI. Asigna el objeto v al elemento i-ésimo de o. 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[i]=v. Esta función
no roba una referencia a v.
If v is NULL, the element is deleted, but this feature is deprecated in favour of using
PySequence_DelItem().
int PySequence_DelItem(PyObject *o, Py_ssize_t i)
Part of the Stable ABI. Elimina el elemento i-ésimo del objeto o. Retorna -1 en caso de falla. Este es el
equivalente de la declaración de Python del o[i].
int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v)
Part of the Stable ABI. Asigna el objeto secuencia v al segmento en el objeto secuencia o de i1 a i2. Este es el
equivalente de la declaración de Python o[i1:i2]=v.
int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
Part of the Stable ABI. Elimina el segmento en el objeto secuencia o de i1 a i2. Retorna -1 en caso de falla.
Este es el equivalente de la declaración de Python del o[i1:i2].
Py_ssize_t PySequence_Count(PyObject *o, PyObject *value)
Part of the Stable ABI. Retorna el número de apariciones de value en o, es decir, retorna el número de claves
para las que o[clave]==value. En caso de fallo, retorna -1. Esto es equivalente a la expresión de Python
o.count(value).
int PySequence_Contains(PyObject *o, PyObject *value)
Part of the Stable ABI. Determine si o contiene valor. Si un elemento en o es igual a value, retorna 1; de lo
contrario, retorna 0. En caso de error, retorna -1. Esto es equivalente a la expresión de Python value in
o.
Py_ssize_t PySequence_Index(PyObject *o, PyObject *value)
Part of the Stable ABI. Retorna el primer índice i para el que o[i]==value. En caso de error, retorna -1.
Esto es equivalente a la expresión de Python o.index(value).
PyObject *PySequence_List(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna un objeto lista con el mismo contenido que la
secuencia o iterable o, o NULL en caso de error. La lista retornada está garantizada como nueva. Esto es
equivalente a la expresión de Python list(o).
PyObject *PySequence_Tuple(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna un objeto tupla con el mismo contenido que la
secuencia o iterable o, o NULL en caso de error. Si o es una tupla, se retornará una nueva referencia; de lo
contrario, se construirá una tupla con el contenido apropiado. Esto es equivalente a la expresión de Python
tupla(o).
PyObject *PySequence_Fast(PyObject *o, const char *m)
Return value: New reference. Part of the Stable ABI. Retorna la secuencia o iterable o como un objeto utilizable
por la otra familia de funciones PySequence_Fast*. Si el objeto no es una secuencia o no es iterable, lanza
TypeError con m como texto del mensaje. Retorna NULL en caso de falla.

7.4. Protocolo de secuencia 105


The Python/C API, Versión 3.12.4

Las funciones PySequence_Fast* se denominan así porque suponen que o es un PyTupleObject o


un PyListObject y acceden a los campos de datos de o directamente.
Como detalle de implementación de CPython, si o ya es una secuencia o lista, se retornará.
Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o)
Returns the length of o, assuming that o was returned by PySequence_Fast() and that
o is not NULL. The size can also be retrieved by calling PySequence_Size() on o, but
PySequence_Fast_GET_SIZE() is faster because it can assume o is a list or tuple.
PyObject *PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i)
Return value: Borrowed reference. Retorna el elemento i-ésimo de o, suponiendo que o haya sido retornado por
PySequence_Fast(), o no es NULL y que i está dentro de los límites.
PyObject **PySequence_Fast_ITEMS(PyObject *o)
Retorna el arreglo subyacente de punteros PyObject. Asume que o fue retornado por PySequence_Fast()
y o no es NULL.
Tenga en cuenta que si una lista cambia de tamaño, la reasignación puede reubicar el arreglo de elementos. Por
lo tanto, solo use el puntero de arreglo subyacente en contextos donde la secuencia no puede cambiar.
PyObject *PySequence_ITEM(PyObject *o, Py_ssize_t i)
Return value: New reference. Retorna el elemento i-ésimo de o o NULL en caso de error. Es la forma más
rápida de PySequence_GetItem() pero sin verificar que PySequence_Check() en o es verdadero
y sin ajuste para índices negativos.

7.5 Protocolo de mapeo

Consulte también PyObject_GetItem(), PyObject_SetItem() y PyObject_DelItem().


int PyMapping_Check(PyObject *o)
Part of the Stable ABI. Return 1 if the object provides the mapping protocol or supports slicing, and 0 ot-
herwise. Note that it returns 1 for Python classes with a __getitem__() method, since in general it is
impossible to determine what type of keys the class supports. This function always succeeds.
Py_ssize_t PyMapping_Size(PyObject *o)
Py_ssize_t PyMapping_Length(PyObject *o)
Part of the Stable ABI. Retorna el número de claves en el objeto o en caso de éxito, y -1 en caso de error. Esto
es equivalente a la expresión de Python len(o).
PyObject *PyMapping_GetItemString(PyObject *o, const char *key)
Return value: New reference. Part of the Stable ABI. This is the same as PyObject_GetItem(), but key
is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *v)
Part of the Stable ABI. This is the same as PyObject_SetItem(), but key is specified as a const char*
UTF-8 encoded bytes string, rather than a PyObject*.
int PyMapping_DelItem(PyObject *o, PyObject *key)
This is an alias of PyObject_DelItem().
int PyMapping_DelItemString(PyObject *o, const char *key)
This is the same as PyObject_DelItem(), but key is specified as a const char* UTF-8 encoded bytes
string, rather than a PyObject*.
int PyMapping_HasKey(PyObject *o, PyObject *key)
Part of the Stable ABI. Retorna 1 si el objeto de mapeo tiene la clave key y 0 de lo contrario. Esto es equivalente
a la expresión de Python key in o. Esta función siempre finaliza con éxito.

106 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

Nota: Exceptions which occur when this calls __getitem__() method are silently ignored. For proper
error handling, use PyObject_GetItem() instead.

int PyMapping_HasKeyString(PyObject *o, const char *key)


Part of the Stable ABI. This is the same as PyMapping_HasKey(), but key is specified as a const char*
UTF-8 encoded bytes string, rather than a PyObject*.

Nota: Exceptions that occur when this calls __getitem__() method or while creating the temporary str
object are silently ignored. For proper error handling, use PyMapping_GetItemString() instead.

PyObject *PyMapping_Keys(PyObject *o)


Return value: New reference. Part of the Stable ABI. En caso de éxito, retorna una lista de las claves en el objeto
o. En caso de fallo, retorna NULL.
Distinto en la versión 3.7: Anteriormente, la función retornaba una lista o una tupla.
PyObject *PyMapping_Values(PyObject *o)
Return value: New reference. Part of the Stable ABI. En caso de éxito, retorna una lista de los valores en el
objeto o. En caso de fallo, retorna NULL.
Distinto en la versión 3.7: Anteriormente, la función retornaba una lista o una tupla.
PyObject *PyMapping_Items(PyObject *o)
Return value: New reference. Part of the Stable ABI. En caso de éxito, retorna una lista de los elementos en
el objeto o, donde cada elemento es una tupla que contiene un par clave-valor (key-value). En caso de fallo,
retorna NULL.
Distinto en la versión 3.7: Anteriormente, la función retornaba una lista o una tupla.

7.6 Protocolo iterador

Hay dos funciones específicas para trabajar con iteradores.


int PyIter_Check(PyObject *o)
Part of the Stable ABI since version 3.8. Return non-zero if the object o can be safely passed to
PyIter_Next(), and 0 otherwise. This function always succeeds.
int PyAIter_Check(PyObject *o)
Part of the Stable ABI since version 3.10. Return non-zero if the object o provides the AsyncIterator
protocol, and 0 otherwise. This function always succeeds.
Added in version 3.10.
PyObject *PyIter_Next(PyObject *o)
Return value: New reference. Part of the Stable ABI. Return the next value from the iterator o. The object must
be an iterator according to PyIter_Check() (it is up to the caller to check this). If there are no remaining
values, returns NULL with no exception set. If an error occurs while retrieving the item, returns NULL and
passes along the exception.
Para escribir un bucle que itera sobre un iterador, el código en C de