0% encontró este documento útil (0 votos)
15 vistas

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)
15 vistas

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 debería verse así:

PyObject *iterator = PyObject_GetIter(obj);


PyObject *item;

if (iterator == NULL) {
/* propagate error */
}
(continúe en la próxima página)

7.6. Protocolo iterador 107


The Python/C API, Versión 3.12.4

(proviene de la página anterior)

while ((item = PyIter_Next(iterator))) {


/* do something with item */
...
/* release reference when done */
Py_DECREF(item);
}

Py_DECREF(iterator);

if (PyErr_Occurred()) {
/* propagate error */
}
else {
/* continue doing useful work */
}

type PySendResult
El valor de enumeración utilizado para representar diferentes resultados de PyIter_Send().
Added in version 3.10.
PySendResult PyIter_Send(PyObject *iter, PyObject *arg, PyObject **presult)
Part of the Stable ABI since version 3.10. Envía el valor arg al iterador iter. Retorna:
• PYGEN_RETURN si el iterador regresa. El valor de retorno se retorna a través de presult.
• PYGEN_NEXT si el iterador cede. El valor cedido se retorna a través de presult.
• PYGEN_ERROR si el iterador ha lanzado una excepción. presult se establece en NULL.
Added in version 3.10.

7.7 Protocolo búfer

Ciertos objetos disponibles en Python ajustan el acceso a un arreglo de memoria subyacente o buffer. Dichos objetos
incluyen el incorporado bytes y bytearray, y algunos tipos de extensión como array.array. Las bibliotecas
de terceros pueden definir sus propios tipos para fines especiales, como el procesamiento de imágenes o el análisis
numérico.
Si bien cada uno de estos tipos tiene su propia semántica, comparten la característica común de estar respaldados por
un búfer de memoria posiblemente grande. Es deseable, en algunas situaciones, acceder a ese búfer directamente y
sin copia intermedia.
Python proporciona una instalación de este tipo en el nivel C en la forma de protocolo búfer. Este protocolo tiene dos
lados:
• en el lado del productor, un tipo puede exportar una «interfaz de búfer» que permite a los objetos de ese tipo
exponer información sobre su búfer subyacente. Esta interfaz se describe en la sección Estructuras de objetos
búfer;
• en el lado del consumidor, hay varios medios disponibles para obtener un puntero a los datos subyacentes sin
procesar de un objeto (por ejemplo, un parámetro de método).
Los objetos simples como bytes y bytearray exponen su búfer subyacente en forma orientada a bytes. Otras
formas son posibles; por ejemplo, los elementos expuestos por un array.array pueden ser valores de varios bytes.
An example consumer of the buffer interface is the write() method of file objects: any object that can export a
series of bytes through the buffer interface can be written to a file. While write() only needs read-only access
to the internal contents of the object passed to it, other methods such as readinto() need write access to the
contents of their argument. The buffer interface allows objects to selectively allow or reject exporting of read-write
and read-only buffers.

108 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

Hay dos formas para que un consumidor de la interfaz del búfer adquiera un búfer sobre un objeto de destino:
• llamar PyObject_GetBuffer() con los parámetros correctos;
• llamar PyArg_ParseTuple() (o uno de sus hermanos) con uno de los y*, w* o s* códigos de formato.
En ambos casos, se debe llamar a PyBuffer_Release() cuando ya no se necesita el búfer. De lo contrario,
podrían surgir varios problemas, como pérdidas de recursos.

7.7.1 Estructura de búfer

Las estructuras de búfer (o simplemente «búferes») son útiles como una forma de exponer los datos binarios de otro
objeto al programador de Python. También se pueden usar como un mecanismo de corte de copia cero. Usando su
capacidad para hacer referencia a un bloque de memoria, es posible exponer cualquier información al programador
Python con bastante facilidad. La memoria podría ser una matriz grande y constante en una extensión C, podría ser
un bloque de memoria sin procesar para su manipulación antes de pasar a una biblioteca del sistema operativo, o
podría usarse para pasar datos estructurados en su formato nativo en memoria .
Contrariamente a la mayoría de los tipos de datos expuestos por el intérprete de Python, los búferes no son punteros
PyObject sino estructuras C simples. Esto les permite ser creados y copiados de manera muy simple. Cuando se
necesita un contenedor genérico alrededor de un búfer, un objeto memoryview puede ser creado.
Para obtener instrucciones breves sobre cómo escribir un objeto de exportación, consulte Estructuras de objetos búfer.
Para obtener un búfer, consulte PyObject_GetBuffer().
type Py_buffer
Part of the Stable ABI (including all members) since version 3.11.
void *buf
Un puntero al inicio de la estructura lógica descrita por los campos del búfer. Puede ser cualquier ubica-
ción dentro del bloque de memoria física subyacente del exportador. Por ejemplo, con negativo strides
el valor puede apuntar al final del bloque de memoria.
Para arreglos contiguous, el valor apunta al comienzo del bloque de memoria.
PyObject *obj
A new reference to the exporting object. The reference is owned by the consumer and automatically
released (i.e. reference count decremented) and set to NULL by PyBuffer_Release(). The field is
the equivalent of the return value of any standard C-API function.
Como un caso especial, para los búferes temporary que están envueltos por
PyMemoryView_FromBuffer() o PyBuffer_FillInfo() este campo es NULL. En
general, los objetos de exportación NO DEBEN usar este esquema.
Py_ssize_t len
product(shape) * itemize. Para arreglos contiguos, esta es la longitud del bloque de memoria
subyacente. Para arreglos no contiguos, es la longitud que tendría la estructura lógica si se copiara en una
representación contigua.
Accede a ((char *)buf)[0] hasta ((char *)buf)[len-1] solo es válido si el búfer se
ha obtenido mediante una solicitud que garantiza la contigüidad. En la mayoría de los casos, dicha soli-
citud será PyBUF_SIMPLE o PyBUF_WRITABLE.
int readonly
Un indicador de si el búfer es de solo lectura. Este campo está controlado por el indicador
PyBUF_WRITABLE.
Py_ssize_t itemsize
Tamaño del elemento en bytes de un solo elemento. Igual que el valor de struct.calcsize()
invocado en valores no NULL format.
Excepción importante: si un consumidor solicita un búfer sin el indicador PyBUF_FORMAT, format
se establecerá en NULL, pero itemsize todavía tiene el valor para el formato original.

7.7. Protocolo búfer 109


The Python/C API, Versión 3.12.4

Si shape está presente, la igualdad product(shape) * itemsize == len aún se mantiene y


el consumidor puede usar itemsize para navegar el búfer.
Si shape es NULL como resultado de un PyBUF_SIMPLE o un PyBUF_WRITABLE, el consumidor
debe ignorar itemsize y asume itemsize == 1.
char *format
A NULL terminated string in struct module style syntax describing the contents of a single item. If
this is NULL, "B" (unsigned bytes) is assumed.
Este campo está controlado por el indicador PyBUF_FORMAT.
int ndim
The number of dimensions the memory represents as an n-dimensional array. If it is 0, buf points to a
single item representing a scalar. In this case, shape, strides and suboffsets MUST be NULL.
The maximum number of dimensions is given by PyBUF_MAX_NDIM .
Py_ssize_t *shape
Un arreglo de Py_ssize_t de longitud ndim que indica la forma de la memoria como un arreglo n-
dimensional. Tenga en cuenta que shape[0] * ... * shape[ndim-1] * itemsize DEBE
ser igual a len.
Los valores de forma están restringidos a shape[n] >= 0. El caso shape[n] == 0 requiere aten-
ción especial. Vea arreglos complejos (complex arrays) para más información.
El arreglo de formas es de sólo lectura para el consumidor.
Py_ssize_t *strides
Un arreglo de Py_ssize_t de longitud ndim que proporciona el número de bytes que se omiten para
llegar a un nuevo elemento en cada dimensión.
Los valores de stride pueden ser cualquier número entero. Para los arreglos regulares, los pasos son ge-
neralmente positivos, pero un consumidor DEBE ser capaz de manejar el caso strides[n] <= 0.
Ver complex arrays para más información.
El arreglo strides es de sólo lectura para el consumidor.
Py_ssize_t *suboffsets
Un arreglo de Py_ssize_t de longitud ndim. Si suboffsets[n] >= 0, los valores almacenados
a lo largo de la enésima dimensión son punteros y el valor del suboffsets dicta cuántos bytes agregar a cada
puntero después de desreferenciarlos. Un valor de suboffsets negativo indica que no debe producirse una
desreferenciación (striding en un bloque de memoria contiguo).
Si todos los suboffsets son negativos (es decir, no se necesita desreferenciar), entonces este campo debe
ser NULL (el valor predeterminado).
Python Imaging Library (PIL) utiliza este tipo de representación de arreglos. Consulte complex arrays
para obtener más información sobre cómo acceder a los elementos de dicho arreglo.
El arreglo de suboffsets es de sólo lectura para el consumidor.
void *internal
Esto es para uso interno del objeto exportador. Por ejemplo, el exportador podría volver a emitirlo como
un número entero y utilizarlo para almacenar indicadores sobre si las matrices de forma, strides y suboffsets
deben liberarse cuando se libera el búfer. El consumidor NO DEBE alterar este valor.
Constants:
PyBUF_MAX_NDIM
The maximum number of dimensions the memory represents. Exporters MUST respect this limit, consumers
of multi-dimensional buffers SHOULD be able to handle up to PyBUF_MAX_NDIM dimensions. Currently
set to 64.

110 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

7.7.2 Tipos de solicitud búfer

Los búferes obtienen generalmente enviando una solicitud de búfer a un objeto de exportación a través de
PyObject_GetBuffer(). Dado que la complejidad de la estructura lógica de la memoria puede variar drásti-
camente, el consumidor usa el argumento flags para especificar el tipo de búfer exacto que puede manejar.
All Py_buffer fields are unambiguously defined by the request type.

campos independientes de solicitud

Los siguientes campos no están influenciados por flags y siempre deben completarse con los valores correctos: obj,
buf, len, itemsize, ndim.

formato de sólo lectura

PyBUF_WRITABLE
Controla el campo readonly. Si se establece, el exportador DEBE proporcionar un búfer de
escritura o, de lo contrario, informar de un error. De lo contrario, el exportador PUEDE propor-
cionar un búfer de solo lectura o de escritura, pero la elección DEBE ser coherente para todos los
consumidores.
PyBUF_FORMAT
Controla el campo format. Si se establece, este campo DEBE completarse correctamente. De lo
contrario, este campo DEBE ser NULL.
PyBUF_WRITABLE puede ser |”d a cualquiera de las banderas en la siguiente sección. Dado que PyBUF_SIMPLE
se define como 0, PyBUF_WRITABLE puede usarse como un indicador independiente para solicitar un búfer de
escritura simple.
PyBUF_FORMAT puede ser |”d para cualquiera de las banderas excepto PyBUF_SIMPLE. Este último ya implica
el formato B (bytes sin signo).

formas, strides, suboffsets

Las banderas que controlan la estructura lógica de la memoria se enumeran en orden decreciente de complejidad.
Tenga en cuenta que cada bandera contiene todos los bits de las banderas debajo de ella.

Solicitud forma strides suboffsets


sí sí si es necesario
PyBUF_INDIRECT

sí sí NULL
PyBUF_STRIDES

sí NULL NULL
PyBUF_ND

NULL NULL NULL


PyBUF_SIMPLE

7.7. Protocolo búfer 111


The Python/C API, Versión 3.12.4

solicitudes de contigüidad

La contigüidad C o Fortran se puede solicitar explícitamente, con y sin información de paso. Sin información de paso,
el búfer debe ser C-contiguo.

Solicitud forma strides suboffsets contig


sí sí NULL C
PyBUF_C_CONTIGUOUS

sí sí NULL F
PyBUF_F_CONTIGUOUS

sí sí NULL CoF
PyBUF_ANY_CONTIGUOUS

PyBUF_ND sí NULL NULL C

solicitudes compuestas

Todas las solicitudes posibles están completamente definidas por alguna combinación de las banderas en la sección
anterior. Por conveniencia, el protocolo de memoria intermedia proporciona combinaciones de uso frecuente como
indicadores únicos.
En la siguiente tabla U significa contigüidad indefinida. El consumidor tendría que llamar a
PyBuffer_IsContiguous() para determinar la contigüidad.

Solicitud forma strides suboffsets contig sólo lectura formato


sí sí si es necesario U 0 sí
PyBUF_FULL

sí sí si es necesario U 1o0 sí
PyBUF_FULL_RO

sí sí NULL U 0 sí
PyBUF_RECORDS

sí sí NULL U 1o0 sí
PyBUF_RECORDS_RO

sí sí NULL U 0 NULL
PyBUF_STRIDED

sí sí NULL U 1o0 NULL


PyBUF_STRIDED_RO

sí NULL NULL C 0 NULL


PyBUF_CONTIG

sí NULL NULL C 1o0 NULL


PyBUF_CONTIG_RO

112 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

7.7.3 Arreglos complejos

Estilo NumPy: forma y strides

La estructura lógica de las matrices de estilo NumPy está definida por itemsize, ndim, shape y strides.
Si ndim == 0, la ubicación de memoria señalada por buf se interpreta como un escalar de tamaño itemsize.
En ese caso, tanto shape como strides son NULL.
Si strides es NULL, el arreglo se interpreta como un arreglo C n-dimensional estándar. De lo contrario, el consu-
midor debe acceder a un arreglo n-dimensional de la siguiente manera:
ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];
item = *((typeof(item) *)ptr);

Como se señaló anteriormente, buf puede apuntar a cualquier ubicación dentro del bloque de memoria real. Un
exportador puede verificar la validez de un búfer con esta función:
def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
"""Verify that the parameters represent a valid array within
the bounds of the allocated memory:
char *mem: start of the physical memory block
memlen: length of the physical memory block
offset: (char *)buf - mem
"""
if offset % itemsize:
return False
if offset < 0 or offset+itemsize > memlen:
return False
if any(v % itemsize for v in strides):
return False

if ndim <= 0:
return ndim == 0 and not shape and not strides
if 0 in shape:
return True

imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)


if strides[j] <= 0)
imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
if strides[j] > 0)

return 0 <= offset+imin and offset+imax+itemsize <= memlen

Estilo PIL: forma, strides y suboffsets

Además de los elementos normales, los arreglos de estilo PIL pueden contener punteros que deben seguirse para
llegar al siguiente elemento en una dimensión. Por ejemplo, el arreglo C tridimensional regular char v[2][2][3]
también se puede ver como un arreglo de 2 punteros a 2 arreglos bidimensionales: char (*v[2])[2][3]. En
la representación de suboffsets, esos dos punteros pueden incrustarse al comienzo de buf, apuntando a dos matrices
char x[2][3] que pueden ubicarse en cualquier lugar de la memoria.
Aquí hay una función que retorna un puntero al elemento en un arreglo N-D a la que apunta un índice N-dimensional
cuando hay strides y suboffsets no NULL:
void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
Py_ssize_t *suboffsets, Py_ssize_t *indices) {
char *pointer = (char*)buf;
int i;
for (i = 0; i < ndim; i++) {
pointer += strides[i] * indices[i];
(continúe en la próxima página)

7.7. Protocolo búfer 113


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


if (suboffsets[i] >=0 ) {
pointer = *((char**)pointer) + suboffsets[i];
}
}
return (void*)pointer;
}

7.7.4 Funciones relacionadas a búfer

int PyObject_CheckBuffer(PyObject *obj)


Part of the Stable ABI since version 3.11. Retorna 1 si obj admite la interfaz de búfer; de lo contrario, 0
cuando se retorna 1, no garantiza que PyObject_GetBuffer() tenga éxito. Esta función siempre finaliza
con éxito.
int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags)
Part of the Stable ABI since version 3.11. Send a request to exporter to fill in view as specified by flags. If the
exporter cannot provide a buffer of the exact type, it MUST raise BufferError, set view->obj to NULL
and return -1.
Si tiene éxito, completa view, establece view->obj en una nueva referencia a exporter y retorna 0. En el
caso de proveedores de búfer encadenados que redirigen las solicitudes a un solo objeto, view->obj PUEDE
referirse a este objeto en lugar de exporter (Ver Estructuras de objetos de búfer).
Las llamadas exitosas a PyObject_GetBuffer() deben combinarse con las llamadas a
PyBuffer_Release(), similar a malloc() y free(). Por lo tanto, después de que el consu-
midor haya terminado con el búfer, PyBuffer_Release() debe llamarse exactamente una vez.
void PyBuffer_Release(Py_buffer *view)
Part of the Stable ABI since version 3.11. Release the buffer view and release the strong reference (i.e. decrement
the reference count) to the view’s supporting object, view->obj. This function MUST be called when the
buffer is no longer being used, otherwise reference leaks may occur.
Es un error llamar a esta función en un búfer que no se obtuvo a través de PyObject_GetBuffer().
Py_ssize_t PyBuffer_SizeFromFormat(const char *format)
Part of the Stable ABI since version 3.11. Return the implied itemsize from format. On error, raise an
exception and return -1.
Added in version 3.9.
int PyBuffer_IsContiguous(const Py_buffer *view, char order)
Part of the Stable ABI since version 3.11. Retorna 1 si la memoria definida por view es de estilo C (order es
'C') o de estilo Fortran (order es 'F') contiguous o uno cualquiera (order es 'A'). Retorna 0 de lo contrario.
Esta función siempre finaliza con éxito.
void *PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices)
Part of the Stable ABI since version 3.11. Obtiene el área de memoria señalada por los indices dentro del view
dado. indices deben apuntar a un arreglo de índices view->ndim.
int PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
Part of the Stable ABI since version 3.11. Copia len bytes contiguos de buf a view. fort puede ser 'C' o 'F'
(para pedidos al estilo C o al estilo Fortran). 0 se retorna en caso de éxito, -1 en caso de error.
int PyBuffer_ToContiguous(void *buf, const Py_buffer *src, Py_ssize_t len, char order)
Part of the Stable ABI since version 3.11. Copia len bytes de src a su representación contigua en buf. order
puede ser 'C' o 'F' o ''A' (para pedidos al estilo C o al estilo Fortran o cualquiera) 0 se retorna en caso
de éxito, -1 en caso de error.
Esta función falla si len != src->len.

114 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.12.4

int PyObject_CopyData(PyObject *dest, PyObject *src)


Part of the Stable ABI since version 3.11. Copiar datos del búfer src al dest. Puede convertir entre búferes de
estilo C o Fortran.
Se retorna 0 en caso de éxito, -1 en caso de error.
void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize,
char order)
Part of the Stable ABI since version 3.11. Rellena el arreglo strides con bytes de paso de un contiguous (estilo
C si order es 'C' o estilo Fortran si order es 'F ' ) arreglo de la forma dada con el número dado de bytes
por elemento.
int PyBuffer_FillInfo(Py_buffer *view, PyObject *exporter, void *buf, Py_ssize_t len, int readonly, int
flags)
Part of the Stable ABI since version 3.11. Maneje las solicitudes de búfer para un exportador que quiera exponer
buf de tamaño len con capacidad de escritura establecida de acuerdo con readonly. buf se interpreta como una
secuencia de bytes sin signo.
El argumento flags indica el tipo de solicitud. Esta función siempre llena view según lo especificado por flags,
a menos que buf haya sido designado como solo lectura y PyBUF_WRITABLE esté configurado en flags.
On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise BufferError,
set view->obj to NULL and return -1;
Si esta función se usa como parte de a getbufferproc, exporter DEBE establecerse en el objeto exportador y
flags deben pasarse sin modificaciones. De lo contrario, exporter DEBE ser NULL.

7.8 Protocolo de búfer antiguo

Obsoleto desde la versión 3.0.


Estas funciones formaban parte de la API del «antiguo protocolo de búfer» en Python 2. En Python 3, este protocolo
ya no existe, pero las funciones aún están expuestas para facilitar la transferencia del código 2.x. Actúan como una
envoltura de compatibilidad alrededor del nuevo protocolo de búfer, pero no le dan control sobre la vida útil de los
recursos adquiridos cuando se exporta un búfer.
Por lo tanto, se recomienda que llame PyObject_GetBuffer() (o y* o w* format codes con la familia de
funciones PyArg_ParseTuple()) para obtener una vista de búfer sobre un objeto, y PyBuffer_Release()
cuando se puede liberar la vista de búfer.
int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len)
Part of the Stable ABI. Retorna un puntero a una ubicación de memoria de solo lectura que se puede usar como
entrada basada en caracteres. El argumento obj debe admitir la interfaz de búfer de caracteres de segmento
único. En caso de éxito, retorna 0, establece buffer en la ubicación de memoria y buffer_len en la longitud del
búfer. Retorna -1 y lanza TypeError en caso de error.
int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
Part of the Stable ABI. Retorna un puntero a una ubicación de memoria de solo lectura que contiene datos
arbitrarios. El argumento obj debe admitir la interfaz de búfer legible de segmento único. En caso de éxito,
retorna 0, establece buffer en la ubicación de memoria y buffer_len en la longitud del búfer. Retorna -1 y lanza
un TypeError en caso de error.
int PyObject_CheckReadBuffer(PyObject *o)
Part of the Stable ABI. Retorna 1 si o admite la interfaz de búfer legible de segmento único. De lo contrario,
retorna 0. Esta función siempre finaliza con éxito.
Tenga en cuenta que esta función intenta obtener y liberar un búfer, y las excepciones que se produ-
cen al llamar a las funciones correspondientes se suprimirán. Para obtener informes de errores, utilice
PyObject_GetBuffer() en su lugar.

7.8. Protocolo de búfer antiguo 115


The Python/C API, Versión 3.12.4

int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len)


Part of the Stable ABI. Retorna un puntero a una ubicación de memoria de escritura. El argumento obj debe
admitir la interfaz de búfer de caracteres de segmento único. En caso de éxito, retorna 0, establece buffer en
la ubicación de memoria y buffer_len en la longitud del búfer. Retorna -1 y lanza un TypeError en caso de
error.

116 Capítulo 7. Capa de objetos abstractos


CAPÍTULO 8

Capa de objetos concretos

Las funciones de este capítulo son específicas de ciertos tipos de objetos de Python. Pasarles un objeto del tipo
incorrecto no es una buena idea; si recibe un objeto de un programa Python y no está seguro de que tenga el tipo
correcto, primero debe realizar una verificación de tipo; por ejemplo, para verificar que un objeto es un diccionario,
utilice PyDict_Check(). El capítulo está estructurado como el «árbol genealógico» de los tipos de objetos Python.

Advertencia: Si bien las funciones descritas en este capítulo verifican cuidadosamente el tipo de objetos que se
pasan, muchos de ellos no verifican si se pasa NULL en lugar de un objeto válido. Permitir que se pase NULL
puede causar violaciones de acceso a la memoria y la terminación inmediata del intérprete.

8.1 Objetos fundamentales

Esta sección describe los objetos de tipo Python y el objeto singleton None.

8.1.1 Objetos tipo

type PyTypeObject
Part of the Limited API (as an opaque struct). La estructura C de los objetos utilizados para describir los tipos
incorporados.
PyTypeObject PyType_Type
Part of the Stable ABI. Este es el objeto tipo para objetos tipo; es el mismo objeto que type en la capa Python.
int PyType_Check(PyObject *o)
Retorna un valor distinto de cero si el objeto o es un objeto tipo, incluidas las instancias de tipos derivados del
objeto de tipo estándar. Retorna 0 en todos los demás casos. Esta función siempre finaliza con éxito.
int PyType_CheckExact(PyObject *o)
Retorna un valor distinto de cero si el objeto o es un objeto tipo, pero no un subtipo del objeto tipo estándar.
Retorna 0 en todos los demás casos. Esta función siempre finaliza con éxito.
unsigned int PyType_ClearCache()
Part of the Stable ABI. Borra la caché de búsqueda interna. Retorna la etiqueta (tag) de la versión actual.

117
The Python/C API, Versión 3.12.4

unsigned long PyType_GetFlags(PyTypeObject *type)


Part of the Stable ABI. Return the tp_flags member of type. This function is primarily meant for use with
Py_LIMITED_API; the individual flag bits are guaranteed to be stable across Python releases, but access to
tp_flags itself is not part of the limited API.
Added in version 3.2.
Distinto en la versión 3.4: El tipo de retorno es ahora unsigned long en vez de long.
PyObject *PyType_GetDict(PyTypeObject *type)
Return the type object’s internal namespace, which is otherwise only exposed via a read-only proxy (cls.
__dict__). This is a replacement for accessing tp_dict directly. The returned dictionary must be treated
as read-only.
This function is meant for specific embedding and language-binding cases, where direct access to the dict is
necessary and indirect access (e.g. via the proxy or PyObject_GetAttr()) isn’t adequate.
Extension modules should continue to use tp_dict, directly or indirectly, when setting up their own types.
Added in version 3.12.
void PyType_Modified(PyTypeObject *type)
Part of the Stable ABI. Invalida la memoria caché de búsqueda interna para el tipo y todos sus subtipos. Esta
función debe llamarse después de cualquier modificación manual de los atributos o clases base del tipo.
int PyType_AddWatcher(PyType_WatchCallback callback)
Register callback as a type watcher. Return a non-negative integer ID which must be passed to future calls to
PyType_Watch(). In case of error (e.g. no more watcher IDs available), return -1 and set an exception.
Added in version 3.12.
int PyType_ClearWatcher(int watcher_id)
Clear watcher identified by watcher_id (previously returned from PyType_AddWatcher()). Return 0 on
success, -1 on error (e.g. if watcher_id was never registered.)
An extension should never call PyType_ClearWatcher with a watcher_id that was not returned to it by a
previous call to PyType_AddWatcher().
Added in version 3.12.
int PyType_Watch(int watcher_id, PyObject *type)
Mark type as watched. The callback granted watcher_id by PyType_AddWatcher() will be called whe-
never PyType_Modified() reports a change to type. (The callback may be called only once for a series of
consecutive modifications to type, if _PyType_Lookup() is not called on type between the modifications;
this is an implementation detail and subject to change.)
An extension should never call PyType_Watch with a watcher_id that was not returned to it by a previous
call to PyType_AddWatcher().
Added in version 3.12.
typedef int (*PyType_WatchCallback)(PyObject *type)
Type of a type-watcher callback function.
The callback must not modify type or cause PyType_Modified() to be called on type or any type in its
MRO; violating this rule could cause infinite recursion.
Added in version 3.12.
int PyType_HasFeature(PyTypeObject *o, int feature)
Retorna un valor distinto de cero si el tipo objeto o establece la característica feature. Las características de
tipo se indican mediante flags de un solo bit.
int PyType_IS_GC(PyTypeObject *o)
Return true if the type object includes support for the cycle detector; this tests the type flag
Py_TPFLAGS_HAVE_GC.

118 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)


Part of the Stable ABI. Retorna verdadero si a es un subtipo de b.
Esta función solo busca subtipos reales, lo que significa que __subclasscheck__() no se llama en b.
Llama PyObject_IsSubclass() para hacer el mismo chequeo que issubclass() haría.
PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Return value: New reference. Part of the Stable ABI. Controlador genérico para la ranura tp_alloc de un
objeto tipo. Usa el mecanismo de asignación de memoria predeterminado de Python para asignar una nueva
instancia e inicializar todo su contenido a NULL.
PyObject *PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
Return value: New reference. Part of the Stable ABI. Controlador genérico para la ranura tp_new de un objeto
tipo. Crea una nueva instancia utilizando la ranura del tipo tp_alloc.
int PyType_Ready(PyTypeObject *type)
Part of the Stable ABI. Finalizar un objeto tipo. Se debe llamar a todos los objetos tipo para finalizar su
inicialización. Esta función es responsable de agregar ranuras heredadas de la clase base de un tipo. Retorna 0
en caso de éxito o retorna -1 y establece una excepción en caso de error.

Nota: If some of the base classes implements the GC protocol and the provided type does not include the
Py_TPFLAGS_HAVE_GC in its flags, then the GC protocol will be automatically implemented from its pa-
rents. On the contrary, if the type being created does include Py_TPFLAGS_HAVE_GC in its flags then it
must implement the GC protocol itself by at least implementing the tp_traverse handle.

PyObject *PyType_GetName(PyTypeObject *type)


Return value: New reference. Part of the Stable ABI since version 3.11. Retorna el nombre del tipo. Equivalente
a obtener el atributo __name__ del tipo.
Added in version 3.11.
PyObject *PyType_GetQualName(PyTypeObject *type)
Return value: New reference. Part of the Stable ABI since version 3.11. Retorna el nombre adecuado del tipo
de objeto. Equivalente a obtener el atributo __qualname__ del objeto tipo.
Added in version 3.11.
void *PyType_GetSlot(PyTypeObject *type, int slot)
Part of the Stable ABI since version 3.4. Retorna el puntero de función almacenado en la ranura dada. Si el
resultado es NULL, esto indica que la ranura es NULL o que la función se llamó con parámetros no válidos.
Las personas que llaman suelen convertir el puntero de resultado en el tipo de función apropiado.
Consulte PyType_Slot.slot para conocer los posibles valores del argumento slot.
Added in version 3.4.
Distinto en la versión 3.10: PyType_GetSlot() ahora puede aceptar todos los tipos. Anteriormente, estaba
limitado a heap types.
PyObject *PyType_GetModule(PyTypeObject *type)
Part of the Stable ABI since version 3.10. Retorna el objeto módulo asociado con el tipo dado cuando se creó
el tipo usando PyType_FromModuleAndSpec().
Si no hay ningún módulo asociado con el tipo dado, establece TypeError y retorna NULL.
This function is usually used to get the module in which a method is defined. Note that in such a method,
PyType_GetModule(Py_TYPE(self)) may not return the intended result. Py_TYPE(self) may
be a subclass of the intended class, and subclasses are not necessarily defined in the same module as their
superclass. See PyCMethod to get the class that defines the method. See PyType_GetModuleByDef()
for cases when PyCMethod cannot be used.
Added in version 3.9.

8.1. Objetos fundamentales 119


The Python/C API, Versión 3.12.4

void *PyType_GetModuleState(PyTypeObject *type)


Part of the Stable ABI since version 3.10. Retorna el estado del objeto de módulo asociado con el tipo dado.
Este es un atajo para llamar PyModule_GetState() en el resultado de PyType_GetModule().
Si no hay ningún módulo asociado con el tipo dado, establece TypeError y retorna NULL.
Si el tipo type tiene un módulo asociado pero su estado es NULL, retorna NULL sin establecer una excepción.
Added in version 3.9.
PyObject *PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
Encuentra la primer superclase cuyo módulo fue creado a partir del PyModuleDef def dado, y retorna ese
módulo.
Si no se encuentra ningún módulo, lanza TypeError y retorna NULL.
Esta función está pensada para ser utilizada junto con PyModule_GetState() para obtener el estado del
módulo de los métodos de ranura (como tp_init o nb_add) y en otros lugares donde la clase que define a
un método no se puede pasar utilizando la convención de llamada PyCMethod.
Added in version 3.11.
int PyUnstable_Type_AssignVersionTag(PyTypeObject *type)

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

Attempt to assign a version tag to the given type.


Returns 1 if the type already had a valid version tag or a new one was assigned, or 0 if a new tag could not be
assigned.
Added in version 3.12.

Crear tipos asignados en montículo (heap)

Las siguientes funciones y estructuras se utilizan para crear heap types.


PyObject *PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec,
PyObject *bases)
Part of the Stable ABI since version 3.12. Create and return a heap type from the spec (see
Py_TPFLAGS_HEAPTYPE).
The metaclass metaclass is used to construct the resulting type object. When metaclass is NULL, the metaclass
is derived from bases (or Py_tp_base[s] slots if bases is NULL, see below).
Metaclasses that override tp_new are not supported, except if tp_new is NULL. (For backwards compati-
bility, other PyType_From* functions allow such metaclasses. They ignore tp_new, which may result in
incomplete initialization. This is deprecated and in Python 3.14+ such metaclasses will not be supported.)
El argumento bases se puede utilizar para especificar clases base; puede ser solo una clase o una tupla de
clases. Si bases es NULL, en su lugar se utiliza la ranura Py_tp_bases. Si esa también es NULL, se usa la ranura
Py_tp_base en su lugar. Si también es NULL, el nuevo tipo se deriva de object.
El argumento module se puede utilizar para registrar el módulo en el que se define la nueva clase. Debe ser un
objeto de módulo o NULL. Si no es NULL, el módulo se asocia con el nuevo tipo y luego se puede recuperar con
PyType_GetModule(). El módulo asociado no es heredado por subclases; debe especificarse para cada
clase individualmente.
Esta función llama PyType_Ready() en el tipo nuevo.
Note that this function does not fully match the behavior of calling type() or using the class statement.
With user-provided base types or metaclasses, prefer calling type (or the metaclass) over PyType_From*
functions. Specifically:

120 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

• __new__() is not called on the new class (and it must be set to type.__new__).
• __init__() is not called on the new class.
• __init_subclass__() is not called on any bases.
• __set_name__() is not called on new descriptors.
Added in version 3.12.
PyObject *PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
Return value: New reference. Part of the Stable ABI since version 3.10. Equivalent to
PyType_FromMetaclass(NULL, module, spec, bases).
Added in version 3.9.
Distinto en la versión 3.10: La función ahora acepta una sola clase como argumento bases y NULL como ranura
tp_doc.
Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the provided base
classes. Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
PyObject *PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Return value: New reference. Part of the Stable ABI since version 3.3. Equivalent to
PyType_FromMetaclass(NULL, NULL, spec, bases).
Added in version 3.3.
Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the provided base
classes. Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
PyObject *PyType_FromSpec(PyType_Spec *spec)
Return value: New reference. Part of the Stable ABI. Equivalent to PyType_FromMetaclass(NULL,
NULL, spec, NULL).
Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the base classes
provided in Py_tp_base[s] slots. Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
type PyType_Spec
Part of the Stable ABI (including all members). Estructura que define el comportamiento de un tipo.
const char *name
Nombre del tipo, utilizado para establecer PyTypeObject.tp_name.
int basicsize
If positive, specifies the size of the instance in bytes. It is used to set PyTypeObject.
tp_basicsize.
If zero, specifies that tp_basicsize should be inherited.
If negative, the absolute value specifies how much space instances of the class need in addition to the
superclass. Use PyObject_GetTypeData() to get a pointer to subclass-specific memory reserved
this way.
Distinto en la versión 3.12: Previously, this field could not be negative.

8.1. Objetos fundamentales 121


The Python/C API, Versión 3.12.4

int itemsize
Size of one element of a variable-size type, in bytes. Used to set PyTypeObject.tp_itemsize.
See tp_itemsize documentation for caveats.
If zero, tp_itemsize is inherited. Extending arbitrary variable-sized classes is dangerous, since some
types use a fixed offset for variable-sized memory, which can then overlap fixed-sized memory used by a
subclass. To help prevent mistakes, inheriting itemsize is only possible in the following situations:
• The base is not variable-sized (its tp_itemsize).
• The requested PyType_Spec.basicsize is positive, suggesting that the memory layout of the
base class is known.
• The requested PyType_Spec.basicsize is zero, suggesting that the subclass does not access
the instance’s memory directly.
• With the Py_TPFLAGS_ITEMS_AT_END flag.
unsigned int flags
Banderas (flags) del tipo, que se usan para establecer PyTypeObject.tp_flags.
Si el indicador Py_TPFLAGS_HEAPTYPE no está establecido, PyType_FromSpecWithBases()
lo establece automáticamente.
PyType_Slot *slots
Arreglo de estructuras PyType_Slot. Terminado por el valor de ranura especial {0, NULL}.
Each slot ID should be specified at most once.
type PyType_Slot
Part of the Stable ABI (including all members). Estructura que define la funcionalidad opcional de un tipo, que
contiene una ranura ID y un puntero de valor.
int slot

Una ranura ID.


Las ranuras IDs se nombran como los nombres de campo de las estructuras PyTypeObject,
PyNumberMethods, PySequenceMethods, PyMappingMethods y
PyAsyncMethods con un prefijo Py_ agregado. Por ejemplo, use:
• Py_tp_dealloc para establecer PyTypeObject.tp_dealloc
• Py_nb_add para establecer PyNumberMethods.nb_add
• Py_sq_length para establecer PySequenceMethods.sq_length
The following “offset” fields cannot be set using PyType_Slot:
• tp_weaklistoffset (use Py_TPFLAGS_MANAGED_WEAKREF instead if
possible)
• tp_dictoffset (use Py_TPFLAGS_MANAGED_DICT instead if possible)
• tp_vectorcall_offset (use "__vectorcalloffset__" in PyMem-
berDef)
If it is not possible to switch to a MANAGED flag (for example, for vectorcall or to
support Python older than 3.12), specify the offset in Py_tp_members. See Py-
MemberDef documentation for details.
The following fields cannot be set at all when creating a heap type:
• tp_vectorcall (use tp_new and/or tp_init)
• Internal fields: tp_dict, tp_mro, tp_cache, tp_subclasses, and
tp_weaklist.
Setting Py_tp_bases or Py_tp_base may be problematic on some platforms. To avoid
issues, use the bases argument of PyType_FromSpecWithBases() instead.

122 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

Distinto en la versión 3.9: Las ranuras en PyBufferProcs se pueden configurar en la API ilimitada.
Distinto en la versión 3.11: bf_getbuffer and bf_releasebuffer are now available under the
limited API.
void *pfunc
El valor deseado de la ranura. En la mayoría de los casos, este es un puntero a una función.
Las ranuras que no sean Py_tp_doc pueden no ser NULL.

8.1.2 El objeto None

Note that the PyTypeObject for None is not directly exposed in the Python/C API. Since None is a singleton,
testing for object identity (using == in C) is sufficient. There is no PyNone_Check() function for the same reason.

PyObject *Py_None
The Python None object, denoting lack of value. This object has no methods and is immortal.
Distinto en la versión 3.12: Py_None is immortal.
Py_RETURN_NONE
Return Py_None from a function.

8.2 Objetos numéricos

8.2.1 Objetos enteros

Todos los enteros se implementan como objetos enteros «largos» (long) de tamaño arbitrario.
En caso de error, la mayoría de las API PyLong_As* retornan (tipo de retorno) -1 que no se puede
distinguir de un número. Use PyErr_Occurred() para desambiguar.
type PyLongObject
Part of the Limited API (as an opaque struct). Este subtipo de PyObject representa un objeto entero de
Python.
PyTypeObject PyLong_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo entero de Python. Este es el
mismo objeto que int en la capa de Python.
int PyLong_Check(PyObject *p)
Retorna verdadero si su argumento es un PyLongObject o un subtipo de PyLongObject. Esta función
siempre finaliza con éxito.
int PyLong_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyLongObject, pero no un subtipo de PyLongObject. Esta
función siempre finaliza con éxito.
PyObject *PyLong_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde v, o
NULL en caso de error.
The current implementation keeps an array of integer objects for all integers between -5 and 256. When you
create an int in that range you actually just get back a reference to the existing object.
PyObject *PyLong_FromUnsignedLong(unsigned long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C
unsigned long, or NULL on failure.

8.2. Objetos numéricos 123


The Python/C API, Versión 3.12.4

PyObject *PyLong_FromSsize_t(Py_ssize_t v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde un C
Py_ssize_t, o NULL en caso de error.
PyObject *PyLong_FromSize_t(size_t v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde un C
size_t, o NULL en caso de error.
PyObject *PyLong_FromLongLong(long long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C long
long, or NULL on failure.
PyObject *PyLong_FromUnsignedLongLong(unsigned long long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C
unsigned long long, or NULL on failure.
PyObject *PyLong_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto PyLongObject de la parte
entera de v, o NULL en caso de error.
PyObject *PyLong_FromString(const char *str, char **pend, int base)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject based on the string value
in str, which is interpreted according to the radix in base, or NULL on failure. If pend is non-NULL, *pend will
point to the end of str on success or to the first character that could not be processed on error. If base is 0,
str is interpreted using the integers definition; in this case, leading zeros in a non-zero decimal number raises
a ValueError. If base is not 0, it must be between 2 and 36, inclusive. Leading and trailing whitespace
and single underscores after a base specifier and between digits are ignored. If there are no digits or str is not
NULL-terminated following the digits and trailing whitespace, ValueError will be raised.
Ver también:
Python methods int.to_bytes() and int.from_bytes() to convert a PyLongObject to/from an
array of bytes in base 256. You can call those from C using PyObject_CallMethod().
PyObject *PyLong_FromUnicodeObject(PyObject *u, int base)
Return value: New reference. Convierte una secuencia de dígitos Unicode en la cadena de caracteres u en un
valor entero de Python.
Added in version 3.3.
PyObject *PyLong_FromVoidPtr(void *p)
Return value: New reference. Part of the Stable ABI. Crea un entero de Python desde el puntero p. El valor del
puntero se puede recuperar del valor resultante usando PyLong_AsVoidPtr().
long PyLong_AsLong(PyObject *obj)
Part of the Stable ABI. Return a C long representation of obj. If obj is not an instance of PyLongObject,
first call its __index__() method (if present) to convert it to a PyLongObject.
Raise OverflowError if the value of obj is out of range for a long.
Retorna -1 en caso de error. Use PyErr_Occurred() para desambiguar.
Distinto en la versión 3.8: Use __index__() if available.
Distinto en la versión 3.10: This function will no longer use __int__().
long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow)
Part of the Stable ABI. Return a C long representation of obj. If obj is not an instance of PyLongObject,
first call its __index__() method (if present) to convert it to a PyLongObject.
If the value of obj is greater than LONG_MAX or less than LONG_MIN, set *overflow to 1 or -1, respectively,
and return -1; otherwise, set *overflow to 0. If any other exception occurs set *overflow to 0 and return -1
as usual.
Retorna -1 en caso de error. Use PyErr_Occurred() para desambiguar.

124 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

Distinto en la versión 3.8: Use __index__() if available.


Distinto en la versión 3.10: This function will no longer use __int__().
long long PyLong_AsLongLong(PyObject *obj)
Part of the Stable ABI. Return a C long long representation of obj. If obj is not an instance of
PyLongObject, first call its __index__() method (if present) to convert it to a PyLongObject.
Raise OverflowError if the value of obj is out of range for a long long.
Retorna -1 en caso de error. Use PyErr_Occurred() para desambiguar.
Distinto en la versión 3.8: Use __index__() if available.
Distinto en la versión 3.10: This function will no longer use __int__().
long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)
Part of the Stable ABI. Return a C long long representation of obj. If obj is not an instance of
PyLongObject, first call its __index__() method (if present) to convert it to a PyLongObject.
If the value of obj is greater than LLONG_MAX or less than LLONG_MIN, set *overflow to 1 or -1, respectively,
and return -1; otherwise, set *overflow to 0. If any other exception occurs set *overflow to 0 and return -1
as usual.
Retorna -1 en caso de error. Use PyErr_Occurred() para desambiguar.
Added in version 3.2.
Distinto en la versión 3.8: Use __index__() if available.
Distinto en la versión 3.10: This function will no longer use __int__().
Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
Part of the Stable ABI. Retorna una representación de C Py_ssize_t de pylong. pylong debe ser una instancia
de PyLongObject.
Lanza OverflowError si el valor de pylong está fuera de rango para un Py_ssize_t.
Retorna -1 en caso de error. Use PyErr_Occurred() para desambiguar.
unsigned long PyLong_AsUnsignedLong(PyObject *pylong)
Part of the Stable ABI. Return a C unsigned long representation of pylong. pylong must be an instance
of PyLongObject.
Raise OverflowError if the value of pylong is out of range for a unsigned long.
Retorna (unsigned long)-1 en caso de error. Use PyErr_Occurred() para desambiguar.
size_t PyLong_AsSize_t(PyObject *pylong)
Part of the Stable ABI. Retorna una representación de C size_t de pylong. pylong debe ser una instancia de
PyLongObject.
Lanza OverflowError si el valor de pylong está fuera de rango para un size_t.
Retorna (size_t) -1 en caso de error. Use PyErr_Occurred() para desambiguar.
unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)
Part of the Stable ABI. Return a C unsigned long long representation of pylong. pylong must be an
instance of PyLongObject.
Raise OverflowError if the value of pylong is out of range for an unsigned long long.
Retorna (unsigned long long) -1 en caso de error. Use PyErr_Occurred() para desambiguar.
Distinto en la versión 3.1: Ahora un pylong negativo lanza un OverflowError, no TypeError.

8.2. Objetos numéricos 125


The Python/C API, Versión 3.12.4

unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)


Part of the Stable ABI. Return a C unsigned long representation of obj. If obj is not an instance of
PyLongObject, first call its __index__() method (if present) to convert it to a PyLongObject.
If the value of obj is out of range for an unsigned long, return the reduction of that value modulo
ULONG_MAX + 1.
Retorna (unsigned long)-1 en caso de error. Use PyErr_Occurred() para desambiguar.
Distinto en la versión 3.8: Use __index__() if available.
Distinto en la versión 3.10: This function will no longer use __int__().
unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj)
Part of the Stable ABI. Return a C unsigned long long representation of obj. If obj is not an instance
of PyLongObject, first call its __index__() method (if present) to convert it to a PyLongObject.
If the value of obj is out of range for an unsigned long long, return the reduction of that value modulo
ULLONG_MAX + 1.
Retorna (unsigned long long) -1 por error. Use PyErr_Occurred() para desambiguar.
Distinto en la versión 3.8: Use __index__() if available.
Distinto en la versión 3.10: This function will no longer use __int__().
double PyLong_AsDouble(PyObject *pylong)
Part of the Stable ABI. Return a C double representation of pylong. pylong must be an instance of
PyLongObject.
Raise OverflowError if the value of pylong is out of range for a double.
Retorna -1.0 en caso de error. Use PyErr_Occurred() para desambiguar.
void *PyLong_AsVoidPtr(PyObject *pylong)
Part of the Stable ABI. Convert a Python integer pylong to a C void pointer. If pylong cannot be converted,
an OverflowError will be raised. This is only assured to produce a usable void pointer for values created
with PyLong_FromVoidPtr().
Retorna NULL en caso de error. Use PyErr_Occurred() para desambiguar.
int PyUnstable_Long_IsCompact(const PyLongObject *op)

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

Return 1 if op is compact, 0 otherwise.


This function makes it possible for performance-critical code to implement a “fast path” for small integers. For
compact values use PyUnstable_Long_CompactValue(); for others fall back to a PyLong_As*
function or calling int.to_bytes().
The speedup is expected to be negligible for most users.
Exactly what values are considered compact is an implementation detail and is subject to change.
Py_ssize_t PyUnstable_Long_CompactValue(const PyLongObject *op)

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

If op is compact, as determined by PyUnstable_Long_IsCompact(), return its value.


Otherwise, the return value is undefined.

126 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.2.2 Objetos booleanos

Booleans in Python are implemented as a subclass of integers. There are only two booleans, Py_False and
Py_True. As such, the normal creation and deletion functions don’t apply to booleans. The following macros are
available, however.
PyTypeObject PyBool_Type
Part of the Stable ABI. This instance of PyTypeObject represents the Python boolean type; it is the same
object as bool in the Python layer.
int PyBool_Check(PyObject *o)
Retorna verdadero si o es de tipo PyBool_Type. Esta función siempre finaliza con éxito.
PyObject *Py_False
The Python False object. This object has no methods and is immortal.
Distinto en la versión 3.12: Py_False is immortal.
PyObject *Py_True
The Python True object. This object has no methods and is immortal.
Distinto en la versión 3.12: Py_True is immortal.
Py_RETURN_FALSE
Return Py_False from a function.
Py_RETURN_TRUE
Return Py_True from a function.
PyObject *PyBool_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Return Py_True or Py_False, depending on the truth
value of v.

8.2.3 Objetos de punto flotante

type PyFloatObject
Este subtipo de PyObject representa un objeto de punto flotante de Python.
PyTypeObject PyFloat_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de punto flotante de Python. Este
es el mismo objeto que float en la capa de Python.
int PyFloat_Check(PyObject *p)
Retorna verdadero si su argumento es un PyFloatObject o un subtipo de PyFloatObject. Esta función
siempre finaliza con éxito.
int PyFloat_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyFloatObject, pero no un subtipo de PyFloatObject. Esta
función siempre finaliza con éxito.
PyObject *PyFloat_FromString(PyObject *str)
Return value: New reference. Part of the Stable ABI. Crea un objeto PyFloatObject basado en la cadena
de caracteres en str, o NULL en caso de error.
PyObject *PyFloat_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. Crea un objeto PyFloatObject a partir de v, o NULL
en caso de error.

8.2. Objetos numéricos 127


The Python/C API, Versión 3.12.4

double PyFloat_AsDouble(PyObject *pyfloat)


Part of the Stable ABI. Return a C double representation of the contents of pyfloat. If pyfloat is not a Python
floating point object but has a __float__() method, this method will first be called to convert pyfloat into a
float. If __float__() is not defined then it falls back to __index__(). This method returns -1.0 upon
failure, so one should call PyErr_Occurred() to check for errors.
Distinto en la versión 3.8: Use __index__() if available.
double PyFloat_AS_DOUBLE(PyObject *pyfloat)
Retorna una representación C double de los contenidos de pyfloat, pero sin verificación de errores.
PyObject *PyFloat_GetInfo(void)
Return value: New reference. Part of the Stable ABI. Retorna una instancia de structseq que contiene información
sobre la precisión, los valores mínimos y máximos de un flotante. Es un contenedor reducido alrededor del
archivo de encabezado float.h.
double PyFloat_GetMax()
Part of the Stable ABI. Retorna el máximo flotante finito representable DBL_MAX como C double.
double PyFloat_GetMin()
Part of the Stable ABI. Retorna el flotante positivo normalizado mínimo DBL_MIN como C double.

Funciones de empaquetado y desempaquetado

Las funciones de empaquetar y desempaquetar proporcionan una manera eficiente e independiente de la plataforma
para almacenar valores de coma flotante como cadenas de bytes. Las rutinas Pack producen una cadena de bytes a
partir de un C double, y las rutinas Desempaquetar producen un C double a partir de dicha cadena de bytes. El
sufijo (2, 4 u 8) especifica el número de bytes en la cadena de bytes.
En plataformas que parecen usar formatos IEEE 754, estas funciones actúan copiando los bits. En otras plataformas,
el formato 2-byte es idéntico al formato de media precision IEEE 754 binary16, el formato de 4-byte (32 bits) es
idéntico al formato de precisión simple binario IEEE 754 binary32, y el formato de 8-byte al formato de doble
precisión binario IEEE 754 binary64, aunque el empaquetado de INFs y NaNs (si existen en la plataforma) no se
maneja correctamente, mientras que intentar desempaquetar una cadena de bytes que contenga un IEEE INF o NaN
generará una excepción.
En plataformas que no son IEEE con más precisión, o mayor rango dinámico, que el IEEE 754 admite, no se pue-
den empaquetar todos los valores; en plataformas que no son IEEE con menos precisión o con un rango dinámico
más pequeño, no se pueden desempaquetar todos los valores. Lo que sucede en tales casos es en parte accidental
(desafortunadamente).
Added in version 3.11.

Funciones de Empaquetado

The pack routines write 2, 4 or 8 bytes, starting at p. le is an int argument, non-zero if you want the bytes string in
little-endian format (exponent last, at p+1, p+3, or p+6 p+7), zero if you want big-endian format (exponent first,
at p). The PY_BIG_ENDIAN constant can be used to use the native endian: it is equal to 1 on big endian processor,
or 0 on little endian processor.
Valor retornado: 0 si todo está bien, -1 si hay error (y se establece una excepción, probablemente
OverflowError).
Hay dos problemas en plataformas que no son IEEE:
• Lo que esto hace es indefinido si x es un NaN o infinito.
• -0.0 and +0.0 produce la misma cadena de bytes.
int PyFloat_Pack2(double x, unsigned char *p, int le)
Empaquete un C doble como el formato de media precisión IEEE 754 binary16.

128 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

int PyFloat_Pack4(double x, unsigned char *p, int le)


Empaque un C doble como el formato de precisión simple IEEE 754 binary32.
int PyFloat_Pack8(double x, unsigned char *p, int le)
Empaque un C doble como el formato de doble precisión IEEE 754 binary64.

Funciones de Desempaquetado

The unpack routines read 2, 4 or 8 bytes, starting at p. le is an int argument, non-zero if the bytes string is in
little-endian format (exponent last, at p+1, p+3 or p+6 and p+7), zero if big-endian (exponent first, at p). The
PY_BIG_ENDIAN constant can be used to use the native endian: it is equal to 1 on big endian processor, or 0 on
little endian processor.
Valor retornado: Doble desempaquetado. Si hay error, -1.0 y PyErr_Occurred() es verdadero (y se establece
una excepción, probablemente OverflowError).
Hay que tener en cuenta que en una plataforma que no sea IEEE, esto se negará a desempaquetar una cadena de bytes
que representa un NaN o infinito.
double PyFloat_Unpack2(const unsigned char *p, int le)
Descomprima el formato de media precisión IEEE 754 binary16 como un doble C.
double PyFloat_Unpack4(const unsigned char *p, int le)
Descomprima el formato de precisión simple IEEE 754 binary32 como un doble C.
double PyFloat_Unpack8(const unsigned char *p, int le)
Descomprima el formato de doble precisión IEEE 754 binary64 como un doble C.

8.2.4 Objetos de números complejos

Los objetos de números complejos de Python se implementan como dos tipos distintos cuando se ven desde la API
de C: uno es el objeto de Python expuesto a los programas de Python, y el otro es una estructura en C que representa
el valor de número complejo real. La API proporciona funciones para trabajar con ambos.

Números complejos como estructuras C

Tenga en cuenta que las funciones que aceptan estas estructuras como parámetros y las retornan como resultados lo
hacen por valor en lugar de desreferenciarlas a través de punteros. Esto es consistente en toda la API.
type Py_complex
La estructura C que corresponde a la porción de valor de un objeto de número complejo de Python. La mayoría
de las funciones para tratar con objetos de números complejos utilizan estructuras de este tipo como valores
de entrada o salida, según corresponda. Se define como:

typedef struct {
double real;
double imag;
} Py_complex;

Py_complex _Py_c_sum(Py_complex left, Py_complex right)


Retorna la suma de dos números complejos, utilizando la representación C Py_complex.
Py_complex _Py_c_diff(Py_complex left, Py_complex right)
Retorna la diferencia entre dos números complejos, usando la representación C Py_complex.
Py_complex _Py_c_neg(Py_complex num)
Retorna la negación del número complejo num, utilizando la representación C Py_complex.

8.2. Objetos numéricos 129


The Python/C API, Versión 3.12.4

Py_complex _Py_c_prod(Py_complex left, Py_complex right)


Retorna el producto de dos números complejos, usando la representación C Py_complex.
Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor)
Retorna el cociente de dos números complejos, utilizando la representación C Py_complex.
If divisor is null, this method returns zero and sets errno to EDOM.
Py_complex _Py_c_pow(Py_complex num, Py_complex exp)
Retorna la exponenciación de num por exp, utilizando la representación C Py_complex.
If num is null and exp is not a positive real number, this method returns zero and sets errno to EDOM.

Números complejos como objetos de Python

type PyComplexObject
Este subtipo de PyObject representa un objeto de número complejo de Python.
PyTypeObject PyComplex_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de número complejo de Python.
Es el mismo objeto que complex en la capa de Python.
int PyComplex_Check(PyObject *p)
Retorna verdadero si su argumento es un PyComplexObject o un subtipo de PyComplexObject. Esta
función siempre finaliza con éxito.
int PyComplex_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyComplexObject, pero no un subtipo de PyComplexObject.
Esta función siempre finaliza con éxito.
PyObject *PyComplex_FromCComplex(Py_complex v)
Return value: New reference. Crea un nuevo objeto de número complejo de Python a partir de un valor C
Py_complex.
PyObject *PyComplex_FromDoubles(double real, double imag)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto PyComplexObject de real e
imag.
double PyComplex_RealAsDouble(PyObject *op)
Part of the Stable ABI. Return the real part of op as a C double.
double PyComplex_ImagAsDouble(PyObject *op)
Part of the Stable ABI. Return the imaginary part of op as a C double.
Py_complex PyComplex_AsCComplex(PyObject *op)
Retorna el valor Py_complex del número complejo op.
If op is not a Python complex number object but has a __complex__() method, this method will first be
called to convert op to a Python complex number object. If __complex__() is not defined then it falls back
to __float__(). If __float__() is not defined then it falls back to __index__(). Upon failure, this
method returns -1.0 as a real value.
Distinto en la versión 3.8: Use __index__() if available.

130 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.3 Objetos de secuencia

Las operaciones genéricas en los objetos de secuencia se discutieron en el capítulo anterior; Esta sección trata sobre
los tipos específicos de objetos de secuencia que son intrínsecos al lenguaje Python.

8.3.1 Objetos bytes

Estas funciones lanzan TypeError cuando se espera un parámetro de bytes y se llama con un parámetro que no es
bytes.
type PyBytesObject
Este subtipo de PyObject representa un objeto bytes de Python.
PyTypeObject PyBytes_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo bytes de Python; es el mismo
objeto que bytes en la capa de Python.
int PyBytes_Check(PyObject *o)
Retorna verdadero si el objeto o es un objeto bytes o una instancia de un subtipo del tipo bytes. Esta función
siempre finaliza con éxito.
int PyBytes_CheckExact(PyObject *o)
Retorna verdadero si el objeto o es un objeto bytes, pero no una instancia de un subtipo del tipo bytes. Esta
función siempre finaliza con éxito.
PyObject *PyBytes_FromString(const char *v)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto bytes con una copia de la cadena
de caracteres v como valor en caso de éxito y NULL en caso de error. El parámetro v no debe ser NULL; no se
comprobará.
PyObject *PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto bytes con una copia de la cadena
de caracteres v como valor y longitud len en caso de éxito y NULL en caso de error. Si v es NULL, el contenido
del objeto bytes no se inicializa.
PyObject *PyBytes_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI. Toma una cadena de caracteres format del estilo C
printf() y un número variable de argumentos, calcula el tamaño del objeto bytes Python resultante y
retorna un objeto bytes con los valores formateados. Los argumentos variables deben ser tipos C y deben
corresponder exactamente a los caracteres de formato en la cadena de caracteres format. Se permiten los
siguientes caracteres de formato:

8.3. Objetos de secuencia 131


The Python/C API, Versión 3.12.4

Caracteres de formato Tipo Comentario


%% n/a El carácter literal %.
%c int Un solo byte, representado como un C int.
%d int Equivalente a printf("%d").1
%u unsigned int Equivalente a printf("%u").Página 132, 1
%ld long Equivalente a printf("%ld").1
%lu unsigned long Equivalente a printf("%lu").1
%zd Py_ssize_t Equivalente a printf("%zd").1
%zu size_t Equivalente a printf("%zu").1
%i int Equivalente a printf("%i").1
%x int Equivalente a printf("%x").1
%s const char* Un arreglo de caracteres C terminados en nulo.
%p const void* La representación hexadecimal de un puntero en C.
Principalmente equivalente a printf("%p") excepto
que se garantiza que comience con el literal 0x,
independientemente de lo que produzca el printf de la
plataforma.

Un carácter de formato no reconocido hace que todo el resto de la cadena de caracteres de formato se copie
como está en el objeto de resultado y se descartan los argumentos adicionales.
PyObject *PyBytes_FromFormatV(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Idéntica a PyBytes_FromFormat() excepto que
toma exactamente dos argumentos.
PyObject *PyBytes_FromObject(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna la representación en bytes del objeto o que im-
plementa el protocolo de búfer.
Py_ssize_t PyBytes_Size(PyObject *o)
Part of the Stable ABI. Retorna la longitud de los bytes en el objeto bytes o.
Py_ssize_t PyBytes_GET_SIZE(PyObject *o)
Forma macro de PyBytes_Size() pero sin verificación de errores.
char *PyBytes_AsString(PyObject *o)
Part of the Stable ABI. Retorna un puntero al contenido de o. El puntero se refiere al búfer interno de o, que
consiste en len(o) + 1 bytes. El último byte en el búfer siempre es nulo, independientemente de si hay
otros bytes nulos. Los datos no deben modificarse de ninguna manera, a menos que el objeto se haya creado
usando PyBytes_FromStringAndSize(NULL, size). No debe ser desasignado. Si o no es un objeto
de bytes en absoluto, PyBytes_AsString() retorna NULL y lanza un TypeError.
char *PyBytes_AS_STRING(PyObject *string)
Forma macro de PyBytes_AsString() pero sin verificación de errores.
int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
Part of the Stable ABI. Return the null-terminated contents of the object obj through the output variables buffer
and length. Returns 0 on success.
Si length es NULL, el objeto bytes no puede contener bytes nulos incrustados; en caso contrario, la función
retorna -1 y se lanza un ValueError.
El búfer se refiere a un búfer interno de obj, que incluye un byte nulo adicional al final (no está considerado
en length). Los datos no deben modificarse de ninguna manera, a menos que el objeto se haya creado usando
PyBytes_FromStringAndSize(NULL, size). No debe ser desasignado. Si obj no es un objeto bytes
en absoluto, PyBytes_AsStringAndSize() retorna -1 y lanza TypeError.
Distinto en la versión 3.5: Anteriormente, TypeError se lanzaba cuando se encontraban bytes nulos incrus-
tados en el objeto bytes.
1 Para especificadores de enteros (d, u, ld, lu, zd, zu, i, x): el indicador de conversión 0 tiene efecto incluso cuando se proporciona una precisión.

132 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

void PyBytes_Concat(PyObject **bytes, PyObject *newpart)


Part of the Stable ABI. Crea un nuevo objeto de bytes en *bytes que contiene el contenido de newpart agregado
a bytes; la persona que llama poseerá la nueva referencia. La referencia al valor anterior de bytes será robada.
Si no se puede crear el nuevo objeto, la referencia anterior a bytes se seguirá descartando y el valor de *bytes
se establecerá en NULL; se establecerá la excepción apropiada.
void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart)
Part of the Stable ABI. Create a new bytes object in *bytes containing the contents of newpart appended to
bytes. This version releases the strong reference to newpart (i.e. decrements its reference count).
int _PyBytes_Resize(PyObject **bytes, Py_ssize_t newsize)
Una forma de cambiar el tamaño de un objeto bytes aunque sea «inmutable». Solo use esto para construir un
nuevo objeto bytes; no use esto si los bytes ya pueden ser conocidos en otras partes del código. Es un error
llamar a esta función si el recuento en el objeto bytes de entrada no es uno. Pasa la dirección de un objeto de
bytes existente como un lvalue (puede escribirse en él) y el nuevo tamaño deseado. En caso de éxito, *bytes
retiene el objeto de bytes redimensionados y se retorna 0; la dirección en *bytes puede diferir de su valor de
entrada. Si la reasignación falla, el objeto de bytes original en *bytes se desasigna, *bytes se establece en NULL,
MemoryError se establece y se retorna -1 .

8.3.2 Objetos de arreglos de bytes (bytearrays)

type PyByteArrayObject
Este subtipo de PyObject representa un objeto arreglo de bytes de Python.
PyTypeObject PyByteArray_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo arreglo de bytes de Python; es el
mismo objeto que bytearray en la capa de Python.

Macros de verificación de tipos

int PyByteArray_Check(PyObject *o)


Retorna verdadero si el objeto o es un objeto de arreglo de bytes o una instancia de un subtipo del tipo arreglo
de bytes. Esta función siempre finaliza con éxito.
int PyByteArray_CheckExact(PyObject *o)
Retorna verdadero si el objeto o es un objeto de arreglo de bytes, pero no una instancia de un subtipo del tipo
arreglo de bytes. Esta función siempre finaliza con éxito.

Funciones API directas

PyObject *PyByteArray_FromObject(PyObject *o)


Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto de arreglo de bytes de cualquier
objeto, o, que implementa el buffer protocol.
PyObject *PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Crea un nuevo objeto de arreglo de bytes a partir de string
y su longitud, len. En caso de fallo, se retorna NULL.
PyObject *PyByteArray_Concat(PyObject *a, PyObject *b)
Return value: New reference. Part of the Stable ABI. Une los arreglos de bytes (bytearrays) a y b y retorna un
nuevo arreglo de bytes (bytearray) con el resultado.
Py_ssize_t PyByteArray_Size(PyObject *bytearray)
Part of the Stable ABI. Retorna el tamaño de bytearray después de buscar un puntero NULL.

8.3. Objetos de secuencia 133


The Python/C API, Versión 3.12.4

char *PyByteArray_AsString(PyObject *bytearray)


Part of the Stable ABI. Retorna el contenido de bytearray como un arreglo de caracteres después de verificar
un puntero NULL. La arreglo retornado siempre tiene un byte nulo adicional agregado.
int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len)
Part of the Stable ABI. Cambia el tamaño del búfer interno de bytearray a len.

Macros

Estos macros intercambian seguridad por velocidad y no comprueban punteros.


char *PyByteArray_AS_STRING(PyObject *bytearray)
Similar a PyByteArray_AsString(), pero sin comprobación de errores.
Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray)
Similar a PyByteArray_Size(), pero sin comprobación de errores.

8.3.3 Objetos y códecs unicode

Objetos unicode

Desde la implementación del PEP 393 en Python 3.3, los objetos Unicode utilizan internamente una variedad de
representaciones, para permitir el manejo del rango completo de caracteres Unicode mientras se mantiene la eficiencia
de memoria. Hay casos especiales para cadenas de caracteres donde todos los puntos de código están por debajo de
128, 256 o 65536; de lo contrario, los puntos de código deben estar por debajo de 1114112 (que es el rango completo
de Unicode).
UTF-8 representation is created on demand and cached in the Unicode object.

Nota: The Py_UNICODE representation has been removed since Python 3.12 with deprecated APIs. See PEP 623
for more information.

Tipo unicode

Estos son los tipos básicos de objetos Unicode utilizados para la implementación de Unicode en Python:
type Py_UCS4
type Py_UCS2
type Py_UCS1
Part of the Stable ABI. Estos tipos son definiciones de tipo (typedefs) para los tipos “enteros sin signo” (unsigned
int) lo suficientemente anchos como para contener caracteres de 32 bits, 16 bits y 8 bits, respectivamente.
Cuando se trate con caracteres Unicode individuales, use Py_UCS4.
Added in version 3.3.
type Py_UNICODE
This is a typedef of wchar_t, which is a 16-bit type or 32-bit type depending on the platform.
Distinto en la versión 3.3: En versiones anteriores, este era un tipo de 16 bits o de 32 bits, dependiendo de si
seleccionó una versión Unicode «estrecha» o «amplia» de Python en el momento de la compilación.
type PyASCIIObject
type PyCompactUnicodeObject

134 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

type PyUnicodeObject
Estos subtipos de PyObject representan un objeto Python Unicode. En casi todos los casos, no deben usarse
directamente, ya que todas las funciones API que se ocupan de objetos Unicode toman y retornan punteros
PyObject.
Added in version 3.3.
PyTypeObject PyUnicode_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo Python Unicode. Está expuesto
al código de Python como str.
The following APIs are C macros and static inlined functions for fast checks and access to internal read-only data of
Unicode objects:
int PyUnicode_Check(PyObject *obj)
Return true if the object obj is a Unicode object or an instance of a Unicode subtype. This function always
succeeds.
int PyUnicode_CheckExact(PyObject *obj)
Return true if the object obj is a Unicode object, but not an instance of a subtype. This function always succeeds.
int PyUnicode_READY(PyObject *unicode)
Returns 0. This API is kept only for backward compatibility.
Added in version 3.3.
Obsoleto desde la versión 3.10: This API does nothing since Python 3.12.
Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)
Return the length of the Unicode string, in code points. unicode has to be a Unicode object in the «canonical»
representation (not checked).
Added in version 3.3.
Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *unicode)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *unicode)
Py_UCS4 *PyUnicode_4BYTE_DATA(PyObject *unicode)
Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 integer types for direct cha-
racter access. No checks are performed if the canonical representation has the correct character size; use
PyUnicode_KIND() to select the right function.
Added in version 3.3.
PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND
Retorna los valores de la macro PyUnicode_KIND().
Added in version 3.3.
Distinto en la versión 3.12: PyUnicode_WCHAR_KIND has been removed.
int PyUnicode_KIND(PyObject *unicode)
Return one of the PyUnicode kind constants (see above) that indicate how many bytes per character this Uni-
code object uses to store its data. unicode has to be a Unicode object in the «canonical» representation (not
checked).
Added in version 3.3.
void *PyUnicode_DATA(PyObject *unicode)
Return a void pointer to the raw Unicode buffer. unicode has to be a Unicode object in the «canonical» repre-
sentation (not checked).
Added in version 3.3.

8.3. Objetos de secuencia 135


The Python/C API, Versión 3.12.4

void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, Py_UCS4 value)


Write into a canonical representation data (as obtained with PyUnicode_DATA()). This function performs
no sanity checks, and is intended for usage in loops. The caller should cache the kind value and data pointer
as obtained from other calls. index is the index in the string (starts at 0) and value is the new code point value
which should be written to that location.
Added in version 3.3.
Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index)
Lee un punto de código de una representación canónica data (obtenido con PyUnicode_DATA()). No se
realizan verificaciones ni llamadas preparadas.
Added in version 3.3.
Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)
Read a character from a Unicode object unicode, which must be in the «canonical» representation. This is less
efficient than PyUnicode_READ() if you do multiple consecutive reads.
Added in version 3.3.
Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *unicode)
Return the maximum code point that is suitable for creating another string based on unicode, which must be
in the «canonical» representation. This is always an approximation but more efficient than iterating over the
string.
Added in version 3.3.
int PyUnicode_IsIdentifier(PyObject *unicode)
Part of the Stable ABI. Retorna 1 si la cadena de caracteres es un identificador válido de acuerdo con la
definición del lenguaje, sección identifiers. Retorna 0 de lo contrario.
Distinto en la versión 3.9: La función ya no llama a Py_FatalError() si la cadena de caracteres no está
lista.

Propiedades de caracteres Unicode

Unicode proporciona muchas propiedades de caracteres diferentes. Los que se necesitan con mayor frecuencia están
disponibles a través de estas macros que se asignan a las funciones de C según la configuración de Python.
int Py_UNICODE_ISSPACE(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter de espacio en blanco.
int Py_UNICODE_ISLOWER(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter en minúscula.
int Py_UNICODE_ISUPPER(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter en mayúscula.
int Py_UNICODE_ISTITLE(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter en caso de título (titlecase).
int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter de salto de línea.
int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter decimal o no.
int Py_UNICODE_ISDIGIT(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter de dígitos.
int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter numérico.

136 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

int Py_UNICODE_ISALPHA(Py_UCS4 ch)


Retorna 1 o 0 dependiendo de si ch es un carácter alfabético.
int Py_UNICODE_ISALNUM(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter alfanumérico.
int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter imprimible. Los caracteres no imprimibles son aquellos
definidos en la base de datos de caracteres Unicode como «Otro» o «Separador», excepto el espacio ASCII
(0x20) que se considera imprimible. (Tenga en cuenta que los caracteres imprimibles en este contexto son
aquellos a los que no se debe escapar cuando repr() se invoca en una cadena de caracteres. No tiene relación
con el manejo de cadenas de caracteres escritas en sys.stdout o sys.stderr.)
Estas API se pueden usar para conversiones caracteres rápidas y directos:
Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)
Retorna el carácter ch convertido a minúsculas.
Obsoleto desde la versión 3.3: Esta función utiliza conversiones simples.
Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)
Retorna el carácter ch convertido a mayúsculas.
Obsoleto desde la versión 3.3: Esta función utiliza conversiones simples.
Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)
Retorna el carácter ch convertido a formato de título (titlecase).
Obsoleto desde la versión 3.3: Esta función utiliza conversiones simples.
int Py_UNICODE_TODECIMAL(Py_UCS4 ch)
Return the character ch converted to a decimal positive integer. Return -1 if this is not possible. This function
does not raise exceptions.
int Py_UNICODE_TODIGIT(Py_UCS4 ch)
Return the character ch converted to a single digit integer. Return -1 if this is not possible. This function does
not raise exceptions.
double Py_UNICODE_TONUMERIC(Py_UCS4 ch)
Return the character ch converted to a double. Return -1.0 if this is not possible. This function does not raise
exceptions.
Estas API se pueden usar para trabajar con sustitutos:
int Py_UNICODE_IS_SURROGATE(Py_UCS4 ch)
Comprueba si ch es un sustituto (0xD800 <= ch <= 0xDFFF).
int Py_UNICODE_IS_HIGH_SURROGATE(Py_UCS4 ch)
Comprueba si ch es un sustituto alto (0xD800 <= ch <= 0xDFFF).
int Py_UNICODE_IS_LOW_SURROGATE(Py_UCS4 ch)
Comprueba si ch es un sustituto bajo (0xD800 <= ch <= 0xDFFF).
Py_UCS4 Py_UNICODE_JOIN_SURROGATES(Py_UCS4 high, Py_UCS4 low)
Join two surrogate characters and return a single Py_UCS4 value. high and low are respectively the leading
and trailing surrogates in a surrogate pair. high must be in the range [0xD800; 0xDBFF] and low must be in
the range [0xDC00; 0xDFFF].

8.3. Objetos de secuencia 137


The Python/C API, Versión 3.12.4

Creando y accediendo a cadenas de caracteres Unicode

Para crear objetos Unicode y acceder a sus propiedades de secuencia básicas, use estas API:
PyObject *PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
Return value: New reference. Crea un nuevo objeto Unicode. maxchar debe ser el punto de código máximo que
se colocará en la cadena de caracteres. Como una aproximación, se puede redondear al valor más cercano en
la secuencia 127, 255, 65535, 1114111.
Esta es la forma recomendada de asignar un nuevo objeto Unicode. Los objetos creados con esta función no se
pueden redimensionar.
Added in version 3.3.
PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
Return value: New reference. Crea un nuevo objeto Unicode con el tipo kind dado (los valores posibles son
PyUnicode_1BYTE_KIND etc., según lo retornado por PyUnicode_KIND()). El búfer debe apuntar a
un vector (array) de tamaño unidades de 1, 2 o 4 bytes por carácter, según el tipo.
Si es necesario, la entrada buffer se copia y se transforma en la representación canónica. Por ejemplo, si el
buffer es una cadena de caracteres UCS4 (PyUnicode_4BYTE_KIND) y consta solo de puntos de código
en el rango UCS1, se transformará en UCS1 (PyUnicode_1BYTE_KIND).
Added in version 3.3.
PyObject *PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from the char buffer str. The bytes
will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. The return value might
be a shared object, i.e. modification of the data is not allowed.
This function raises SystemError when:
• size < 0,
• str is NULL and size > 0
Distinto en la versión 3.12: str == NULL with size > 0 is not allowed anymore.
PyObject *PyUnicode_FromString(const char *str)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from a UTF-8 encoded null-
terminated char buffer str.
PyObject *PyUnicode_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI. Take a C printf()-style format string and a variable
number of arguments, calculate the size of the resulting Python Unicode string and return a string with the
values formatted into it. The variable arguments must be C types and must correspond exactly to the format
characters in the format ASCII-encoded string.
A conversion specifier contains two or more characters and has the following components, which must occur
in this order:
1. The '%' character, which marks the start of the specifier.
2. Conversion flags (optional), which affect the result of some conversion types.
3. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is given in the next
argument, which must be of type int, and the object to convert comes after the minimum field width
and optional precision.
4. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk),
the actual precision is given in the next argument, which must be of type int, and the value to convert
comes after the precision.
5. Length modifier (optional).
6. Conversion type.

138 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

The conversion flag characters are:

Flag Meaning
0 The conversion will be zero padded for numeric values.
- The converted value is left adjusted (overrides the 0 flag if both are given).

The length modifiers for following integer conversions (d, i, o, u, x, or X) specify the type of the argument
(int by default):

Modifier Types
l long or unsigned long
ll long long or unsigned long long
j intmax_t or uintmax_t
z size_t or ssize_t
t ptrdiff_t

The length modifier l for following conversions s or V specify that the type of the argument is const
wchar_t*.
The conversion specifiers are:

Con- Tipo Comentario


version
Speci-
fier
% n/a The literal % character.
d, i Specified by the The decimal representation of a signed C integer.
length modifier
u Specified by the The decimal representation of an unsigned C integer.
length modifier
o Specified by the The octal representation of an unsigned C integer.
length modifier
x Specified by the The hexadecimal representation of an unsigned C integer (lowercase).
length modifier
X Specified by the The hexadecimal representation of an unsigned C integer (uppercase).
length modifier
c int A single character.
s const char* or Un arreglo de caracteres de C terminada en nulo.
const wchar_t*
p const void* The hex representation of a C pointer. Mostly equivalent to
printf("%p") except that it is guaranteed to start with the literal
0x regardless of what the platform’s printf yields.
A PyObject* El resultado de llamar ascii().
U PyObject* Un objeto unicode.
V PyObject*, Un objeto Unicode (que puede ser NULL) y un arreglo de caracteres
const char* or de C terminada en nulo como segundo parámetro (que se utilizará, si
const wchar_t* el primer parámetro es NULL).
S PyObject* El resultado de llamar PyObject_Str().
R PyObject* El resultado de llamar PyObject_Repr().

Nota: The width formatter unit is number of characters rather than bytes. The precision formatter unit is
number of bytes or wchar_t items (if the length modifier l is used) for "%s" and "%V" (if the PyObject*

8.3. Objetos de secuencia 139


The Python/C API, Versión 3.12.4

argument is NULL), and a number of characters for "%A", "%U", "%S", "%R" and "%V" (if the PyObject*
argument is not NULL).

Nota: Unlike to C printf() the 0 flag has effect even when a precision is given for integer conversions (d,
i, u, o, x, or X).

Distinto en la versión 3.2: Soporte agregado para "%lld" y "%llu".


Distinto en la versión 3.3: Soporte agregado para "%li", "%lli" y "%zi".
Distinto en la versión 3.4: Soporte agregado para formateadores de anchura y precisión para "%s", "%A",
"%U", "%V", "%S", "%R".
Distinto en la versión 3.12: Support for conversion specifiers o and X. Support for length modifiers j and t.
Length modifiers are now applied to all integer conversions. Length modifier l is now applied to conversion
specifiers s and V. Support for variable width and precision *. Support for flag -.
An unrecognized format character now sets a SystemError. In previous versions it caused all the rest of
the format string to be copied as-is to the result string, and any extra arguments discarded.
PyObject *PyUnicode_FromFormatV(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Idéntico a PyUnicode_FromFormat() excepto que
toma exactamente dos argumentos.
PyObject *PyUnicode_FromObject(PyObject *obj)
Return value: New reference. Part of the Stable ABI. Copy an instance of a Unicode subtype to a new true
Unicode object if necessary. If obj is already a true Unicode object (not a subtype), return a new strong reference
to the object.
Los objetos que no sean Unicode o sus subtipos causarán un TypeError.
PyObject *PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. Decodifica un objeto codificado obj en un objeto Unicode.
bytes, bytearray y otros los objetos similares a bytes se decodifican de acuerdo con el encoding dado y
utilizan el manejo de errores definido por errors. Ambos pueden ser NULL para que la interfaz use los valores
predeterminados (ver Códecs incorporados para más detalles).
Todos los demás objetos, incluidos los objetos Unicode, hacen que se establezca un TypeError.
La API retorna NULL si hubo un error. La entidad que hace la llamadas es la responsable de desreferenciar los
objetos retornados.
Py_ssize_t PyUnicode_GetLength(PyObject *unicode)
Part of the Stable ABI since version 3.7. Retorna la longitud del objeto Unicode, en puntos de código.
Added in version 3.3.
Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t
from_start, Py_ssize_t how_many)
Copy characters from one Unicode object into another. This function performs character conversion when
necessary and falls back to memcpy() if possible. Returns -1 and sets an exception on error, otherwise
returns the number of copied characters.
Added in version 3.3.
Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)
Rellena una cadena con un carácter: escriba fill_char en unicode[inicio:inicio+longitud].
Falla si fill_char es más grande que el carácter máximo de la cadena, o si la cadena tiene más de 1 referencia.
Retorna el número de caracteres escritos o retorna -1 y lanza una excepción en caso de error.
Added in version 3.3.

140 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 character)


Part of the Stable ABI since version 3.7. Escribe un carácter en una cadena de caracteres. La cadena debe
haberse creado a través de PyUnicode_New(). Dado que se supone que las cadenas de caracteres Unicode
son inmutables, la cadena no debe compartirse o no se ha cifrado todavía.
Esta función comprueba que unicode es un objeto Unicode, que el índice no está fuera de los límites y que el
objeto se puede modificar de forma segura (es decir, si su número de referencia es uno).
Added in version 3.3.
Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
Part of the Stable ABI since version 3.7. Read a character from a string. This function checks that unicode
is a Unicode object and the index is not out of bounds, in contrast to PyUnicode_READ_CHAR(), which
performs no error checking.
Added in version 3.3.
PyObject *PyUnicode_Substring(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
Return value: New reference. Part of the Stable ABI since version 3.7. Return a substring of unicode, from
character index start (included) to character index end (excluded). Negative indices are not supported.
Added in version 3.3.
Py_UCS4 *PyUnicode_AsUCS4(PyObject *unicode, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)
Part of the Stable ABI since version 3.7. Copy the string unicode into a UCS4 buffer, including a null character,
if copy_null is set. Returns NULL and sets an exception on error (in particular, a SystemError if buflen is
smaller than the length of unicode). buffer is returned on success.
Added in version 3.3.
Py_UCS4 *PyUnicode_AsUCS4Copy(PyObject *unicode)
Part of the Stable ABI since version 3.7. Copy the string unicode into a new UCS4 buffer that is allocated using
PyMem_Malloc(). If this fails, NULL is returned with a MemoryError set. The returned buffer always
has an extra null code point appended.
Added in version 3.3.

Codificación regional

La codificación local actual se puede utilizar para decodificar texto del sistema operativo.
PyObject *PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t length, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7. Decodifica una cadena de caracteres
UTF-8 en Android y VxWorks, o de la codificación de configuración regional actual en otras plataformas. Los
manejadores de errores admitidos son "estricto" y "subrogateescape" (PEP 383). El decodifica-
dor usa el controlador de errores "estricto" si errors es NULL. str debe terminar con un carácter nulo pero
no puede contener caracteres nulos incrustados.
Use PyUnicode_DecodeFSDefaultAndSize() to decode a string from the filesystem encoding and
error handler.
Esta función ignora el modo Python UTF-8.
Ver también:
La función Py_DecodeLocale().
Added in version 3.3.
Distinto en la versión 3.7: La función ahora también usa la codificación de configuración regional actual para el
controlador de errores subrogateescape, excepto en Android. Anteriormente, Py_DecodeLocale()
se usaba para el subrogateescape, y la codificación local actual se usaba para estricto.

8.3. Objetos de secuencia 141


The Python/C API, Versión 3.12.4

PyObject *PyUnicode_DecodeLocale(const char *str, const char *errors)


Return value: New reference. Part of the Stable ABI since version 3.7. Similar to
PyUnicode_DecodeLocaleAndSize(), but compute the string length using strlen().
Added in version 3.3.
PyObject *PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7. Codifica un objeto Unicode UTF-8
en Android y VxWorks, o en la codificación local actual en otras plataformas. Los manejadores de errores
admitidos son "estricto" y "subrogateescape" (PEP 383). El codificador utiliza el controlador de
errores "estricto" si errors es NULL. Retorna un objeto bytes. unicode no puede contener caracteres
nulos incrustados.
Use PyUnicode_EncodeFSDefault() to encode a string to the filesystem encoding and error handler.
Esta función ignora el modo Python UTF-8.
Ver también:
La función Py_EncodeLocale().
Added in version 3.3.
Distinto en la versión 3.7: La función ahora también usa la codificación de configuración regional actual para el
controlador de errores subrogateescape, excepto en Android. Anteriormente, Py_EncodeLocale()
se usaba para el subrogateescape, y la codificación local actual se usaba para estricto.

Codificación del sistema de archivos

Functions encoding to and decoding from the filesystem encoding and error handler (PEP 383 and PEP 529).
To encode file names to bytes during argument parsing, the "O&" converter should be used, passing
PyUnicode_FSConverter() as the conversion function:
int PyUnicode_FSConverter(PyObject *obj, void *result)
Part of the Stable ABI. ParseTuple converter: encode str objects – obtained directly or through the os.
PathLike interface – to bytes using PyUnicode_EncodeFSDefault(); bytes objects are output
as-is. result must be a PyBytesObject* which must be released when it is no longer used.
Added in version 3.1.
Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).
Para decodificar nombres de archivo a str durante el análisis de argumentos, se debe usar el convertidor "O&",
pasando PyUnicode_FSDecoder() como la función de conversión:
int PyUnicode_FSDecoder(PyObject *obj, void *result)
Part of the Stable ABI. ParseTuple converter: decode bytes objects – obtained either directly or indirectly
through the os.PathLike interface – to str using PyUnicode_DecodeFSDefaultAndSize();
str objects are output as-is. result must be a PyUnicodeObject* which must be released when it is no
longer used.
Added in version 3.2.
Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).
PyObject *PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Decodifica una cadena desde el codificador de sistema de
archivos y gestor de errores.
If you need to decode a string from the current locale encoding, use
PyUnicode_DecodeLocaleAndSize().
Ver también:
La función Py_DecodeLocale().

142 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

Distinto en la versión 3.6: The filesystem error handler is now used.


PyObject *PyUnicode_DecodeFSDefault(const char *str)
Return value: New reference. Part of the Stable ABI. Decodifica una cadena terminada en nulo desde el codi-
ficador de sistema de archivos y gestor de errores.
If the string length is known, use PyUnicode_DecodeFSDefaultAndSize().
Distinto en la versión 3.6: The filesystem error handler is now used.
PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Encode a Unicode object to the filesystem encoding and
error handler, and return bytes. Note that the resulting bytes object can contain null bytes.
If you need to encode a string to the current locale encoding, use PyUnicode_EncodeLocale().
Ver también:
La función Py_EncodeLocale().
Added in version 3.2.
Distinto en la versión 3.6: The filesystem error handler is now used.

soporte wchar_t

wchar_t support for platforms which support it:


PyObject *PyUnicode_FromWideChar(const wchar_t *wstr, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from the wchar_t buffer
wstr of the given size. Passing -1 as the size indicates that the function must itself compute the length, using
wcslen(). Return NULL on failure.
Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *wstr, Py_ssize_t size)
Part of the Stable ABI. Copy the Unicode object contents into the wchar_t buffer wstr. At most size
wchar_t characters are copied (excluding a possibly trailing null termination character). Return the number
of wchar_t characters copied or -1 in case of an error.
When wstr is NULL, instead return the size that would be required to store all of unicode including a terminating
null.
Note that the resulting wchar_t* string may or may not be null-terminated. It is the responsibility of the caller
to make sure that the wchar_t* string is null-terminated in case this is required by the application. Also, note
that the wchar_t* string might contain null characters, which would cause the string to be truncated when
used with most C functions.
wchar_t *PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)
Part of the Stable ABI since version 3.7. Convert the Unicode object to a wide character string. The output
string always ends with a null character. If size is not NULL, write the number of wide characters (excluding
the trailing null termination character) into *size. Note that the resulting wchar_t string might contain null
characters, which would cause the string to be truncated when used with most C functions. If size is NULL and
the wchar_t* string contains null characters a ValueError is raised.
Returns a buffer allocated by PyMem_New (use PyMem_Free() to free it) on success. On error, returns
NULL and *size is undefined. Raises a MemoryError if memory allocation is failed.
Added in version 3.2.
Distinto en la versión 3.7: Raises a ValueError if size is NULL and the wchar_t* string contains null
characters.

8.3. Objetos de secuencia 143


The Python/C API, Versión 3.12.4

Códecs incorporados

Python proporciona un conjunto de códecs integrados que están escritos en C para mayor velocidad. Todos estos
códecs se pueden usar directamente a través de las siguientes funciones.
Muchas de las siguientes API toman dos argumentos de encoding y errors, y tienen la misma semántica que las del
constructor de objetos de cadena incorporado str().
Setting encoding to NULL causes the default encoding to be used which is UTF-8. The file system calls should
use PyUnicode_FSConverter() for encoding file names. This uses the filesystem encoding and error handler
internally.
El manejo de errores se establece mediante errors que también pueden establecerse en NULL, lo que significa usar el
manejo predeterminado definido para el códec. El manejo de errores predeterminado para todos los códecs integrados
es «estricto» (se lanza ValueError).
The codecs all use a similar interface. Only deviations from the following generic ones are documented for simplicity.

Códecs genéricos

Estas son las APIs de códecs genéricos:


PyObject *PyUnicode_Decode(const char *str, Py_ssize_t size, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
encoded string str. encoding and errors have the same meaning as the parameters of the same name in the
str() built-in function. The codec to be used is looked up using the Python codec registry. Return NULL if
an exception was raised by the codec.
PyObject *PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode y retorna el resultado como un
objeto de bytes de Python. encoding y errors tienen el mismo significado que los parámetros del mismo nombre
en el método Unicode encode(). El códec que se utilizará se busca utilizando el registro de códec Python.
Retorna NULL si el códec provocó una excepción.

Códecs UTF-8

Estas son las APIs del códec UTF-8:


PyObject *PyUnicode_DecodeUTF8(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
UTF-8 encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeUTF8Stateful(const char *str, Py_ssize_t size, const char *errors,
Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF8(). Si consumed no es NULL, las secuencias de bytes UTF-8 incompletas no se
tratarán como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados
se almacenará en consumed.
PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando UTF-8 y retorna el
resultado como un objeto de bytes de Python. El manejo de errores es «estricto». Retorna NULL si el códec
provocó una excepción.
const char *PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)
Part of the Stable ABI since version 3.10. Retorna un puntero a la codificación UTF-8 del objeto Unicode y
almacena el tamaño de la representación codificada (en bytes) en size. El argumento size puede ser NULL; en
este caso no se almacenará el tamaño. El búfer retornado siempre tiene un byte nulo adicional agregado (no
incluido en size), independientemente de si hay otros puntos de código nulo.

144 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

En caso de error, se retorna NULL con un conjunto de excepciones y no se almacena size.


This caches the UTF-8 representation of the string in the Unicode object, and subsequent calls will return a
pointer to the same buffer. The caller is not responsible for deallocating the buffer. The buffer is deallocated
and pointers to it become invalid when the Unicode object is garbage collected.
Added in version 3.3.
Distinto en la versión 3.7: El tipo de retorno ahora es const char * en lugar de char *.
Distinto en la versión 3.10: This function is a part of the limited API.
const char *PyUnicode_AsUTF8(PyObject *unicode)
Como PyUnicode_AsUTF8AndSize(), pero no almacena el tamaño.
Added in version 3.3.
Distinto en la versión 3.7: El tipo de retorno ahora es const char * en lugar de char *.

Códecs UTF-32

Estas son las APIs de códecs para UTF-32:


PyObject *PyUnicode_DecodeUTF32(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
Return value: New reference. Part of the Stable ABI. Decodifica size bytes de una cadena de búfer codificada
UTF-32 y retorna el objeto Unicode correspondiente. errors (si no es NULL) define el manejo de errores. Su
valor predeterminado es «estricto».
Si byteorder no es NULL, el decodificador comienza a decodificar utilizando el orden de bytes dado:

*byteorder == -1: little endian


*byteorder == 0: native order
*byteorder == 1: big endian

Si *byteorder es cero, y los primeros cuatro bytes de los datos de entrada son una marca de orden de bytes
(BOM), el decodificador cambia a este orden de bytes y la BOM no se copia en la cadena de caracteres Unicode
resultante. Si *byteorder es -1 o 1, cualquier marca de orden de bytes se copia en la salida.
Una vez completado, *byteorder se establece en el orden de bytes actual al final de los datos de entrada.
Si byteorder es NULL, el códec se inicia en modo de orden nativo.
Retorna NULL si el códec provocó una excepción.
PyObject *PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF32(). Si consumed no es NULL, PyUnicode_DecodeUTF32Stateful()
no tratará las secuencias de bytes UTF-32 incompletas finales (como un número de bytes no divisible por cua-
tro) como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se
almacenará en consumed.
PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Retorna una cadena de bytes de Python usando la codi-
ficación UTF-32 en orden de bytes nativo. La cadena siempre comienza con una marca BOM. El manejo de
errores es «estricto». Retorna NULL si el códec provocó una excepción.

8.3. Objetos de secuencia 145


The Python/C API, Versión 3.12.4

Códecs UTF-16

Estas son las APIs de códecs para UTF-16:


PyObject *PyUnicode_DecodeUTF16(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
Return value: New reference. Part of the Stable ABI. Decodifica size bytes de una cadena de caracteres de búfer
codificada UTF-16 y retorna el objeto Unicode correspondiente. errors (si no es NULL) define el manejo de
errores. Su valor predeterminado es «estricto».
Si byteorder no es NULL, el decodificador comienza a decodificar utilizando el orden de bytes dado:

*byteorder == -1: little endian


*byteorder == 0: native order
*byteorder == 1: big endian

Si *byteorder es cero, y los primeros dos bytes de los datos de entrada son una marca de orden de bytes
(BOM), el decodificador cambia a este orden de bytes y la BOM no se copia en la cadena de caracteres Unicode
resultante. Si *byteorder es -1 o 1, cualquier marca de orden de bytes se copia en la salida (donde dará
como resultado un \ufeff o un carácter \ufffe).
After completion, *byteorder is set to the current byte order at the end of input data.
Si byteorder es NULL, el códec se inicia en modo de orden nativo.
Retorna NULL si el códec provocó una excepción.
PyObject *PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF16(). Si consumed no es NULL, PyUnicode_DecodeUTF16Stateful()
no tratará las secuencias de bytes UTF-16 incompletas finales (como un número impar de bytes o un par sustitu-
to dividido) como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados
se almacenará en consumed.
PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Retorna una cadena de bytes de Python usando la codi-
ficación UTF-16 en orden de bytes nativo. La cadena siempre comienza con una marca BOM. El manejo de
errores es «estricto». Retorna NULL si el códec provocó una excepción.

Códecs UTF-7

Estas son las APIs del códec UTF-7:


PyObject *PyUnicode_DecodeUTF7(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
UTF-7 encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeUTF7Stateful(const char *str, Py_ssize_t size, const char *errors,
Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF7(). Si consumed no es NULL, las secciones UTF-7 base-64 incompletas no
se tratarán como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados
se almacenará en consumed.

146 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

Códecs Unicode escapado

Estas son las APIs de códecs para Unicode escapado:


PyObject *PyUnicode_DecodeUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
Unicode-Escape encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando Unicode escapado
(Unicode-Escape) y retorna el resultado como un objeto de bytes. El manejo de errores es «estricto». Retorna
NULL si el códec provocó una excepción.

Códecs para Unicode escapado en bruto

Estas son las API del códec Unicode escapado en bruto (Raw Unicode Escape):
PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
Raw-Unicode-Escape encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando Unicode escapado en
bruto (Raw-Unicode-Escape) y retorna el resultado como un objeto de bytes. El manejo de errores es «estricto».
Retorna NULL si el códec provocó una excepción.

Códecs Latin-1

Estas son las API del códec Latin-1: Latin-1 corresponde a los primeros 256 ordinales Unicode y solo estos son
aceptados por los códecs durante la codificación.
PyObject *PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
Latin-1 encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando Latin-1 y retorna
el resultado como un objeto de bytes Python. El manejo de errores es «estricto». Retorna NULL si el códec
provocó una excepción.

Códecs ASCII

Estas son las API del códec ASCII. Solo se aceptan datos ASCII de 7 bits. Todos los demás códigos generan errores.
PyObject *PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
ASCII encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando ASCII y retorna el
resultado como un objeto de bytes de Python. El manejo de errores es «estricto». Retorna NULL si el códec
provocó una excepción.

8.3. Objetos de secuencia 147


The Python/C API, Versión 3.12.4

Códecs de mapa de caracteres

This codec is special in that it can be used to implement many different codecs (and this is in fact what was done
to obtain most of the standard codecs included in the encodings package). The codec uses mappings to enco-
de and decode characters. The mapping objects provided must support the __getitem__() mapping interface;
dictionaries and sequences work well.
Estos son las API de códec de mapeo:
PyObject *PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, PyObject *mapping, const char
*errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
encoded string str using the given mapping object. Return NULL if an exception was raised by the codec.
Si mapping es NULL, se aplicará la decodificación Latin-1. De lo contrario, mapping debe asignar bytes ordi-
nales (enteros en el rango de 0 a 255) a cadenas de caracteres Unicode, enteros (que luego se interpretan como
ordinales Unicode) o None. Los bytes de datos sin asignar - los que causan un LookupError, así como los
que se asignan a None, 0xFFFE o '\ ufffe', se tratan como asignaciones indefinidas y causan un error.
PyObject *PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando el objeto mapping
dado y retorna el resultado como un objeto de bytes. El manejo de errores es «estricto». Retorna NULL si el
códec provocó una excepción.
El objeto mapping debe asignar enteros ordinales Unicode a objetos de bytes, enteros en el rango de 0 a 255 o
None. Los ordinales de caracteres no asignados (los que causan un LookupError), así como los asignados
a Ninguno, se tratan como «mapeo indefinido» y causan un error.
La siguiente API de códec es especial en que asigna Unicode a Unicode.
PyObject *PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
Return value: New reference. Part of the Stable ABI. Traduce una cadena de caracteres aplicando una tabla de
mapeo y retornando el objeto Unicode resultante. Retorna NULL cuando el códec provocó una excepción.
La tabla de mapeo debe mapear enteros ordinales Unicode a enteros ordinales Unicode o None (causando la
eliminación del carácter).
Mapping tables need only provide the __getitem__() interface; dictionaries and sequences work well.
Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is.
errors tiene el significado habitual para los códecs. Puede ser NULL, lo que indica que debe usar el manejo de
errores predeterminado.

Códecs MBCS para Windows

Estas son las API de códec MBCS. Actualmente solo están disponibles en Windows y utilizan los convertidores Win32
MBCS para implementar las conversiones. Tenga en cuenta que MBCS (o DBCS) es una clase de codificaciones, no
solo una. La codificación de destino está definida por la configuración del usuario en la máquina que ejecuta el códec.

PyObject *PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors)


Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Create a Unicode object by
decoding size bytes of the MBCS encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeMBCSStateful(const char *str, Py_ssize_t size, const char *errors,
Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Si con-
sumed es NULL, se comporta como PyUnicode_DecodeMBCS(). Si consumed no es NULL,
PyUnicode_DecodeMBCSStateful() no decodificará el byte inicial y el número de bytes que se han
decodificado se almacenará en consumed.

148 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

PyObject *PyUnicode_AsMBCSString(PyObject *unicode)


Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Codifica un objeto Unicode
usando MBCS y retorna el resultado como un objeto de bytes de Python. El manejo de errores es «estricto».
Retorna NULL si el códec provocó una excepción.
PyObject *PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Encode the Unicode object
using the specified code page and return a Python bytes object. Return NULL if an exception was raised by the
codec. Use CP_ACP code page to get the MBCS encoder.
Added in version 3.3.

Métodos & Ranuras (Slots)

Métodos y funciones de ranura (Slot)

Las siguientes API son capaces de manejar objetos Unicode y cadenas de caracteres en la entrada (nos referimos a
ellos como cadenas de caracteres en las descripciones) y retorna objetos Unicode o enteros según corresponda.
Todos retornan NULL o -1 si ocurre una excepción.
PyObject *PyUnicode_Concat(PyObject *left, PyObject *right)
Return value: New reference. Part of the Stable ABI. Une dos cadenas de caracteres que dan una nueva cadena
de caracteres Unicode.
PyObject *PyUnicode_Split(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
Return value: New reference. Part of the Stable ABI. Divide una cadena de caracteres dando una lista de cadenas
de caracteres Unicode. Si sep es NULL, la división se realizará en todas las subcadenas de espacios en blanco.
De lo contrario, las divisiones ocurren en el separador dado. A lo sumo se realizarán maxsplit divisiones. Si es
negativo, no se establece ningún límite. Los separadores no están incluidos en la lista resultante.
PyObject *PyUnicode_Splitlines(PyObject *unicode, int keepends)
Return value: New reference. Part of the Stable ABI. Split a Unicode string at line breaks, returning a list of
Unicode strings. CRLF is considered to be one line break. If keepends is 0, the Line break characters are not
included in the resulting strings.
PyObject *PyUnicode_Join(PyObject *separator, PyObject *seq)
Return value: New reference. Part of the Stable ABI. Une una secuencia de cadenas de caracteres usando el
separator dado y retorna la cadena de caracteres Unicode resultante.
Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
Part of the Stable ABI. Return 1 if substr matches unicode[start:end] at the given tail end (direction
== -1 means to do a prefix match, direction == 1 a suffix match), 0 otherwise. Return -1 if an error occurred.
Py_ssize_t PyUnicode_Find(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
Part of the Stable ABI. Return the first position of substr in unicode[start:end] using the given direction
(direction == 1 means to do a forward search, direction == -1 a backward search). The return value is the index
of the first match; a value of -1 indicates that no match was found, and -2 indicates that an error occurred
and an exception has been set.
Py_ssize_t PyUnicode_FindChar(PyObject *unicode, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int
direction)
Part of the Stable ABI since version 3.7. Return the first position of the character ch in
unicode[start:end] using the given direction (direction == 1 means to do a forward search, di-
rection == -1 a backward search). The return value is the index of the first match; a value of -1 indicates that
no match was found, and -2 indicates that an error occurred and an exception has been set.
Added in version 3.3.

8.3. Objetos de secuencia 149


The Python/C API, Versión 3.12.4

Distinto en la versión 3.7: start and end are now adjusted to behave like unicode[start:end].
Py_ssize_t PyUnicode_Count(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
Part of the Stable ABI. Return the number of non-overlapping occurrences of substr in
unicode[start:end]. Return -1 if an error occurred.
PyObject *PyUnicode_Replace(PyObject *unicode, PyObject *substr, PyObject *replstr, Py_ssize_t
maxcount)
Return value: New reference. Part of the Stable ABI. Replace at most maxcount occurrences of substr in unicode
with replstr and return the resulting Unicode object. maxcount == -1 means replace all occurrences.
int PyUnicode_Compare(PyObject *left, PyObject *right)
Part of the Stable ABI. Compara dos cadenas de caracteres y retorna -1, 0, 1 para menor que, igual y mayor
que, respectivamente.
Esta función retorna -1 en caso de falla, por lo que se debe llamar a PyErr_Occurred() para verificar si
hay errores.
int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
Part of the Stable ABI. Compare a Unicode object, unicode, with string and return -1, 0, 1 for less than, equal,
and greater than, respectively. It is best to pass only ASCII-encoded strings, but the function interprets the input
string as ISO-8859-1 if it contains non-ASCII characters.
Esta función no lanza excepciones.
PyObject *PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Return value: New reference. Part of the Stable ABI. Comparación enriquecida de dos cadenas de caracteres
Unicode y retorna uno de los siguientes:
• NULL en caso de que se produzca una excepción
• Py_True or Py_False for successful comparisons
• Py_NotImplemented in case the type combination is unknown
Possible values for op are Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, and Py_LE.
PyObject *PyUnicode_Format(PyObject *format, PyObject *args)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto de cadena de caracteres desde
format y args; esto es análogo al format % args.
int PyUnicode_Contains(PyObject *unicode, PyObject *substr)
Part of the Stable ABI. Check whether substr is contained in unicode and return true or false accordingly.
substr has to coerce to a one element Unicode string. -1 is returned if there was an error.
void PyUnicode_InternInPlace(PyObject **p_unicode)
Part of the Stable ABI. Intern the argument *p_unicode in place. The argument must be the address of a
pointer variable pointing to a Python Unicode string object. If there is an existing interned string that is the same
as *p_unicode, it sets *p_unicode to it (releasing the reference to the old string object and creating a new
strong reference to the interned string object), otherwise it leaves *p_unicode alone and interns it (creating
a new strong reference). (Clarification: even though there is a lot of talk about references, think of this function
as reference-neutral; you own the object after the call if and only if you owned it before the call.)
PyObject *PyUnicode_InternFromString(const char *str)
Return value: New reference. Part of the Stable ABI. Una combinación de PyUnicode_FromString() y
PyUnicode_InternInPlace(), que retorna un nuevo objeto de cadena de caracteres Unicode que ha
sido creado internamente o una nueva referencia(«propia») a un objeto de cadena de caracteres interno anterior
con el mismo valor.

150 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.3.4 Objetos tupla

type PyTupleObject
Este subtipo de PyObject representa un objeto tupla de Python.
PyTypeObject PyTuple_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo tupla de Python; es el mismo
objeto que tuple en la capa de Python.
int PyTuple_Check(PyObject *p)
Retorna verdadero si p es un objeto tupla o una instancia de un subtipo del tipo tupla. Esta función siempre
finaliza con éxito.
int PyTuple_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto tupla pero no una instancia de un subtipo del tipo tupla. Esta función
siempre finaliza con éxito.
PyObject *PyTuple_New(Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto tupla de tamaño len o NULL en
caso de falla.
PyObject *PyTuple_Pack(Py_ssize_t n, ...)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto tupla de tamaño n, o NULL en
caso de falla. Los valores de tupla se inicializan en los argumentos C posteriores n que apuntan a objetos de
Python. PyTuple_Pack (2, a, b) es equivalente a Py_BuildValue("(OO)", a, b).
Py_ssize_t PyTuple_Size(PyObject *p)
Part of the Stable ABI. Toma un puntero a un objeto de tupla y retorna el tamaño de esa tupla.
Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
Retorna el tamaño de la tupla p, que no debe ser NULL y apunta a una tupla; No se realiza ninguna comprobación
de errores.
PyObject *PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto en la posición pos en la tupla señala-
da por p. Si pos es negativo o está fuera de los límites, retorna NULL y establece una excepción IndexError.
The returned reference is borrowed from the tuple p (that is: it is only valid as long as you hold
a reference to p). To get a strong reference, use Py_NewRef(PyTuple_GetItem(...)) or
PySequence_GetItem().
PyObject *PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Como PyTuple_GetItem(), pero no verifica sus argumentos.
PyObject *PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)
Return value: New reference. Part of the Stable ABI. Return the slice of the tuple pointed to by p between low
and high, or NULL on failure. This is the equivalent of the Python expression p[low:high]. Indexing from
the end of the tuple is not supported.
int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Part of the Stable ABI. Inserta una referencia al objeto o en la posición pos de la tupla señalada por p. Retorna
0 en caso de éxito. Si pos está fuera de límites, retorna -1 y establece una excepción IndexError.

Nota: Esta función «roba» una referencia a o y descarta una referencia a un elemento que ya está en la tupla
en la posición afectada.

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


Al igual que PyTuple_SetItem(), pero no realiza ninguna comprobación de errores, y debe solo usarse
para completar tuplas nuevas.

8.3. Objetos de secuencia 151


The Python/C API, Versión 3.12.4

Nota: Esta función «roba» una referencia a o y, a diferencia de PyTuple_SetItem(), no descarta una
referencia a ningún elemento que se está reemplazando; cualquier referencia en la tupla en la posición pos se
filtrará.

int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)


Se puede usar para cambiar el tamaño de una tupla. newsize será el nuevo tamaño de la tupla. Debido a que se
supone que las tuplas son inmutables, esto solo debe usarse si solo hay una referencia al objeto. No use esto si
la tupla ya puede ser conocida por alguna otra parte del código. La tupla siempre crecerá o disminuirá al final.
Piense en esto como destruir la antigua tupla y crear una nueva, solo que de manera más eficiente. Retorna 0
en caso de éxito. El código del cliente nunca debe suponer que el valor resultante de *p será el mismo que
antes de llamar a esta función. Si se reemplaza el objeto referenciado por *p, se destruye el original *p. En
caso de fallo, retorna -1 y establece *p en NULL, y lanza MemoryError o SystemError.

8.3.5 Objetos de secuencia de estructura

Los objetos de secuencia de estructura son el equivalente en C de los objetos namedtuple(), es decir, una se-
cuencia a cuyos elementos también se puede acceder a través de atributos. Para crear una secuencia de estructura,
primero debe crear un tipo de secuencia de estructura específico.
PyTypeObject *PyStructSequence_NewType(PyStructSequence_Desc *desc)
Return value: New reference. Part of the Stable ABI. Crea un nuevo tipo de secuencia de estructura a partir
de los datos en desc, que se describen a continuación. Las instancias del tipo resultante se pueden crear con
PyStructSequence_New().
void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)
Inicializa una secuencia de estructura tipo type desde desc en su lugar.
int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc)
Lo mismo que PyStructSequence_InitType, pero retorna 0 en caso de éxito y -1 en caso de error.
Added in version 3.4.
type PyStructSequence_Desc
Part of the Stable ABI (including all members). Contiene la meta información de un tipo de secuencia de
estructura para crear.
const char *name
Name of the struct sequence type.
const char *doc
Pointer to docstring for the type or NULL to omit.
PyStructSequence_Field *fields
Pointer to NULL-terminated array with field names of the new type.
int n_in_sequence
Number of fields visible to the Python side (if used as tuple).
type PyStructSequence_Field
Part of the Stable ABI (including all members). Describes a field of a struct sequence. As a struct sequen-
ce is modeled as a tuple, all fields are typed as PyObject*. The index in the fields array of the
PyStructSequence_Desc determines which field of the struct sequence is described.
const char *name
Name for the field or NULL to end the list of named fields, set to
PyStructSequence_UnnamedField to leave unnamed.
const char *doc
Field docstring or NULL to omit.

152 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

const char *const PyStructSequence_UnnamedField


Part of the Stable ABI since version 3.11. Valor especial para un nombre de campo para dejarlo sin nombre.
Distinto en la versión 3.9: El tipo se cambió de char *.
PyObject *PyStructSequence_New(PyTypeObject *type)
Return value: New reference. Part of the Stable ABI. Crea una instancia de type, que debe haberse creado con
PyStructSequence_NewType().
PyObject *PyStructSequence_GetItem(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto en la posición pos en la secuencia
de estructura apuntada por p. No se realiza la comprobación de límites.
PyObject *PyStructSequence_GET_ITEM(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Macro equivalente de PyStructSequence_GetItem().
void PyStructSequence_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Part of the Stable ABI. Establece el campo en el índice pos de la secuencia de estructura p en el valor o. Como
PyTuple_SET_ITEM(), esto solo debe usarse para completar instancias nuevas.

Nota: Esta función «roba» una referencia a o.

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


Similar a PyStructSequence_SetItem(), pero implementada como una función estática inline.

Nota: Esta función «roba» una referencia a o.

8.3.6 Objetos lista

type PyListObject
Este subtipo de PyObject representa un objeto lista de Python.
PyTypeObject PyList_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de lista de Python. Este es el
mismo objeto que list en la capa de Python.
int PyList_Check(PyObject *p)
Retorna verdadero si p es un objeto de lista o una instancia de un subtipo del tipo lista. Esta función siempre
finaliza con éxito.
int PyList_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto lista, pero no una instancia de un subtipo del tipo lista. Esta función siempre
finaliza con éxito.
PyObject *PyList_New(Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Retorna una nueva lista de longitud len en caso de éxito o
NULL en caso de error.

Nota: Si len es mayor que cero, los elementos del objeto de la lista retornada se establecen en NULL. Por lo
tanto, no puede utilizar funciones API abstractas como PySequence_SetItem() o exponer el objeto al
código Python antes de configurar todos los elementos en un objeto real con PyList_SetItem().

Py_ssize_t PyList_Size(PyObject *list)


Part of the Stable ABI. Retorna la longitud del objeto lista en list; esto es equivalente a len(list) en un
objeto lista.

8.3. Objetos de secuencia 153


The Python/C API, Versión 3.12.4

Py_ssize_t PyList_GET_SIZE(PyObject *list)


Similar to PyList_Size(), but without error checking.
PyObject *PyList_GetItem(PyObject *list, Py_ssize_t index)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto en la posición index en la lista a la
que apunta list. La posición no debe ser negativa; La indexación desde el final de la lista no es compatible. Si
index está fuera de los límites (<0 o >= len(list)), retorna NULL y establece una excepción IndexError.
PyObject *PyList_GET_ITEM(PyObject *list, Py_ssize_t i)
Return value: Borrowed reference. Similar to PyList_GetItem(), but without error checking.
int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)
Part of the Stable ABI. Establece el elemento en el índice index en la lista a item. Retorna 0 en caso de éxito.
Si index está fuera de límites, retorna -1 y establece una excepción IndexError.

Nota: Esta función «roba» una referencia a item y descarta una referencia a un elemento que ya está en la lista
en la posición afectada.

void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o)


Forma macro de PyList_SetItem() sin comprobación de errores. Esto normalmente solo se usa para
completar nuevas listas donde no hay contenido anterior.

Nota: Este macro «roba» una referencia a item y, a diferencia de PyList_SetItem(), no descarta una
referencia a ningún elemento que se está reemplazando; cualquier referencia en list en la posición i se filtrará.

int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item)


Part of the Stable ABI. Inserta el elemento item en la lista list delante del índice index. Retorna 0 si tiene éxito;
retorna -1 y establece una excepción si no tiene éxito. Análogo a list.insert(index, item).
int PyList_Append(PyObject *list, PyObject *item)
Part of the Stable ABI. Agrega el objeto item al final de la lista list. Retorna 0 si tiene éxito; retorna -1 y
establece una excepción si no tiene éxito. Análogo a list.append(item).
PyObject *PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high)
Return value: New reference. Part of the Stable ABI. Retorna una lista de los objetos en list que contie-
ne los objetos between, low y high. Retorna NULL y establece una excepción si no tiene éxito. Análogo a
list[low:high]. La indexación desde el final de la lista no es compatible.
int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)
Part of the Stable ABI. Establece el segmento de list entre low y high para el contenido de itemlist. Análogo
a list[low:high] = itemlist. La lista itemlist puede ser NULL, lo que indica la asignación de una
lista vacía (eliminación de segmentos). Retorna 0 en caso de éxito, -1 en caso de error. La indexación desde
el final de la lista no es compatible.
int PyList_Sort(PyObject *list)
Part of the Stable ABI. Ordena los elementos de list en su lugar. Retorna 0 en caso de éxito, -1 en caso de
error. Esto es equivalente a list.sort().
int PyList_Reverse(PyObject *list)
Part of the Stable ABI. Invierte los elementos de la lista list en su lugar. Retorna 0 en caso de éxito, -1 en caso
de error. Este es el equivalente de list.reverse().
PyObject *PyList_AsTuple(PyObject *list)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto tupla que contiene el contenido
de list; equivalente a tuple(list).

154 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.4 Objetos contenedor

8.4.1 Objetos diccionario

type PyDictObject
Este subtipo de PyObject representa un objeto diccionario de Python.
PyTypeObject PyDict_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo diccionario de Python. Este es
el mismo objeto que dict en la capa de Python.
int PyDict_Check(PyObject *p)
Retorna verdadero si p es un objeto dict o una instancia de un subtipo del tipo dict. Esta función siempre
finaliza con éxito.
int PyDict_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto dict, pero no una instancia de un subtipo del tipo dict. Esta función
siempre finaliza con éxito.
PyObject *PyDict_New()
Return value: New reference. Part of the Stable ABI. Retorna un nuevo diccionario vacío, o NULL en caso de
falla.
PyObject *PyDictProxy_New(PyObject *mapping)
Return value: New reference. Part of the Stable ABI. Retorna un objeto a types.MappingProxyType
para una asignación que imponga un comportamiento de solo lectura. Esto normalmente se usa para crear una
vista para evitar la modificación del diccionario para los tipos de clase no dinámicos.
void PyDict_Clear(PyObject *p)
Part of the Stable ABI. Vacía un diccionario existente de todos los pares clave-valor (key-value).
int PyDict_Contains(PyObject *p, PyObject *key)
Part of the Stable ABI. Determine si el diccionario p contiene key. Si un elemento en p coincide con la clave
key, retorna 1; de lo contrario, retorna 0. En caso de error, retorna -1. Esto es equivalente a la expresión de
Python key in p.
PyObject *PyDict_Copy(PyObject *p)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo diccionario que contiene los mismos
pares clave-valor (key-value) que p.
int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
Part of the Stable ABI. Inserta val en el diccionario p con una clave key. key debe ser hashable; si no lo es, se
lanzará TypeError. Retorna 0 en caso de éxito o -1 en caso de error. Esta función no roba una referencia
a val.
int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
Part of the Stable ABI. This is the same as PyDict_SetItem(), but key is specified as a const char*
UTF-8 encoded bytes string, rather than a PyObject*.
int PyDict_DelItem(PyObject *p, PyObject *key)
Part of the Stable ABI. Remove the entry in dictionary p with key key. key must be hashable; if it isn’t,
TypeError is raised. If key is not in the dictionary, KeyError is raised. Return 0 on success or -1 on
failure.
int PyDict_DelItemString(PyObject *p, const char *key)
Part of the Stable ABI. This is the same as PyDict_DelItem(), but key is specified as a const char*
UTF-8 encoded bytes string, rather than a PyObject*.

8.4. Objetos contenedor 155


The Python/C API, Versión 3.12.4

PyObject *PyDict_GetItem(PyObject *p, PyObject *key)


Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto del diccionario p que tiene una
clave key. Retorna NULL si la clave key no está presente, pero sin lanzar una excepción.

Nota: Exceptions that occur while this calls __hash__() and __eq__() methods are silently ignored.
Prefer the PyDict_GetItemWithError() function instead.

Distinto en la versión 3.10: Llamar a esta API sin retener el GIL había sido permitido por motivos históricos.Ya
no está permitido.
PyObject *PyDict_GetItemWithError(PyObject *p, PyObject *key)
Return value: Borrowed reference. Part of the Stable ABI. Variante de PyDict_GetItem() que no suprime
las excepciones. Retorna NULL con una excepción establecida si se produjo una excepción. Retorna NULL sin
una excepción establecida si la clave no estaba presente.
PyObject *PyDict_GetItemString(PyObject *p, const char *key)
Return value: Borrowed reference. Part of the Stable ABI. This is the same as PyDict_GetItem(), but key
is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.

Nota: Exceptions that occur while this calls __hash__() and __eq__() methods or while creating the
temporary str object are silently ignored. Prefer using the PyDict_GetItemWithError() function
with your own PyUnicode_FromString() key instead.

PyObject *PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)


Return value: Borrowed reference. Esto es lo mismo al nivel de Python dict.setdefault(). Si está pre-
sente, retorna el valor correspondiente a key del diccionario p. Si la clave no está en el dict, se inserta con el
valor defaultobj y se retorna defaultobj. Esta función evalúa la función hash de key solo una vez, en lugar de
evaluarla independientemente para la búsqueda y la inserción.
Added in version 3.4.
PyObject *PyDict_Items(PyObject *p)
Return value: New reference. Part of the Stable ABI. Retorna un PyListObject que contiene todos los
elementos del diccionario.
PyObject *PyDict_Keys(PyObject *p)
Return value: New reference. Part of the Stable ABI. Retorna un PyListObject que contiene todas las claves
del diccionario.
PyObject *PyDict_Values(PyObject *p)
Return value: New reference. Part of the Stable ABI. Retorna un PyListObject que contiene todos los
valores del diccionario p.
Py_ssize_t PyDict_Size(PyObject *p)
Part of the Stable ABI. Retorna el número de elementos en el diccionario. Esto es equivalente a len(p) en
un diccionario.
int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Part of the Stable ABI. Iterate over all key-value pairs in the dictionary p. The Py_ssize_t referred to by
ppos must be initialized to 0 prior to the first call to this function to start the iteration; the function returns true
for each pair in the dictionary, and false once all pairs have been reported. The parameters pkey and pvalue
should either point to PyObject* variables that will be filled in with each key and value, respectively, or may
be NULL. Any references returned through them are borrowed. ppos should not be altered during iteration. Its
value represents offsets within the internal dictionary structure, and since the structure is sparse, the offsets are
not consecutive.
Por ejemplo:

156 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

PyObject *key, *value;


Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) {


/* do something interesting with the values... */
...
}

El diccionario p no debe mutarse durante la iteración. Es seguro modificar los valores de las claves a medida
que recorre el diccionario, pero solo mientras el conjunto de claves no cambie. Por ejemplo:
PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) {


long i = PyLong_AsLong(value);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
PyObject *o = PyLong_FromLong(i + 1);
if (o == NULL)
return -1;
if (PyDict_SetItem(self->dict, key, o) < 0) {
Py_DECREF(o);
return -1;
}
Py_DECREF(o);
}

int PyDict_Merge(PyObject *a, PyObject *b, int override)


Part of the Stable ABI. Itera sobre el objeto de mapeo b agregando pares clave-valor al diccionario a. b puede
ser un diccionario o cualquier objeto que soporte PyMapping_Keys() y PyObject_GetItem(). Si
override es verdadero, los pares existentes en a se reemplazarán si se encuentra una clave coincidente en b, de
lo contrario, los pares solo se agregarán si no hay una clave coincidente en a. Retorna 0 en caso de éxito o -1
si se lanza una excepción.
int PyDict_Update(PyObject *a, PyObject *b)
Part of the Stable ABI. Esto es lo mismo que PyDict_Merge(a, b, 1) en C, y es similar a a.
update(b) en Python excepto que PyDict_Update() no vuelve a la iteración sobre una secuencia de
pares de valores clave si el segundo argumento no tiene el atributo «claves». Retorna 0 en caso de éxito o -1
si se produjo una excepción.
int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
Part of the Stable ABI. Actualiza o combina en el diccionario a, desde los pares clave-valor en seq2. seq2 debe
ser un objeto iterable que produzca objetos iterables de longitud 2, vistos como pares clave-valor. En el caso
de claves duplicadas, el último gana si override es verdadero, de lo contrario, el primero gana. Retorna 0 en
caso de éxito o -1 si se produjo una excepción. El equivalente en Python (excepto el valor de retorno)
def PyDict_MergeFromSeq2(a, seq2, override):
for key, value in seq2:
if override or key not in a:
a[key] = value

int PyDict_AddWatcher(PyDict_WatchCallback callback)


Register callback as a dictionary watcher. Return a non-negative integer id which must be passed to future calls
to PyDict_Watch(). In case of error (e.g. no more watcher IDs available), return -1 and set an exception.
Added in version 3.12.
int PyDict_ClearWatcher(int watcher_id)
Clear watcher identified by watcher_id previously returned from PyDict_AddWatcher(). Return 0 on
success, -1 on error (e.g. if the given watcher_id was never registered.)

8.4. Objetos contenedor 157


The Python/C API, Versión 3.12.4

Added in version 3.12.


int PyDict_Watch(int watcher_id, PyObject *dict)
Mark dictionary dict as watched. The callback granted watcher_id by PyDict_AddWatcher() will be
called when dict is modified or deallocated. Return 0 on success or -1 on error.
Added in version 3.12.
int PyDict_Unwatch(int watcher_id, PyObject *dict)
Mark dictionary dict as no longer watched. The callback granted watcher_id by PyDict_AddWatcher()
will no longer be called when dict is modified or deallocated. The dict must previously have been watched by
this watcher. Return 0 on success or -1 on error.
Added in version 3.12.
type PyDict_WatchEvent
Enumeration of possible dictionary watcher events: PyDict_EVENT_ADDED,
PyDict_EVENT_MODIFIED, PyDict_EVENT_DELETED, PyDict_EVENT_CLONED,
PyDict_EVENT_CLEARED, or PyDict_EVENT_DEALLOCATED.
Added in version 3.12.
typedef int (*PyDict_WatchCallback)(PyDict_WatchEvent event, PyObject *dict, PyObject *key, PyObject
*new_value)
Type of a dict watcher callback function.
If event is PyDict_EVENT_CLEARED or PyDict_EVENT_DEALLOCATED, both key and new_value
will be NULL. If event is PyDict_EVENT_ADDED or PyDict_EVENT_MODIFIED, new_value will be
the new value for key. If event is PyDict_EVENT_DELETED, key is being deleted from the dictionary and
new_value will be NULL.
PyDict_EVENT_CLONED occurs when dict was previously empty and another dict is merged into it. To
maintain efficiency of this operation, per-key PyDict_EVENT_ADDED events are not issued in this case;
instead a single PyDict_EVENT_CLONED is issued, and key will be the source dictionary.
The callback may inspect but must not modify dict; doing so could have unpredictable effects, including infinite
recursion. Do not trigger Python code execution in the callback, as it could modify the dict as a side effect.
If event is PyDict_EVENT_DEALLOCATED, taking a new reference in the callback to the about-to-be-
destroyed dictionary will resurrect it and prevent it from being freed at this time. When the resurrected object
is destroyed later, any watcher callbacks active at that time will be called again.
Callbacks occur before the notified modification to dict takes place, so the prior state of dict can be inspected.
If the callback sets an exception, it must return -1; this exception will be printed as an unraisable exception
using PyErr_WriteUnraisable(). Otherwise it should return 0.
There may already be a pending exception set on entry to the callback. In this case, the callback should return 0
with the same exception still set. This means the callback may not call any other API that can set an exception
unless it saves and clears the exception state first, and restores it before returning.
Added in version 3.12.

8.4.2 Objetos conjunto

Esta sección detalla la API pública de los objetos set y frozenset. Cualquier funcionalidad que
no esté listada a continuación se accede mejor utilizando el protocolo abstracto de objetos (inclu-
yendo PyObject_CallMethod(), PyObject_RichCompareBool(), PyObject_Hash(),
PyObject_Repr(), PyObject_IsTrue(), PyObject_Print(), y PyObject_GetIter()) o el
protocolo numérico abstracto (incluyendo PyNumber_And(), PyNumber_Subtract(), PyNumber_Or(),
PyNumber_Xor(), PyNumber_InPlaceAnd(), PyNumber_InPlaceSubtract(),
PyNumber_InPlaceOr(), y PyNumber_InPlaceXor()).

158 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

type PySetObject
Este subtipo de PyObject se utiliza para mantener los datos internos de los objetos set y frozenset.
Es como un PyDictObject en el sentido de que tiene un tamaño fijo para los conjuntos pequeños (muy
parecido al almacenamiento de tuplas) y apuntará a un bloque de memoria separado y de tamaño variable para
los conjuntos de tamaño medio y grande (muy parecido al almacenamiento de listas). Ninguno de los campos
de esta estructura debe considerarse público y todos están sujetos a cambios. Todo el acceso debe hacerse a
través de la API documentada en lugar de manipular los valores de la estructura.
PyTypeObject PySet_Type
Part of the Stable ABI. Esta es una instancia de PyTypeObject que representa el tipo Python set.
PyTypeObject PyFrozenSet_Type
Part of the Stable ABI. Esta es una instancia de PyTypeObject que representa el tipo Python frozenset.
Los siguientes macros de comprobación de tipos funcionan en punteros a cualquier objeto de Python. Del mismo
modo, las funciones del constructor funcionan con cualquier objeto Python iterable.
int PySet_Check(PyObject *p)
Retorna verdadero si p es un objeto set o una instancia de un subtipo. Esta función siempre finaliza con éxito.
int PyFrozenSet_Check(PyObject *p)
Retorna verdadero si p es un objeto frozenset o una instancia de un subtipo. Esta función siempre finaliza
con éxito.
int PyAnySet_Check(PyObject *p)
Retorna verdadero si p es un objeto set, un objeto frozenset, o una instancia de un subtipo. Esta función
siempre finaliza con éxito.
int PySet_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto set pero no una instancia de un subtipo. Esta función siempre finaliza con
éxito.
Added in version 3.10.
int PyAnySet_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto set o un objeto frozenset pero no una instancia de un subtipo. Esta
función siempre finaliza con éxito.
int PyFrozenSet_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto frozenset pero no una instancia de un subtipo. Esta función siempre
finaliza con éxito.
PyObject *PySet_New(PyObject *iterable)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo set que contiene objetos retornados
por iterable. El iterable puede ser NULL para crear un nuevo conjunto vacío. Retorna el nuevo conjunto en
caso de éxito o NULL en caso de error. Lanza TypeError si iterable no es realmente iterable. El constructor
también es útil para copiar un conjunto (c=set(s)).
PyObject *PyFrozenSet_New(PyObject *iterable)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo frozenset que contiene objetos
retornados por iterable. El iterable puede ser NULL para crear un nuevo conjunto congelado vacío. Retorna
el nuevo conjunto en caso de éxito o NULL en caso de error. Lanza TypeError si iterable no es realmente
iterable.
Las siguientes funciones y macros están disponibles para instancias de set o frozenset o instancias de sus sub-
tipos.
Py_ssize_t PySet_Size(PyObject *anyset)
Part of the Stable ABI. Return the length of a set or frozenset object. Equivalent to len(anyset).
Raises a SystemError if anyset is not a set, frozenset, or an instance of a subtype.

8.4. Objetos contenedor 159


The Python/C API, Versión 3.12.4

Py_ssize_t PySet_GET_SIZE(PyObject *anyset)


Forma macro de PySet_Size() sin comprobación de errores.
int PySet_Contains(PyObject *anyset, PyObject *key)
Part of the Stable ABI. Return 1 if found, 0 if not found, and -1 if an error is encountered. Unlike the Python
__contains__() method, this function does not automatically convert unhashable sets into temporary
frozensets. Raise a TypeError if the key is unhashable. Raise SystemError if anyset is not a set,
frozenset, or an instance of a subtype.
int PySet_Add(PyObject *set, PyObject *key)
Part of the Stable ABI. Añade key a una instancia set. También funciona con instancias de frozenset
(al igual que PyTuple_SetItem() puede usarse para rellenar los valores de nuevos frozensets antes
de que sean expuestos a otro código). Retorna 0 en caso de éxito o -1 en caso de fallo. Lanza un error
TypeError si la key no se puede intercambiar. Lanza un MemoryError si no hay espacio para crecer.
Lanza un SystemError si set no es una instancia de set o su subtipo.
Las siguientes funciones están disponibles para instancias de set o sus subtipos, pero no para instancias de
frozenset o sus subtipos.
int PySet_Discard(PyObject *set, PyObject *key)
Part of the Stable ABI. Return 1 if found and removed, 0 if not found (no action taken), and -1 if an error
is encountered. Does not raise KeyError for missing keys. Raise a TypeError if the key is unhashable.
Unlike the Python discard() method, this function does not automatically convert unhashable sets into
temporary frozensets. Raise SystemError if set is not an instance of set or its subtype.
PyObject *PySet_Pop(PyObject *set)
Return value: New reference. Part of the Stable ABI. Retorna una nueva referencia a un objeto arbitrario en
el set y elimina el objeto del set. Retorna NULL en caso de falla. Lanza KeyError si el conjunto está vacío.
Lanza a SystemError si set no es una instancia de set o su subtipo.
int PySet_Clear(PyObject *set)
Part of the Stable ABI. Empty an existing set of all elements. Return 0 on success. Return -1 and raise
SystemError if set is not an instance of set or its subtype.

8.5 Objetos de función

8.5.1 Objetos función

Hay algunas funciones específicas para las funciones de Python.


type PyFunctionObject
La estructura C utilizada para las funciones.
PyTypeObject PyFunction_Type
Esta es una instancia de PyTypeObject y representa el tipo función de Python. Está expuesto a los progra-
madores de Python como types.FunctionType.
int PyFunction_Check(PyObject *o)
Retorna verdadero si o es un objeto función (tiene tipo PyFunction_Type). El parámetro no debe ser
NULL. Esta función siempre finaliza con éxito.
PyObject *PyFunction_New(PyObject *code, PyObject *globals)
Return value: New reference. Retorna un nuevo objeto función asociado con el objeto código code. globals debe
ser un diccionario con las variables globales accesibles para la función.
The function’s docstring and name are retrieved from the code object. __module__ is retrieved from globals.
The argument defaults, annotations and closure are set to NULL. __qualname__ is set to the same value as
the code object’s co_qualname field.

160 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

PyObject *PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)


Return value: New reference. As PyFunction_New(), but also allows setting the function object’s
__qualname__ attribute. qualname should be a unicode object or NULL; if NULL, the __qualname__
attribute is set to the same value as the code object’s co_qualname field.
Added in version 3.3.
PyObject *PyFunction_GetCode(PyObject *op)
Return value: Borrowed reference. Retorna el objeto código asociado con el objeto función op.
PyObject *PyFunction_GetGlobals(PyObject *op)
Return value: Borrowed reference. Retorna el diccionario global asociado con el objeto función op.
PyObject *PyFunction_GetModule(PyObject *op)
Return value: Borrowed reference. Return a borrowed reference to the __module__ attribute of the function
object op. It can be NULL.
This is normally a string containing the module name, but can be set to any other object by Python code.
PyObject *PyFunction_GetDefaults(PyObject *op)
Return value: Borrowed reference. Retorna los valores predeterminados del argumento del objeto función op.
Esto puede ser una tupla de argumentos o NULL.
int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
Establece los valores predeterminados del argumento para el objeto función op. defaults deben ser Py_None
o una tupla.
Lanza SystemError y retorna -1 en caso de error.
void PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
Set the vectorcall field of a given function object func.
Warning: extensions using this API must preserve the behavior of the unaltered (default) vectorcall function!
Added in version 3.12.
PyObject *PyFunction_GetClosure(PyObject *op)
Return value: Borrowed reference. Retorna el cierre asociado con el objeto función op. Esto puede ser NULL o
una tupla de objetos celda.
int PyFunction_SetClosure(PyObject *op, PyObject *closure)
Establece el cierre asociado con el objeto función op. cierre debe ser Py_None o una tupla de objetos celda.
Lanza SystemError y retorna -1 en caso de error.
PyObject *PyFunction_GetAnnotations(PyObject *op)
Return value: Borrowed reference. Retorna las anotaciones del objeto función op. Este puede ser un diccionario
mutable o NULL.
int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
Establece las anotaciones para el objeto función op. annotations debe ser un diccionario o Py_None.
Lanza SystemError y retorna -1 en caso de error.
int PyFunction_AddWatcher(PyFunction_WatchCallback callback)
Register callback as a function watcher for the current interpreter. Return an ID which may be passed to
PyFunction_ClearWatcher(). In case of error (e.g. no more watcher IDs available), return -1 and set
an exception.
Added in version 3.12.
int PyFunction_ClearWatcher(int watcher_id)
Clear watcher identified by watcher_id previously returned from PyFunction_AddWatcher() for the
current interpreter. Return 0 on success, or -1 and set an exception on error (e.g. if the given watcher_id was
never registered.)

8.5. Objetos de función 161


The Python/C API, Versión 3.12.4

Added in version 3.12.


type PyFunction_WatchEvent
Enumeration of possible function watcher events: - PyFunction_EVENT_CREATE
- PyFunction_EVENT_DESTROY - PyFunction_EVENT_MODIFY_CODE -
PyFunction_EVENT_MODIFY_DEFAULTS - PyFunction_EVENT_MODIFY_KWDEFAULTS
Added in version 3.12.
typedef int (*PyFunction_WatchCallback)(PyFunction_WatchEvent event, PyFunctionObject *func,
PyObject *new_value)
Type of a function watcher callback function.
If event is PyFunction_EVENT_CREATE or PyFunction_EVENT_DESTROY then new_value will be
NULL. Otherwise, new_value will hold a borrowed reference to the new value that is about to be stored in func
for the attribute that is being modified.
The callback may inspect but must not modify func; doing so could have unpredictable effects, including infinite
recursion.
If event is PyFunction_EVENT_CREATE, then the callback is invoked after func has been fully initialized.
Otherwise, the callback is invoked before the modification to func takes place, so the prior state of func can be
inspected. The runtime is permitted to optimize away the creation of function objects when possible. In such
cases no event will be emitted. Although this creates the possibility of an observable difference of runtime
behavior depending on optimization decisions, it does not change the semantics of the Python code being
executed.
If event is PyFunction_EVENT_DESTROY, Taking a reference in the callback to the about-to-be-destroyed
function will resurrect it, preventing it from being freed at this time. When the resurrected object is destroyed
later, any watcher callbacks active at that time will be called again.
If the callback sets an exception, it must return -1; this exception will be printed as an unraisable exception
using PyErr_WriteUnraisable(). Otherwise it should return 0.
There may already be a pending exception set on entry to the callback. In this case, the callback should return 0
with the same exception still set. This means the callback may not call any other API that can set an exception
unless it saves and clears the exception state first, and restores it before returning.
Added in version 3.12.

8.5.2 Objetos de método de instancia

An instance method is a wrapper for a PyCFunction and the new way to bind a PyCFunction to a class object.
It replaces the former call PyMethod_New(func, NULL, class).
PyTypeObject PyInstanceMethod_Type
Esta instancia de PyTypeObject representa el tipo de método de instancia de Python. No está expuesto a
los programas de Python.
int PyInstanceMethod_Check(PyObject *o)
Retorna verdadero si o es un objeto de método de instancia (tiene tipo PyInstanceMethod_Type). El
parámetro no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PyInstanceMethod_New(PyObject *func)
Return value: New reference. Return a new instance method object, with func being any callable object. func is
the function that will be called when the instance method is called.
PyObject *PyInstanceMethod_Function(PyObject *im)
Return value: Borrowed reference. Retorna el objeto de función asociado con el método de instancia im.
PyObject *PyInstanceMethod_GET_FUNCTION(PyObject *im)
Return value: Borrowed reference. Versión macro de PyInstanceMethod_Function() que evita la
comprobación de errores.

162 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.5.3 Objetos método

Los métodos son objetos de función enlazados. Los métodos siempre están vinculados a una instancia de una clase
definida por el usuario. Los métodos no vinculados (métodos vinculados a un objeto de clase) ya no están disponibles.

PyTypeObject PyMethod_Type
Esta instancia de PyTypeObject representa el tipo de método Python. Esto está expuesto a los programas
de Python como types.MethodType.
int PyMethod_Check(PyObject *o)
Retorna verdadero si o es un objeto de método (tiene tipo PyMethod_Type). El parámetro no debe ser
NULL. Esta función siempre finaliza con éxito.
PyObject *PyMethod_New(PyObject *func, PyObject *self)
Return value: New reference. Retorna un nuevo objeto de método, con func como cualquier objeto invocable
y self la instancia en la que se debe vincular el método. func es la función que se llamará cuando se llame al
método. self no debe ser NULL.
PyObject *PyMethod_Function(PyObject *meth)
Return value: Borrowed reference. Retorna el objeto de función asociado con el método meth.
PyObject *PyMethod_GET_FUNCTION(PyObject *meth)
Return value: Borrowed reference. Versión macro de PyMethod_Function() que evita la comprobación
de errores.
PyObject *PyMethod_Self(PyObject *meth)
Return value: Borrowed reference. Retorna la instancia asociada con el método meth.
PyObject *PyMethod_GET_SELF(PyObject *meth)
Return value: Borrowed reference. Versión macro de PyMethod_Self() que evita la comprobación de
errores.

8.5.4 Objetos celda

Los objetos celda (cell) se utilizan para implementar variables a las que hacen referencia varios ámbitos. Para cada
variable, se crea un objeto de celda para almacenar el valor; Las variables locales de cada marco de pila que hace
referencia al valor contienen una referencia a las celdas de ámbitos externos que también usan esa variable. Cuando
se accede al valor, se utiliza el valor contenido en la celda en lugar del objeto de la celda en sí. Esta desreferenciación
del objeto de celda requiere soporte del código de bytes generado; estos no se eliminan automáticamente cuando se
accede a ellos. No es probable que los objetos celda sean útiles en otros lugares.
type PyCellObject
La estructura C utilizada para objetos celda.
PyTypeObject PyCell_Type
El objeto tipo correspondiente a los objetos celda.
int PyCell_Check(PyObject *ob)
Retorna verdadero si ob es un objeto de celda; ob no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PyCell_New(PyObject *ob)
Return value: New reference. Crea y retorna un nuevo objeto de celda que contiene el valor ob. El parámetro
puede ser NULL.
PyObject *PyCell_Get(PyObject *cell)
Return value: New reference. Retorna el contenido de la celda cell.

8.5. Objetos de función 163


The Python/C API, Versión 3.12.4

PyObject *PyCell_GET(PyObject *cell)


Return value: Borrowed reference. Retorna el contenido de la celda cell, pero sin verificar que cell no sea NULL
y que sea un objeto de celda.
int PyCell_Set(PyObject *cell, PyObject *value)
Establece el contenido del objeto de celda cell con el valor value. Esto libera la referencia a cualquier contenido
actual de la celda. value puede ser NULL. cell no debe ser NULL; Si no es un objeto de celda, se retornará -1.
En caso de éxito, se retornará 0.
void PyCell_SET(PyObject *cell, PyObject *value)
Establece el valor del objeto de celda cell en el valor value. No se ajustan los recuentos de referencia y no se
realizan verificaciones de seguridad; cell no debe ser NULL y debe ser un objeto de celda.

8.5.5 Objetos código

Los objetos código son un detalle de bajo nivel de la implementación de CPython. Cada uno representa un fragmento
de código ejecutable que aún no se ha vinculado a una función.
type PyCodeObject
La estructura en C de los objetos utilizados para describir objetos código. Los campos de este tipo están sujetos
a cambios en cualquier momento.
PyTypeObject PyCode_Type
This is an instance of PyTypeObject representing the Python code object.
int PyCode_Check(PyObject *co)
Return true if co is a code object. This function always succeeds.
Py_ssize_t PyCode_GetNumFree(PyCodeObject *co)
Return the number of free variables in a code object.
int PyCode_GetFirstFree(PyCodeObject *co)
Return the position of the first free variable in a code object.
PyCodeObject *PyUnstable_Code_New(int argcount, int kwonlyargcount, int nlocals, int stacksize, int flags,
PyObject *code, PyObject *consts, PyObject *names, PyObject
*varnames, PyObject *freevars, PyObject *cellvars, PyObject
*filename, PyObject *name, PyObject *qualname, int firstlineno,
PyObject *linetable, PyObject *exceptiontable)

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

Return a new code object. If you need a dummy code object to create a frame, use PyCode_NewEmpty()
instead.
Since the definition of the bytecode changes often, calling PyUnstable_Code_New() directly can bind
you to a precise Python version.
The many arguments of this function are inter-dependent in complex ways, meaning that subtle changes to
values are likely to result in incorrect execution or VM crashes. Use this function only with extreme care.
Distinto en la versión 3.11: Added qualname and exceptiontable parameters.
Distinto en la versión 3.12: Renamed from PyCode_New as part of Unstable C API. The old name is depre-
cated, but will remain available until the signature changes again.

164 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

PyCodeObject *PyUnstable_Code_NewWithPosOnlyArgs(int argcount, int posonlyargcount, int


kwonlyargcount, int nlocals, int stacksize, int
flags, PyObject *code, PyObject *consts,
PyObject *names, PyObject *varnames,
PyObject *freevars, PyObject *cellvars,
PyObject *filename, PyObject *name,
PyObject *qualname, int firstlineno, PyObject
*linetable, PyObject *exceptiontable)

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

Similar to PyUnstable_Code_New(), but with an extra «posonlyargcount» for positional-only arguments.


The same caveats that apply to PyUnstable_Code_New also apply to this function.
Added in version 3.8: as PyCode_NewWithPosOnlyArgs
Distinto en la versión 3.11: Added qualname and exceptiontable parameters.
Distinto en la versión 3.12: Renamed to PyUnstable_Code_NewWithPosOnlyArgs. The old name is
deprecated, but will remain available until the signature changes again.
PyCodeObject *PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
Return value: New reference. Retorna un nuevo objeto de código vacío con el nombre de archivo especificado,
el nombre de la función y el número de la primera línea. Si el objeto código resultante es ejecutado, lanzará
una Exception.
int PyCode_Addr2Line(PyCodeObject *co, int byte_offset)
Retorna el número de línea de la instrucción que se produce en o antes de byte_offset y finaliza después.
Si solo necesita el número de línea de un marco, use PyFrame_GetLineNumber() en su lugar.
Para iterar de manera eficiente sobre los números de línea en un objeto de código, use la API descrita en PEP
626.
int PyCode_Addr2Location(PyObject *co, int byte_offset, int *start_line, int *start_column, int *end_line,
int *end_column)
Establece los punteros int pasados en los números de línea y columna del código fuente para las instrucciones
en byte_offset. Establece el valor en 0 cuando la información no está disponible para algún elemento en
particular.
Retorna 1 si la función fue exitosa y 0 de lo contrario.
Added in version 3.11.
PyObject *PyCode_GetCode(PyCodeObject *co)
Equivalente al código Python getattr(co, 'co_code'). Retorna una referencia fuerte a un
PyBytesObject representando el bytecode en un objecto código. En caso de error se retorna NULL y
se lanza una excepción.
Este PyBytesObject puede ser creado a pedido del intérprete y no necesariamente representa el bytecode
que es realmente ejecutado por CPython. Los casos de uso principales para esta función son depuradores y
perfiladores.
Added in version 3.11.
PyObject *PyCode_GetVarnames(PyCodeObject *co)
Equivalente al código Python getattr(co, 'co_varnames'). Retorna una nueva referencia a un
PyTupleObject que contiene los nombres de las variables locales. En caso de error, retorna NULL y lanza
una excepción.
Added in version 3.11.

8.5. Objetos de función 165


The Python/C API, Versión 3.12.4

PyObject *PyCode_GetCellvars(PyCodeObject *co)


Equivalente al código Python getattr(co, 'co_cellvars'). Retorna una nueva referencia a un
PyTupleObject que contiene los nombres de las variables locales referenciadas por funciones anidadas.
En caso de error, retorna NULL y lanza una excepción.
Added in version 3.11.
PyObject *PyCode_GetFreevars(PyCodeObject *co)
Equivalente al código Python getattr(co, 'co_freevars'). Retorna una nueva referencia a un
PyTupleObject que contiene los nombres de las variables libres. En caso de error, retorna NULL y lanza
una excepción.
Added in version 3.11.
int PyCode_AddWatcher(PyCode_WatchCallback callback)
Register callback as a code object watcher for the current interpreter. Return an ID which may be passed to
PyCode_ClearWatcher(). In case of error (e.g. no more watcher IDs available), return -1 and set an
exception.
Added in version 3.12.
int PyCode_ClearWatcher(int watcher_id)
Clear watcher identified by watcher_id previously returned from PyCode_AddWatcher() for the current
interpreter. Return 0 on success, or -1 and set an exception on error (e.g. if the given watcher_id was never
registered.)
Added in version 3.12.
type PyCodeEvent
Enumeration of possible code object watcher events: - PY_CODE_EVENT_CREATE -
PY_CODE_EVENT_DESTROY
Added in version 3.12.
typedef int (*PyCode_WatchCallback)(PyCodeEvent event, PyCodeObject *co)
Type of a code object watcher callback function.
If event is PY_CODE_EVENT_CREATE, then the callback is invoked after co has been fully initialized. Other-
wise, the callback is invoked before the destruction of co takes place, so the prior state of co can be inspected.
If event is PY_CODE_EVENT_DESTROY, taking a reference in the callback to the about-to-be-destroyed code
object will resurrect it and prevent it from being freed at this time. When the resurrected object is destroyed
later, any watcher callbacks active at that time will be called again.
Users of this API should not rely on internal runtime implementation details. Such details may include, but
are not limited to, the exact order and timing of creation and destruction of code objects. While changes in
these details may result in differences observable by watchers (including whether a callback is invoked or not),
it does not change the semantics of the Python code being executed.
If the callback sets an exception, it must return -1; this exception will be printed as an unraisable exception
using PyErr_WriteUnraisable(). Otherwise it should return 0.
There may already be a pending exception set on entry to the callback. In this case, the callback should return 0
with the same exception still set. This means the callback may not call any other API that can set an exception
unless it saves and clears the exception state first, and restores it before returning.
Added in version 3.12.

166 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.5.6 Extra information

To support low-level extensions to frame evaluation, such as external just-in-time compilers, it is possible to attach
arbitrary extra data to code objects.
These functions are part of the unstable C API tier: this functionality is a CPython implementation detail, and the
API may change without deprecation warnings.
Py_ssize_t PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)

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

Return a new an opaque index value used to adding data to code objects.
You generally call this function once (per interpreter) and use the result with PyCode_GetExtra and
PyCode_SetExtra to manipulate data on individual code objects.
If free is not NULL: when a code object is deallocated, free will be called on non-NULL data stored under the
new index. Use Py_DecRef() when storing PyObject.
Added in version 3.6: as _PyEval_RequestCodeExtraIndex
Distinto en la versión 3.12: Renamed to PyUnstable_Eval_RequestCodeExtraIndex. The old pri-
vate name is deprecated, but will be available until the API changes.
int PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)

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

Set extra to the extra data stored under the given index. Return 0 on success. Set an exception and return -1 on
failure.
If no data was set under the index, set extra to NULL and return 0 without setting an exception.
Added in version 3.6: as _PyCode_GetExtra
Distinto en la versión 3.12: Renamed to PyUnstable_Code_GetExtra. The old private name is depre-
cated, but will be available until the API changes.
int PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)

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

Set the extra data stored under the given index to extra. Return 0 on success. Set an exception and return -1 on
failure.
Added in version 3.6: as _PyCode_SetExtra
Distinto en la versión 3.12: Renamed to PyUnstable_Code_SetExtra. The old private name is depre-
cated, but will be available until the API changes.

8.5. Objetos de función 167


The Python/C API, Versión 3.12.4

8.6 Otros objetos

8.6.1 Objetos archivo

These APIs are a minimal emulation of the Python 2 C API for built-in file objects, which used to rely on the
buffered I/O (FILE*) support from the C standard library. In Python 3, files and streams use the new io module,
which defines several layers over the low-level unbuffered I/O of the operating system. The functions described below
are convenience C wrappers over these new APIs, and meant mostly for internal error reporting in the interpreter;
third-party code is advised to access the io APIs instead.
PyObject *PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding,
const char *errors, const char *newline, int closefd)
Return value: New reference. Part of the Stable ABI. Crea un objeto archivo Python a partir del descriptor de
archivo de un archivo ya abierto fd. Los argumentos name, encoding, errors y newline pueden ser NULL para
usar los valores predeterminados; buffering puede ser -1 para usar el valor predeterminado. name se ignora y
se mantiene por compatibilidad con versiones anteriores. Retorna NULL en caso de error. Para obtener una
descripción más completa de los argumentos, consulte la documentación de la función io.open().

Advertencia: Dado que las transmisiones (streams) de Python tienen su propia capa de almacenamiento
en búfer, combinarlas con descriptores de archivos a nivel del sistema operativo puede producir varios
problemas (como un pedido inesperado de datos).

Distinto en la versión 3.2: Ignora el atributo name.


int PyObject_AsFileDescriptor(PyObject *p)
Part of the Stable ABI. Return the file descriptor associated with p as an int. If the object is an integer, its
value is returned. If not, the object’s fileno() method is called if it exists; the method must return an integer,
which is returned as the file descriptor value. Sets an exception and returns -1 on failure.
PyObject *PyFile_GetLine(PyObject *p, int n)
Return value: New reference. Part of the Stable ABI. Equivalente a p.readline([n]), esta función lee
una línea del objeto p. p puede ser un objeto archivo o cualquier objeto con un método readline(). Si n
es 0, se lee exactamente una línea, independientemente de la longitud de la línea. Si n es mayor que 0, no se
leerán más de n bytes del archivo; se puede retornar una línea parcial. En ambos casos, se retorna una cadena
de caracteres vacía si se llega al final del archivo de inmediato. Si n es menor que 0, sin embargo, se lee una
línea independientemente de la longitud, pero EOFError se lanza si se llega al final del archivo de inmediato.
int PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction handler)
Sobrescribe el comportamiento normal de io.open_code() para pasar su parámetro a través del contro-
lador proporcionado.
The handler is a function of type:
type Py_OpenCodeHookFunction
Equivalent of PyObject *(*)(PyObject *path, void *userData), where path is gua-
ranteed to be PyUnicodeObject.
El puntero userData se pasa a la función de enlace. Dado que las funciones de enlace pueden llamarse desde
diferentes tiempos de ejecución, este puntero no debe referirse directamente al estado de Python.
Como este hook se usa intencionalmente durante la importación, evite importar nuevos módulos durante su
ejecución a menos que se sepa que están congelados o disponibles en sys.modules.
Una vez que se ha establecido un hook, no se puede quitar ni reemplazar, y luego llamadas a
PyFile_SetOpenCodeHook() fallarán. En caso de error, la función retorna -1 y establece una excepción
si el intérprete se ha inicializado.
Es seguro llamar a esta función antes de Py_Initialize().
Genera un evento de auditoría setopencodehook sin argumentos.

168 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

Added in version 3.8.


int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
Part of the Stable ABI. Write object obj to file object p. The only supported flag for flags is Py_PRINT_RAW;
if given, the str() of the object is written instead of the repr(). Return 0 on success or -1 on failure; the
appropriate exception will be set.
int PyFile_WriteString(const char *s, PyObject *p)
Part of the Stable ABI. Escribe la cadena s en el objeto archivo p. Retorna 0 en caso de éxito o -1 en caso de
error; se establecerá la excepción apropiada.

8.6.2 Objetos módulo

PyTypeObject PyModule_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de módulo Python. Esto está
expuesto a los programas de Python como types.ModuleType.
int PyModule_Check(PyObject *p)
Retorna verdadero si p es un objeto de módulo o un subtipo de un objeto de módulo. Esta función siempre
finaliza con éxito.
int PyModule_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto módulo, pero no un subtipo de PyModule_Type. Esta función siempre
finaliza con éxito.
PyObject *PyModule_NewObject(PyObject *name)
Return value: New reference. Part of the Stable ABI since version 3.7. Retorna un nuevo objeto módu-
lo con el atributo __name__ establecido en name. Los atributos del módulo __name__, __doc__,
__package__, y __loader__ se completan (todos menos __name__ están configurados en None);
quien llama es responsable de proporcionar un atributo __file__.
Added in version 3.3.
Distinto en la versión 3.4: __package__ y __loader__ están configurados en None.
PyObject *PyModule_New(const char *name)
Return value: New reference. Part of the Stable ABI. Similar a PyModule_NewObject(), pero el nombre
es una cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
PyObject *PyModule_GetDict(PyObject *module)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto del diccionario que implementa
el espacio de nombres de module; este objeto es el mismo que el atributo __dict__ del objeto módulo. Si
module no es un objeto módulo (o un subtipo de un objeto de módulo), se lanza SystemError y se retorna
NULL.
It is recommended extensions use other PyModule_* and PyObject_* functions rather than directly ma-
nipulate a module’s __dict__.
PyObject *PyModule_GetNameObject(PyObject *module)
Return value: New reference. Part of the Stable ABI since version 3.7. Retorna el valor __name__ del module.
Si el módulo no proporciona uno, o si no es una cadena de caracteres, SystemError se lanza y se retorna
NULL.
Added in version 3.3.
const char *PyModule_GetName(PyObject *module)
Part of the Stable ABI. Similar a PyModule_GetNameObject() pero retorna el nombre codificado a
'utf-8'.

8.6. Otros objetos 169


The Python/C API, Versión 3.12.4

void *PyModule_GetState(PyObject *module)


Part of the Stable ABI. Retorna el «estado» del módulo, es decir, un puntero al bloque de memoria asignado
en el momento de la creación del módulo, o NULL. Ver PyModuleDef.m_size.
PyModuleDef *PyModule_GetDef(PyObject *module)
Part of the Stable ABI. Retorna un puntero a la estructura PyModuleDef a partir de la cual se creó el módulo,
o NULL si el módulo no se creó a partir de una definición.
PyObject *PyModule_GetFilenameObject(PyObject *module)
Return value: New reference. Part of the Stable ABI. Retorna el nombre del archivo desde el cual module se
cargó utilizando el atributo __file__ del module. Si esto no está definido, o si no es una cadena de caracteres
unicode, lanza SystemError y retornar NULL; de lo contrario, retorna una referencia a un objeto Unicode.
Added in version 3.2.
const char *PyModule_GetFilename(PyObject *module)
Part of the Stable ABI. Similar a PyModule_GetFilenameObject() pero retorna el nombre de archivo
codificado a “utf-8”.
Obsoleto desde la versión 3.2: PyModule_GetFilename() raises UnicodeEncodeError on unen-
codable filenames, use PyModule_GetFilenameObject() instead.

Inicializando módulos en C

Los objetos módulos generalmente se crean a partir de módulos de extensión (bibliotecas compartidas que ex-
portan una función de inicialización) o módulos compilados (donde la función de inicialización se agrega usando
PyImport_AppendInittab()). Consulte building o extendiendo con incrustación para más detalles.
La función de inicialización puede pasar una instancia de definición de módulo a PyModule_Create(), y retornar
el objeto módulo resultante, o solicitar una «inicialización de múltiples fases» retornando la estructura de definición.
type PyModuleDef
Part of the Stable ABI (including all members). La estructura de definición de módulo, que contiene toda
la información necesaria para crear un objeto módulo. Por lo general, solo hay una variable estáticamente
inicializada de este tipo para cada módulo.
PyModuleDef_Base m_base
Always initialize this member to PyModuleDef_HEAD_INIT.
const char *m_name
Nombre para el nuevo módulo.
const char *m_doc
Docstring para el módulo; por lo general, se usa una variable docstring creada con PyDoc_STRVAR.
Py_ssize_t m_size
El estado del módulo se puede mantener en un área de memoria por módulo que se puede recuperar con
PyModule_GetState(), en lugar de en globales estáticos. Esto hace que los módulos sean seguros
para su uso en múltiples sub-interpretadores.
This memory area is allocated based on m_size on module creation, and freed when the module object is
deallocated, after the m_free function has been called, if present.
Establecer m_size en -1 significa que el módulo no admite sub-interpretadores, porque tiene un estado
global.
Establecerlo en un valor no negativo significa que el módulo se puede reinicializar y especifica la cantidad
adicional de memoria que requiere para su estado. Se requiere m_size no negativo para la inicialización
de múltiples fases.
Ver PEP 3121 para más detalles.

170 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

PyMethodDef *m_methods
Un puntero a una tabla de funciones de nivel de módulo, descrito por valores PyMethodDef. Puede
ser NULL si no hay funciones presentes.
PyModuleDef_Slot *m_slots
Un conjunto de definiciones de ranura para la inicialización de múltiples fases, terminadas por una entrada
{0, NULL}. Cuando se utiliza la inicialización monofásica, m_slots debe ser NULL.
Distinto en la versión 3.5: Antes de la versión 3.5, este miembro siempre estaba configurado en NULL y
se definía como:
inquiry m_reload

traverseproc m_traverse
Una función transversal para llamar durante el recorrido GC del objeto del módulo, o NULL si no es
necesario.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.
inquiry m_clear
Una función clara para llamar durante la limpieza GC del objeto del módulo, o NULL si no es necesario.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Tal como PyTypeObject.tp_clear, esta función no siempre es llamada antes de la designación de
un módulo. Por ejemplo, cuando el recuento de referencias está listo para determinar que un objeto no se
usa más, la recolección de basura cíclica no se involucra y se llama a m_free directamente.
Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.
freefunc m_free
Una función para llamar durante la desasignación del objeto del módulo, o NULL si no es necesario.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.

Inicialización monofásica

La función de inicialización del módulo puede crear y retornar el objeto módulo directamente. Esto se conoce como
«inicialización monofásica» y utiliza una de las siguientes funciones de creación de dos módulos:
PyObject *PyModule_Create(PyModuleDef *def)
Return value: New reference. Create a new module object, given the definition in def. This behaves like
PyModule_Create2() with module_api_version set to PYTHON_API_VERSION.
PyObject *PyModule_Create2(PyModuleDef *def, int module_api_version)
Return value: New reference. Part of the Stable ABI. Crea un nuevo objeto de módulo, dada la definición en
def, asumiendo la versión de API module_api_version. Si esa versión no coincide con la versión del intérprete
en ejecución, se emite un RuntimeWarning.

8.6. Otros objetos 171


The Python/C API, Versión 3.12.4

Nota: La mayoría de los usos de esta función deberían usar PyModule_Create() en su lugar; solo use
esto si está seguro de que lo necesita.

Antes de que se retorne desde la función de inicialización, el objeto del módulo resultante normalmente se llena
utilizando funciones como PyModule_AddObjectRef().

Inicialización multifase

An alternate way to specify extensions is to request «multi-phase initialization». Extension modules created this
way behave more like Python modules: the initialization is split between the creation phase, when the module ob-
ject is created, and the execution phase, when it is populated. The distinction is similar to the __new__() and
__init__() methods of classes.
Unlike modules created using single-phase initialization, these modules are not singletons: if the sys.modules entry
is removed and the module is re-imported, a new module object is created, and the old module is subject to normal
garbage collection – as with Python modules. By default, multiple modules created from the same definition should
be independent: changes to one should not affect the others. This means that all state should be specific to the module
object (using e.g. using PyModule_GetState()), or its contents (such as the module’s __dict__ or individual
classes created with PyType_FromSpec()).
Se espera que todos los módulos creados mediante la inicialización de múltiples fases admitan sub-interpretadores.
Asegurándose de que varios módulos sean independientes suele ser suficiente para lograr esto.
Para solicitar la inicialización de múltiples fases, la función de inicialización (PyInit_modulename) retorna una ins-
tancia de PyModuleDef con un m_slots no vacío. Antes de que se retorna, la instancia PyModuleDef debe
inicializarse con la siguiente función:
PyObject *PyModuleDef_Init(PyModuleDef *def)
Return value: Borrowed reference. Part of the Stable ABI since version 3.5. Asegura que la definición de un
módulo sea un objeto Python correctamente inicializado que informe correctamente su tipo y conteo de refe-
rencias.
Retorna def convertido a PyObject* o NULL si se produjo un error.
Added in version 3.5.
El miembro m_slots de la definición del módulo debe apuntar a un arreglo de estructuras PyModuleDef_Slot:
type PyModuleDef_Slot

int slot
Una ranura ID, elegida entre los valores disponibles que se explican a continuación.
void *value
Valor de la ranura, cuyo significado depende de la ID de la ranura.
Added in version 3.5.
El arreglo m_slots debe estar terminada por una ranura con id 0.
Los tipos de ranura disponibles son:
Py_mod_create
Especifica una función que se llama para crear el objeto del módulo en sí. El puntero value de este espacio debe
apuntar a una función de la firma:
PyObject *create_module(PyObject *spec, PyModuleDef *def)

La función recibe una instancia de ModuleSpec, como se define en PEP 451, y la definición del módulo.
Debería retornar un nuevo objeto de módulo, o establecer un error y retornar NULL.
Esta función debe mantenerse mínima. En particular, no debería llamar a código arbitrario de Python, ya que
intentar importar el mismo módulo nuevamente puede dar como resultado un bucle infinito.

172 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

Múltiples ranuras Py_mod_create no pueden especificarse en una definición de módulo.


Si no se especifica Py_mod_create, la maquinaria de importación creará un objeto de módulo normal
usando PyModule_New(). El nombre se toma de spec, no de la definición, para permitir que los módulos
de extensión se ajusten dinámicamente a su lugar en la jerarquía de módulos y se importen bajo diferentes
nombres a través de enlaces simbólicos, todo mientras se comparte una definición de módulo único.
No es necesario que el objeto retornado sea una instancia de PyModule_Type. Se puede usar cualquier tipo,
siempre que admita la configuración y la obtención de atributos relacionados con la importación. Sin embargo,
solo se pueden retornar instancias PyModule_Type si el PyModuleDef no tiene NULL m_traverse,
m_clear, m_free; m_size distinto de cero; o ranuras que no sean Py_mod_create.
Py_mod_exec
Especifica una función que se llama para ejecutar (execute) el módulo. Esto es equivalente a ejecutar el código
de un módulo Python: por lo general, esta función agrega clases y constantes al módulo. La firma de la función
es:
int exec_module(PyObject *module)

Si se especifican varias ranuras Py_mod_exec, se procesan en el orden en que aparecen en el arreglo m_slots.
Py_mod_multiple_interpreters
Specifies one of the following values:
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
The module does not support being imported in subinterpreters.
Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
The module supports being imported in subinterpreters, but only when they share the main interpreter’s
GIL. (See isolating-extensions-howto.)
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
The module supports being imported in subinterpreters, even when they have their own GIL. (See
isolating-extensions-howto.)
This slot determines whether or not importing this module in a subinterpreter will fail.
Multiple Py_mod_multiple_interpreters slots may not be specified in one module definition.
If Py_mod_multiple_interpreters is not specified, the import machinery defaults to
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED.
Added in version 3.12.
Ver PEP 489 para más detalles sobre la inicialización de múltiples fases.

Funciones de creación de módulos de bajo nivel

Las siguientes funciones se invocan en segundo plano cuando se utiliza la inicialización de múltiples fases. Se pue-
den usar directamente, por ejemplo, al crear objetos de módulo de forma dinámica. Tenga en cuenta que tanto
PyModule_FromDefAndSpec como PyModule_ExecDef deben llamarse para inicializar completamente
un módulo.
PyObject *PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)
Return value: New reference. Create a new module object, given the definition in def and the Mo-
duleSpec spec. This behaves like PyModule_FromDefAndSpec2() with module_api_version set to
PYTHON_API_VERSION.
Added in version 3.5.
PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)
Return value: New reference. Part of the Stable ABI since version 3.7. Create a new module object, given the
definition in def and the ModuleSpec spec, assuming the API version module_api_version. If that version does
not match the version of the running interpreter, a RuntimeWarning is emitted.

8.6. Otros objetos 173


The Python/C API, Versión 3.12.4

Nota: La mayoría de los usos de esta función deberían usar PyModule_FromDefAndSpec() en su lugar;
solo use esto si está seguro de que lo necesita.

Added in version 3.5.


int PyModule_ExecDef(PyObject *module, PyModuleDef *def)
Part of the Stable ABI since version 3.7. Procesa cualquier ranura de ejecución (Py_mod_exec) dado en def.
Added in version 3.5.
int PyModule_SetDocString(PyObject *module, const char *docstring)
Part of the Stable ABI since version 3.7. Establece la cadena de caracteres de documentación para module en
docstring. Esta función se llama automáticamente cuando se crea un módulo desde PyModuleDef, usando
PyModule_Create o PyModule_FromDefAndSpec.
Added in version 3.5.
int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)
Part of the Stable ABI since version 3.7. Agrega las funciones del arreglo functions terminadas en NULL a mo-
dule. Consulte la documentación de PyMethodDef para obtener detalles sobre entradas individuales (debido
a la falta de un espacio de nombres de módulo compartido, las «funciones» de nivel de módulo implementadas
en C generalmente reciben el módulo como su primer parámetro, haciéndolos similares a la instancia métodos
en clases de Python). Esta función se llama automáticamente cuando se crea un módulo desde PyModuleDef,
usando PyModule_Create o PyModule_FromDefAndSpec.
Added in version 3.5.

Funciones de soporte

La función de inicialización del módulo (si usa la inicialización de fase única) o una función llamada desde un intervalo
de ejecución del módulo (si usa la inicialización de múltiples fases), puede usar las siguientes funciones para ayudar
a inicializar el estado del módulo:
int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
Part of the Stable ABI since version 3.10. Agrega un objeto a module como name. Esta es una función de
conveniencia que se puede usar desde la función de inicialización del módulo.
En caso de éxito, retorna 0. En caso de error, lanza una excepción y retorna -1.
Retorna NULL si value es NULL. Debe llamarse lanzando una excepción en este caso.
Ejemplo de uso

static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_DECREF(obj);
return res;
}

El ejemplo puede también ser escrito sin verificar explicitamente si obj es NULL:

static int
add_spam(PyObject *module, int value)
{
(continúe en la próxima página)

174 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


PyObject *obj = PyLong_FromLong(value);
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_XDECREF(obj);
return res;
}

Note que Py_XDECREF() debería ser usado en vez de Py_DECREF() en este caso, ya que obj puede ser
NULL.
Added in version 3.10.
int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
Part of the Stable ABI. Similar a PyModule_AddObjectRef(), pero roba una referencia a value en caso
de éxito (en este caso retorna 0).
Se recomienda la nueva función PyModule_AddObjectRef(), ya que es sencillo introducir fugas de
referencias por un uso incorrecto de la función PyModule_AddObject().

Nota: Unlike other functions that steal references, PyModule_AddObject() only releases the reference
to value on success.
Esto significa que su valor de retorno debe ser verificado, y el código de llamada debe Py_DECREF() value
manualmente en caso de error.

Ejemplo de uso

static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
if (PyModule_AddObject(module, "spam", obj) < 0) {
Py_DECREF(obj);
return -1;
}
// PyModule_AddObject() stole a reference to obj:
// Py_DECREF(obj) is not needed here
return 0;
}

El ejemplo puede también ser escrito sin verificar explicitamente si obj es NULL:

static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (PyModule_AddObject(module, "spam", obj) < 0) {
Py_XDECREF(obj);
return -1;
}
// PyModule_AddObject() stole a reference to obj:
// Py_DECREF(obj) is not needed here
return 0;
}

Note que Py_XDECREF() debería ser usado en vez de Py_DECREF() en este caso, ya que obj puede ser
NULL.

8.6. Otros objetos 175


The Python/C API, Versión 3.12.4

int PyModule_AddIntConstant(PyObject *module, const char *name, long value)


Part of the Stable ABI. Agrega una constante entera a module como name. Esta función de conveniencia se
puede usar desde la función de inicialización del módulo. Retorna -1 en caso de error, 0 en caso de éxito.
int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
Part of the Stable ABI. Agrega una constante de cadena a module como name. Esta función de conveniencia se
puede usar desde la función de inicialización del módulo. La cadena de caracteres value debe estar terminada
en NULL. Retorna -1 en caso de error, 0 en caso de éxito.
PyModule_AddIntMacro(module, macro)
Agrega una constante int a module. El nombre y el valor se toman de macro. Por ejemplo,
PyModule_AddIntMacro(module, AF_INET) agrega la constante int AF_INET con el valor de
AF_INET a module. Retorna -1 en caso de error, 0 en caso de éxito.
PyModule_AddStringMacro(module, macro)
Agrega una constante de cadena de caracteres a module.
int PyModule_AddType(PyObject *module, PyTypeObject *type)
Part of the Stable ABI since version 3.10. Agrega un objeto tipo a module. El objeto tipo se finaliza llamando
internamente PyType_Ready(). El nombre del objeto tipo se toma del último componente de tp_name
después del punto. Retorna -1 en caso de error, 0 en caso de éxito.
Added in version 3.9.

Búsqueda de módulos

La inicialización monofásica crea módulos singleton que se pueden buscar en el contexto del intérprete actual. Esto
permite que el objeto módulo se recupere más tarde con solo una referencia a la definición del módulo.
Estas funciones no funcionarán en módulos creados mediante la inicialización de múltiples fases, ya que se pueden
crear múltiples módulos de este tipo desde una sola definición.
PyObject *PyState_FindModule(PyModuleDef *def)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto módulo que se creó a partir de
def para el intérprete actual. Este método requiere que el objeto módulo se haya adjuntado al estado del intér-
prete con PyState_AddModule() de antemano. En caso de que el objeto módulo correspondiente no se
encuentre o no se haya adjuntado al estado del intérprete, retornará NULL.
int PyState_AddModule(PyObject *module, PyModuleDef *def)
Part of the Stable ABI since version 3.3. Adjunta el objeto del módulo pasado a la función al estado del intérprete.
Esto permite que se pueda acceder al objeto del módulo a través de PyState_FindModule().
Solo es efectivo en módulos creados con la inicialización monofásica.
Python llama a PyState_AddModule automáticamente después de importar un módulo, por lo que es
innecesario (pero inofensivo) llamarlo desde el código de inicialización del módulo. Solo se necesita una lla-
mada explícita si el propio código de inicio del módulo llama posteriormente PyState_FindModule. La
función está destinada principalmente a implementar mecanismos de importación alternativos (ya sea llamán-
dolo directamente o refiriéndose a su implementación para obtener detalles de las actualizaciones de estado
requeridas).
La persona que llama debe retener el GIL.
Retorna 0 en caso de éxito o -1 en caso de error.
Added in version 3.3.
int PyState_RemoveModule(PyModuleDef *def)
Part of the Stable ABI since version 3.3. Elimina el objeto del módulo creado a partir de def del estado del
intérprete. Retorna 0 en caso de éxito o -1 en caso de error.
La persona que llama debe retener el GIL.
Added in version 3.3.

176 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.6.3 Objetos iteradores

Python provides two general-purpose iterator objects. The first, a sequence iterator, works with an arbitrary sequence
supporting the __getitem__() method. The second works with a callable object and a sentinel value, calling the
callable for each item in the sequence, and ending the iteration when the sentinel value is returned.
PyTypeObject PySeqIter_Type
Part of the Stable ABI. Objeto tipo para objetos iteradores retornados por PySeqIter_New() y la forma
de un argumento de la función incorporada iter() para los tipos de secuencia incorporados.
int PySeqIter_Check(PyObject *op)
Retorna verdadero si el tipo de op es PySeqIter_Type. Esta función siempre finaliza con éxito.
PyObject *PySeqIter_New(PyObject *seq)
Return value: New reference. Part of the Stable ABI. Retorna un iterador que funciona con un objeto de se-
cuencia general, seq. La iteración termina cuando la secuencia lanza IndexError para la operación de
suscripción.
PyTypeObject PyCallIter_Type
Part of the Stable ABI. Objeto tipo para los objetos iteradores retornados por PyCallIter_New() y la
forma de dos argumentos de la función incorporada iter().
int PyCallIter_Check(PyObject *op)
Retorna verdadero si el tipo de op es PyCallIter_Type. Esta función siempre finaliza con éxito.
PyObject *PyCallIter_New(PyObject *callable, PyObject *sentinel)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo iterador. El primer parámetro, callable,
puede ser cualquier objeto invocable de Python que se pueda invocar sin parámetros; cada llamada debe retornar
el siguiente elemento en la iteración. Cuando callable retorna un valor igual a sentinel, la iteración finalizará.

8.6.4 Objetos descriptores

Los «descriptores» son objetos que describen algún atributo de un objeto. Se encuentran en el diccionario de objetos
tipo.
PyTypeObject PyProperty_Type
Part of the Stable ABI. El objeto de tipo para los tipos de descriptor incorporado.
PyObject *PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
Return value: New reference.
PyObject *PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
Return value: New reference. Part of the Stable ABI.
int PyDescr_IsData(PyObject *descr)
Retorna distinto de cero si el descriptor objetos descr describe un atributo de datos, o 0 si describe un método.
descr debe ser un objeto descriptor; no hay comprobación de errores.
PyObject *PyWrapper_New(PyObject*, PyObject*)
Return value: New reference. Part of the Stable ABI.

8.6. Otros objetos 177


The Python/C API, Versión 3.12.4

8.6.5 Objetos rebanada (slice)

PyTypeObject PySlice_Type
Part of the Stable ABI. El objeto tipo para objetos rebanadas. Esto es lo mismo que slice en la capa de
Python.
int PySlice_Check(PyObject *ob)
Retorna verdadero si ob es un objeto rebanada; ob no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto rebanada con los valores da-
dos. Los parámetros start, stop y step se utilizan como los valores de los atributos del objeto rebanada de los
mismos nombres. Cualquiera de los valores puede ser NULL, en cuyo caso se usará None para el atributo
correspondiente. Retorna NULL si no se puedo asignar el nuevo objeto.
int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t
*step)
Part of the Stable ABI. Recupera los índices start, stop y step del objeto rebanada slice, suponiendo una secuencia
de longitud length. Trata los índices mayores que length como errores.
Returns 0 on success and -1 on error with no exception set (unless one of the indices was not None and failed
to be converted to an integer, in which case -1 is returned with an exception set).
Probablemente no quiera usar esta función.
Distinto en la versión 3.2: El tipo de parámetro para el parámetro slice era PySliceObject* antes.
int PySlice_GetIndicesEx(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t
*step, Py_ssize_t *slicelength)
Part of the Stable ABI. Reemplazo utilizable para PySlice_GetIndices(). Recupera los índices de start,
stop, y step del objeto rebanada slice asumiendo una secuencia de longitud length, y almacena la longitud de
la rebanada en slicelength. Los índices fuera de los límites se recortan de manera coherente con el manejo de
sectores normales.
Retorna 0 en caso de éxito y -1 en caso de error con excepción establecida.

Nota: Esta función se considera no segura para secuencias redimensionables. Su invocación debe ser reem-
plazada por una combinación de PySlice_Unpack() y PySlice_AdjustIndices() donde:

if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) <␣


,→0) {

// return error
}

es reemplazado por:

if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {


// return error
}
slicelength = PySlice_AdjustIndices(length, &start, &stop, step);

Distinto en la versión 3.2: El tipo de parámetro para el parámetro slice era PySliceObject* antes.
Distinto en la versión 3.6.1: Si Py_LIMITED_API no se establece o establece el valor entre 0x03050400 y
0x03060000 (sin incluir) o 0x03060100 o un superior PySlice_GetIndicesEx() se implementa
como un macro usando PySlice_Unpack() y PySlice_AdjustIndices(). Los argumentos start,
stop y step se evalúan más de una vez.
Obsoleto desde la versión 3.6.1: Si Py_LIMITED_API se establece en un valor menor que 0x03050400 o
entre 0x03060000 y 0x03060100 (sin incluir) PySlice_GetIndicesEx() es una función obsoleta.

178 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)


Part of the Stable ABI since version 3.7. Extrae los miembros de datos start, stop, y step de un obje-
to rebanada como enteros en C. Reduce silenciosamente los valores mayores que PY_SSIZE_T_MAX a
PY_SSIZE_T_MAX, aumenta silenciosamente los valores start y stop inferiores a PY_SSIZE_T_MIN
a PY_SSIZE_T_MIN, y silenciosamente aumenta los valores de step a menos de -PY_SSE a
-PY_SSIZE_T_MAX.
Retorna -1 en caso de error, 0 en caso de éxito.
Added in version 3.6.1.
Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)
Part of the Stable ABI since version 3.7. Ajusta los índices de corte de inicio/fin asumiendo una secuencia de
la longitud especificada. Los índices fuera de los límites se recortan de manera coherente con el manejo de
sectores normales.
Retorna la longitud de la rebanada. Siempre exitoso. No llama al código de Python.
Added in version 3.6.1.

Objeto elipsis

PyObject *Py_Ellipsis
The Python Ellipsis object. This object has no methods. Like Py_None, it is an immortal. singleton
object.
Distinto en la versión 3.12: Py_Ellipsis is immortal.

8.6.6 Objetos de vista de memoria (MemoryView )

Un objeto memoryview expone la interfaz de búfer a nivel de C como un objeto Python que luego puede pasarse
como cualquier otro objeto.
PyObject *PyMemoryView_FromObject(PyObject *obj)
Return value: New reference. Part of the Stable ABI. Crea un objeto de vista de memoria memoryview a partir
de un objeto que proporciona la interfaz del búfer. Si obj admite exportaciones de búfer de escritura, el objeto
de vista de memoria será de lectura/escritura, de lo contrario puede ser de solo lectura o de lectura/escritura a
discreción del exportador.
PyBUF_READ
Flag to request a readonly buffer.
PyBUF_WRITE
Flag to request a writable buffer.
PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
Return value: New reference. Part of the Stable ABI since version 3.7. Crea un objeto de vista de memoria
usando mem como el búfer subyacente. flags pueden ser uno de PyBUF_READ o PyBUF_WRITE.
Added in version 3.3.
PyObject *PyMemoryView_FromBuffer(const Py_buffer *view)
Return value: New reference. Part of the Stable ABI since version 3.11. Crea un objeto de vista de
memoria que ajuste la estructura de búfer dada view. Para memorias intermedias de bytes simples,
PyMemoryView_FromMemory() es la función preferida.
PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
Return value: New reference. Part of the Stable ABI. Crea un objeto de vista de memoria memoryview para
un fragmento de memoria contiguo (contiguous, en order “C” o “F” de Fortran) desde un objeto que define la
interfaz del búfer. Si la memoria es contigua, el objeto de vista de memoria apunta a la memoria original. De
lo contrario, se realiza una copia y la vista de memoria apunta a un nuevo objeto de bytes.

8.6. Otros objetos 179


The Python/C API, Versión 3.12.4

buffertype can be one of PyBUF_READ or PyBUF_WRITE.


int PyMemoryView_Check(PyObject *obj)
Retorna verdadero si el objeto obj es un objeto de vista de memoria. Actualmente no está permitido crear
subclases de memoryview. Esta función siempre finaliza con éxito.
Py_buffer *PyMemoryView_GET_BUFFER(PyObject *mview)
Retorna un puntero a la copia privada de la vista de memoria del búfer del exportador. mview debe ser una
instancia de memoryview; este macro no verifica su tipo, debe hacerlo usted mismo o correrá el riesgo de fallas.
PyObject *PyMemoryView_GET_BASE(PyObject *mview)
Retorna un puntero al objeto de exportación en el que se basa la vista de memoria o NULL si
la vista de memoria ha sido creada por una de las funciones PyMemoryView_FromMemory() o
PyMemoryView_FromBuffer(). mview debe ser una instancia de memoryview.

8.6.7 Objetos de referencia débil

Python soporta referencias débiles como objetos de primera clase. Hay dos tipos de objetos específicos que imple-
mentan directamente referencias débiles. El primero es un objeto con referencia simple, y el segundo actúa como un
proxy del objeto original tanto como pueda.
int PyWeakref_Check(PyObject *ob)
Retorna verdadero (true) si ob es una referencia o un objeto proxy. Esta función siempre finaliza con éxito.
int PyWeakref_CheckRef(PyObject *ob)
Retorna verdadero (true) si ob es un objeto de referencia. Esta función siempre finaliza con éxito.
int PyWeakref_CheckProxy(PyObject *ob)
Retorna verdadero (true) si ob es un objeto proxy. Esta función siempre finaliza con éxito.
PyObject *PyWeakref_NewRef(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference object for the object ob. This
will always return a new reference, but is not guaranteed to create a new object; an existing reference object
may be returned. The second parameter, callback, can be a callable object that receives notification when ob is
garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback
may also be None or NULL. If ob is not a weakly referenceable object, or if callback is not callable, None, or
NULL, this will return NULL and raise TypeError.
PyObject *PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference proxy object for the object ob.
This will always return a new reference, but is not guaranteed to create a new object; an existing proxy object
may be returned. The second parameter, callback, can be a callable object that receives notification when ob is
garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback
may also be None or NULL. If ob is not a weakly referenceable object, or if callback is not callable, None, or
NULL, this will return NULL and raise TypeError.
PyObject *PyWeakref_GetObject(PyObject *ref)
Return value: Borrowed reference. Part of the Stable ABI. Return the referenced object from a weak reference,
ref. If the referent is no longer live, returns Py_None.

Nota: Esta función retorna una referencia borrowed reference al objeto referenciado. Esto significa que siempre
debe llamar a Py_INCREF() sobre el objeto, excepto cuando no pueda ser destruido antes del último uso de
la referencia prestada.

PyObject *PyWeakref_GET_OBJECT(PyObject *ref)


Return value: Borrowed reference. Similar to PyWeakref_GetObject(), but does no error checking.

180 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

void PyObject_ClearWeakRefs(PyObject *object)


Part of the Stable ABI. This function is called by the tp_dealloc handler to clear weak references.
This iterates through the weak references for object and calls callbacks for those references which have one. It
returns when all callbacks have been attempted.

8.6.8 Cápsulas

Consulta using-capsules para obtener más información sobre el uso de estos objetos.
Added in version 3.1.
type PyCapsule
Este subtipo de PyObject representa un valor opaco, útil para los módulos de extensión C que necesitan
pasar un valor opaco (como un puntero void*) a través del código Python a otro código C . A menudo se usa
para hacer que un puntero de función C definido en un módulo esté disponible para otros módulos, por lo que
el mecanismo de importación regular se puede usar para acceder a las API C definidas en módulos cargados
dinámicamente.
type PyCapsule_Destructor
Part of the Stable ABI. El tipo de devolución de llamada de un destructor para una cápsula. Definido como:

typedef void (*PyCapsule_Destructor)(PyObject *);

Consulte PyCapsule_New() para conocer la semántica de las devoluciones de llamada de PyCapsu-


le_Destructor.
int PyCapsule_CheckExact(PyObject *p)
Retorna verdadero si su argumento es a PyCapsule. Esta función siempre finaliza con éxito.
PyObject *PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor)
Return value: New reference. Part of the Stable ABI. Crea un PyCapsule encapsulando el pointer. El argu-
mento pointer puede no ser NULL.
En caso de falla, establece una excepción y retorna NULL.
La cadena de caracteres name puede ser NULL o un puntero a una cadena C válida. Si no es NULL, esta cadena
de caracteres debe sobrevivir a la cápsula. (Aunque está permitido liberarlo dentro del destructor).
Si el argumento destructor no es NULL, se llamará con la cápsula como argumento cuando se destruya.
Si esta cápsula se almacenará como un atributo de un módulo, el nombre name debe especificarse co-
mo modulename.attributename. Esto permitirá que otros módulos importen la cápsula usando
PyCapsule_Import().
void *PyCapsule_GetPointer(PyObject *capsule, const char *name)
Part of the Stable ABI. Recupera el pointer almacenado en la cápsula. En caso de falla, establece una excepción
y retorna NULL.
The name parameter must compare exactly to the name stored in the capsule. If the name stored in the capsule
is NULL, the name passed in must also be NULL. Python uses the C function strcmp() to compare capsule
names.
PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule)
Part of the Stable ABI. Retorna el destructor actual almacenado en la cápsula. En caso de falla, establece una
excepción y retorna NULL.
Es legal que una cápsula tenga un destructor NULL. Esto hace que un código de retorno NULL sea algo ambiguo;
use PyCapsule_IsValid() o PyErr_Occurred() para desambiguar.

8.6. Otros objetos 181


The Python/C API, Versión 3.12.4

void *PyCapsule_GetContext(PyObject *capsule)


Part of the Stable ABI. Retorna el contexto actual almacenado en la cápsula. En caso de falla, establece una
excepción y retorna NULL.
Es legal que una cápsula tenga un contexto NULL. Esto hace que un código de retorno NULL sea algo ambiguo;
use PyCapsule_IsValid() o PyErr_Occurred() para desambiguar.
const char *PyCapsule_GetName(PyObject *capsule)
Part of the Stable ABI. Retorna el nombre actual almacenado en la cápsula. En caso de falla, establece una
excepción y retorna NULL.
Es legal que una cápsula tenga un nombre NULL. Esto hace que un código de retorno NULL sea algo ambiguo;
use PyCapsule_IsValid() o PyErr_Occurred() para desambiguar.
void *PyCapsule_Import(const char *name, int no_block)
Part of the Stable ABI. Importa un puntero a un objeto C desde un atributo cápsula en un módulo. El parámetro
name debe especificar el nombre completo del atributo, como en module.attribute. El nombre name
almacenado en la cápsula debe coincidir exactamente con esta cadena de caracteres.
Retorna el puntero pointer interno de la cápsula en caso de éxito. En caso de falla, establece una excepción y
retorna NULL.
Distinto en la versión 3.3: no_block ya no tiene efecto.
int PyCapsule_IsValid(PyObject *capsule, const char *name)
Part of the Stable ABI. Determina si capsule es o no una cápsula válida. Una cápsula válida no es NULL,
pasa PyCapsule_CheckExact(), tiene un puntero no NULL almacenado y su nombre interno coincide
con el parámetro name. (Consulte PyCapsule_GetPointer() para obtener información sobre cómo se
comparan los nombres de las cápsulas).
In other words, if PyCapsule_IsValid() returns a true value, calls to any of the accessors (any function
starting with PyCapsule_Get) are guaranteed to succeed.
Retorna un valor distinto de cero si el objeto es válido y coincide con el nombre pasado. Retorna 0 de lo
contrario. Esta función no fallará.
int PyCapsule_SetContext(PyObject *capsule, void *context)
Part of the Stable ABI. Establece el puntero de contexto dentro de capsule a context.
Retorna 0 en caso de éxito. Retorna distinto de cero y establece una excepción en caso de error.
int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor)
Part of the Stable ABI. Establece el destructor dentro de capsule en destructor.
Retorna 0 en caso de éxito. Retorna distinto de cero y establece una excepción en caso de error.
int PyCapsule_SetName(PyObject *capsule, const char *name)
Part of the Stable ABI. Establece el nombre dentro de capsule a name. Si no es NULL, el nombre debe sobrevivir
a la cápsula. Si el name anterior almacenado en la cápsula no era NULL, no se intenta liberarlo.
Retorna 0 en caso de éxito. Retorna distinto de cero y establece una excepción en caso de error.
int PyCapsule_SetPointer(PyObject *capsule, void *pointer)
Part of the Stable ABI. Establece el puntero vacío dentro de capsule a pointer. El puntero puede no ser NULL.
Retorna 0 en caso de éxito. Retorna distinto de cero y establece una excepción en caso de error.

182 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.6.9 Objetos frame

type PyFrameObject
Part of the Limited API (as an opaque struct). La estructura C de los objetos utilizados para describir los objetos
del frame.
No hay miembros públicos en esta estructura.
Distinto en la versión 3.11: Los miembros de esta estructura se han eliminado de la API pública de C. Consulte
la entrada Novedades para más detalles.
Las funciones PyEval_GetFrame() y PyThreadState_GetFrame() pueden utilizarse para obtener un
objeto frame.
Véase también Reflexión.
PyTypeObject PyFrame_Type
The type of frame objects. It is the same object as types.FrameType in the Python layer.
Distinto en la versión 3.11: Previously, this type was only available after including <frameobject.h>.
int PyFrame_Check(PyObject *obj)
Return non-zero if obj is a frame object.
Distinto en la versión 3.11: Previously, this function was only available after including <frameobject.h>.
PyFrameObject *PyFrame_GetBack(PyFrameObject *frame)
Obtiene el frame exterior siguiente.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Added in version 3.9.
PyObject *PyFrame_GetBuiltins(PyFrameObject *frame)
Get the frame’s f_builtins attribute.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Added in version 3.11.
PyCodeObject *PyFrame_GetCode(PyFrameObject *frame)
Part of the Stable ABI since version 3.10. Obtenga el código frame.
Retorna un strong reference.
El resultado (frame code) no puede ser NULL.
Added in version 3.9.
PyObject *PyFrame_GetGenerator(PyFrameObject *frame)
Obtiene el generador, rutina o generador asíncrono al que pertenece este frame, o NULL si este frame no es
propiedad de un generador. No lanza una excepción, incluso si el valor de retorno es NULL.
Retorna un strong reference, o NULL.
Added in version 3.11.
PyObject *PyFrame_GetGlobals(PyFrameObject *frame)
Get the frame’s f_globals attribute.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Added in version 3.11.
int PyFrame_GetLasti(PyFrameObject *frame)
Get the frame’s f_lasti attribute.
Retorna -1 si frame.f_lasti es None.
Added in version 3.11.

8.6. Otros objetos 183


The Python/C API, Versión 3.12.4

PyObject *PyFrame_GetVar(PyFrameObject *frame, PyObject *name)


Get the variable name of frame.
• Return a strong reference to the variable value on success.
• Raise NameError and return NULL if the variable does not exist.
• Raise an exception and return NULL on error.
name type must be a str.
Added in version 3.12.
PyObject *PyFrame_GetVarString(PyFrameObject *frame, const char *name)
Similar to PyFrame_GetVar(), but the variable name is a C string encoded in UTF-8.
Added in version 3.12.
PyObject *PyFrame_GetLocals(PyFrameObject *frame)
Get the frame’s f_locals attribute (dict).
Retorna un strong reference.
Added in version 3.11.
int PyFrame_GetLineNumber(PyFrameObject *frame)
Part of the Stable ABI since version 3.10. Retorna el número de línea en la que se está ejecutando el frame.

Internal Frames

Unless using PEP 523, you will not need this.


struct _PyInterpreterFrame
The interpreter’s internal frame representation.
Added in version 3.11.
PyObject *PyUnstable_InterpreterFrame_GetCode(struct _PyInterpreterFrame *frame);

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

Return a strong reference to the code object for the frame.

Added in version 3.12.


int PyUnstable_InterpreterFrame_GetLasti(struct _PyInterpreterFrame *frame);

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

Return the byte offset into the last executed instruction.


Added in version 3.12.
int PyUnstable_InterpreterFrame_GetLine(struct _PyInterpreterFrame *frame);

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

Return the currently executing line number, or -1 if there is no line number.


Added in version 3.12.

184 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.6.10 Objetos generadores

Los objetos generadores son lo que Python usa para implementar iteradores generadores. Normalmente se
crean iterando sobre una función que produce valores, en lugar de llamar explícitamente PyGen_New() o
PyGen_NewWithQualName().
type PyGenObject
La estructura en C utilizada para los objetos generadores.
PyTypeObject PyGen_Type
El objeto tipo correspondiente a los objetos generadores.
int PyGen_Check(PyObject *ob)
Retorna verdadero si ob es un objeto generador; ob no debe ser NULL. Esta función siempre finaliza con éxito.
int PyGen_CheckExact(PyObject *ob)
Retorna verdadero si el tipo de ob es PyGen_Type; ob no debe ser NULL. Esta función siempre finaliza con
éxito.
PyObject *PyGen_New(PyFrameObject *frame)
Return value: New reference. Crea y retorna un nuevo objeto generador basado en el objeto frame. Una refe-
rencia a frame es robada por esta función. El argumento no debe ser NULL.
PyObject *PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname)
Return value: New reference. Crea y retorna un nuevo objeto generador basado en el objeto frame, con
__name__ y __qualname__ establecido en name y qualname. Una referencia a frame es robada por
esta función. El argumento frame no debe ser NULL.

8.6.11 Objetos corrutina

Added in version 3.5.


Los objetos de corrutina son las funciones declaradas con un retorno de palabra clave async.
type PyCoroObject
La estructura en C utilizada para objeto corrutina.
PyTypeObject PyCoro_Type
El tipo de objeto correspondiente a los objetos corrutina.
int PyCoro_CheckExact(PyObject *ob)
Retorna verdadero si el tipo de ob es PyCoro_Type; ob no debe ser NULL. Esta función siempre finaliza con
éxito.
PyObject *PyCoro_New(PyFrameObject *frame, PyObject *name, PyObject *qualname)
Return value: New reference. Crea y retorna un nuevo objeto corrutina basado en el objeto frame, con
__name__ y __qualname__ establecido en name y qualname. Una referencia a frame es robada por
esta función. El argumento frame no debe ser NULL.

8.6.12 Objetos de variables de contexto

Added in version 3.7.


Distinto en la versión 3.7.1:

Nota: En Python 3.7.1, las firmas de todas las variables de contexto C APIs fueron cambiadas para usar punteros
PyObject en lugar de PyContext, PyContextVar, y PyContextToken, por ejemplo:

8.6. Otros objetos 185


The Python/C API, Versión 3.12.4

// in 3.7.0:
PyContext *PyContext_New(void);

// in 3.7.1+:
PyObject *PyContext_New(void);

Ver bpo-34762 para más detalles.

Esta sección detalla la API pública de C para el módulo contextvars.


type PyContext
La estructura C utilizada para representar un objeto contextvars.Context.
type PyContextVar
La estructura C utilizada para representar un objeto contextvars.ContextVar.
type PyContextToken
La estructura C solía representar un objeto contextvars.Token.
PyTypeObject PyContext_Type
El objeto de tipo que representa el tipo context.
PyTypeObject PyContextVar_Type
El objeto tipo que representa el tipo variable de contexto.
PyTypeObject PyContextToken_Type
El tipo objeto que representa el tipo token de variable de contexto.
Macros de verificación de tipo:
int PyContext_CheckExact(PyObject *o)
Retorna verdadero si o es de tipo PyContext_Type. o no debe ser NULL. Esta función siempre finaliza con
éxito.
int PyContextVar_CheckExact(PyObject *o)
Retorna verdadero si o es de tipo PyContextVar_Type. o no debe ser NULL. Esta función siempre finaliza
con éxito.
int PyContextToken_CheckExact(PyObject *o)
Retorna verdadero si o es de tipo PyContextToken_Type. o no debe ser NULL. Esta función siempre
finaliza con éxito.
Funciones de gestión de objetos de contexto:
PyObject *PyContext_New(void)
Return value: New reference. Crea un nuevo objeto de contexto vacío. Retorna NULL si se ha producido un
error.
PyObject *PyContext_Copy(PyObject *ctx)
Return value: New reference. Crea una copia superficial del objeto de contexto ctx pasado. Retorna NULL si se
ha producido un error.
PyObject *PyContext_CopyCurrent(void)
Return value: New reference. Crea una copia superficial del contexto actual del hilo. Retorna NULL si se ha
producido un error.
int PyContext_Enter(PyObject *ctx)
Establece ctx como el contexto actual para el hilo actual. Retorna 0 en caso de éxito y -1 en caso de error.
int PyContext_Exit(PyObject *ctx)
Desactiva el contexto ctx y restaura el contexto anterior como el contexto actual para el hilo actual. Retorna 0
en caso de éxito y -1 en caso de error.

186 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

Funciones variables de contexto:


PyObject *PyContextVar_New(const char *name, PyObject *def)
Return value: New reference. Crea un nuevo objeto ContextVar. El parámetro name se usa para propósitos
de introspección y depuración. El parámetro def especifica el valor predeterminado para la variable de contexto,
o NULL para no especificar un valor predeterminado. Si se ha producido un error, esta función retorna NULL.
int PyContextVar_Get(PyObject *var, PyObject *default_value, PyObject **value)
Obtiene el valor de una variable de contexto. Retorna -1 si se produjo un error durante la búsqueda y 0 si no
se produjo ningún error, se haya encontrado o no un valor.
Si se encontró la variable de contexto, value será un puntero a ella. Si la variable de contexto not se encontró,
value apuntará a:
• default_value, si no es NULL;
• el valor predeterminado de var, si no es NULL;
• NULL
A excepción de NULL, la función retorna una nueva referencia.
PyObject *PyContextVar_Set(PyObject *var, PyObject *value)
Return value: New reference. Establece el valor de var en value en el contexto actual. Retorna un nuevo objeto
token para este cambio, o NULL si se ha producido un error.
int PyContextVar_Reset(PyObject *var, PyObject *token)
Restablece el estado de la variable de contexto var a la que estaba antes PyContextVar_Set() que retornó
el token fue llamado. Esta función retorna 0 en caso de éxito y -1 en caso de error.

8.6.13 Objetos DateTime

Various date and time objects are supplied by the datetime module. Before using any of these functions, the header
file datetime.h must be included in your source (note that this is not included by Python.h), and the macro
PyDateTime_IMPORT must be invoked, usually as part of the module initialisation function. The macro puts a
pointer to a C structure into a static variable, PyDateTimeAPI, that is used by the following macros.
type PyDateTime_Date
This subtype of PyObject represents a Python date object.
type PyDateTime_DateTime
This subtype of PyObject represents a Python datetime object.
type PyDateTime_Time
This subtype of PyObject represents a Python time object.
type PyDateTime_Delta
This subtype of PyObject represents the difference between two datetime values.
PyTypeObject PyDateTime_DateType
This instance of PyTypeObject represents the Python date type; it is the same object as datetime.date
in the Python layer.
PyTypeObject PyDateTime_DateTimeType
This instance of PyTypeObject represents the Python datetime type; it is the same object as datetime.
datetime in the Python layer.
PyTypeObject PyDateTime_TimeType
This instance of PyTypeObject represents the Python time type; it is the same object as datetime.time
in the Python layer.

8.6. Otros objetos 187


The Python/C API, Versión 3.12.4

PyTypeObject PyDateTime_DeltaType
This instance of PyTypeObject represents Python type for the difference between two datetime values; it
is the same object as datetime.timedelta in the Python layer.
PyTypeObject PyDateTime_TZInfoType
This instance of PyTypeObject represents the Python time zone info type; it is the same object as
datetime.tzinfo in the Python layer.
Macro para acceder al singleton UTC:
PyObject *PyDateTime_TimeZone_UTC
Retorna la zona horaria singleton que representa UTC, el mismo objeto que datetime.timezone.utc.
Added in version 3.7.
Macros de verificación de tipo:
int PyDate_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DateType or a subtype of PyDateTime_DateType. ob must
not be NULL. This function always succeeds.
int PyDate_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_DateType. ob no debe ser NULL. Esta función siempre
finaliza con éxito.
int PyDateTime_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DateTimeType or a subtype of
PyDateTime_DateTimeType. ob must not be NULL. This function always succeeds.
int PyDateTime_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_DateTimeType. ob no debe ser NULL. Esta función
siempre finaliza con éxito.
int PyTime_Check(PyObject *ob)
Return true if ob is of type PyDateTime_TimeType or a subtype of PyDateTime_TimeType. ob must
not be NULL. This function always succeeds.
int PyTime_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_TimeType. ob no debe ser NULL. Esta función siempre
finaliza con éxito.
int PyDelta_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DeltaType or a subtype of PyDateTime_DeltaType. ob
must not be NULL. This function always succeeds.
int PyDelta_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_DeltaType. ob no debe ser NULL. Esta función siempre
finaliza con éxito.
int PyTZInfo_Check(PyObject *ob)
Return true if ob is of type PyDateTime_TZInfoType or a subtype of PyDateTime_TZInfoType.
ob must not be NULL. This function always succeeds.
int PyTZInfo_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_TZInfoType. ob no debe ser NULL. Esta función siempre
finaliza con éxito.
Macros para crear objetos:
PyObject *PyDate_FromDate(int year, int month, int day)
Return value: New reference. Retorna un objeto datetime.date con el año, mes y día especificados.

188 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

PyObject *PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int
usecond)
Return value: New reference. Retorna un objeto datetime.datetime con el año, mes, día, hora, minuto,
segundo y micro segundo especificados.
PyObject *PyDateTime_FromDateAndTimeAndFold(int year, int month, int day, int hour, int minute, int
second, int usecond, int fold)
Return value: New reference. Retorna un objeto datetime.datetime con el año, mes, día, hora, minuto,
segundo, micro segundo y doblez especificados.
Added in version 3.6.
PyObject *PyTime_FromTime(int hour, int minute, int second, int usecond)
Return value: New reference. Retorna un objeto datetime.time con la hora, minuto, segundo y micro
segundo especificados.
PyObject *PyTime_FromTimeAndFold(int hour, int minute, int second, int usecond, int fold)
Return value: New reference. Retorna un objeto datetime.time con la hora, minuto, segundo, micro se-
gundo y doblez especificados.
Added in version 3.6.
PyObject *PyDelta_FromDSU(int days, int seconds, int useconds)
Return value: New reference. Retorna un objeto datetime.timedelta que representa el número dado
de días, segundos y micro segundos. La normalización se realiza de modo que el número resultante de micro
segundos y segundos se encuentre en los rangos documentados para los objetos datetime.timedelta.
PyObject *PyTimeZone_FromOffset(PyObject *offset)
Return value: New reference. Retorna un objeto datetime.timezone con un desplazamiento fijo sin nom-
bre representado por el argumento offset.
Added in version 3.7.
PyObject *PyTimeZone_FromOffsetAndName(PyObject *offset, PyObject *name)
Return value: New reference. Retorna un objeto datetime.timezone con un desplazamiento fijo repre-
sentado por el argumento offset y con tzname name.
Added in version 3.7.
Macros to extract fields from date objects. The argument must be an instance of PyDateTime_Date, including
subclasses (such as PyDateTime_DateTime). The argument must not be NULL, and the type is not checked:
int PyDateTime_GET_YEAR(PyDateTime_Date *o)
Regrese el año, como un int positivo.
int PyDateTime_GET_MONTH(PyDateTime_Date *o)
Regresa el mes, como int del 1 al 12.
int PyDateTime_GET_DAY(PyDateTime_Date *o)
Retorna el día, como int del 1 al 31.
Macros to extract fields from datetime objects. The argument must be an instance of PyDateTime_DateTime,
including subclasses. The argument must not be NULL, and the type is not checked:
int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)
Retorna la hora, como un int de 0 hasta 23.
int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)
Retorna el minuto, como un int de 0 hasta 59.
int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)
Retorna el segundo, como un int de 0 hasta 59.

8.6. Otros objetos 189


The Python/C API, Versión 3.12.4

int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o)


Retorna el micro segundo, como un int de 0 hasta 999999.
int PyDateTime_DATE_GET_FOLD(PyDateTime_DateTime *o)
Return the fold, as an int from 0 through 1.
Added in version 3.6.
PyObject *PyDateTime_DATE_GET_TZINFO(PyDateTime_DateTime *o)
Retorna el tzinfo (que puede ser None).
Added in version 3.10.
Macros to extract fields from time objects. The argument must be an instance of PyDateTime_Time, including
subclasses. The argument must not be NULL, and the type is not checked:
int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o)
Retorna la hora, como un int de 0 hasta 23.
int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o)
Retorna el minuto, como un int de 0 hasta 59.
int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o)
Retorna el segundo, como un int de 0 hasta 59.
int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o)
Retorna el micro segundo, como un int de 0 hasta 999999.
int PyDateTime_TIME_GET_FOLD(PyDateTime_Time *o)
Return the fold, as an int from 0 through 1.
Added in version 3.6.
PyObject *PyDateTime_TIME_GET_TZINFO(PyDateTime_Time *o)
Retorna el tzinfo (que puede ser None).
Added in version 3.10.
Macros to extract fields from time delta objects. The argument must be an instance of PyDateTime_Delta,
including subclasses. The argument must not be NULL, and the type is not checked:
int PyDateTime_DELTA_GET_DAYS(PyDateTime_Delta *o)
Retorna el número de días, como un int desde -999999999 a 999999999.
Added in version 3.3.
int PyDateTime_DELTA_GET_SECONDS(PyDateTime_Delta *o)
Retorna el número de segundos, como un int de 0 a 86399.
Added in version 3.3.
int PyDateTime_DELTA_GET_MICROSECONDS(PyDateTime_Delta *o)
Retorna el número de micro segundos, como un int de 0 a 999999.
Added in version 3.3.
Macros para la conveniencia de módulos que implementan la API DB:
PyObject *PyDateTime_FromTimestamp(PyObject *args)
Return value: New reference. Crea y retorna un nuevo objeto datetime.datetime dado una tupla de
argumentos adecuada para pasar a datetime.datetime.fromtimestamp().
PyObject *PyDate_FromTimestamp(PyObject *args)
Return value: New reference. Crea y retorna un nuevo objeto datetime.date dado una tupla de argumentos
adecuada para pasar a datetime.date.fromtimestamp().

190 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.12.4

8.6.14 Objetos para indicaciones de tipado

Se proporcionan varios tipos incorporados para indicaciones de tipado. Actualmente existen dos tipos – GenericAlias
y Union. Solo GenericAlias es expuesto a C.
PyObject *Py_GenericAlias(PyObject *origin, PyObject *args)
Part of the Stable ABI since version 3.9. Create a GenericAlias object. Equivalent to calling the Python
class types.GenericAlias. The origin and args arguments set the GenericAlias“s __origin__
and __args__ attributes respectively. origin should be a PyTypeObject*, and args can be a
PyTupleObject* or any PyObject*. If args passed is not a tuple, a 1-tuple is automatically constructed
and __args__ is set to (args,). Minimal checking is done for the arguments, so the function will succeed
even if origin is not a type. The GenericAlias“s __parameters__ attribute is constructed lazily from
__args__. On failure, an exception is raised and NULL is returned.
Aquí hay un ejemplo sobre cómo hacer un tipo de extensión genérica:

...
static PyMethodDef my_obj_methods[] = {
// Other methods.
...
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}
...
}

Ver también:
The data model method __class_getitem__().
Added in version 3.9.
PyTypeObject Py_GenericAliasType
Part of the Stable ABI since version 3.9. El tipo en C del objeto retornado por Py_GenericAlias().
Equivalente a types.GenericAlias en Python.
Added in version 3.9.

8.6. Otros objetos 191


The Python/C API, Versión 3.12.4

192 Capítulo 8. Capa de objetos concretos


CAPÍTULO 9

Inicialización, finalización e hilos

Consulte también Configuración de inicialización de Python.

9.1 Antes de la inicialización de Python

En una aplicación que incorpora Python, se debe llamar a la función Py_Initialize() antes de usar cualquier
otra función de API Python/C; con la excepción de algunas funciones y variables de configuración global.
Las siguientes funciones se pueden invocar de forma segura antes de que se inicializa Python:
• Funciones de configuración:
– PyImport_AppendInittab()
– PyImport_ExtendInittab()
– PyInitFrozenExtensions()
– PyMem_SetAllocator()
– PyMem_SetupDebugHooks()
– PyObject_SetArenaAllocator()
– Py_SetPath()
– Py_SetProgramName()
– Py_SetPythonHome()
– Py_SetStandardStreamEncoding()
– PySys_AddWarnOption()
– PySys_AddXOption()
– PySys_ResetWarnOptions()
• Funciones informativas:
– Py_IsInitialized()
– PyMem_GetAllocator()
– PyObject_GetArenaAllocator()

193
The Python/C API, Versión 3.12.4

– Py_GetBuildInfo()
– Py_GetCompiler()
– Py_GetCopyright()
– Py_GetPlatform()
– Py_GetVersion()
• Utilidades:
– Py_DecodeLocale()
• Asignadores de memoria:
– PyMem_RawMalloc()
– PyMem_RawRealloc()
– PyMem_RawCalloc()
– PyMem_RawFree()

Nota: Las siguientes funciones no deben llamarse antes de Py_Initialize(): Py_EncodeLocale(),


Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), Py_GetProgramFullPath(),
Py_GetPythonHome(), Py_GetProgramName() y PyEval_InitThreads().

9.2 Variables de configuración global

Python tiene variables para la configuración global para controlar diferentes características y opciones. De forma
predeterminada, estos indicadores están controlados por opciones de línea de comando.
Cuando una opción establece un indicador, el valor del indicador es la cantidad de veces que se configuró la opción.
Por ejemplo, -b establece Py_BytesWarningFlag en 1 y -bb establece Py_BytesWarningFlag en 2.
int Py_BytesWarningFlag
This API is kept for backward compatibility: setting PyConfig.bytes_warning should be used instead,
see Python Initialization Configuration.
Emite una advertencia al comparar bytes o bytearray con str o bytes con int. Emite un error si es
mayor o igual a 2.
Establecido por la opción -b.
Obsoleto desde la versión 3.12.
int Py_DebugFlag
This API is kept for backward compatibility: setting PyConfig.parser_debug should be used instead,
see Python Initialization Configuration.
Activa la salida de depuración del analizador (solo para expertos, según las opciones de compilación).
Establecido por la opción -d y la variable de entorno PYTHONDEBUG.
Obsoleto desde la versión 3.12.
int Py_DontWriteBytecodeFlag
This API is kept for backward compatibility: setting PyConfig.write_bytecode should be used instead,
see Python Initialization Configuration.
Si se establece en un valor distinto de cero, Python no intentará escribir archivos .pyc en la importación de
módulos fuente.
Establecido por la opción -B y la variable de entorno PYTHONDONTWRITEBYTECODE.

194 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

Obsoleto desde la versión 3.12.


int Py_FrozenFlag
This API is kept for backward compatibility: setting PyConfig.pathconfig_warnings should be used
instead, see Python Initialization Configuration.
Suprime los mensajes de error al calcular la ruta de búsqueda del módulo en Py_GetPath().
Indicador privado utilizado por los programas _freeze_module y frozenmain.
Obsoleto desde la versión 3.12.
int Py_HashRandomizationFlag
This API is kept for backward compatibility: setting PyConfig.hash_seed and PyConfig.
use_hash_seed should be used instead, see Python Initialization Configuration.
Se establece en 1 si la variable de entorno PYTHONHASHSEED se establece en una cadena de caracteres no
vacía.
Si el indicador no es cero, lee la variable de entorno PYTHONHASHSEED para inicializar la semilla de hash
secreta.
Obsoleto desde la versión 3.12.
int Py_IgnoreEnvironmentFlag
This API is kept for backward compatibility: setting PyConfig.use_environment should be used ins-
tead, see Python Initialization Configuration.
Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME, that might be set.
Establecido por las opciones -E y -I.
Obsoleto desde la versión 3.12.
int Py_InspectFlag
This API is kept for backward compatibility: setting PyConfig.inspect should be used instead, see Pyt-
hon Initialization Configuration.
Cuando se pasa una secuencia de comandos (script) como primer argumento o se usa la opción -c, ingresa al
modo interactivo después de ejecutar la secuencia de comandos o el comando, incluso cuando sys.stdin
no parece ser un terminal.
Establecido por la opción -i y la variable de entorno PYTHONINSPECT.
Obsoleto desde la versión 3.12.
int Py_InteractiveFlag
This API is kept for backward compatibility: setting PyConfig.interactive should be used instead,
see Python Initialization Configuration.
Establecido por la opción -i.
Obsoleto desde la versión 3.12.
int Py_IsolatedFlag
This API is kept for backward compatibility: setting PyConfig.isolated should be used instead, see
Python Initialization Configuration.
Ejecuta Python en modo aislado. En modo aislado sys.path no contiene ni el directorio de la secuencia de
comandos (script) ni el directorio de paquetes del sitio del usuario (site-pacages).
Establecido por la opción -I.
Added in version 3.4.
Obsoleto desde la versión 3.12.

9.2. Variables de configuración global 195


The Python/C API, Versión 3.12.4

int Py_LegacyWindowsFSEncodingFlag
This API is kept for backward compatibility: setting PyPreConfig.
legacy_windows_fs_encoding should be used instead, see Python Initialization Configuration.
Si la bandera no es cero, utilice la codificación mbcs con el gestor de errores replace en lugar de la co-
dificación UTF-8 con el gestor de error surrogatepass, para la filesystem encoding and error handler
(codificación del sistema de archivos y gestor de errores).
Establece en 1 si la variable de entorno PYTHONLEGACYWINDOWSFSENCODING está configurada en una
cadena de caracteres no vacía.
Ver PEP 529 para más detalles.
Disponibilidad: Windows.
Obsoleto desde la versión 3.12.
int Py_LegacyWindowsStdioFlag
This API is kept for backward compatibility: setting PyConfig.legacy_windows_stdio should be
used instead, see Python Initialization Configuration.
If the flag is non-zero, use io.FileIO instead of io._WindowsConsoleIO for sys standard streams.
Establece en 1 si la variable de entorno PYTHONLEGACYWINDOWSSTDIO está configurada en una cadena
de caracteres no vacía.
Ver PEP 528 para más detalles.
Disponibilidad: Windows.
Obsoleto desde la versión 3.12.
int Py_NoSiteFlag
This API is kept for backward compatibility: setting PyConfig.site_import should be used instead,
see Python Initialization Configuration.
Deshabilita la importación del módulo site y las manipulaciones dependientes del sitio de sys.path que
conlleva. También deshabilita estas manipulaciones si site se importa explícitamente más tarde (llama a
site.main() si desea que se activen).
Establecido por la opción -S.
Obsoleto desde la versión 3.12.
int Py_NoUserSiteDirectory
This API is kept for backward compatibility: setting PyConfig.user_site_directory should be used
instead, see Python Initialization Configuration.
No agregue el directorio de paquetes de sitio del usuario (site-packages) a sys.
path.
Establecido por las opciones -s y -I, y la variable de entorno PYTHONNOUSERSITE.
Obsoleto desde la versión 3.12.
int Py_OptimizeFlag
This API is kept for backward compatibility: setting PyConfig.optimization_level should be used
instead, see Python Initialization Configuration.
Establecido por la opción -O y la variable de entorno PYTHONOPTIMIZE.
Obsoleto desde la versión 3.12.
int Py_QuietFlag
This API is kept for backward compatibility: setting PyConfig.quiet should be used instead, see Python
Initialization Configuration.
No muestre los mensajes de copyright y de versión incluso en modo interactivo.

196 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

Establecido por la opción -q.


Added in version 3.2.
Obsoleto desde la versión 3.12.
int Py_UnbufferedStdioFlag
This API is kept for backward compatibility: setting PyConfig.buffered_stdio should be used instead,
see Python Initialization Configuration.
Obliga a las secuencias stdout y stderr a que no tengan búfer.
Establecido por la opción -u y la variable de entorno PYTHONUNBUFFERED.
Obsoleto desde la versión 3.12.
int Py_VerboseFlag
This API is kept for backward compatibility: setting PyConfig.verbose should be used instead, see Pyt-
hon Initialization Configuration.
Imprime un mensaje cada vez que se inicializa un módulo, mostrando el lugar (nombre de archivo o módulo
incorporado) desde el que se carga. Si es mayor o igual a 2, imprime un mensaje para cada archivo que se
verifica al buscar un módulo. También proporciona información sobre la limpieza del módulo a la salida.
Establecido por la opción -v y la variable de entorno PYTHONVERBOSE.
Obsoleto desde la versión 3.12.

9.3 Inicializando y finalizando el intérprete

void Py_Initialize()
Part of the Stable ABI. Inicializa el intérprete de Python. En una aplicación que incorpora Python, se debe
llamar antes de usar cualquier otra función de API Python/C; vea Antes de la inicialización de Python para ver
algunas excepciones.
Esto inicializa la tabla de módulos cargados (sys.modules) y crea los módulos fundamentales builtins,
__main__ y sys. También inicializa la ruta de búsqueda del módulo (sys.path). No establece sys.
argv; use PySys_SetArgvEx() para eso. Este es un no-op cuando se llama por segunda vez (sin llamar
primero a Py_FinalizeEx()). No hay valor de retorno; es un error fatal si falla la inicialización.
Use the Py_InitializeFromConfig() function to customize the Python Initialization Configuration.

Nota: En Windows, cambia el modo de consola de O_TEXT a O_BINARY, lo que también afectará los usos
de la consola que no sean de Python utilizando C Runtime.

void Py_InitializeEx(int initsigs)


Part of the Stable ABI. Esta función funciona como Py_Initialize() si initsigs es 1. Si initsigs es 0, omite
el registro de inicialización de los manejadores de señal, lo que podría ser útil cuando Python está incrustado.
Use the Py_InitializeFromConfig() function to customize the Python Initialization Configuration.
int Py_IsInitialized()
Part of the Stable ABI. Retorna verdadero (distinto de cero) cuando el intérprete de Python se ha inicia-
lizado, falso (cero) si no. Después de que se llama a Py_FinalizeEx(), esto retorna falso hasta que
Py_Initialize() se llama de nuevo.
int Py_FinalizeEx()
Part of the Stable ABI since version 3.6. Deshace todas las inicializaciones realizadas por
Py_Initialize() y el uso posterior de las funciones de Python/C API, y destruye todos los sub-
intérpretes (ver Py_NewInterpreter() a continuación) que se crearon y aún no se destruyeron desde el
última llamada a Py_Initialize(). Idealmente, esto libera toda la memoria asignada por el intérprete de

9.3. Inicializando y finalizando el intérprete 197


The Python/C API, Versión 3.12.4

Python. Este es un no-op cuando se llama por segunda vez (sin llamar a Py_Initialize() nuevamente
primero). Normalmente el valor de retorno es 0. Si hubo errores durante la finalización (lavado de datos
almacenados en el búfer), se retorna -1.
Esta función se proporciona por varias razones. Una aplicación de incrustación puede querer reiniciar Python
sin tener que reiniciar la aplicación misma. Una aplicación que ha cargado el intérprete de Python desde una
biblioteca cargable dinámicamente (o DLL) puede querer liberar toda la memoria asignada por Python antes
de descargar la DLL. Durante una búsqueda de pérdidas de memoria en una aplicación, un desarrollador puede
querer liberar toda la memoria asignada por Python antes de salir de la aplicación.
Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause
destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules.
Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated
by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular
references between objects is not freed. Some memory allocated by extension modules may not be freed. Some
extensions may not work properly if their initialization routine is called more than once; this can happen if an
application calls Py_Initialize() and Py_FinalizeEx() more than once.
Genera un evento de auditoría cpython._PySys_ClearAuditHooks sin argumentos.
Added in version 3.6.
void Py_Finalize()
Part of the Stable ABI. Esta es una versión compatible con versiones anteriores de Py_FinalizeEx() que
ignora el valor de retorno.

9.4 Parámetros de todo el proceso

int Py_SetStandardStreamEncoding(const char *encoding, const char *errors)


Esta API se mantiene para la compatibilidad con versiones anteriores: en su lugar, se debe usar la configuración
de PyConfig.stdio_encoding y PyConfig.stdio_errors, consulta Configuración de iniciali-
zación de Python.
Esta función debería llamarse antes de Py_Initialize(), si es que se llama. Especifica qué codificación
y manejo de errores usar con IO estándar, con los mismos significados que en str.encode().
Reemplaza los valores PYTHONIOENCODING, y permite incrustar código para controlar la codificación IO
cuando la variable de entorno no funciona.
codificación o errores pueden ser NULL para usar PYTHONIOENCODING o valores predeterminados (depen-
diendo de otras configuraciones).
Tenga en cuenta que sys.stderr siempre usa el controlador de error «backslashreplace», independiente-
mente de esta configuración (o cualquier otra).
Si se llama a Py_FinalizeEx(), será necesario volver a llamar a esta función para afectar las llamadas
posteriores a Py_Initialize().
Retorna 0 si tiene éxito, un valor distinto de cero en caso de error (por ejemplo, llamar después de que el
intérprete ya se haya inicializado)
Added in version 3.4.
Obsoleto desde la versión 3.11.
void Py_SetProgramName(const wchar_t *name)
Part of the Stable ABI. Esta API se mantiene para la compatibilidad con versiones anteriores: en su lugar,
se debe usar la configuración de PyConfig.program_name, consulta Configuración de inicialización de
Python.
Esta función debería llamarse antes Py_Initialize() se llama por primera vez, si es que se llama. Le dice
al intérprete el valor del argumento argv[0] para la función main() del programa (convertido a caracteres
anchos). Esto es utilizado por Py_GetPath() y algunas otras funciones a continuación para encontrar las

198 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

bibliotecas de tiempo de ejecución de Python relativas al ejecutable del intérprete. El valor predeterminado
es 'python'. El argumento debe apuntar a una cadena de caracteres anchos terminada en cero en almace-
namiento estático cuyo contenido no cambiará mientras dure la ejecución del programa. Ningún código en el
intérprete de Python cambiará el contenido de este almacenamiento.
Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.
Obsoleto desde la versión 3.11.
wchar_t *Py_GetProgramName()
Part of the Stable ABI. Retorna el nombre del programa establecido con Py_SetProgramName(), o el
valor predeterminado. La cadena de caracteres retornada apunta al almacenamiento estático; la persona que
llama no debe modificar su valor.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.
wchar_t *Py_GetPrefix()
Part of the Stable ABI. Return the prefix for installed platform-independent files. This is derived through a
number of complicated rules from the program name set with Py_SetProgramName() and some environ-
ment variables; for example, if the program name is '/usr/local/bin/python', the prefix is '/usr/
local'. The returned string points into static storage; the caller should not modify its value. This corresponds
to the prefix variable in the top-level Makefile and the --prefix argument to the configure script
at build time. The value is available to Python code as sys.prefix. It is only useful on Unix. See also the
next function.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.
wchar_t *Py_GetExecPrefix()
Part of the Stable ABI. Retorna el exec-prefix para los archivos instalados dependientes de la platafor-
ma. Esto se deriva a través de una serie de reglas complicadas del nombre del programa establecido con
Py_SetProgramName() y algunas variables de entorno; por ejemplo, si el nombre del programa es '/
usr/local/bin/python', el prefijo exec es '/usr/local'. La cadena de caracteres retornada apun-
ta al almacenamiento estático; la persona que llama no debe modificar su valor. Esto corresponde a la variable
exec_prefix en el archivo de nivel superior Makefile y el argumento --exec-prefix a la secuen-
cia de comandos (script) configure en tiempo de compilación. El valor está disponible para el código de
Python como sys.exec_prefix. Solo es útil en Unix.
Antecedentes: el prefijo exec difiere del prefijo cuando los archivos dependientes de la plataforma (como eje-
cutables y bibliotecas compartidas) se instalan en un árbol de directorios diferente. En una instalación típica,
los archivos dependientes de la plataforma pueden instalarse en el subárbol /usr/local/plat mientras
que la plataforma independiente puede instalarse en /usr/local.
En términos generales, una plataforma es una combinación de familias de hardware y software, por ejemplo,
las máquinas Sparc que ejecutan el sistema operativo Solaris 2.x se consideran la misma plataforma, pero las
máquinas Intel que ejecutan Solaris 2.x son otra plataforma, y las máquinas Intel que ejecutan Linux son otra
plataforma más. Las diferentes revisiones importantes del mismo sistema operativo generalmente también for-
man plataformas diferentes. Los sistemas operativos que no son Unix son una historia diferente; Las estrategias
de instalación en esos sistemas son tan diferentes que el prefijo y el prefijo exec no tienen sentido y se configu-
ran en la cadena vacía. Tenga en cuenta que los archivos de bytecode compilados de Python son independientes
de la plataforma (¡pero no independientes de la versión de Python con la que fueron compilados!).
Los administradores de sistemas sabrán cómo configurar los programas mount o automount para compartir
/usr/local entre plataformas mientras que /usr/local/plat sea un sistema de archivos diferente
para cada plataforma.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.

9.4. Parámetros de todo el proceso 199


The Python/C API, Versión 3.12.4

wchar_t *Py_GetProgramFullPath()
Part of the Stable ABI. Retorna el nombre completo del programa del ejecutable de Python; esto se calcula co-
mo un efecto secundario de derivar la ruta de búsqueda predeterminada del módulo del nombre del programa
(establecido por Py_SetProgramName() arriba). La cadena de caracteres retornada apunta al almacena-
miento estático; la persona que llama no debe modificar su valor. El valor está disponible para el código de
Python como sys.executable.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.
wchar_t *Py_GetPath()
Part of the Stable ABI. Retorna la ruta de búsqueda del módulo predeterminado; esto se calcula a partir del
nombre del programa (establecido por Py_SetProgramName() antes mencionado) y algunas variables de
entorno. La cadena de caracteres retornada consiste en una serie de nombres de directorio separados por un
carácter delimitador dependiente de la plataforma. El carácter delimitador es ':' en Unix y macOS, ';'
en Windows. La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no
debe modificar su valor. La lista sys.path se inicializa con este valor en el inicio del intérprete; se puede (y
generalmente se realiza) modificar más adelante para cambiar la ruta de búsqueda para cargar módulos.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.
void Py_SetPath(const wchar_t*)
Part of the Stable ABI since version 3.7. Esta API se mantiene para la compatibilidad con versiones anterio-
res: en su lugar, se debe usar la configuración de PyConfig.module_search_paths y PyConfig.
module_search_paths_set, consulta Configuración de inicialización de Python.
Establece la ruta de búsqueda del módulo predeterminado. Si se llama a esta función antes de
Py_Initialize(), entonces Py_GetPath() no intentará computar una ruta de búsqueda predetermi-
nada, sino que utilizará la proporcionada en su lugar. Esto es útil si Python está incrustado por una aplicación
que tiene pleno conocimiento de la ubicación de todos los módulos. Los componentes de la ruta deben estar
separados por el carácter delimitador dependiente de la plataforma, el cual es ':' en Unix y macOS, ';' en
Windows.
Esto también hace que sys.executable se configure en la ruta completa del programa (consulte
Py_GetProgramFullPath()) y para sys.prefix y sys.exec_prefix a estar vacío. Depende
de la persona que llama modificarlos si es necesario después de llamar Py_Initialize().
Utilice Py_DecodeLocale() para decodificar una cadena de bytes para obtener una cadena de tipo
wchar_*.
El argumento de ruta se copia internamente, por lo que la persona que llama puede liberarlo después de que se
complete la llamada.
Distinto en la versión 3.8: La ruta completa del programa ahora se usa para sys.executable, en lugar del
nombre del programa.
Obsoleto desde la versión 3.11.
const char *Py_GetVersion()
Part of the Stable ABI. Retorna la versión de este intérprete de Python. Esta es una cadena de caracteres que
se parece a
"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"

La primera palabra (hasta el primer carácter de espacio) es la versión actual de Python; los primeros tres
caracteres son la versión mayor y menor separados por un punto. La cadena de caracteres retornada apunta
al almacenamiento estático; la persona que llama no debe modificar su valor. El valor está disponible para el
código Python como sys.version.
Consulta también la constante Py_Version.

200 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

const char *Py_GetPlatform()


Part of the Stable ABI. Retorna el identificador de plataforma para la plataforma actual. En Unix, esto se forma
a partir del nombre «oficial» del sistema operativo, convertido a minúsculas, seguido del número de revisión
principal; por ejemplo, para Solaris 2.x, que también se conoce como SunOS 5.x, el valor es 'sunos5'. En
macOS, es 'darwin'. En Windows, es 'win'. La cadena de caracteres retornada apunta al almacenamiento
estático; la persona que llama no debe modificar su valor. El valor está disponible para el código de Python
como sys.platform.
const char *Py_GetCopyright()
Part of the Stable ABI. Retorna la cadena de caracteres de copyright oficial para la versión actual de Python,
por ejemplo
'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'
La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no debe modificar
su valor. El valor está disponible para el código de Python como sys.copyright.
const char *Py_GetCompiler()
Part of the Stable ABI. Retorna una indicación del compilador utilizado para construir la versión actual de
Python, entre corchetes, por ejemplo:

"[GCC 2.7.2.2]"

La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no debe modificar
su valor. El valor está disponible para el código Python como parte de la variable sys.version.
const char *Py_GetBuildInfo()
Part of the Stable ABI. Retorna información sobre el número de secuencia y la fecha y hora de compilación de
la instancia actual de intérprete de Python, por ejemplo:

"#67, Aug 1 1997, 22:34:28"

La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no debe modificar
su valor. El valor está disponible para el código Python como parte de la variable sys.version.
void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Part of the Stable ABI. Esta API se mantiene para la compatibilidad con versiones anteriores: en su lugar, se de-
be usar la configuración de PyConfig.argv, PyConfig.parse_argv y PyConfig.safe_path,
consulta Configuración de inicialización de Python.
Establece sys.argv basado en argc y argv. Estos parámetros son similares a los pasados a la función del
programa main() con la diferencia de que la primera entrada debe referirse al archivo de la secuencia de
comandos (script) que se ejecutará en lugar del ejecutable que aloja el intérprete de Python. Si no se ejecuta
una secuencia de comandos (script), la primera entrada en argv puede ser una cadena de caracteres vacía. Si
esta función no puede inicializar sys.argv, una condición fatal se señala usando Py_FatalError().
Si updatepath es cero, esto es todo lo que hace la función. Si updatepath no es cero, la función también modifica
sys.path de acuerdo con el siguiente algoritmo:
• Si el nombre de una secuencia de comandos (script) existente se pasa en argv[0], la ruta absoluta del
directorio donde se encuentra el script se antepone a sys.path.
• De lo contrario (es decir, si argc es 0 o argv[0] no apunta a un nombre de archivo existente), una
cadena de caracteres vacía se antepone a sys.path, que es lo mismo que anteponer el directorio de
trabajo actual (".").
Utilice Py_DecodeLocale() para decodificar una cadena de bytes para obtener una cadena de tipo
wchar_*.
Consulta también los miembros de PyConfig.orig_argv y PyConfig.argv de Python Initialization
Configuration.

9.4. Parámetros de todo el proceso 201


The Python/C API, Versión 3.12.4

Nota: It is recommended that applications embedding the Python interpreter for purposes other than executing
a single script pass 0 as updatepath, and update sys.path themselves if desired. See CVE-2008-5983.
En las versiones anteriores a 3.1.3, puede lograr el mismo efecto quitando manualmente el primer elemento
(popping) sys.path después de haber llamado PySys_SetArgv(), por ejemplo usando

PyRun_SimpleString("import sys; sys.path.pop(0)\n");

Added in version 3.1.3.


Obsoleto desde la versión 3.11.
void PySys_SetArgv(int argc, wchar_t **argv)
Part of the Stable ABI. Esta API se mantiene para la compatibilidad con versiones anteriores: en su lugar, se
debe usar la configuración de PyConfig.argv y PyConfig.parse_argv, consulta Configuración de
inicialización de Python.
Esta función funciona como PySys_SetArgvEx() con updatepath establecido en 1 a menos que el intér-
prete python se haya iniciado con la opción -I.
Utilice Py_DecodeLocale() para decodificar una cadena de bytes para obtener una cadena de tipo
wchar_*.
Consulta también los miembros de PyConfig.orig_argv y PyConfig.argv de Python Initialization
Configuration.
Distinto en la versión 3.4: El valor updatepath depende de la opción -I.
Obsoleto desde la versión 3.11.
void Py_SetPythonHome(const wchar_t *home)
Part of the Stable ABI. Esta API se mantiene para la compatibilidad con versiones anteriores: en su lugar, se
debe usar la configuración de PyConfig.home, consulta Configuración de inicialización de Python.
Establece el directorio «inicio» («home») predeterminado, es decir, la ubicación de las bibliotecas estándar de
Python. Ver PYTHONHOME para el significado de la cadena de caracteres de argumento.
El argumento debe apuntar a una cadena de caracteres terminada en cero en el almacenamiento estático cuyo
contenido no cambiará mientras dure la ejecución del programa. Ningún código en el intérprete de Python
cambiará el contenido de este almacenamiento.
Utilice Py_DecodeLocale() para decodificar una cadena de bytes para obtener una cadena de tipo
wchar_*.
Obsoleto desde la versión 3.11.
wchar_t *Py_GetPythonHome()
Part of the Stable ABI. Retorna el «inicio» (home) predeterminado, es decir, el valor establecido por una
llamada anterior a Py_SetPythonHome(), o el valor de la variable de entorno PYTHONHOME si está
configurado.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.

202 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

9.5 Estado del hilo y el bloqueo global del intérprete

El intérprete de Python no es completamente seguro para hilos (thread-safe). Para admitir programas Python multi-
proceso, hay un bloqueo global, denominado global interpreter lock o GIL, que debe mantener el hilo actual antes de
que pueda acceder de forma segura a los objetos Python. Sin el bloqueo, incluso las operaciones más simples podrían
causar problemas en un programa de hilos múltiples: por ejemplo, cuando dos hilos incrementan simultáneamente el
conteo de referencias del mismo objeto, el conteo de referencias podría terminar incrementándose solo una vez en
lugar de dos veces.
Por lo tanto, existe la regla de que solo el hilo que ha adquirido GIL puede operar en objetos Python o llamar a fun-
ciones API Python/C. Para emular la concurrencia de ejecución, el intérprete regularmente intenta cambiar los hilos
(ver sys.setswitchinterval()). El bloqueo también se libera para bloquear potencialmente las operaciones
de E/S, como leer o escribir un archivo, para que otros hilos de Python puedan ejecutarse mientras tanto.
El intérprete de Python mantiene cierta información de contabilidad específica de hilos dentro de una estructura de
datos llamada PyThreadState. También hay una variable global que apunta a la actual PyThreadState: se
puede recuperar usando PyThreadState_Get().

9.5.1 Liberando el GIL del código de extensión

La mayoría del código de extensión que manipula el GIL tiene la siguiente estructura simple

Save the thread state in a local variable.


Release the global interpreter lock.
... Do some blocking I/O operation ...
Reacquire the global interpreter lock.
Restore the thread state from the local variable.

Esto es tan común que existen un par de macros para simplificarlo:

Py_BEGIN_ALLOW_THREADS
... Do some blocking I/O operation ...
Py_END_ALLOW_THREADS

La macro Py_BEGIN_ALLOW_THREADS abre un nuevo bloque y declara una variable local oculta; la macro
Py_END_ALLOW_THREADS cierra el bloque.
El bloque anterior se expande al siguiente código:

PyThreadState *_save;

_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
PyEval_RestoreThread(_save);

Así es como funcionan estas funciones: el bloqueo global del intérprete se usa para proteger el puntero al estado actual
del hilo. Al liberar el bloqueo y guardar el estado del hilo, el puntero del estado del hilo actual debe recuperarse antes
de que se libere el bloqueo (ya que otro hilo podría adquirir inmediatamente el bloqueo y almacenar su propio estado
de hilo en la variable global). Por el contrario, al adquirir el bloqueo y restaurar el estado del hilo, el bloqueo debe
adquirirse antes de almacenar el puntero del estado del hilo.

Nota: Llamar a las funciones de E/S del sistema es el caso de uso más común para liberar el GIL, pero también
puede ser útil antes de llamar a cálculos de larga duración que no necesitan acceso a objetos de Python, como las
funciones de compresión o criptográficas que operan sobre memorias intermedias. Por ejemplo, los módulos estándar
zlib y hashlib liberan el GIL al comprimir o mezclar datos.

9.5. Estado del hilo y el bloqueo global del intérprete 203


The Python/C API, Versión 3.12.4

9.5.2 Hilos creados sin Python

Cuando se crean hilos utilizando las API dedicadas de Python (como el módulo threading), se les asocia auto-
máticamente un estado del hilo y, por lo tanto, el código que se muestra arriba es correcto. Sin embargo, cuando
los hilos se crean desde C (por ejemplo, por una biblioteca de terceros con su propia administración de hilos), no
contienen el GIL, ni existe una estructura de estado de hilos para ellos.
Si necesita llamar al código Python desde estos subprocesos (a menudo esto será parte de una API de devolución
de llamada proporcionada por la biblioteca de terceros mencionada anteriormente), primero debe registrar estos
subprocesos con el intérprete creando una estructura de datos de estado del subproceso, luego adquiriendo el GIL, y
finalmente almacenando su puntero de estado de hilo, antes de que pueda comenzar a usar la API Python/C Cuando
haya terminado, debe restablecer el puntero del estado del hilo, liberar el GIL y finalmente liberar la estructura de
datos del estado del hilo.
Las funciones PyGILState_Ensure() y PyGILState_Release() hacen todo lo anterior automáticamen-
te. El idioma típico para llamar a Python desde un hilo C es:

PyGILState_STATE gstate;
gstate = PyGILState_Ensure();

/* Perform Python actions here. */


result = CallSomeFunction();
/* evaluate result or handle exception */

/* Release the thread. No Python API allowed beyond this point. */


PyGILState_Release(gstate);

Tenga en cuenta que las funciones PyGILState_* asumen que solo hay un intérprete global (creado
automáticamente por Py_Initialize()). Python admite la creación de intérpretes adicionales (usando
Py_NewInterpreter()), pero la mezcla de varios intérpretes y la API PyGILState_* no está soportada.

9.5.3 Precauciones sobre fork()

Otra cosa importante a tener en cuenta sobre los hilos es su comportamiento frente a la llamada C fork(). En la
mayoría de los sistemas con fork(), después de que un proceso se bifurca, solo existirá el hilo que emitió el fork.
Esto tiene un impacto concreto tanto en cómo se deben manejar las cerraduras como en todo el estado almacenado
en el tiempo de ejecución de CPython.
The fact that only the «current» thread remains means any locks held by other threads will never be released. Python
solves this for os.fork() by acquiring the locks it uses internally before the fork, and releasing them afterwards.
In addition, it resets any lock-objects in the child. When extending or embedding Python, there is no way to inform
Python of additional (non-Python) locks that need to be acquired before or reset after a fork. OS facilities such
as pthread_atfork() would need to be used to accomplish the same thing. Additionally, when extending or
embedding Python, calling fork() directly rather than through os.fork() (and returning to or calling into
Python) may result in a deadlock by one of Python’s internal locks being held by a thread that is defunct after the
fork. PyOS_AfterFork_Child() tries to reset the necessary locks, but is not always able to.
El hecho de que todos los otros hilos desaparezcan también significa que el estado de ejecución de CPython
debe limpiarse correctamente, lo que os.fork() lo hace. Esto significa finalizar todos los demás objetos
PyThreadState que pertenecen al intérprete actual y todos los demás objetos PyInterpreterState. De-
bido a esto y a la naturaleza especial del intérprete «principal», fork() solo debería llamarse en el hilo «principal»
de ese intérprete, donde el CPython global el tiempo de ejecución se inicializó originalmente. La única excepción es
si exec() se llamará inmediatamente después.

204 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

9.5.4 API de alto nivel

Estos son los tipos y funciones más utilizados al escribir código de extensión C o al incrustar el intérprete de Python:
type PyInterpreterState
Part of the Limited API (as an opaque struct). Esta estructura de datos representa el estado compartido por
varios subprocesos cooperantes. Los hilos que pertenecen al mismo intérprete comparten la administración de
su módulo y algunos otros elementos internos. No hay miembros públicos en esta estructura.
Los hilos que pertenecen a diferentes intérpretes inicialmente no comparten nada, excepto el estado del proceso
como memoria disponible, descriptores de archivos abiertos y demás. El bloqueo global del intérprete también
es compartido por todos los hilos, independientemente de a qué intérprete pertenezcan.
type PyThreadState
Part of the Limited API (as an opaque struct). This data structure represents the state of a single thread. The
only public data member is:
PyInterpreterState *interp
This thread’s interpreter state.
void PyEval_InitThreads()
Part of the Stable ABI. Función deprecada que no hace nada.
En Python 3.6 y versiones anteriores, esta función creaba el GIL si no existía.
Distinto en la versión 3.9: La función ahora no hace nada.
Distinto en la versión 3.7: Esta función ahora es llamada por Py_Initialize(), por lo que ya no tiene
que llamarla usted mismo.
Distinto en la versión 3.2: Esta función ya no se puede llamar antes de Py_Initialize().
Obsoleto desde la versión 3.9.
int PyEval_ThreadsInitialized()
Part of the Stable ABI. Retorna un valor distinto de cero si se ha llamado a PyEval_InitThreads().
Esta función se puede invocar sin mantener el GIL y, por lo tanto, se puede utilizar para evitar llamadas a la
API de bloqueo cuando se ejecuta un solo hilo.
Distinto en la versión 3.7: El término GIL ahora se inicializa con Py_Initialize().
Obsoleto desde la versión 3.9.
PyThreadState *PyEval_SaveThread()
Part of the Stable ABI. Libere el bloqueo global del intérprete (si se ha creado) y restablezca el estado del hilo
a NULL, retornando el estado del hilo anterior (que no es NULL). Si se ha creado el bloqueo, el hilo actual debe
haberlo adquirido.
void PyEval_RestoreThread(PyThreadState *tstate)
Part of the Stable ABI. Adquiera el bloqueo global del intérprete (si se ha creado) y establezca el estado del
hilo en tstate, que no debe ser NULL. Si se ha creado el bloqueo, el hilo actual no debe haberlo adquirido, de
lo contrario se produce un deadlock.

Nota: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to
check if the interpreter is in process of being finalized before calling this function to avoid unwanted termina-
tion.

PyThreadState *PyThreadState_Get()
Part of the Stable ABI. Retorna el estado actual del hilo. Se debe mantener el bloqueo global del intérprete.
Cuando el estado actual del hilo es NULL, esto genera un error fatal (por lo que la persona que llama no necesita
verificar NULL).

9.5. Estado del hilo y el bloqueo global del intérprete 205


The Python/C API, Versión 3.12.4

PyThreadState *PyThreadState_Swap(PyThreadState *tstate)


Part of the Stable ABI. Cambia el estado del hilo actual con el estado del hilo dado por el argumento tstate, que
puede ser NULL. El bloqueo global del intérprete debe mantenerse y no se libera.
Las siguientes funciones utilizan almacenamiento local de hilos y no son compatibles con subinterpretes:
PyGILState_STATE PyGILState_Ensure()
Part of the Stable ABI. Asegúrese de que el subproceso actual esté listo para llamar a la API de Pyt-
hon C, independientemente del estado actual de Python o del bloqueo global del intérprete. Esto se pue-
de invocar tantas veces como lo desee un subproceso siempre que cada llamada coincida con una llama-
da a PyGILState_Release(). En general, se pueden usar otras API relacionadas con subprocesos
entre PyGILState_Ensure() y PyGILState_Release() invoca siempre que el estado del sub-
proceso se restablezca a su estado anterior antes del Release(). Por ejemplo, el uso normal de las macros
Py_BEGIN_ALLOW_THREADS y Py_END_ALLOW_THREADS es aceptable.
El valor de retorno es un «identificador» opaco al estado del hilo cuando PyGILState_Ensure()
fue llamado, y debe pasarse a PyGILState_Release() para asegurar que Python se deje en el mis-
mo estado. Aunque las llamadas recursivas están permitidas, estos identificadores no pueden compartir-
se; cada llamada única a PyGILState_Ensure() debe guardar el identificador para su llamada a
PyGILState_Release().
Cuando la función regrese, el hilo actual contendrá el GIL y podrá llamar a código arbitrario de Python. El
fracaso es un error fatal.

Nota: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to
check if the interpreter is in process of being finalized before calling this function to avoid unwanted termina-
tion.

void PyGILState_Release(PyGILState_STATE)
Part of the Stable ABI. Libera cualquier recurso previamente adquirido. Después de esta llamada, el estado de
Python será el mismo que antes de la llamada correspondiente PyGILState_Ensure() (pero en general
este estado será desconocido para la persona que llama, de ahí el uso de la API GILState).
Cada llamada a PyGILState_Ensure() debe coincidir con una llamada a PyGILState_Release()
en el mismo hilo.
PyThreadState *PyGILState_GetThisThreadState()
Part of the Stable ABI. Obtenga el estado actual del hilo para este hilo. Puede retornar NULL si no se ha utilizado
la API GILState en el hilo actual. Tenga en cuenta que el subproceso principal siempre tiene dicho estado
de subproceso, incluso si no se ha realizado una llamada de estado de subproceso automático en el subproceso
principal. Esta es principalmente una función auxiliar y de diagnóstico.
int PyGILState_Check()
Retorna 1 si el hilo actual mantiene el GIL y 0 de lo contrario. Esta función se puede llamar desde cualquier
hilo en cualquier momento. Solo si se ha inicializado el hilo de Python y actualmente mantiene el GIL, retornará
1. Esta es principalmente una función auxiliar y de diagnóstico. Puede ser útil, por ejemplo, en contextos de
devolución de llamada o funciones de asignación de memoria cuando saber que el GIL está bloqueado puede
permitir que la persona que llama realice acciones confidenciales o se comporte de otra manera de manera
diferente.
Added in version 3.4.
Las siguientes macros se usan normalmente sin punto y coma final; busque, por ejemplo, el uso en la distribución
fuente de Python.
Py_BEGIN_ALLOW_THREADS
Part of the Stable ABI. Esta macro se expande a {PyThreadState *_save; _save =
PyEval_SaveThread();. Tenga en cuenta que contiene una llave de apertura; debe coincidir con
la siguiente macro Py_END_ALLOW_THREADS. Ver arriba para una discusión más detallada de esta macro.

206 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

Py_END_ALLOW_THREADS
Part of the Stable ABI. Esta macro se expande a PyEval_RestoreThread(_save); }. Tenga en cuen-
ta que contiene una llave de cierre; debe coincidir con una macro anterior Py_BEGIN_ALLOW_THREADS.
Ver arriba para una discusión más detallada de esta macro.
Py_BLOCK_THREADS
Part of the Stable ABI. Esta macro se expande a PyEval_RestoreThread(_save);: es equivalente a
Py_END_ALLOW_THREADS sin la llave de cierre.
Py_UNBLOCK_THREADS
Part of the Stable ABI. Esta macro se expande a _save = PyEval_SaveThread();: es equivalente a
Py_BEGIN_ALLOW_THREADS sin la llave de apertura y la declaración de variable.

9.5.5 API de bajo nivel

Todas las siguientes funciones deben llamarse después de Py_Initialize().


Distinto en la versión 3.7: Py_Initialize() ahora inicializa el GIL.
PyInterpreterState *PyInterpreterState_New()
Part of the Stable ABI. Crea un nuevo objeto de estado de intérprete. No es necesario retener el bloqueo global
del intérprete, pero se puede retener si es necesario para serializar llamadas a esta función.
Genera un evento de auditoría python.PyInterpreterState_New sin argumentos.
void PyInterpreterState_Clear(PyInterpreterState *interp)
Part of the Stable ABI. Restablece toda la información en un objeto de estado de intérprete. Se debe mantener
el bloqueo global del intérprete.
Lanza una eventos de auditoría python.PyInterpreterState Clear sin argumentos.
void PyInterpreterState_Delete(PyInterpreterState *interp)
Part of the Stable ABI. Destruye un objeto de estado de intérprete. No es necesario mantener el blo-
queo global del intérprete. El estado del intérprete debe haberse restablecido con una llamada previa a
PyInterpreterState_Clear().
PyThreadState *PyThreadState_New(PyInterpreterState *interp)
Part of the Stable ABI. Crea un nuevo objeto de estado de hilo que pertenece al objeto de intérprete dado.
No es necesario retener el bloqueo global del intérprete, pero se puede retener si es necesario para serializar
llamadas a esta función.
void PyThreadState_Clear(PyThreadState *tstate)
Part of the Stable ABI. Restablece toda la información en un objeto de estado de hilo. Se debe mantener el
bloqueo global del intérprete.
Distinto en la versión 3.9: Esta función ahora llama a la retrollamada PyThreadState.on_delete. An-
teriormente, eso sucedía en PyThreadState_Delete().
void PyThreadState_Delete(PyThreadState *tstate)
Part of the Stable ABI. Destruye un objeto de estado de hilo. No es necesario mantener el bloqueo global del in-
térprete. El estado del hilo debe haberse restablecido con una llamada previa a PyThreadState_Clear().
void PyThreadState_DeleteCurrent(void)
Destruye un objeto de estado de hilo y suelta el bloqueo del intérprete global. Como
PyThreadState_Delete(), no es necesario mantener el bloqueo del intérprete global. El estado
del hilo debe haberse restablecido con una llamada anterior a PyThreadState_Clear().
PyFrameObject *PyThreadState_GetFrame(PyThreadState *tstate)
Part of the Stable ABI since version 3.10. Obtiene el marco actual del estado del hilo de Python tstate.
Retorna una strong reference (referencia sólida). Retorna NULL si no se está ejecutando ningún cuadro.
Vea también PyEval_GetFrame().

9.5. Estado del hilo y el bloqueo global del intérprete 207


The Python/C API, Versión 3.12.4

tstate no debe ser NULL.


Added in version 3.9.
uint64_t PyThreadState_GetID(PyThreadState *tstate)
Part of the Stable ABI since version 3.10. Obtiene el identificador de estado de subproceso único del estado del
hilo de Python tstate.
tstate no debe ser NULL.
Added in version 3.9.
PyInterpreterState *PyThreadState_GetInterpreter(PyThreadState *tstate)
Part of the Stable ABI since version 3.10. Obtiene el intérprete del estado del hilo de Python tstate.
tstate no debe ser NULL.
Added in version 3.9.
void PyThreadState_EnterTracing(PyThreadState *tstate)
Suspender el seguimiento y el perfilado en el estado del hilo de Python tstate.
Reanudelos usando la función PyThreadState_LeaveTracing().
Added in version 3.11.
void PyThreadState_LeaveTracing(PyThreadState *tstate)
Reanudar el seguimiento y el perfilado en el estado del hilo de Python tstate suspendido por la función
PyThreadState_EnterTracing().
Consulte también las funciones PyEval_SetTrace() y PyEval_SetProfile().
Added in version 3.11.
PyInterpreterState *PyInterpreterState_Get(void)
Part of the Stable ABI since version 3.9. Obtiene el intérprete actual.
Emite un error fatal si no hay un estado actual del hilo de Python o no hay un intérprete actual. No puede
retornar NULL.
La persona que llama debe retener el GIL.
Added in version 3.9.
int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
Part of the Stable ABI since version 3.7. Retorna la identificación única del intérprete. Si hubo algún error al
hacerlo, entonces se retorna -1 y se establece un error.
La persona que llama debe retener el GIL.
Added in version 3.7.
PyObject *PyInterpreterState_GetDict(PyInterpreterState *interp)
Part of the Stable ABI since version 3.8. Retorna un diccionario en el que se pueden almacenar datos específicos
del intérprete. Si esta función retorna NULL, no se ha producido ninguna excepción y la persona que llama debe
suponer que no hay disponible una instrucción específica del intérprete.
Esto no reemplaza a PyModule_GetState(), que las extensiones deben usar para almacenar información
de estado específica del intérprete.
Added in version 3.8.
typedef PyObject *(*_PyFrameEvalFunction)(PyThreadState *tstate, _PyInterpreterFrame *frame, int
throwflag)
Tipo de función de evaluación de marcos.
El parámetro throwflag es usado por el método de generadores throw(): si no es cero, maneja la excepción
actual.

208 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

Distinto en la versión 3.9: La función ahora recibe un parámetro tstate.


Distinto en la versión 3.11: El parámetro frame cambió de PyFrameObject* a
_PyInterpreterFrame*.
_PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
Obtiene la función de evaluación de marcos.
Consulte PEP 523 «Adición de una API de evaluación de marcos a CPython».
Added in version 3.9.
void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction
eval_frame)
Configura la función de evaluación del marco.
Consulte PEP 523 «Adición de una API de evaluación de marcos a CPython».
Added in version 3.9.
PyObject *PyThreadState_GetDict()
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario en el que las extensiones
pueden almacenar información de estado específica del hilo. Cada extensión debe usar una clave única para
almacenar el estado en el diccionario. Está bien llamar a esta función cuando no hay un estado del hilo actual
disponible. Si esta función retorna NULL, no se ha producido ninguna excepción y la persona que llama debe
asumir que no hay disponible ningún estado del hilo actual.
int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
Part of the Stable ABI. Asynchronously raise an exception in a thread. The id argument is the thread id of
the target thread; exc is the exception object to be raised. This function does not steal any references to exc.
To prevent naive misuse, you must write your own C extension to call this. Must be called with the GIL held.
Returns the number of thread states modified; this is normally one, but will be zero if the thread id isn’t found.
If exc is NULL, the pending exception (if any) for the thread is cleared. This raises no exceptions.
Distinto en la versión 3.7: El tipo del parámetro id cambia de long a unsigned long.
void PyEval_AcquireThread(PyThreadState *tstate)
Part of the Stable ABI. Adquiere el bloqueo global del intérprete y establece el estado actual del hilo en tstate,
que no debe ser NULL. El bloqueo debe haber sido creado anteriormente. Si este hilo ya tiene el bloqueo, se
produce un deadlock.

Nota: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to
check if the interpreter is in process of being finalized before calling this function to avoid unwanted termina-
tion.

Distinto en la versión 3.8: Actualiza para ser coherente con PyEval_RestoreThread(),


Py_END_ALLOW_THREADS(), y PyGILState_Ensure(), y termina el hilo actual si se llama
mientras el intérprete está finalizando.
PyEval_RestoreThread() es una función de nivel superior que siempre está disponible (incluso cuando
los subprocesos no se han inicializado).
void PyEval_ReleaseThread(PyThreadState *tstate)
Part of the Stable ABI. Restablece el estado actual del hilo a NULL y libera el bloqueo global del intérprete. El
bloqueo debe haberse creado antes y debe estar retenido por el hilo actual. El argumento tstate, que no debe
ser NULL, solo se usa para verificar que representa el estado actual del hilo — si no lo es, se informa un error
fatal.
PyEval_SaveThread() es una función de nivel superior que siempre está disponible (incluso cuando los
hilos no se han inicializado).

9.5. Estado del hilo y el bloqueo global del intérprete 209


The Python/C API, Versión 3.12.4

void PyEval_AcquireLock()
Part of the Stable ABI. Adquiera el bloqueo global de intérprete. El bloqueo debe haber sido creado anterior-
mente. Si este hilo ya tiene el bloqueo, se produce un deadlock.
Obsoleto desde la versión 3.2: Esta función no actualiza el estado actual del hilo. Utilice
PyEval_RestoreThread() o PyEval_AcquireThread() en su lugar.

Nota: Llamar a esta función desde un hilo cuando finalice el tiempo de ejecución terminará el hilo, incluso si
Python no creó el hilo. Puede usar _Py_IsFinalizing() o sys.is_finalizing() para verificar
si el intérprete está en proceso de finalización antes de llamar a esta función para evitar una terminación no
deseada.

Distinto en la versión 3.8: Actualiza para ser coherente con PyEval_RestoreThread(),


Py_END_ALLOW_THREADS(), y PyGILState_Ensure(), y termina el hilo actual si se llama
mientras el intérprete está finalizando.
void PyEval_ReleaseLock()
Part of the Stable ABI. Libere el bloqueo global del intérprete. El bloqueo debe haber sido creado anteriormente.
Obsoleto desde la versión 3.2: Esta función no actualiza el estado actual del hilo. Utilice
PyEval_SaveThread() o PyEval_ReleaseThread() en su lugar.

9.6 Soporte de subinterprete

Si bien en la mayoría de los usos, solo incrustará un solo intérprete de Python, hay casos en los que necesita crear varios
intérpretes independientes en el mismo proceso y tal vez incluso en el mismo hilo. Los subinterpretes le permiten hacer
eso.
El intérprete «principal» es el primero creado cuando se inicializa el tiempo de ejecución. Suele ser el único intérprete
de Python en un proceso. A diferencia de los subinterpretes, el intérprete principal tiene responsabilidades globales
de proceso únicas, como el manejo de señales. También es responsable de la ejecución durante la inicialización del
tiempo de ejecución y generalmente es el intérprete activo durante la finalización del tiempo de ejecución. La función
PyInterpreterState_Main() retorna un puntero a su estado.
Puede cambiar entre subinterpretes utilizando la función PyThreadState_Swap(). Puede crearlos y destruirlos
utilizando las siguientes funciones:
type PyInterpreterConfig
Structure containing most parameters to configure a sub-interpreter. Its values are used only in
Py_NewInterpreterFromConfig() and never modified by the runtime.
Added in version 3.12.
Structure fields:
int use_main_obmalloc
If this is 0 then the sub-interpreter will use its own «object» allocator state. Otherwise it will use (share)
the main interpreter’s.
If this is 0 then check_multi_interp_extensions must be 1 (non-zero). If this is 1 then gil
must not be PyInterpreterConfig_OWN_GIL.
int allow_fork
If this is 0 then the runtime will not support forking the process in any thread where the sub-interpreter
is currently active. Otherwise fork is unrestricted.
Note that the subprocess module still works when fork is disallowed.

210 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

int allow_exec
If this is 0 then the runtime will not support replacing the current process via exec (e.g. os.execv())
in any thread where the sub-interpreter is currently active. Otherwise exec is unrestricted.
Note that the subprocess module still works when exec is disallowed.
int allow_threads
If this is 0 then the sub-interpreter’s threading module won’t create threads. Otherwise threads are
allowed.
int allow_daemon_threads
If this is 0 then the sub-interpreter’s threading module won’t create daemon threads. Otherwise dae-
mon threads are allowed (as long as allow_threads is non-zero).
int check_multi_interp_extensions
If this is 0 then all extension modules may be imported, including legacy (single-phase init) modules,
in any thread where the sub-interpreter is currently active. Otherwise only multi-phase init extension
modules (see PEP 489) may be imported. (Also see Py_mod_multiple_interpreters.)
This must be 1 (non-zero) if use_main_obmalloc is 0.
int gil
This determines the operation of the GIL for the sub-interpreter. It may be one of the following:
PyInterpreterConfig_DEFAULT_GIL
Use the default selection (PyInterpreterConfig_SHARED_GIL).
PyInterpreterConfig_SHARED_GIL
Use (share) the main interpreter’s GIL.
PyInterpreterConfig_OWN_GIL
Use the sub-interpreter’s own GIL.
If this is PyInterpreterConfig_OWN_GIL then PyInterpreterConfig.
use_main_obmalloc must be 0.
PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)
Crea un nuevo subinterprete. Este es un entorno (casi) totalmente separado para la ejecución de código Python.
En particular, el nuevo intérprete tiene versiones separadas e independientes de todos los módulos importados,
incluidos los módulos fundamentales builtins, __main__ y sys. La tabla de módulos cargados (sys.
modules) y la ruta de búsqueda del módulo (sys.path) también están separados. El nuevo entorno no tiene
variable sys.argv. Tiene nuevos objetos de archivo de flujo de E/S estándar sys.stdin, sys.stdout
y sys.stderr (sin embargo, estos se refieren a los mismos descriptores de archivo subyacentes).
The given config controls the options with which the interpreter is initialized.
Upon success, tstate_p will be set to the first thread state created in the new sub-interpreter. This thread state
is made in the current thread state. Note that no actual thread is created; see the discussion of thread states
below. If creation of the new interpreter is unsuccessful, tstate_p is set to NULL; no exception is set since the
exception state is stored in the current thread state and there may not be a current thread state.
Like all other Python/C API functions, the global interpreter lock must be held before calling this function
and is still held when it returns. Likewise a current thread state must be set on entry. On success, the returned
thread state will be set as current. If the sub-interpreter is created with its own GIL then the GIL of the calling
interpreter will be released. When the function returns, the new interpreter’s GIL will be held by the current
thread and the previously interpreter’s GIL will remain released here.
Added in version 3.12.
Sub-interpreters are most effective when isolated from each other, with certain functionality restricted:
PyInterpreterConfig config = {
.use_main_obmalloc = 0,
.allow_fork = 0,
(continúe en la próxima página)

9.6. Soporte de subinterprete 211


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


.allow_exec = 0,
.allow_threads = 1,
.allow_daemon_threads = 0,
.check_multi_interp_extensions = 1,
.gil = PyInterpreterConfig_OWN_GIL,
};
PyThreadState *tstate = Py_NewInterpreterFromConfig(&config);

Note that the config is used only briefly and does not get modified. During initialization the config’s values
are converted into various PyInterpreterState values. A read-only copy of the config may be stored
internally on the PyInterpreterState.
Los módulos de extensión se comparten entre (sub) intérpretes de la siguiente manera:
• Para módulos que usan inicialización multifase, por ejemplo PyModule_FromDefAndSpec(), se
crea e inicializa un objeto de módulo separado para cada intérprete. Solo las variables estáticas y globales
de nivel C se comparten entre estos objetos de módulo.
• Para módulos que utilizan inicialización monofásica, por ejemplo PyModule_Create(), la primera
vez que se importa una extensión en particular, se inicializa normalmente y una copia (superficial) del
diccionario de su módulo se guarda. Cuando otro (sub) intérprete importa la misma extensión, se inicializa
un nuevo módulo y se llena con el contenido de esta copia; no se llama a la función init de la extensión.
Los objetos en el diccionario del módulo terminan compartidos entre (sub) intérpretes, lo que puede
causar un comportamiento no deseado (ver Errores y advertencias (Bugs and caveats) a continuación).
Tenga en cuenta que esto es diferente de lo que sucede cuando se importa una extensión después de que el
intérprete se haya reiniciado por completo llamando a Py_FinalizeEx() y Py_Initialize();
en ese caso, la función initmodule de la extensión es llamada nuevamente. Al igual que con la inicia-
lización de múltiples fases, esto significa que solo se comparten variables estáticas y globales de nivel C
entre estos módulos.
PyThreadState *Py_NewInterpreter(void)
Part of the Stable ABI. Create a new sub-interpreter. This is essentially just a wrapper around
Py_NewInterpreterFromConfig() with a config that preserves the existing behavior. The result is
an unisolated sub-interpreter that shares the main interpreter’s GIL, allows fork/exec, allows daemon threads,
and allows single-phase init modules.
void Py_EndInterpreter(PyThreadState *tstate)
Part of the Stable ABI. Destroy the (sub-)interpreter represented by the given thread state. The given thread state
must be the current thread state. See the discussion of thread states below. When the call returns, the current
thread state is NULL. All thread states associated with this interpreter are destroyed. The global interpreter
lock used by the target interpreter must be held before calling this function. No GIL is held when it returns.
Py_FinalizeEx() will destroy all sub-interpreters that haven’t been explicitly destroyed at that point.

9.6.1 A Per-Interpreter GIL

Using Py_NewInterpreterFromConfig() you can create a sub-interpreter that is completely isolated from
other interpreters, including having its own GIL. The most important benefit of this isolation is that such an interpreter
can execute Python code without being blocked by other interpreters or blocking any others. Thus a single Python
process can truly take advantage of multiple CPU cores when running Python code. The isolation also encourages a
different approach to concurrency than that of just using threads. (See PEP 554.)
Using an isolated interpreter requires vigilance in preserving that isolation. That especially means not sharing any
objects or mutable state without guarantees about thread-safety. Even objects that are otherwise immutable (e.g.
None, (1, 5)) can’t normally be shared because of the refcount. One simple but less-efficient approach around
this is to use a global lock around all use of some state (or object). Alternately, effectively immutable objects (like
integers or strings) can be made safe in spite of their refcounts by making them «immortal». In fact, this has been
done for the builtin singletons, small integers, and a number of other builtin objects.

212 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

If you preserve isolation then you will have access to proper multi-core computing without the complications that
come with free-threading. Failure to preserve isolation will expose you to the full consequences of free-threading,
including races and hard-to-debug crashes.
Aside from that, one of the main challenges of using multiple isolated interpreters is how to communicate between
them safely (not break isolation) and efficiently. The runtime and stdlib do not provide any standard approach to
this yet. A future stdlib module would help mitigate the effort of preserving isolation and expose effective tools for
communicating (and sharing) data between interpreters.
Added in version 3.12.

9.6.2 Errores y advertencias

Debido a que los subinterpretes (y el intérprete principal) son parte del mismo proceso, el aislamiento entre ellos no es
perfecto — por ejemplo, usando operaciones de archivos de bajo nivel como os.close() pueden (accidentalmente
o maliciosamente) afectar los archivos abiertos del otro. Debido a la forma en que las extensiones se comparten entre
(sub) intérpretes, algunas extensiones pueden no funcionar correctamente; esto es especialmente probable cuando
se utiliza la inicialización monofásica o las variables globales (estáticas). Es posible insertar objetos creados en un
subinterprete en un espacio de nombres de otro (sub) intérprete; Esto debe evitarse si es posible.
Se debe tener especial cuidado para evitar compartir funciones, métodos, instancias o clases definidas por el usua-
rio entre los subinterpretes, ya que las operaciones de importación ejecutadas por dichos objetos pueden afectar el
diccionario (sub-) intérprete incorrecto de los módulos cargados. Es igualmente importante evitar compartir objetos
desde los que se pueda acceder a lo anterior.
También tenga en cuenta que la combinación de esta funcionalidad con PyGILState_* APIs es delicada, porque
estas APIs suponen una biyección entre los estados de hilo de Python e hilos a nivel del sistema operativo, una
suposición rota por la presencia de subinterpretes. Se recomienda encarecidamente que no cambie los subinterpretes
entre un par de llamadas coincidentes PyGILState_Ensure() y PyGILState_Release(). Además, las
extensiones (como ctypes) que usan estas APIs para permitir la llamada de código Python desde hilos no creados
por Python probablemente se rompan cuando se usan subinterpretes.

9.7 Notificaciones asincrónicas

Se proporciona un mecanismo para hacer notificaciones asincrónicas al hilo principal del intérprete. Estas notifica-
ciones toman la forma de un puntero de función y un argumento de puntero nulo.
int Py_AddPendingCall(int (*func)(void*), void *arg)
Part of the Stable ABI. Programa una función para que se llame desde el hilo principal del intérprete. En caso
de éxito, se retorna 0 y se pone en cola func para ser llamado en el hilo principal. En caso de fallo, se retorna
-1 sin establecer ninguna excepción.
Cuando se puso en cola con éxito, func será eventualmente invocado desde el hilo principal del intérprete con
el argumento arg. Se llamará de forma asincrónica con respecto al código Python que se ejecuta normalmente,
pero con ambas condiciones cumplidas:
• en un límite bytecode;
• con el hilo principal que contiene el global interpreter lock (func, por lo tanto, puede usar la API C
completa).
func debe retornar 0 en caso de éxito o -1 en caso de error con una excepción establecida. func no se in-
terrumpirá para realizar otra notificación asíncrona de forma recursiva, pero aún se puede interrumpir para
cambiar hilos si se libera el bloqueo global del intérprete.
Esta función no necesita un estado de hilo actual para ejecutarse y no necesita el bloqueo global del intérprete.
Para llamar a esta función en un subinterprete, quien llama debe mantener el GIL. De lo contrario, la función
func se puede programar para que se llame desde el intérprete incorrecto.

9.7. Notificaciones asincrónicas 213


The Python/C API, Versión 3.12.4

Advertencia: Esta es una función de bajo nivel, solo útil para casos muy especiales. No hay garantía de que
func se llame lo más rápido posible. Si el hilo principal está ocupado ejecutando una llamada al sistema,
no se llamará func antes de que vuelva la llamada del sistema. Esta función generalmente no es adecuada
para llamar a código Python desde hilos C arbitrarios. En su lugar, use PyGILState API.

Added in version 3.1.


Distinto en la versión 3.9: Si esta función se llama en un subinterprete, la función func ahora está programada
para ser llamada desde el subinterprete, en lugar de ser llamada desde el intérprete principal. Cada subinterprete
ahora tiene su propia lista de llamadas programadas.

9.8 Perfilado y Rastreo

El intérprete de Python proporciona soporte de bajo nivel para adjuntar funciones de creación de perfiles y seguimiento
de ejecución. Estos se utilizan para herramientas de análisis de perfiles, depuración y cobertura.
Esta interfaz C permite que el código de perfilado o rastreo evite la sobrecarga de llamar a través de objetos invocables
a nivel de Python, haciendo una llamada directa a la función C en su lugar. Los atributos esenciales de la instalación no
han cambiado; la interfaz permite instalar funciones de rastreo por hilos, y los eventos básicos informados a la función
de rastreo son los mismos que se informaron a las funciones de rastreo a nivel de Python en versiones anteriores.
typedef int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
The type of the trace function registered using PyEval_SetProfile() and PyEval_SetTrace().
The first parameter is the object passed to the registration function as obj, frame is the frame object to which the
event pertains, what is one of the constants PyTrace_CALL, PyTrace_EXCEPTION, PyTrace_LINE,
PyTrace_RETURN, PyTrace_C_CALL, PyTrace_C_EXCEPTION, PyTrace_C_RETURN, or
PyTrace_OPCODE, and arg depends on the value of what:

Valor de what Significado de arg


PyTrace_CALL Siempre Py_None.
PyTrace_EXCEPTION Información de excepción retornada por sys.exc_info().
PyTrace_LINE Siempre Py_None.
PyTrace_RETURN Valor retornado al que llama, o NULL si es causado por una excepción.
PyTrace_C_CALL Objeto función que se llaman.
PyTrace_C_EXCEPTION Objeto función que se llaman.
PyTrace_C_RETURN Objeto función que se llaman.
PyTrace_OPCODE Siempre Py_None.

int PyTrace_CALL
El valor del parámetro what para una función Py_tracefunc cuando se informa una nueva llamada a una
función o método, o una nueva entrada en un generador. Tenga en cuenta que la creación del iterador para una
función de generador no se informa ya que no hay transferencia de control al código de bytes de Python en la
marco correspondiente.
int PyTrace_EXCEPTION
El valor del parámetro what para una función Py_tracefunc cuando se ha producido una excepción. La
función de devolución de llamada se llama con este valor para what cuando después de que se procese cualquier
bytecode, después de lo cual la excepción se establece dentro del marco que se está ejecutando. El efecto de
esto es que a medida que la propagación de la excepción hace que la pila de Python se desenrolle, el retorno de
llamada se llama al retornar a cada marco a medida que se propaga la excepción. Solo las funciones de rastreo
reciben estos eventos; el perfilador (profiler) no los necesita.
int PyTrace_LINE
The value passed as the what parameter to a Py_tracefunc function (but not a profiling function) when a

214 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

line-number event is being reported. It may be disabled for a frame by setting f_trace_lines to 0 on that
frame.
int PyTrace_RETURN
El valor para el parámetro what para Py_tracefunc funciona cuando una llamada está por regresar.
int PyTrace_C_CALL
El valor del parámetro what para Py_tracefunc funciona cuando una función C está a punto de ser invo-
cada.
int PyTrace_C_EXCEPTION
El valor del parámetro what para funciones Py_tracefunc cuando una función C ha lanzado una excepción.
int PyTrace_C_RETURN
El valor del parámetro what para Py_tracefunc funciona cuando una función C ha retornado.
int PyTrace_OPCODE
The value for the what parameter to Py_tracefunc functions (but not profiling functions) when a new
opcode is about to be executed. This event is not emitted by default: it must be explicitly requested by setting
f_trace_opcodes to 1 on the frame.
void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
Set the profiler function to func. The obj parameter is passed to the function as its first parameter, and may
be any Python object, or NULL. If the profile function needs to maintain state, using a different value for obj
for each thread provides a convenient and thread-safe place to store it. The profile function is called for all
monitored events except PyTrace_LINE PyTrace_OPCODE and PyTrace_EXCEPTION.
Consulte también la función sys.setprofile().
La persona que llama debe mantener el GIL.
void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)
Like PyEval_SetProfile() but sets the profile function in all running threads belonging to the current
interpreter instead of the setting it only on the current thread.
La persona que llama debe mantener el GIL.
As PyEval_SetProfile(), this function ignores any exceptions raised while setting the profile functions
in all threads.
Added in version 3.12.
void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
Set the tracing function to func. This is similar to PyEval_SetProfile(), except the tracing function
does receive line-number events and per-opcode events, but does not receive any event related to C fun-
ction objects being called. Any trace function registered using PyEval_SetTrace() will not receive
PyTrace_C_CALL, PyTrace_C_EXCEPTION or PyTrace_C_RETURN as a value for the what pa-
rameter.
Consulte también la función sys.settrace().
La persona que llama debe mantener el GIL.
void PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *obj)
Like PyEval_SetTrace() but sets the tracing function in all running threads belonging to the current
interpreter instead of the setting it only on the current thread.
La persona que llama debe mantener el GIL.
As PyEval_SetTrace(), this function ignores any exceptions raised while setting the trace functions in
all threads.
Added in version 3.12.

9.8. Perfilado y Rastreo 215


The Python/C API, Versión 3.12.4

9.9 Soporte avanzado del depurador

Estas funciones solo están destinadas a ser utilizadas por herramientas de depuración avanzadas.
PyInterpreterState *PyInterpreterState_Head()
Retorna el objeto de estado del intérprete al principio de la lista de todos esos objetos.
PyInterpreterState *PyInterpreterState_Main()
Retorna el objeto de estado del intérprete principal.
PyInterpreterState *PyInterpreterState_Next(PyInterpreterState *interp)
Retorna el siguiente objeto de estado de intérprete después de interp de la lista de todos esos objetos.
PyThreadState *PyInterpreterState_ThreadHead(PyInterpreterState *interp)
Retorna el puntero al primer objeto PyThreadState en la lista de hilos asociados con el intérprete interp.
PyThreadState *PyThreadState_Next(PyThreadState *tstate)
Retorna el siguiente objeto de estado del hilo después de tstate de la lista de todos los objetos que pertenecen
al mismo objeto PyInterpreterState.

9.10 Soporte de almacenamiento local de hilo

El intérprete de Python proporciona soporte de bajo nivel para el almacenamiento local de hilos (TLS) que envuelve
la implementación de TLS nativa subyacente para admitir la API de almacenamiento local de hilos de nivel Python
(threading.local). Las APIs de nivel CPython C son similares a las ofrecidas por pthreads y Windows: use
una clave de hilo y funciones para asociar un valor de void* por hilo.
El GIL no necesita ser retenido al llamar a estas funciones; proporcionan su propio bloqueo.
Tenga en cuenta que Python.h no incluye la declaración de las API de TLS, debe incluir pythread.h para usar
el almacenamiento local de hilos.

Nota: Ninguna de estas funciones API maneja la administración de memoria en nombre de los valores void*. Debe
asignarlos y desasignarlos usted mismo. Si los valores void* son PyObject*, estas funciones tampoco realizan
operaciones de conteo de referencias en ellos.

9.10.1 API de almacenamiento específico de hilo (TSS, Thread Specific Storage)

La API de TSS se introduce para reemplazar el uso de la API TLS existente dentro del intérprete de CPython. Esta
API utiliza un nuevo tipo Py_tss_t en lugar de int para representar las claves del hilo.
Added in version 3.7.
Ver también:
«Una nueva C-API para Thread-Local Storage en CPython» (PEP 539)
type Py_tss_t
Esta estructura de datos representa el estado de una clave del hilo, cuya definición puede depender de la imple-
mentación de TLS subyacente, y tiene un campo interno que representa el estado de inicialización de la clave.
No hay miembros públicos en esta estructura.
Cuando Py_LIMITED_API no está definido, la asignación estática de este tipo por Py_tss_NEEDS_INIT
está permitida.
Py_tss_NEEDS_INIT
Esta macro se expande al inicializador para variables Py_tss_t. Tenga en cuenta que esta macro no se
definirá con Py_LIMITED_API.

216 Capítulo 9. Inicialización, finalización e hilos


The Python/C API, Versión 3.12.4

Asignación dinámica

Asignación dinámica de Py_tss_t, requerida en los módulos de extensión construidos con Py_LIMITED_API,
donde la asignación estática de este tipo no es posible debido a que su implementación es opaca en el momento de la
compilación.
Py_tss_t *PyThread_tss_alloc()
Part of the Stable ABI since version 3.7. Retorna un valor que es el mismo estado que un valor inicializado con
Py_tss_NEEDS_INIT, o NULL en caso de falla de asignación dinámica.
void PyThread_tss_free(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Libera la clave asignada por PyThread_tss_alloc(), después
de llamar por primera vez PyThread_tss_delete() para asegurarse de que los hilos locales asociados
no hayan sido asignados. Esto es un no-op si el argumento clave es NULL.

Nota: Una clave liberada se convierte en un puntero colgante. Debería restablecer la clave a NULL.

Métodos

El parámetro key de estas funciones no debe ser NULL. Además, los comportamientos de PyThread_tss_set()
y PyThread_tss_get() no están definidos si el Py_tss_t dado no ha sido inicializado por
PyThread_tss_create().
int PyThread_tss_is_created(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Retorna un valor distinto de cero si Py_tss_t ha sido inicializado
por PyThread_tss_create().
int PyThread_tss_create(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Retorna un valor cero en la inicialización exitosa de una clave
TSS. El comportamiento no está definido si el valor señalado por el argumento key no se inicializa con
Py_tss_NEEDS_INIT. Esta función se puede invocar repetidamente en la misma tecla: llamarla a una
tecla ya inicializada es un no-op e inmediatamente retorna el éxito.
void PyThread_tss_delete(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Destruye una clave TSS para olvidar los valores asociados con la clave
en todos los hilos y cambie el estado de inicialización de la clave a no inicializado. Una clave destruida se puede
inicializar nuevamente mediante PyThread_tss_create(). Esta función se puede invocar repetidamente
en la misma llave; llamarla en una llave ya destruida es un no-op.
int PyThread_tss_set(Py_tss_t *key, void *value)
Part of the Stable ABI since version 3.7. Retorna un valor cero para indicar la asociación exitosa de un valor a
void* con una clave TSS en el hilo actual. Cada hilo tiene un mapeo distinto de la clave a un valor void*.
void *PyThread_tss_get(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Retorna el valor void* asociado con una clave TSS en el hilo actual.
Esto retorna NULL si no hay ningún valor asociado con la clave en el hilo actual.

9.10. Soporte de almacenamiento local de hilo 217


The Python/C API, Versión 3.12.4

9.10.2 API de almacenamiento local de hilos (TLS, Thread Local Storage)

Obsoleto desde la versión 3.7: Esta API es reemplazada por API de Almacenamiento Específico de Hilos (TSS, por
sus significado en inglés *Thread Specific Storage*).

Nota: Esta versión de la API no es compatible con plataformas donde la clave TLS nativa se define de una manera
que no se puede transmitir de forma segura a int. En tales plataformas, PyThread_create_key() regresará
inmediatamente con un estado de falla, y las otras funciones TLS serán no operativas en tales plataformas.

Debido al problema de compatibilidad mencionado anteriormente, esta versión de la API no debe usarse en código
nuevo.
int PyThread_create_key()
Part of the Stable ABI.
void PyThread_delete_key(int key)
Part of the Stable ABI.
int PyThread_set_key_value(int key, void *value)
Part of the Stable ABI.
void *PyThread_get_key_value(int key)
Part of the Stable ABI.
void PyThread_delete_key_value(int key)
Part of the Stable ABI.
void PyThread_ReInitTLS()
Part of the Stable ABI.

218 Capítulo 9. Inicialización, finalización e hilos


CAPÍTULO 10

Configuración de inicialización de Python

Added in version 3.8.


Python se puede inicializar con Py_InitializeFromConfig() y la estructura PyConfig. Se puede preini-
cializar con Py_PreInitialize() y la estructura PyPreConfig.
Hay dos tipos de configuración:
• The Python Configuration can be used to build a customized Python which behaves as the regular Python. For
example, environment variables and command line arguments are used to configure Python.
• The Isolated Configuration can be used to embed Python into an application. It isolates Python from the system.
For example, environment variables are ignored, the LC_CTYPE locale is left unchanged and no signal handler
is registered.
La función Py_RunMain() se puede utilizar para escribir un programa Python personalizado.
Consulte también Inicialización, finalización y subprocesos.
Ver también:
PEP 587 «Configuración de inicialización de Python».

10.1 Ejemplo

Ejemplo de Python personalizado que siempre se ejecuta en modo aislado:

int main(int argc, char **argv)


{
PyStatus status;

PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;

/* Decode command line arguments.


Implicitly preinitialize Python (in isolated mode). */
status = PyConfig_SetBytesArgv(&config, argc, argv);
if (PyStatus_Exception(status)) {
goto exception;
(continúe en la próxima página)

219
The Python/C API, Versión 3.12.4

(proviene de la página anterior)


}

status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);

return Py_RunMain();

exception:
PyConfig_Clear(&config);
if (PyStatus_IsExit(status)) {
return status.exitcode;
}
/* Display the error message and exit the process with
non-zero exit code */
Py_ExitStatusException(status);
}

10.2 PyWideStringList

type PyWideStringList
Lista de cadenas de caracteres wchar_t*.
Si length no es cero, items no deben ser NULL y todas las cadenas de caracteres deben ser no NULL.
Métodos:
PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)
Agregar item a list.
Python debe estar preinicializado para llamar a esta función.
PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)
Inserta item en list en index.
Si index es mayor o igual que el largo de list, agrega item a list.
index must be greater than or equal to 0.
Python debe estar preinicializado para llamar a esta función.
Campos de estructura:
Py_ssize_t length
Longitud de la lista.
wchar_t **items
Elementos de la lista.

220 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

10.3 PyStatus

type PyStatus
Estructura para almacenar el estado de una función de inicialización: éxito, error o salida.
Para un error, puede almacenar el nombre de la función C que creó el error.
Campos de estructura:
int exitcode
Código de salida El argumento pasó a exit().
const char *err_msg
Mensaje de error.
const char *func
El nombre de la función que creó un error puede ser NULL.
Funciones para crear un estado:
PyStatus PyStatus_Ok(void)
Éxito.
PyStatus PyStatus_Error(const char *err_msg)
Error de inicialización con un mensaje.
err_msg no debe ser NULL.
PyStatus PyStatus_NoMemory(void)
Error de asignación de memoria (sin memoria).
PyStatus PyStatus_Exit(int exitcode)
Sale de Python con el código de salida especificado.
Funciones para manejar un estado:
int PyStatus_Exception(PyStatus status)
¿Es el estado un error o una salida? Si es verdadero, la excepción debe ser manejada; por ejemplo llamando
a Py_ExitStatusException().
int PyStatus_IsError(PyStatus status)
¿Es el resultado un error?
int PyStatus_IsExit(PyStatus status)
¿El resultado es una salida?
void Py_ExitStatusException(PyStatus status)
Llama a exit(exitcode) si status es una salida. Imprime el mensaje de error y sale con un código de
salida distinto de cero si status es un error. Solo se debe llamar si PyStatus_Exception(status)
no es cero.

Nota: Internamente, Python usa macros que establecen PyStatus.func, mientras que las funciones para crear
un estado establecen func en NULL.

Ejemplo:

PyStatus alloc(void **ptr, size_t size)


{
*ptr = PyMem_RawMalloc(size);
if (*ptr == NULL) {
return PyStatus_NoMemory();
(continúe en la próxima página)

10.3. PyStatus 221


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


}
return PyStatus_Ok();
}

int main(int argc, char **argv)


{
void *ptr;
PyStatus status = alloc(&ptr, 16);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
PyMem_Free(ptr);
return 0;
}

10.4 PyPreConfig

type PyPreConfig
Estructura utilizada para preinicializar Python.
Función para inicializar una preconfiguración:
void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
Inicializa la preconfiguración con Configuración de Python.
void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
Inicializa la preconfiguración con Configuración aislada.
Campos de estructura:
int allocator
Nombre de los asignadores de memoria de Python:
• PYMEM_ALLOCATOR_NOT_SET (0): no cambia asignadores de memoria (usa los valores prede-
terminados)
• PYMEM_ALLOCATOR_DEFAULT (1): asignadores de memoria predeterminados.
• PYMEM_ALLOCATOR_DEBUG (2): asignadores de memoria predeterminados con ganchos de de-
puración.
• PYMEM_ALLOCATOR_MALLOC (3): usa malloc() de la biblioteca C.
• PYMEM_ALLOCATOR_MALLOC_DEBUG (4): fuerza el uso de malloc() con ganchos de depu-
ración.
• PYMEM_ALLOCATOR_PYMALLOC (5): asignador de memoria pymalloc de Python
• PYMEM_ALLOCATOR_PYMALLOC_DEBUG (6): asignador de memoria pymalloc de Python con
ganchos de depuración.
PYMEM_ALLOCATOR_PYMALLOC y PYMEM_ALLOCATOR_PYMALLOC_DEBUG no son compati-
bles si Python es configurado usando --without-pymalloc.
Ver Administración de memorias.
Predeterminado: PYMEM_ALLOCATOR_NOT_SET.
int configure_locale
Set the LC_CTYPE locale to the user preferred locale.
If equals to 0, set coerce_c_locale and coerce_c_locale_warn members to 0.
Vea el locale encoding.

222 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

Predeterminado: 1 en la configuración de Python, 0 en la configuración aislada.


int coerce_c_locale
If equals to 2, coerce the C locale.
If equals to 1, read the LC_CTYPE locale to decide if it should be coerced.
Vea el locale encoding.
Predeterminado: -1 en la configuración de Python, 0 en la configuración aislada.
int coerce_c_locale_warn
Si no es cero, emita una advertencia si la configuración regional C está coaccionada.
Predeterminado: -1 en la configuración de Python, 0 en la configuración aislada.
int dev_mode
Python Development Mode: see PyConfig.dev_mode.
Por defecto: -1 en modo Python, 0 en modo aislado.
int isolated
Modo aislado: consulte PyConfig.isolated.
Por defecto: 0 en modo Python, 1 en modo aislado.
int legacy_windows_fs_encoding
Si no es cero:
• Establezca PyPreConfig.utf8_mode en 0,
• Establezca PyConfig.filesystem_encoding en "mbcs",
• Establezca PyConfig.filesystem_errors en "replace".
Inicializado desde valor de variable de entorno PYTHONLEGACYWINDOWSFSENCODING.
Solo disponible en Windows. La macro #ifdef MS_WINDOWS se puede usar para el código específico
de Windows.
Predeterminado: 0.
int parse_argv
Si no es cero, Py_PreInitializeFromArgs() y Py_PreInitializeFromBytesArgs()
analizan su argumento argv de la misma manera que Python analiza los argumentos de la línea de
comandos: ver Argumentos de línea de comandos.
Predeterminado: 1 en la configuración de Python, 0 en la configuración aislada.
int use_environment
¿Utiliza variables de entorno? Consulte PyConfig.use_environment.
Predeterminado: 1 en la configuración de Python y 0 en la configuración aislada.
int utf8_mode
Si es distinto de cero, habilite Python UTF-8 Mode.
Set to 0 or 1 by the -X utf8 command line option and the PYTHONUTF8 environment variable.
También se pone a 1 si la configuración regional LC_CTYPE es C o POSIX.
Predeterminado: -1 en la configuración de Python y 0 en la configuración aislada.

10.4. PyPreConfig 223


The Python/C API, Versión 3.12.4

10.5 Preinicialización de Python con PyPreConfig

La preinicialización de Python:
• Establecer los asignadores de memoria de Python (PyPreConfig.allocator)
• Configurar la configuración regional LC_CTYPE (locale encoding)
• Establecer el Python UTF-8 Mode (PyPreConfig.utf8_mode)
La preconfiguración actual (tipo PyPreConfig) se almacena en _PyRuntime.preconfig.
Funciones para preinicializar Python:
PyStatus Py_PreInitialize(const PyPreConfig *preconfig)
Preinicializa Python desde la preconfiguración preconfig.
preconfig no debe ser NULL.
PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char *const *argv)
Preinicializa Python desde la preconfiguración preconfig.
Analice los argumentos de la línea de comando argv (cadenas de bytes) si parse_argv de preconfig no es
cero.
preconfig no debe ser NULL.
PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t *const *argv)
Preinicializa Python desde la preconfiguración preconfig.
Analice los argumentos de la línea de comando argv (cadenas anchas) si parse_argv de preconfig no es
cero.
preconfig no debe ser NULL.
La persona que llama es responsable de manejar las excepciones (error o salida) usando PyStatus_Exception()
y Py_ExitStatusException().
Para Configuración de Python (PyPreConfig_InitPythonConfig()), si Python se inicializa con argumentos
de línea de comando, los argumentos de la línea de comando también deben pasarse para preinicializar Python, ya
que tienen un efecto en la preconfiguración como codificaciones. Por ejemplo, la opción de línea de comando -X
utf8 habilita el Python UTF-8 Mode.
PyMem_SetAllocator() se puede llamar después de Py_PreInitialize() y antes
Py_InitializeFromConfig() para instalar un asignador de memoria personalizado. Se pue-
de llamar antes Py_PreInitialize() si PyPreConfig.allocator está configurado en
PYMEM_ALLOCATOR_NOT_SET.
Las funciones de asignación de memoria de Python como PyMem_RawMalloc() no deben usarse antes de la
preinicialización de Python, mientras que llamar directamente a malloc() y free() siempre es seguro. No se
debe llamar a Py_DecodeLocale() antes de la preinicialización de Python.
Ejemplo usando la preinicialización para habilitar el Python UTF-8 Mode

PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);

preconfig.utf8_mode = 1;

status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}

/* at this point, Python speaks UTF-8 */


(continúe en la próxima página)

224 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

(proviene de la página anterior)

Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();

10.6 PyConfig

type PyConfig
Estructura que contiene la mayoría de los parámetros para configurar Python.
Cuando termine, se debe utilizar la función PyConfig_Clear() para liberar la memoria de configuración.
Métodos de estructura:
void PyConfig_InitPythonConfig(PyConfig *config)
Inicialice la configuración con la Configuración de Python.
void PyConfig_InitIsolatedConfig(PyConfig *config)
Inicialice la configuración con la Configuración Aislada.
PyStatus PyConfig_SetString(PyConfig *config, wchar_t *const *config_str, const wchar_t *str)
Copia la cadena de caracteres anchos str en *config_str.
Preinicializa Python si es necesario.
PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t *const *config_str, const char *str)
Decodifique str usando Py_DecodeLocale() y establezca el resultado en *config_str.
Preinicializa Python si es necesario.
PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t *const *argv)
Configure los argumentos de la línea de comando (miembro argv de config) de la lista argv de cadenas
de caracteres anchas.
Preinicializa Python si es necesario.
PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char *const *argv)
Establezca argumentos de línea de comando (miembro argv de config) de la lista argv de cadenas de
bytes. Decodifica bytes usando Py_DecodeLocale().
Preinicializa Python si es necesario.
PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t
length, wchar_t **items)
Establece la lista de cadenas de caracteres anchas list a length y items.
Preinicializa Python si es necesario.
PyStatus PyConfig_Read(PyConfig *config)
Lee toda la configuración de Python.
Los campos que ya están inicializados no se modifican.
Los campos para la configuración de ruta ya no se calculan ni modifican al llamar a esta función, a partir
de Python 3.11.
La función PyConfig_Read() solo analiza los argumentos PyConfig.argv una vez:
PyConfig.parse_argv se establece en 2 después de analizar los argumentos. Dado que los ar-
gumentos de Python se eliminan de PyConfig.argv, analizar los argumentos dos veces analizaría las
opciones de la aplicación como opciones de Python.
Preinicializa Python si es necesario.

10.6. PyConfig 225


The Python/C API, Versión 3.12.4

Distinto en la versión 3.10: Los argumentos PyConfig.argv ahora solo se analizan una vez,
PyConfig.parse_argv se establece en 2 después de analizar los argumentos y los argumentos
solo se analizan si PyConfig.parse_argv es igual a 1.
Distinto en la versión 3.11: PyConfig_Read() ya no calcula todas las rutas, por lo que los
campos listados en Python Path Configuration ya no pueden ser actualizados hasta que se llame a
Py_InitializeFromConfig().
void PyConfig_Clear(PyConfig *config)
Libera memoria de configuración.
La mayoría de los método PyConfig preinitializan Python si es necesario. En ese caso, la configuración de
preinicialización de Python (PyPreConfig) se basa en PyConfig. Si se ajustan los campos de configura-
ción que son comunes con PyPreConfig, deben establecerse antes de llamar a un método PyConfig:
• PyConfig.dev_mode
• PyConfig.isolated
• PyConfig.parse_argv
• PyConfig.use_environment
Moreover, if PyConfig_SetArgv() or PyConfig_SetBytesArgv() is used, this method must be
called before other methods, since the preinitialization configuration depends on command line arguments (if
parse_argv is non-zero).
Quien llama de estos métodos es responsable de manejar las excepciones (error o salida) usando
PyStatus_Exception() y Py_ExitStatusException().
Campos de estructura:
PyWideStringList argv
Argumentos de la línea de comando: sys.argv.
Configure parse_argv en 1 para analizar argv de la misma manera que Python normal analiza los
argumentos de la línea de comandos de Python y luego quita los argumentos de Python de argv.
Si argv está vacío, se agrega una cadena vacía para garantizar que sys.argv siempre exista y nunca
esté vacío.
Valor predeterminado: NULL.
Consulte también el miembro orig_argv.
int safe_path
Si es igual a cero, Py_RunMain() agrega una ruta potencialmente insegura a sys.path al inicio:
• Si argv[0] es igual a L"-m" (python -m module), añade el directorio de trabajo actual.
• If running a script (python script.py), prepend the script’s directory. If it’s a symbolic link,
resolve symbolic links.
• En caso contrario (python -c code and python), añade una cadena vacía, que significa el
directorio de trabajo actual.
Set to 1 by the -P command line option and the PYTHONSAFEPATH environment variable.
Default: 0 in Python config, 1 in isolated config.
Added in version 3.11.
wchar_t *base_exec_prefix
sys.base_exec_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.

226 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

wchar_t *base_executable
Ejecutable base de Python: sys._base_executable.
Establecido por la variable de entorno __PYVENV_LAUNCHER__.
Establecido desde PyConfig.executable si NULL.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
wchar_t *base_prefix
sys.base_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
int buffered_stdio
If equals to 0 and configure_c_stdio is non-zero, disable buffering on the C streams stdout and
stderr.
Set to 0 by the -u command line option and the PYTHONUNBUFFERED environment variable.
stdin siempre se abre en modo de búfer.
Predeterminado: 1.
int bytes_warning
If equals to 1, issue a warning when comparing bytes or bytearray with str, or comparing bytes
with int.
If equal or greater to 2, raise a BytesWarning exception in these cases.
Incrementado por la opción de línea de comando -b.
Predeterminado: 0.
int warn_default_encoding
Si no es cero, emite una advertencia EncodingWarning cuando io.TextIOWrapper usa su co-
dificación predeterminada. Consulte io-encoding-warning para obtener más detalles.
Predeterminado: 0.
Added in version 3.10.
int code_debug_ranges
If equals to 0, disables the inclusion of the end line and column mappings in code objects. Also disables
traceback printing carets to specific error locations.
Set to 0 by the PYTHONNODEBUGRANGES environment variable and by the -X no_debug_ranges
command line option.
Predeterminado: 1.
Added in version 3.11.
wchar_t *check_hash_pycs_mode
Controla el comportamiento de validación de archivos .pyc basados en hash: valor de la opción de línea
de comando --check-hash-based-pycs.
Valores válidos:
• L"always": Calcula el hash el archivo fuente para invalidación independientemente del valor de
la marca “check_source”.
• L"never": suponga que los pycs basados en hash siempre son válidos.
• L"default": El indicador “check_source” en pycs basados en hash determina la invalidación.

10.6. PyConfig 227


The Python/C API, Versión 3.12.4

Predeterminado: L"default".
Consulte también PEP 552 «Pycs deterministas».
int configure_c_stdio
Si es distinto de cero, configure los flujos estándar de C:
• En Windows, configure el modo binario (O_BINARY) en stdin, stdout y stderr.
• Si buffered_stdio es igual a cero, deshabilite el almacenamiento en búfer de los flujos stdin,
stdout y stderr.
• Si interactive no es cero, habilite el almacenamiento en búfer de flujo en stdin y stdout (solo
stdout en Windows).
Predeterminado: 1 en la configuración de Python, 0 en la configuración aislada.
int dev_mode
Si es distinto de cero, habilita Modo de desarrollo de Python.
Set to 1 by the -X dev option and the PYTHONDEVMODE environment variable.
Por defecto: -1 en modo Python, 0 en modo aislado.
int dump_refs
Dump Python references?
Si no es cero, volcar todos los objetos que aún están vivos en la salida.
Establecido en 1 por la variable de entorno PYTHONDUMPREFS.
Necesita una compilación especial de Python con la macro Py_TRACE_REFS definida: consulte la
opción de configure --with-trace-refs option.
Predeterminado: 0.
wchar_t *exec_prefix
El prefijo de directorio específico del sitio donde se instalan los archivos Python dependientes de la
plataforma: sys.exec_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
wchar_t *executable
La ruta absoluta del binario ejecutable para el intérprete de Python: sys.executable.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
int faulthandler
¿Habilitar administrador de fallas?
Si no es cero, llama a faulthandler.enable() al inicio.
Establecido en 1 por -X faulthandler y la variable de entorno PYTHONFAULTHANDLER.
Por defecto: -1 en modo Python, 0 en modo aislado.
wchar_t *filesystem_encoding
Codificación del sistema de archvios: sys.getfilesystemencoding().
En macOS, Android y VxWorks: use "utf-8" de forma predeterminada.
En Windows: utilice "utf-8" de forma predeterminada o "mbcs" si
legacy_windows_fs_encoding de PyPreConfig no es cero.
Codificación predeterminada en otras plataformas:
• "utf-8" si PyPreConfig.utf8_mode es distinto de cero.

228 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

• "ascii" if Python detects that nl_langinfo(CODESET) announces the ASCII encoding,


whereas the mbstowcs() function decodes from a different encoding (usually Latin1).
• "utf-8" si nl_langinfo(CODESET) retorna una cadena vacía.
• De lo contrario, utilice el resultado locale encoding: nl_langinfo(CODESET).
Al inicio de Python, el nombre de codificación se normaliza al nombre del códec de Python. Por ejemplo,
"ANSI_X3.4-1968" se reemplaza por "ascii".
Consulte también el miembro filesystem_errors.
wchar_t *filesystem_errors
Manejador de errores del sistema de archivos: sys.getfilesystemencodeerrors().
En Windows: utilice "surrogatepass" de forma predeterminada o "replace" si
legacy_windows_fs_encoding de PyPreConfig no es cero.
En otras plataformas: utilice "surrogateescape" de forma predeterminada.
Controladores de errores admitidos:
• "strict"
• "surrogateescape"
• "surrogatepass" (solo compatible con la codificación UTF-8)
Consulte también el miembro filesystem_encoding.
unsigned long hash_seed

int use_hash_seed
Funciones de semillas aleatorias hash.
Si use_hash_seed es cero, se elige una semilla al azar en el inicio de Python y se ignora hash_seed.
Establecido por la variable de entorno PYTHONHASHSEED.
Valor predeterminado de use_hash_seed: -1 en modo Python, 0 en modo aislado.
wchar_t *home
Directorio de inicio de Python.
Si se ha llamado a Py_SetPythonHome(), use su argumento si no es NULL.
Establecido por la variable de entorno PYTHONHOME.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
int import_time
Si no es cero, el tiempo de importación del perfil.
Configure el 1 mediante la opción -X importtime y la variable de entorno
PYTHONPROFILEIMPORTTIME.
Predeterminado: 0.
int inspect
Ingresa al modo interactivo después de ejecutar un script o un comando.
If greater than 0, enable inspect: when a script is passed as first argument or the -c option is used, enter
interactive mode after executing the script or the command, even when sys.stdin does not appear to
be a terminal.
Incrementado por la opción de línea de comando -i. Establecido en 1 si la variable de entorno
PYTHONINSPECT no está vacía.
Predeterminado: 0.

10.6. PyConfig 229


The Python/C API, Versión 3.12.4

int install_signal_handlers
¿Instalar controladores de señales de Python?
Por defecto: 1 en modo Python, 0 en modo aislado.
int interactive
If greater than 0, enable the interactive mode (REPL).
Incrementado por la opción de línea de comando -i.
Predeterminado: 0.
int int_max_str_digits
Configures the integer string conversion length limitation. An initial value of -1 means the value will
be taken from the command line or environment or otherwise default to 4300 (sys.int_info.
default_max_str_digits). A value of 0 disables the limitation. Values greater than zero but less
than 640 (sys.int_info.str_digits_check_threshold) are unsupported and will produ-
ce an error.
Configured by the -X int_max_str_digits command line flag or the
PYTHONINTMAXSTRDIGITS environment variable.
Default: -1 in Python mode. 4300 (sys.int_info.default_max_str_digits) in isolated
mode.
Added in version 3.12.
int isolated
If greater than 0, enable isolated mode:
• Set safe_path to 1: don’t prepend a potentially unsafe path to sys.path at Python startup,
such as the current directory, the script’s directory or an empty string.
• Set use_environment to 0: ignore PYTHON environment variables.
• Set user_site_directory to 0: don’t add the user site directory to sys.path.
• Python REPL no importa readline ni habilita la configuración predeterminada de readline en
mensajes interactivos.
Set to 1 by the -I command line option.
Por defecto: 0 en modo Python, 1 en modo aislado.
See also the Isolated Configuration and PyPreConfig.isolated.
int legacy_windows_stdio
If non-zero, use io.FileIO instead of io._WindowsConsoleIO for sys.stdin, sys.
stdout and sys.stderr.
Establecido en 1 si la variable de entorno PYTHONLEGACYWINDOWSSTDIO está establecida en una
cadena no vacía.
Solo disponible en Windows. La macro #ifdef MS_WINDOWS se puede usar para el código específico
de Windows.
Predeterminado: 0.
Consulte también PEP 528 (Cambiar la codificación de la consola de Windows a UTF-8).
int malloc_stats
Si no es cero, volcar las estadísticas en Asignador de memoria Python pymalloc en la salida.
Establecido en 1 por la variable de entorno PYTHONMALLOCSTATS.
La opción se ignora si Python es configurado usando la opción
--without-pymalloc.
Predeterminado: 0.

230 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

wchar_t *platlibdir
Nombre del directorio de la biblioteca de la plataforma: sys.platlibdir.
Establecido por la variable de entorno PYTHONPLATLIBDIR.
Default: value of the PLATLIBDIR macro which is set by the configure --with-platlibdir
option (default: "lib", or "DLLs" on Windows).
Parte de la entrada Python Path Configuration.
Added in version 3.9.
Distinto en la versión 3.11: Esta macro se utiliza ahora en Windows para localizar los módulos de exten-
sión de la biblioteca estándar, normalmente en DLLs. Sin embargo, por compatibilidad, tenga en cuenta
que este valor se ignora para cualquier disposición no estándar, incluyendo las construcciones dentro del
árbol y los entornos virtuales.
wchar_t *pythonpath_env
Module search paths (sys.path) as a string separated by DELIM (os.pathsep).
Establecido por la variable de entorno PYTHONPATH.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
PyWideStringList module_search_paths

int module_search_paths_set
Rutas de búsqueda del módulo: sys.path.
If module_search_paths_set is equal to 0, Py_InitializeFromConfig() will replace
module_search_paths and sets module_search_paths_set to 1.
Por defecto: lista vacía (module_search_paths) y 0 (module_search_paths_set).
Parte de la salida Python Path Configuration.
int optimization_level
Nivel de optimización de compilación:
• 0: Optimizador de mirilla, configure __debug__ en True.
• 1: Nivel 0, elimina las aserciones, establece __debug__ en False.
• 2: Nivel 1, elimina docstrings.
Incrementado por la opción de línea de comando -O. Establecido en el valor de la variable de entorno
PYTHONOPTIMIZE.
Predeterminado: 0.
PyWideStringList orig_argv
La lista de los argumentos originales de la línea de comandos pasados al ejecutable de Python: sys.
orig_argv.
Si la lista orig_argv está vacía y argv no es una lista que solo contiene una cadena vacía,
PyConfig_Read() copia argv en orig_argv antes de modificar argv (si parse_argv no
es cero).
Consulte también el miembro argv y la función Py_GetArgcArgv().
Predeterminado: lista vacía.
Added in version 3.10.

10.6. PyConfig 231


The Python/C API, Versión 3.12.4

int parse_argv
¿Analizar los argumentos de la línea de comando?
Si es igual a 1, analiza argv de la misma forma que Python normal analiza argumentos de línea de
comando y elimina los argumentos de Python de argv.
La función PyConfig_Read() solo analiza los argumentos PyConfig.argv una vez:
PyConfig.parse_argv se establece en 2 después de analizar los argumentos. Dado que los ar-
gumentos de Python se eliminan de PyConfig.argv, analizar los argumentos dos veces analizaría las
opciones de la aplicación como opciones de Python.
Por defecto: 1 en modo Python, 0 en modo aislado.
Distinto en la versión 3.10: Los argumentos PyConfig.argv ahora solo se analizan si PyConfig.
parse_argv es igual a 1.
int parser_debug
Parser debug mode. If greater than 0, turn on parser debugging output (for expert only, depending on
compilation options).
Incrementado por la opción de línea de comando -d. Establecido en el valor de la variable de entorno
PYTHONDEBUG.
Need a debug build of Python (the Py_DEBUG macro must be defined).
Predeterminado: 0.
int pathconfig_warnings
If non-zero, calculation of path configuration is allowed to log warnings into stderr. If equals to 0,
suppress these warnings.
Por defecto: 1 en modo Python, 0 en modo aislado.
Parte de la entrada Python Path Configuration.
Distinto en la versión 3.11: Ahora también se aplica en Windows.
wchar_t *prefix
El prefijo de directorio específico del sitio donde se instalan los archivos Python independientes de la
plataforma: sys.prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
wchar_t *program_name
Nombre del programa utilizado para inicializar executable y en los primeros mensajes de error du-
rante la inicialización de Python.
• Si se ha llamado a Py_SetProgramName(), usa su argumento.
• En macOS, usa la variable de entorno PYTHONEXECUTABLE si está configurada.
• Si se define la macro WITH_NEXT_FRAMEWORK, utiliza la variable de entorno
__PYVENV_LAUNCHER__ si está configurada.
• Utiliza argv[0] de argv si está disponible y no está vacío.
• De lo contrario, utiliza L"python" en Windows o L"python3" en otras plataformas.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
wchar_t *pycache_prefix
Directorio donde se escriben los archivos .pyc almacenados en caché: sys.pycache_prefix.
Establecido por la opción de línea de comando -X pycache_prefix=PATH y la variable de entorno
PYTHONPYCACHEPREFIX.

232 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

Si NULL, sys.pycache_prefix es establecido a None.


Valor predeterminado: NULL.
int quiet
Quiet mode. If greater than 0, don’t display the copyright and version at Python startup in interactive
mode.
Incrementado por la opción de línea de comando -q.
Predeterminado: 0.
wchar_t *run_command
Valor de la opción de línea de comando -c.
Usado por Py_RunMain().
Valor predeterminado: NULL.
wchar_t *run_filename
Filename passed on the command line: trailing command line argument without -c or -m. It is used by
the Py_RunMain() function.
For example, it is set to script.py by the python3 script.py arg command line.
See also the PyConfig.skip_source_first_line option.
Valor predeterminado: NULL.
wchar_t *run_module
Valor de la opción de línea de comando -m.
Usado por Py_RunMain().
Valor predeterminado: NULL.
int show_ref_count
Show total reference count at exit (excluding immortal objects)?
Set to 1 by -X showrefcount command line option.
Necesita una compilación de depuración de Python (se debe definir la macro Py_REF_DEBUG).
Predeterminado: 0.
int site_import
¿Importar el módulo site al inicio?
Si es igual a cero, desactive la importación del sitio del módulo y las manipulaciones dependientes del
sitio de sys.path que conlleva.
También deshabilite estas manipulaciones si el módulo site se importa explícitamente más tarde (llame
a site.main() si desea que se activen).
Establecido en 0 mediante la opción de línea de comando -S.
sys.flags.no_site is set to the inverted value of site_import.
Predeterminado: 1.
int skip_source_first_line
Si no es cero, omita la primera línea de la fuente PyConfig.run_filename.
Permite el uso de formas de #!cmd que no son Unix. Esto está destinado únicamente a un truco específico
de DOS.
Establecido en 1 mediante la opción de línea de comando -x.
Predeterminado: 0.

10.6. PyConfig 233


The Python/C API, Versión 3.12.4

wchar_t *stdio_encoding

wchar_t *stdio_errors
Codificación y errores de codificación de sys.stdin, sys.stdout y sys.stderr (pero sys.
stderr siempre usa el controlador de errores "backslashreplace").
Si se ha llamado a Py_SetStandardStreamEncoding(), utilice sus argumentos error y errors si
no son NULL.
Utilice la variable de entorno PYTHONIOENCODING si no está vacía.
Codificación predeterminada:
• "UTF-8" si PyPreConfig.utf8_mode es distinto de cero.
• De lo contrario, usa el locale encoding.
Manejador de errores predeterminado:
• En Windows: use "surrogateescape".
• "surrogateescape" si PyPreConfig.utf8_mode no es cero o si la configuración regio-
nal LC_CTYPE es «C» o «POSIX».
• "strict" de lo contrario.
int tracemalloc
¿Habilitar tracemalloc?
Si no es cero, llama a tracemalloc.start() al inicio.
Establecido por la opción de línea de comando -X tracemalloc=N y por la variable de entorno
PYTHONTRACEMALLOC.
Por defecto: -1 en modo Python, 0 en modo aislado.
int perf_profiling
Enable compatibility mode with the perf profiler?
If non-zero, initialize the perf trampoline. See perf_profiling for more information.
Set by -X perf command line option and by the PYTHONPERFSUPPORT environment variable.
Default: -1.
Added in version 3.12.
int use_environment
¿Utiliza variables de entorno?
Si es igual a cero, ignora las variables de entorno.
Set to 0 by the -E environment variable.
Predeterminado: 1 en la configuración de Python y 0 en la configuración aislada.
int user_site_directory
Si es distinto de cero, agregue el directorio del sitio del usuario a sys.path.
Establecido en 0 por las opciones de línea de comando -s y -I.
Establecido en 0 por la variable de entorno PYTHONNOUSERSITE.
Por defecto: 1 en modo Python, 0 en modo aislado.
int verbose
Verbose mode. If greater than 0, print a message each time a module is imported, showing the place
(filename or built-in module) from which it is loaded.
If greater than or equal to 2, print a message for each file that is checked for when searching for a module.
Also provides information on module cleanup at exit.

234 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

Incrementado por la opción de línea de comando -v.


Set by the PYTHONVERBOSE environment variable value.
Predeterminado: 0.
PyWideStringList warnoptions
Opciones del módulo warnings para crear filtros de advertencias, de menor a mayor prioridad: sys.
warnoptions.
El módulo warnings agrega sys.warnoptions en el orden inverso: el último elemento
PyConfig.warnoptions se convierte en el primer elemento de warnings.filters que es
verificado primero (máxima prioridad).
Las opciones de la línea de comando -W agregan su valor a warnoptions, se puede usar varias veces.
La variable de entorno PYTHONWARNINGS también se puede utilizar para agregar opciones de adver-
tencia. Se pueden especificar varias opciones, separadas por comas (,).
Predeterminado: lista vacía.
int write_bytecode
If equal to 0, Python won’t try to write .pyc files on the import of source modules.
Establecido en 0 por la opción de línea de comando -B y la variable de entorno
PYTHONDONTWRITEBYTECODE.
sys.dont_write_bytecode se inicializa al valor invertido de write_bytecode.
Predeterminado: 1.
PyWideStringList xoptions
Valores de las opciones de la línea de comando -X: sys._xoptions.
Predeterminado: lista vacía.
Si parse_argv no es cero, los argumentos de argv se analizan de la misma forma que Python normal analiza
argumentos de línea de comando, y los argumentos de Python se eliminan de argv.
Las opciones de xoptions se analizan para establecer otras opciones: consulte la opción de línea de comando -X.
Distinto en la versión 3.9: El campo show_alloc_count fue removido.

10.7 Inicialización con PyConfig

Función para inicializar Python:


PyStatus Py_InitializeFromConfig(const PyConfig *config)
Inicializa Python desde la configuración config.
La persona que llama es responsable de manejar las excepciones (error o salida) usando PyStatus_Exception()
y Py_ExitStatusException().
Si se utilizan PyImport_FrozenModules(), PyImport_AppendInittab() o
PyImport_ExtendInittab(), deben establecerse o llamarse después de la preinicialización de
Python y antes de la inicialización de Python. Si Python se inicializa varias veces, se debe llamar a
PyImport_AppendInittab() o PyImport_ExtendInittab() antes de cada inicialización de
Python.
La configuración actual (tipo PyConfig) se almacena en PyInterpreterState.config.
Ejemplo de configuración del nombre del programa:

10.7. Inicialización con PyConfig 235


The Python/C API, Versión 3.12.4

void init_python(void)
{
PyStatus status;

PyConfig config;
PyConfig_InitPythonConfig(&config);

/* Set the program name. Implicitly preinitialize Python. */


status = PyConfig_SetString(&config, &config.program_name,
L"/path/to/my_program");
if (PyStatus_Exception(status)) {
goto exception;
}

status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return;

exception:
PyConfig_Clear(&config);
Py_ExitStatusException(status);
}

More complete example modifying the default configuration, read the configuration, and then override some para-
meters. Note that since 3.11, many parameters are not calculated until initialization, and so values cannot be read
from the configuration structure. Any values set before initialize is called will be left unchanged by initialization:
PyStatus init_python(const char *program_name)
{
PyStatus status;

PyConfig config;
PyConfig_InitPythonConfig(&config);

/* Set the program name before reading the configuration


(decode byte string from the locale encoding).

Implicitly preinitialize Python. */


status = PyConfig_SetBytesString(&config, &config.program_name,
program_name);
if (PyStatus_Exception(status)) {
goto done;
}

/* Read all configuration at once */


status = PyConfig_Read(&config);
if (PyStatus_Exception(status)) {
goto done;
}

/* Specify sys.path explicitly */


/* If you want to modify the default set of paths, finish
initialization first and then use PySys_GetObject("path") */
config.module_search_paths_set = 1;
status = PyWideStringList_Append(&config.module_search_paths,
L"/path/to/stdlib");
if (PyStatus_Exception(status)) {
goto done;
}
(continúe en la próxima página)

236 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


status = PyWideStringList_Append(&config.module_search_paths,
L"/path/to/more/modules");
if (PyStatus_Exception(status)) {
goto done;
}

/* Override executable computed by PyConfig_Read() */


status = PyConfig_SetString(&config, &config.executable,
L"/path/to/my_executable");
if (PyStatus_Exception(status)) {
goto done;
}

status = Py_InitializeFromConfig(&config);

done:
PyConfig_Clear(&config);
return status;
}

10.8 Configuración aislada

PyPreConfig_InitIsolatedConfig() y las funciones PyConfig_InitIsolatedConfig() crean


una configuración para aislar Python del sistema. Por ejemplo, para incrustar Python en una aplicación.
This configuration ignores global configuration variables, environment variables, command line arguments
(PyConfig.argv is not parsed) and user site directory. The C standard streams (ex: stdout) and the
LC_CTYPE locale are left unchanged. Signal handlers are not installed.
Los archivos de configuración se siguen utilizando con esta configuración para determinar las rutas que no se espe-
cifican. Asegúrese de que se especifica PyConfig.home para evitar que se calcule la configuración de la ruta por
defecto.

10.9 Configuración de Python

PyPreConfig_InitPythonConfig() y las funciones PyConfig_InitPythonConfig() crean una


configuración para construir un Python personalizado que se comporta como el Python normal.
Las variables de entorno y los argumentos de la línea de comandos se utilizan para configurar Python, mientras que
las variables de configuración global se ignoran.
Esta función habilita la coerción de configuración regional C (PEP 538) y Python UTF-8 Mode (PEP 540) según la
configuración regional LC_CTYPE, las variables de entorno PYTHONUTF8 y PYTHONCOERCECLOCALE.

10.10 Configuración de la ruta de Python

PyConfig contiene múltiples campos para la configuración de ruta:


• Entradas de configuración de ruta:
– PyConfig.home
– PyConfig.platlibdir
– PyConfig.pathconfig_warnings
– PyConfig.program_name

10.8. Configuración aislada 237


The Python/C API, Versión 3.12.4

– PyConfig.pythonpath_env
– directorio de trabajo actual: para obtener rutas absolutas
– Variable de entorno PATH para obtener la ruta completa del programa (de PyConfig.
program_name)
– Variable de entorno __PYVENV_LAUNCHER__
– (Solo Windows) Rutas de aplicación en el registro en «SoftwarePythonPythonCoreX.YPythonPath» de
HKEY_CURRENT_USER y HKEY_LOCAL_MACHINE (donde X.Y es la versión de Python).
• Campos de salida de configuración de ruta:
– PyConfig.base_exec_prefix
– PyConfig.base_executable
– PyConfig.base_prefix
– PyConfig.exec_prefix
– PyConfig.executable
– PyConfig.module_search_paths_set, PyConfig.module_search_paths
– PyConfig.prefix
Si al menos un «campo de salida» no está establecido, Python calcula la configuración de la ruta para rellenar los
campos no establecidos. Si module_search_paths_set es igual a 0, module_search_paths se anula y
module_search_paths_set se establece en 1.
It is possible to completely ignore the function calculating the default path configuration by setting expli-
citly all path configuration output fields listed above. A string is considered as set even if it is non-empty.
module_search_paths is considered as set if module_search_paths_set is set to 1. In this case,
module_search_paths will be used without modification.
Set pathconfig_warnings to 0 to suppress warnings when calculating the path configuration (Unix only, Win-
dows does not log any warning).
Si base_prefix o los campos base_exec_prefix no están establecidos, heredan su valor de prefix y
exec_prefix respectivamente.
Py_RunMain() y Py_Main() modifican sys.path:
• Si run_filename está configurado y es un directorio que contiene un script __main__.py, anteponga
run_filename a sys.path.
• Si isolated es cero:
– Si run_module está configurado, anteponga el directorio actual a sys.path. No haga nada si el
directorio actual no se puede leer.
– Si run_filename está configurado, anteponga el directorio del nombre del archivo a sys.path.
– De lo contrario, anteponga una cadena de caracteres vacía a sys.path.
Si site_import no es cero, sys.path puede ser modificado por el módulo site. Si
user_site_directory no es cero y el directorio del paquete del sitio del usuario existe, el módulo
site agrega el directorio del paquete del sitio del usuario a sys.path.
La configuración de ruta utiliza los siguientes archivos de configuración:
• pyvenv.cfg
• archivo ._pth (ej: python._pth)
• pybuilddir.txt (sólo Unix)
Si un archivo ._pth está presente:
• Set isolated to 1.

238 Capítulo 10. Configuración de inicialización de Python


The Python/C API, Versión 3.12.4

• Set use_environment to 0.
• Set site_import to 0.
• Set safe_path to 1.
La variable de entorno __PYVENV_LAUNCHER__ se usa para establecer PyConfig.base_executable

10.11 Py_RunMain()

int Py_RunMain(void)
Ejecuta el comando (PyConfig.run_command), el script (PyConfig.run_filename) o el módulo
(PyConfig.run_module) especificado en la línea de comando o en la configuración.
Por defecto y cuando se usa la opción -i, ejecuta el REPL.
Finalmente, finaliza Python y retorna un estado de salida que se puede pasar a la función exit().
Consulte Configuración de Python para ver un ejemplo de Python personalizado que siempre se ejecuta en modo
aislado usando Py_RunMain().

10.12 Py_GetArgcArgv()

void Py_GetArgcArgv(int *argc, wchar_t ***argv)


Obtiene los argumentos originales de la línea de comandos, antes de que Python los modificara.
Ver también el miembro PyConfig.orig_argv.

10.13 API Provisional Privada de Inicialización Multifásica

This section is a private provisional API introducing multi-phase initialization, the core feature of PEP 432:
• Fase de inicialización «Core», «Python mínimo»:
– Tipos incorporados;
– Excepciones incorporadas;
– Módulos incorporados y congelados;
– El módulo sys solo se inicializa parcialmente (por ejemplo sys.path aún no existe).
• Fase de inicialización «principal», Python está completamente inicializado:
– Instala y configura importlib;
– Aplique la Configuración de ruta;
– Instala manejadores de señal;
– Finaliza la inicialización del módulo sys (por ejemplo: crea sys.stdout y sys.path);
– Habilita características opcionales como faulthandler y tracemalloc;
– Importe el módulo site;
– etc.
API provisional privada:
• PyConfig._init_main: if set to 0, Py_InitializeFromConfig() stops at the «Core» initializa-
tion phase.

10.11. Py_RunMain() 239


The Python/C API, Versión 3.12.4

PyStatus _Py_InitializeMain(void)
Vaya a la fase de inicialización «Principal», finalice la inicialización de Python.
No se importa ningún módulo durante la fase «Core» y el módulo importlib no está configurado: la Configuración
de ruta solo se aplica durante la fase «Principal». Puede permitir personalizar Python en Python para anular o ajustar
Configuración de ruta, tal vez instale un importador personalizado sys.meta_path o un enlace de importación,
etc.
It may become possible to calculate the Path Configuration in Python, after the Core phase and before the Main phase,
which is one of the PEP 432 motivation.
La fase «Núcleo» no está definida correctamente: lo que debería estar y lo que no debería estar disponible en esta
fase aún no se ha especificado. La API está marcada como privada y provisional: la API se puede modificar o incluso
eliminar en cualquier momento hasta que se diseñe una API pública adecuada.
Ejemplo de ejecución de código Python entre las fases de inicialización «Core» y «Main»:

void init_python(void)
{
PyStatus status;

PyConfig config;
PyConfig_InitPythonConfig(&config);
config._init_main = 0;

/* ... customize 'config' configuration ... */

status = Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}

/* Use sys.stderr because sys.stdout is only created


by _Py_InitializeMain() */
int res = PyRun_SimpleString(
"import sys; "
"print('Run Python code before _Py_InitializeMain', "
"file=sys.stderr)");
if (res < 0) {
exit(1);
}

/* ... put more configuration code here ... */

status = _Py_InitializeMain();
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
}

240 Capítulo 10. Configuración de inicialización de Python


CAPÍTULO 11

Gestión de la memoria

11.1 Visión general

La gestión de memoria en Python implica un montón privado que contiene todos los objetos de Python y estructu-
ras de datos. El administrador de memoria de Python garantiza internamente la gestión de este montón privado. El
administrador de memoria de Python tiene diferentes componentes que se ocupan de varios aspectos de la gestión
dinámica del almacenamiento, como compartir, segmentación, asignación previa o almacenamiento en caché.
En el nivel más bajo, un asignador de memoria sin procesar asegura que haya suficiente espacio en el montón privado
para almacenar todos los datos relacionados con Python al interactuar con el administrador de memoria del sistema
operativo. Además del asignador de memoria sin procesar, varios asignadores específicos de objeto operan en el
mismo montón e implementan políticas de administración de memoria distintas adaptadas a las peculiaridades de
cada tipo de objeto. Por ejemplo, los objetos enteros se administran de manera diferente dentro del montón que las
cadenas, tuplas o diccionarios porque los enteros implican diferentes requisitos de almacenamiento y compensaciones
de velocidad / espacio. El administrador de memoria de Python delega parte del trabajo a los asignadores específicos
de objeto, pero asegura que este último opere dentro de los límites del montón privado.
Es importante comprender que la gestión del montón de Python la realiza el propio intérprete y que el usuario no
tiene control sobre él, incluso si manipulan regularmente punteros de objetos a bloques de memoria dentro de ese
montón. El administrador de memoria de Python realiza la asignación de espacio de almacenamiento dinámico para
los objetos de Python y otros búferes internos a pedido a través de las funciones de API de Python/C enumeradas en
este documento.
Para evitar daños en la memoria, los escritores de extensiones nunca deberían intentar operar en objetos Python con
las funciones exportadas por la biblioteca C: malloc(), calloc(), realloc() y free(). Esto dará como
resultado llamadas mixtas entre el asignador de C y el administrador de memoria de Python con consecuencias fatales,
ya que implementan diferentes algoritmos y operan en diferentes montones. Sin embargo, uno puede asignar y liberar
de forma segura bloques de memoria con el asignador de la biblioteca C para fines individuales, como se muestra en
el siguiente ejemplo:

PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */

if (buf == NULL)
return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyBytes_FromString(buf);
(continúe en la próxima página)

241
The Python/C API, Versión 3.12.4

(proviene de la página anterior)


free(buf); /* malloc'ed */
return res;

En este ejemplo, la solicitud de memoria para el búfer de E/S es manejada por el asignador de la biblioteca C. El
administrador de memoria de Python solo participa en la asignación del objeto de bytes retornado como resultado.
Sin embargo, en la mayoría de las situaciones, se recomienda asignar memoria del montón de Python específicamente
porque este último está bajo el control del administrador de memoria de Python. Por ejemplo, esto es necesario cuando
el intérprete se amplía con nuevos tipos de objetos escritos en C. Otra razón para usar el montón de Python es el deseo
de informar al administrador de memoria de Python sobre las necesidades de memoria del módulo de extensión.
Incluso cuando la memoria solicitada se usa exclusivamente para fines internos y altamente específicos, delegar todas
las solicitudes de memoria al administrador de memoria de Python hace que el intérprete tenga una imagen más
precisa de su huella de memoria en su conjunto. En consecuencia, bajo ciertas circunstancias, el administrador de
memoria de Python puede o no desencadenar acciones apropiadas, como recolección de basura, compactación de
memoria u otros procedimientos preventivos. Tenga en cuenta que al usar el asignador de la biblioteca C como se
muestra en el ejemplo anterior, la memoria asignada para el búfer de E/S escapa completamente al administrador de
memoria Python.
Ver también:
La variable de entorno PYTHONMALLOC puede usarse para configurar los asignadores de memoria utilizados por
Python.
La variable de entorno PYTHONMALLOCSTATS se puede utilizar para imprimir estadísticas de asignador de me-
moria pymalloc cada vez que se crea un nuevo escenario de objetos pymalloc, y en el apagado.

11.2 Dominios del asignador

Todas las funciones de asignación pertenecen a uno de los tres «dominios» diferentes (ver también
PyMemAllocatorDomain). Estos dominios representan diferentes estrategias de asignación y están optimiza-
dos para diferentes propósitos. Los detalles específicos sobre cómo cada dominio asigna memoria o qué funciones
internas llama cada dominio se considera un detalle de implementación, pero para fines de depuración, se puede en-
contrar una tabla simplificada en here. No existe un requisito estricto para usar la memoria retornada por las funciones
de asignación que pertenecen a un dominio dado solo para los propósitos sugeridos por ese dominio (aunque esta
es la práctica recomendada). Por ejemplo, se podría usar la memoria retornada por PyMem_RawMalloc() para
asignar objetos Python o la memoria retornada por PyObject_Malloc() para asignar memoria para búferes.
Los tres dominios de asignación son:
• Dominio sin formato: destinado a asignar memoria para búferes de memoria de uso general donde la asig-
nación debe ir al asignador del sistema o donde el asignador puede operar sin el GIL. La memoria se solicita
directamente al sistema.
• Dominio «Mem»: destinado a asignar memoria para búferes de Python y búferes de memoria de propósito
general donde la asignación debe realizarse con el GIL retenido. La memoria se toma del montículo privado de
Python.
• Dominio de objeto: destinado a asignar memoria perteneciente a objetos de Python. La memoria se toma del
montículo privado de Python.
Cuando se libera memoria previamente asignada por las funciones de asignación que pertenecen a un dominio dado,
se deben utilizar las funciones de desasignación específicas coincidentes. Por ejemplo, PyMem_Free() debe usarse
para liberar memoria asignada usando PyMem_Malloc().

242 Capítulo 11. Gestión de la memoria


The Python/C API, Versión 3.12.4

11.3 Interfaz de memoria sin procesar

Los siguientes conjuntos de funciones son envoltorios para el asignador del sistema. Estas funciones son seguras para
subprocesos, no es necesario mantener el GIL.
The default raw memory allocator uses the following functions: malloc(), calloc(), realloc() and
free(); call malloc(1) (or calloc(1, 1)) when requesting zero bytes.
Added in version 3.4.
void *PyMem_RawMalloc(size_t n)
Asigna n bytes y retorna un puntero de tipo void* a la memoria asignada, o NULL si la solicitud falla.
Solicitar cero bytes retorna un puntero distinto que no sea NULL si es posible, como si en su lugar se hubiera
llamado a PyMem_RawMalloc(1). La memoria no se habrá inicializado de ninguna manera.
void *PyMem_RawCalloc(size_t nelem, size_t elsize)
Asigna nelem elementos cada uno cuyo tamaño en bytes es elsize y retorna un puntero de tipo void* a la
memoria asignada, o NULL si la solicitud falla. La memoria se inicializa a ceros.
Solicitar elementos cero o elementos de tamaño cero bytes retorna un puntero distinto NULL si es posible,
como si en su lugar se hubiera llamado PyMem_RawCalloc(1, 1).
Added in version 3.5.
void *PyMem_RawRealloc(void *p, size_t n)
Cambia el tamaño del bloque de memoria señalado por p a n bytes. Los contenidos no se modificarán al mínimo
de los tamaños antiguo y nuevo.
Si p es NULL, la llamada es equivalente a PyMem_RawMalloc(n); de lo contrario, si n es igual a cero, el
bloque de memoria cambia de tamaño pero no se libera, y el puntero retornado no es NULL.
A menos que p sea NULL, debe haber sido retornado por una llamada previa a PyMem_RawMalloc(),
PyMem_RawRealloc() o PyMem_RawCalloc().
Si la solicitud falla, PyMem_RawRealloc() retorna NULL y p sigue siendo un puntero válido al área de
memoria anterior.
void PyMem_RawFree(void *p)
Libera el bloque de memoria al que apunta p, que debe haber sido retornado por una llamada anterior a
PyMem_RawMalloc(), PyMem_RawRealloc() o PyMem_RawCalloc(). De lo contrario, o si se
ha llamado antes a PyMem_RawFree(p), se produce un comportamiento indefinido.
Si p es NULL, no se realiza ninguna operación.

11.4 Interfaz de memoria

Los siguientes conjuntos de funciones, modelados según el estándar ANSI C, pero que especifican el comportamiento
cuando se solicitan cero bytes, están disponibles para asignar y liberar memoria del montón de Python.
El asignador de memoria predeterminado usa el asignador de memorya pymalloc.

Advertencia: El GIL debe mantenerse cuando se utilizan estas funciones.

Distinto en la versión 3.6: El asignador predeterminado ahora es pymalloc en lugar del malloc() del sistema.
void *PyMem_Malloc(size_t n)
Part of the Stable ABI. Asigna n bytes y retorna un puntero de tipo void* a la memoria asignada, o NULL si
la solicitud falla.
Solicitar cero bytes retorna un puntero distinto que no sea NULL si es posible, como si en su lugar se hubiera
llamado a PyMem_Malloc(1). La memoria no se habrá inicializado de ninguna manera.

11.3. Interfaz de memoria sin procesar 243


The Python/C API, Versión 3.12.4

void *PyMem_Calloc(size_t nelem, size_t elsize)


Part of the Stable ABI since version 3.7. Asigna nelem elementos cada uno cuyo tamaño en bytes es elsize y
retorna un puntero de tipo void* a la memoria asignada, o NULL si la solicitud falla. La memoria se inicializa
a ceros.
Solicitar elementos cero o elementos de tamaño cero bytes retorna un puntero distinto NULL si es posible,
como si en su lugar se hubiera llamado PyMem_Calloc(1, 1).
Added in version 3.5.
void *PyMem_Realloc(void *p, size_t n)
Part of the Stable ABI. Cambia el tamaño del bloque de memoria señalado por p a n bytes. Los contenidos no
se modificarán al mínimo de los tamaños antiguo y nuevo.
Si p es NULL, la llamada es equivalente a PyMem_Malloc(n); de lo contrario, si n es igual a cero, el bloque
de memoria cambia de tamaño pero no se libera, y el puntero retornado no es NULL.
A menos que p sea NULL, debe haber sido retornado por una llamada previa a PyMem_Malloc(),
PyMem_Realloc() o PyMem_Calloc().
Si la solicitud falla, PyMem_Realloc() retorna NULL y p sigue siendo un puntero válido al área de memoria
anterior.
void PyMem_Free(void *p)
Part of the Stable ABI. Libera el bloque de memoria señalado por p, que debe haber sido retornado por una
llamada anterior a PyMem_Malloc(), PyMem_Realloc() o PyMem_Calloc(). De lo contrario, o si
se ha llamado antes a PyMem_Free(p), se produce un comportamiento indefinido.
Si p es NULL, no se realiza ninguna operación.
Las siguientes macros orientadas a tipos se proporcionan por conveniencia. Tenga en cuenta que TYPE se refiere a
cualquier tipo de C.
PyMem_New(TYPE, n)
Same as PyMem_Malloc(), but allocates (n * sizeof(TYPE)) bytes of memory. Returns a pointer
cast to TYPE*. The memory will not have been initialized in any way.
PyMem_Resize(p, TYPE, n)
Same as PyMem_Realloc(), but the memory block is resized to (n * sizeof(TYPE)) bytes. Returns
a pointer cast to TYPE*. On return, p will be a pointer to the new memory area, or NULL in the event of failure.
Esta es una macro de preprocesador C; p siempre se reasigna. Guarde el valor original de p para evitar perder
memoria al manejar errores.
void PyMem_Del(void *p)
La misma que PyMem_Free().
Además, se proporcionan los siguientes conjuntos de macros para llamar al asignador de memoria de Python direc-
tamente, sin involucrar las funciones de API de C mencionadas anteriormente. Sin embargo, tenga en cuenta que su
uso no conserva la compatibilidad binaria entre las versiones de Python y, por lo tanto, está en desuso en los módulos
de extensión.
• PyMem_MALLOC(size)
• PyMem_NEW(type, size)
• PyMem_REALLOC(ptr, size)
• PyMem_RESIZE(ptr, type, size)
• PyMem_FREE(ptr)
• PyMem_DEL(ptr)

244 Capítulo 11. Gestión de la memoria


The Python/C API, Versión 3.12.4

11.5 Asignadores de objetos

Los siguientes conjuntos de funciones, modelados según el estándar ANSI C, pero que especifican el comportamiento
cuando se solicitan cero bytes, están disponibles para asignar y liberar memoria del montón de Python.

Nota: No hay garantía de que la memoria retornada por estos asignadores se pueda convertir con éxito en un ob-
jeto Python al interceptar las funciones de asignación en este dominio mediante los métodos descritos en la sección
Personalizar Asignadores de Memoria.

El asignador predeterminado de objetos usa el asignador de memoria pymalloc.

Advertencia: El GIL debe mantenerse cuando se utilizan estas funciones.

void *PyObject_Malloc(size_t n)
Part of the Stable ABI. Asigna n bytes y retorna un puntero de tipo void* a la memoria asignada, o NULL si
la solicitud falla.
Solicitar cero bytes retorna un puntero distinto que no sea NULL si es posible, como si en su lugar se hubiera
llamado a PyObject_Malloc(1). La memoria no se habrá inicializado de ninguna manera.
void *PyObject_Calloc(size_t nelem, size_t elsize)
Part of the Stable ABI since version 3.7. Asigna nelem elementos cada uno cuyo tamaño en bytes es elsize y
retorna un puntero de tipo void* a la memoria asignada, o NULL si la solicitud falla. La memoria se inicializa
a ceros.
Solicitar elementos cero o elementos de tamaño cero bytes retorna un puntero distinto NULL si es posible,
como si en su lugar se hubiera llamado PyObject_Calloc(1, 1).
Added in version 3.5.
void *PyObject_Realloc(void *p, size_t n)
Part of the Stable ABI. Cambia el tamaño del bloque de memoria señalado por p a n bytes. Los contenidos no
se modificarán al mínimo de los tamaños antiguo y nuevo.
Si p es NULL, la llamada es equivalente a PyObject_Malloc(n); de lo contrario, si n es igual a cero, el
bloque de memoria cambia de tamaño pero no se libera, y el puntero retornado no es NULL.
A menos que p sea NULL, debe haber sido retornado por una llamada previa a PyObject_Malloc(),
PyObject_Realloc() o PyObject_Calloc().
Si la solicitud falla, PyObject_Realloc() retorna NULL y p sigue siendo un puntero válido al área de
memoria anterior.
void PyObject_Free(void *p)
Part of the Stable ABI. Libera el bloque de memoria al que apunta p, que debe haber sido retornado por una
llamada anterior a PyObject_Malloc(), PyObject_Realloc() o PyObject_Calloc(). De lo
contrario, o si se ha llamado antes a PyObject_Free(p), se produce un comportamiento indefinido.
Si p es NULL, no se realiza ninguna operación.

11.5. Asignadores de objetos 245


The Python/C API, Versión 3.12.4

11.6 Asignadores de memoria predeterminados

Asignadores de memoria predeterminados:

Configuración Nombre Py- Py- PyOb-


Mem_RawMalloc Mem_Malloc ject_Malloc
Lanzamiento de compilación "pymalloc" malloc malloc + de- malloc + de-
bug bug
Compilación de depuración "pymalloc_debug"
malloc + de- pymalloc + pymalloc +
bug debug debug
Lanzamiento de compilación, sin "malloc" malloc malloc malloc
pymalloc
Compilación de depuración, sin "malloc_debug" malloc + de- malloc + de- malloc + de-
pymalloc bug bug bug

Leyenda:
• Nombre: valor para variable de entorno PYTHONMALLOC.
• malloc: asignadores del sistema de la biblioteca C estándar, funciones C: malloc(), calloc(),
realloc() y free().
• pymalloc: asignador de memoria pymalloc.
• «+ debug»: con enlaces de depuración en los asignadores de memoria de Python.
• «Debug build»: Compilación de Python en modo de depuración.

11.7 Personalizar asignadores de memoria

Added in version 3.4.


type PyMemAllocatorEx
Estructura utilizada para describir un asignador de bloque de memoria. La estructura tiene cuatro campos:

Campo Significado
void *ctx contexto de usuario pasado como primer
argumento
void* malloc(void *ctx, size_t size) asignar un bloque de memoria
void* calloc(void *ctx, size_t nelem, asignar un bloque de memoria inicializado
size_t elsize) con ceros
void* realloc(void *ctx, void *ptr, asignar o cambiar el tamaño de un bloque
size_t new_size) de memoria
void free(void *ctx, void *ptr) liberar un bloque de memoria

Distinto en la versión 3.5: The PyMemAllocator structure was renamed to PyMemAllocatorEx and a
new calloc field was added.
type PyMemAllocatorDomain
Enum se utiliza para identificar un dominio asignador. Dominios:
PYMEM_DOMAIN_RAW
Funciones:
• PyMem_RawMalloc()
• PyMem_RawRealloc()

246 Capítulo 11. Gestión de la memoria


The Python/C API, Versión 3.12.4

• PyMem_RawCalloc()
• PyMem_RawFree()
PYMEM_DOMAIN_MEM
Funciones:
• PyMem_Malloc(),
• PyMem_Realloc()
• PyMem_Calloc()
• PyMem_Free()
PYMEM_DOMAIN_OBJ
Funciones:
• PyObject_Malloc()
• PyObject_Realloc()
• PyObject_Calloc()
• PyObject_Free()
void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Obtenga el asignador de bloque de memoria del dominio especificado.
void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Establece el asignador de bloque de memoria del dominio especificado.
El nuevo asignador debe retornar un puntero distinto NULL al solicitar cero bytes.
For the PYMEM_DOMAIN_RAW domain, the allocator must be thread-safe: the GIL is not held when the allo-
cator is called.
For the remaining domains, the allocator must also be thread-safe: the allocator may be called in different
interpreters that do not share a GIL.
Si el nuevo asignador no es un enlace (no llama al asignador anterior), se debe llamar a la función
PyMem_SetupDebugHooks() para reinstalar los enlaces de depuración en la parte superior del nuevo
asignador.
Vea también PyPreConfig.allocator y Preinicialización de Python con PyPreConfig.

Advertencia: PyMem_SetAllocator() does have the following contract:


• It can be called after Py_PreInitialize() and before Py_InitializeFromConfig()
to install a custom memory allocator. There are no restrictions over the installed allocator other than
the ones imposed by the domain (for instance, the Raw Domain allows the allocator to be called
without the GIL held). See the section on allocator domains for more information.
• If called after Python has finish initializing (after Py_InitializeFromConfig() has been
called) the allocator must wrap the existing allocator. Substituting the current allocator for some
other arbitrary one is not supported.

Distinto en la versión 3.12: All allocators must be thread-safe.


void PyMem_SetupDebugHooks(void)
Configurar enlaces de depuración en los asignadores de memoria de Python para detectar errores de memoria.

11.7. Personalizar asignadores de memoria 247


The Python/C API, Versión 3.12.4

11.8 Configurar enlaces para detectar errores en las funciones del


asignador de memoria de Python

Cuando Python está construido en modo de depuración, la función PyMem_SetupDebugHooks() se llama en


Preinicialización de Python para configurar los enlaces de depuración en Python asignadores de memoria para detectar
errores de memoria.
La variable de entorno PYTHONMALLOC se puede utilizar para instalar enlaces de depuración en un Python compi-
lado en modo de lanzamiento (por ejemplo: PYTHONMALLOC=debug).
La función PyMem_SetupDebugHooks() se puede utilizar para establecer enlaces de depuración después de
llamar a PyMem_SetAllocator().
Estos enlaces de depuración llenan bloques de memoria asignados dinámicamente con patrones de bits especiales y
reconocibles. La memoria recién asignada se llena con el byte 0xCD (PYMEM_CLEANBYTE), la memoria liberada
se llena con el byte 0xDD (PYMEM_DEADBYTE). Los bloques de memoria están rodeados por «bytes prohibidos»
rellenos con el byte 0xFD (PYMEM_FORBIDDENBYTE). Es poco probable que las cadenas de estos bytes sean
direcciones válidas, flotantes o cadenas ASCII.
Verificaciones de tiempo de ejecución:
• Detecte violaciones de API, por ejemplo: PyObject_Free() llamado en un búfer asignado por
PyMem_Malloc().
• Detectar escritura antes del inicio del búfer (desbordamiento del búfer)
• Detectar escritura después del final del búfer (desbordamiento del búfer)
• Check that the GIL is held when allocator functions of PYMEM_DOMAIN_OBJ (ex: PyObject_Malloc())
and PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) domains are called.
En caso de error, los enlaces de depuración usan el módulo tracemalloc para obtener el rastreo donde se asignó
un bloque de memoria. El rastreo solo se muestra si tracemalloc rastrea las asignaciones de memoria de Python
y se rastrea el bloque de memoria.
Sea S = sizeof(size_t). Se agregan 2*S bytes en cada extremo de cada bloque de N bytes solicitados. El diseño
de la memoria es así, donde p representa la dirección retornada por una función similar a malloc o realloc (p[i:j]
significa el segmento de bytes de *(p+i) inclusive hasta *(p+j) exclusivo; tenga en cuenta que el tratamiento de
los índices negativos difiere de un segmento de Python):
p[-2*S:-S]
Número de bytes solicitados originalmente. Este es un size_t, big-endian (más fácil de leer en un volcado de
memoria).
p[-S]
Identificador de API (carácter ASCII):
• 'r' for PYMEM_DOMAIN_RAW.
• 'm' for PYMEM_DOMAIN_MEM .
• 'o' for PYMEM_DOMAIN_OBJ.
p[-S+1:0]
Copias de PYMEM_FORBIDDENBYTE. Se utiliza para detectar suscripciones y lecturas.
p[0:N]
La memoria solicitada, llena de copias de PYMEM_CLEANBYTE, utilizada para capturar la referencia a la
memoria no inicializada. Cuando se llama a una función similar a realloc solicitando un bloque de memoria
más grande, los nuevos bytes en exceso también se llenan con PYMEM_CLEANBYTE. Cuando se llama a
una función de tipo free, se sobrescriben con PYMEM_DEADBYTE, para captar la referencia a la memoria
liberada. Cuando se llama a una función similar a la realloc solicitando un bloque de memoria más pequeño,
los bytes antiguos sobrantes también se llenan con PYMEM_DEADBYTE.
p[N:N+S]
Copias de PYMEM_FORBIDDENBYTE. Se utiliza para detectar sobrescrituras y lecturas.

248 Capítulo 11. Gestión de la memoria


The Python/C API, Versión 3.12.4

p[N+S:N+2*S]
Solo se utiliza si la macro PYMEM_DEBUG_SERIALNO está definida (no definida por defecto).
A serial number, incremented by 1 on each call to a malloc-like or realloc-like function. Big-endian size_t.
If «bad memory» is detected later, the serial number gives an excellent way to set a breakpoint on the next run,
to capture the instant at which this block was passed out. The static function bumpserialno() in obmalloc.c is
the only place the serial number is incremented, and exists so you can set such a breakpoint easily.
Una función de tipo realloc o de tipo free primero verifica que los bytes PYMEM_FORBIDDENBYTE en cada
extremo estén intactos. Si se han modificado, la salida de diagnóstico se escribe en stderr y el programa se aborta
mediante Py_FatalError(). El otro modo de falla principal es provocar un error de memoria cuando un programa
lee uno de los patrones de bits especiales e intenta usarlo como una dirección. Si ingresa a un depurador y observa
el objeto, es probable que vea que está completamente lleno de PYMEM_DEADBYTE (lo que significa que se está
usando la memoria liberada) o PYMEM_CLEANBYTE (que significa que se está usando la memoria no inicializada).
Distinto en la versión 3.6: The PyMem_SetupDebugHooks() function now also works on Python compiled in
release mode. On error, the debug hooks now use tracemalloc to get the traceback where a memory block
was allocated. The debug hooks now also check if the GIL is held when functions of PYMEM_DOMAIN_OBJ and
PYMEM_DOMAIN_MEM domains are called.
Distinto en la versión 3.8: Los patrones de bytes 0xCB (PYMEM_CLEANBYTE), 0xDB (PYMEM_DEADBYTE) y
0xFB (PYMEM_FORBIDDENBYTE) se han reemplazado por 0xCD, 0xDD y 0xFD para usar los mismos valores
que la depuración de Windows CRT malloc() y free().

11.9 El asignador pymalloc

Python has a pymalloc allocator optimized for small objects (smaller or equal to 512 bytes) with a short lifetime. It
uses memory mappings called «arenas» with a fixed size of either 256 KiB on 32-bit platforms or 1 MiB on 64-bit
platforms. It falls back to PyMem_RawMalloc() and PyMem_RawRealloc() for allocations larger than 512
bytes.
pymalloc is the default allocator of the PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) and
PYMEM_DOMAIN_OBJ (ex: PyObject_Malloc()) domains.
El asignador de arena utiliza las siguientes funciones:
• VirtualAlloc() and VirtualFree() on Windows,
• mmap() and munmap() if available,
• malloc() y free() en caso contrario.
Este asignador está deshabilitado si Python está configurado con la opción --without-pymalloc. También
se puede deshabilitar en tiempo de ejecución usando la variable de entorno PYTHONMALLOC (por ejemplo:
PYTHONMALLOC=malloc).

11.9.1 Personalizar asignador de arena de pymalloc

Added in version 3.4.


type PyObjectArenaAllocator
Estructura utilizada para describir un asignador de arena. La estructura tiene tres campos:

Campo Significado
void *ctx contexto de usuario pasado como primer ar-
gumento
void* alloc(void *ctx, size_t size) asignar una arena de bytes de tamaño
void free(void *ctx, void *ptr, size_t liberar la arena
size)

11.9. El asignador pymalloc 249


The Python/C API, Versión 3.12.4

void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)


Consigue el asignador de arena.
void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
Establecer el asignador de arena.

11.10 tracemalloc C API

Added in version 3.7.


int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size)
Rastree un bloque de memoria asignado en el módulo tracemalloc.
Retorna 0 en caso de éxito, retorna -1 en caso de error (no se pudo asignar memoria para almacenar la traza).
Retorna -2 si tracemalloc está deshabilitado.
Si el bloque de memoria ya está rastreado, actualice el rastreo existente.
int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)
Descomprima un bloque de memoria asignado en el módulo tracemalloc. No haga nada si el bloque no
fue rastreado.
Retorna -2 si tracemalloc está deshabilitado; de lo contrario, retorna 0.

11.11 Ejemplos

Aquí está el ejemplo de la sección Visión general, reescrito para que el búfer de E/S se asigne desde el montón de
Python utilizando el primer conjunto de funciones:

PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */

if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;

El mismo código que utiliza el conjunto de funciones orientado a tipos:

PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */

if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Del(buf); /* allocated with PyMem_New */
return res;

Tenga en cuenta que en los dos ejemplos anteriores, el búfer siempre se manipula a través de funciones que pertenecen
al mismo conjunto. De hecho, es necesario usar la misma familia de API de memoria para un bloque de memoria
dado, de modo que el riesgo de mezclar diferentes asignadores se reduzca al mínimo. La siguiente secuencia de
código contiene dos errores, uno de los cuales está etiquetado como fatal porque mezcla dos asignadores diferentes
que operan en montones diferentes.:

250 Capítulo 11. Gestión de la memoria


The Python/C API, Versión 3.12.4

char *buf1 = PyMem_New(char, BUFSIZ);


char *buf2 = (char *) malloc(BUFSIZ);
char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
...
PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
free(buf2); /* Right -- allocated via malloc() */
free(buf1); /* Fatal -- should be PyMem_Del() */

In addition to the functions aimed at handling raw memory blocks from the Python heap, objects in Python are
allocated and released with PyObject_New, PyObject_NewVar and PyObject_Del().
Esto se explicará en el próximo capítulo sobre cómo definir e implementar nuevos tipos de objetos en C.

11.11. Ejemplos 251


The Python/C API, Versión 3.12.4

252 Capítulo 11. Gestión de la memoria


CAPÍTULO 12

Soporte de implementación de objetos

Este capítulo describe las funciones, los tipos y las macros utilizados al definir nuevos tipos de objetos.

12.1 Asignación de objetos en el montículo

PyObject *_PyObject_New(PyTypeObject *type)


Return value: New reference.
PyVarObject *_PyObject_NewVar(PyTypeObject *type, Py_ssize_t size)
Return value: New reference.
PyObject *PyObject_Init(PyObject *op, PyTypeObject *type)
Return value: Borrowed reference. Part of the Stable ABI. Initialize a newly allocated object op with its type
and initial reference. Returns the initialized object. If type indicates that the object participates in the cyclic
garbage detector, it is added to the detector’s set of observed objects. Other fields of the object are not affected.
PyVarObject *PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size)
Return value: Borrowed reference. Part of the Stable ABI. Esto hace todo lo que PyObject_Init() hace,
y también inicializa la información de longitud para un objeto de tamaño variable.
PyObject_New(TYPE, typeobj)
Allocate a new Python object using the C structure type TYPE and the Python type object typeobj
(PyTypeObject*). Fields not defined by the Python object header are not initialized. The caller will own
the only reference to the object (i.e. its reference count will be one). The size of the memory allocation is
determined from the tp_basicsize field of the type object.
PyObject_NewVar(TYPE, typeobj, size)
Allocate a new Python object using the C structure type TYPE and the Python type object typeobj
(PyTypeObject*). Fields not defined by the Python object header are not initialized. The allocated me-
mory allows for the TYPE structure plus size (Py_ssize_t) fields of the size given by the tp_itemsize
field of typeobj. This is useful for implementing objects like tuples, which are able to determine their size at
construction time. Embedding the array of fields into the same allocation decreases the number of allocations,
improving the memory management efficiency.
void PyObject_Del(void *op)
Releases memory allocated to an object using PyObject_New or PyObject_NewVar. This is normally

253
The Python/C API, Versión 3.12.4

called from the tp_dealloc handler specified in the object’s type. The fields of the object should not be
accessed after this call as the memory is no longer a valid Python object.
PyObject _Py_NoneStruct
Objeto que es visible en Python como None. Esto solo se debe acceder utilizando el macro Py_None, que se
evalúa como un puntero a este objeto.
Ver también:
PyModule_Create()
Para asignar y crear módulos de extensión.

12.2 Estructuras de objetos comunes

Hay un gran número de estructuras que se utilizan en la definición de los tipos de objetos de Python. Esta sección
describe estas estructuras y la forma en que se utilizan.

12.2.1 Tipos objeto base y macros

All Python objects ultimately share a small number of fields at the beginning of the object’s representation in memory.
These are represented by the PyObject and PyVarObject types, which are defined, in turn, by the expansions of
some macros also used, whether directly or indirectly, in the definition of all other Python objects. Additional macros
can be found under reference counting.
type PyObject
Part of the Limited API. (Only some members are part of the stable ABI.) All object types are extensions of this
type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In
a normal «release» build, it contains only the object’s reference count and a pointer to the corresponding type
object. Nothing is actually declared to be a PyObject, but every pointer to a Python object can be cast to a
PyObject*. Access to the members must be done by using the macros Py_REFCNT and Py_TYPE.
type PyVarObject
Part of the Limited API. (Only some members are part of the stable ABI.) This is an extension of PyObject
that adds the ob_size field. This is only used for objects that have some notion of length. This type does not
often appear in the Python/C API. Access to the members must be done by using the macros Py_REFCNT,
Py_TYPE, and Py_SIZE.
PyObject_HEAD
Esta es una macro utilizado cuando se declara nuevos tipos que representan objetos sin una longitud variable.
La macro PyObject_HEAD se expande a:

PyObject ob_base;

Consulte la documentación de PyObject en secciones anteriores.


PyObject_VAR_HEAD
Esta es una macro utilizado cuando se declara nuevos tipos que representan objetos con una longitud que varía
de una instancia a otra instancia. La macro PyObject_VAR_HEAD se expande a:

PyVarObject ob_base;

Consulte la documentación de PyVarObject anteriormente.


int Py_Is(PyObject *x, PyObject *y)
Part of the Stable ABI since version 3.10. Prueba si el objeto x es el objeto y, lo mismo que x is y en Python.
Added in version 3.10.

254 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

int Py_IsNone(PyObject *x)


Part of the Stable ABI since version 3.10. Prueba si un objeto es la instancia única None, lo mismo que x is
None en Python.
Added in version 3.10.
int Py_IsTrue(PyObject *x)
Part of the Stable ABI since version 3.10. Prueba si un objeto es la instancia única True, lo mismo que x is
True en Python.
Added in version 3.10.
int Py_IsFalse(PyObject *x)
Part of the Stable ABI since version 3.10. Prueba si un objeto es la instancia única False, lo mismo que x
is False en Python.
Added in version 3.10.
PyTypeObject *Py_TYPE(PyObject *o)
Obtiene el tipo de objeto Python o.
Retorna una referencia prestada (borrowed reference).
Use the Py_SET_TYPE() function to set an object type.
Distinto en la versión 3.11: Py_TYPE() se cambia a una función estática inline. El tipo de parámetro ya no
es const PyObject*.
int Py_IS_TYPE(PyObject *o, PyTypeObject *type)
Retorna un valor distinto de cero si el objeto o tipo es type. Retorna cero en caso contrario. Equivalente a:
Py_TYPE(o) == type.
Added in version 3.9.
void Py_SET_TYPE(PyObject *o, PyTypeObject *type)
Establece el tipo del objeto o a type.
Added in version 3.9.
Py_ssize_t Py_SIZE(PyVarObject *o)
Obtiene el tamaño del objeto Python o.
Use the Py_SET_SIZE() function to set an object size.
Distinto en la versión 3.11: Py_SIZE() se cambia a una función estática inline. El tipo de parámetro ya no
es const PyVarObject*.
void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size)
Establece el tamaño del objeto o a size.
Added in version 3.9.
PyObject_HEAD_INIT(type)
Esta es una macro que se expande para valores de inicialización para un nuevo tipo PyObject. Esta macro
expande:

_PyObject_EXTRA_INIT
1, type,

PyVarObject_HEAD_INIT(type, size)
This is a macro which expands to initialization values for a new PyVarObject type, including the ob_size
field. This macro expands to:

_PyObject_EXTRA_INIT
1, type, size,

12.2. Estructuras de objetos comunes 255


The Python/C API, Versión 3.12.4

12.2.2 Implementando funciones y métodos

type PyCFunction
Part of the Stable ABI. Type of the functions used to implement most Python callables in C. Functions of this
type take two PyObject* parameters and return one such value. If the return value is NULL, an exception
shall have been set. If not NULL, the return value is interpreted as the return value of the function as exposed
in Python. The function must return a new reference.
La firma de la función es:

PyObject *PyCFunction(PyObject *self,


PyObject *args);

type PyCFunctionWithKeywords
Part of the Stable ABI. Type of the functions used to implement Python callables in C with signature
METH_VARARGS | METH_KEYWORDS. The function signature is:

PyObject *PyCFunctionWithKeywords(PyObject *self,


PyObject *args,
PyObject *kwargs);

type _PyCFunctionFast
Type of the functions used to implement Python callables in C with signature METH_FASTCALL. The function
signature is:

PyObject *_PyCFunctionFast(PyObject *self,


PyObject *const *args,
Py_ssize_t nargs);

type _PyCFunctionFastWithKeywords
Type of the functions used to implement Python callables in C with signature METH_FASTCALL |
METH_KEYWORDS. The function signature is:

PyObject *_PyCFunctionFastWithKeywords(PyObject *self,


PyObject *const *args,
Py_ssize_t nargs,
PyObject *kwnames);

type PyCMethod
Type of the functions used to implement Python callables in C with signature METH_METHOD |
METH_FASTCALL | METH_KEYWORDS. The function signature is:

PyObject *PyCMethod(PyObject *self,


PyTypeObject *defining_class,
PyObject *const *args,
Py_ssize_t nargs,
PyObject *kwnames)

Added in version 3.9.


type PyMethodDef
Part of the Stable ABI (including all members). Estructura utiliza para describir un método de un tipo de
extensión. Esta estructura tiene cuatro campos:
const char *ml_name
Name of the method.
PyCFunction ml_meth
Pointer to the C implementation.

256 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

int ml_flags
Flags bits indicating how the call should be constructed.
const char *ml_doc
Points to the contents of the docstring.
The ml_meth is a C function pointer. The functions may be of different types, but they always return PyObject*.
If the function is not of the PyCFunction, the compiler will require a cast in the method table. Even though
PyCFunction defines the first parameter as PyObject*, it is common that the method implementation uses the
specific C type of the self object.
The ml_flags field is a bitfield which can include the following flags. The individual flags indicate either a calling
convention or a binding convention.
Existen estas convenciones de llamada:
METH_VARARGS
This is the typical calling convention, where the methods have the type PyCFunction. The function expects
two PyObject* values. The first one is the self object for methods; for module functions, it is the module
object. The second parameter (often called args) is a tuple object representing all arguments. This parameter
is typically processed using PyArg_ParseTuple() or PyArg_UnpackTuple().
METH_KEYWORDS
Can only be used in certain combinations with other flags: METH_VARARGS | METH_KEYWORDS,
METH_FASTCALL | METH_KEYWORDS and METH_METHOD | METH_FASTCALL | METH_KEYWORDS.
METH_VARARGS | METH_KEYWORDS
Los métodos con estas flags deben ser del tipo PyCFunctionWithKeywords. La función espera tres
parámetros: self, args, kwargs donde kwargs es un diccionario de todos los argumentos de palabras clave o,
posiblemente, NULL si no hay argumentos de palabra clave. Los parámetros se procesan típicamente usando
PyArg_ParseTupleAndKeywords().
METH_FASTCALL
Fast calling convention supporting only positional arguments. The methods have the type
_PyCFunctionFast. The first parameter is self, the second parameter is a C array of PyObject* values
indicating the arguments and the third parameter is the number of arguments (the length of the array).
Added in version 3.7.
Distinto en la versión 3.10: METH_FASTCALL is now part of the stable ABI.
METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL supporting also keyword arguments, with methods of type
_PyCFunctionFastWithKeywords. Keyword arguments are passed the same way as in the vec-
torcall protocol: there is an additional fourth PyObject* parameter which is a tuple representing the names
of the keyword arguments (which are guaranteed to be strings) or possibly NULL if there are no keywords.
The values of the keyword arguments are stored in the args array, after the positional arguments.
Added in version 3.7.
METH_METHOD
Can only be used in the combination with other flags: METH_METHOD | METH_FASTCALL |
METH_KEYWORDS.
METH_METHOD | METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL | METH_KEYWORDS supporting the defining class, that is, the class that
contains the method in question. The defining class might be a superclass of Py_TYPE(self).
El método debe ser de tipo PyCMethod, lo mismo que para METH_FASTCALL | METH_KEYWORDS con
el argumento defining_clase añadido después de self.
Added in version 3.9.

12.2. Estructuras de objetos comunes 257


The Python/C API, Versión 3.12.4

METH_NOARGS
Methods without parameters don’t need to check whether arguments are given if they are listed with the
METH_NOARGS flag. They need to be of type PyCFunction. The first parameter is typically named self
and will hold a reference to the module or object instance. In all cases the second parameter will be NULL.
La función debe tener 2 parámetros. Dado que el segundo parámetro no se usa, Py_UNUSED se puede usar
para evitar una advertencia del compilador.
METH_O
Methods with a single object argument can be listed with the METH_O flag, instead of invoking
PyArg_ParseTuple() with a "O" argument. They have the type PyCFunction, with the self para-
meter, and a PyObject* parameter representing the single argument.
Estas dos constantes no se utilizan para indicar la convención de llamada si no la vinculación cuando su usan con
métodos de las clases. Estos no se pueden usar para funciones definidas para módulos. A lo sumo uno de estos flags
puede establecerse en un método dado.
METH_CLASS
Al método se le pasará el objeto tipo como primer parámetro, en lugar de una instancia del tipo. Esto se
utiliza para crear métodos de clase (class methods), similar a lo que se crea cuando se utiliza la función
classmethod() incorporada.
METH_STATIC
El método pasará NULL como el primer parámetro en lugar de una instancia del tipo. Esto se utiliza para crear
métodos estáticos (static methods), similar a lo que se crea cuando se utiliza la función staticmethod()
incorporada.
En otros controles constantes dependiendo si se carga un método en su lugar (in place) de otra definición con el mismo
nombre del método.
METH_COEXIST
The method will be loaded in place of existing definitions. Without METH_COEXIST, the default is to skip
repeated definitions. Since slot wrappers are loaded before the method table, the existence of a sq_contains
slot, for example, would generate a wrapped method named __contains__() and preclude the loading of
a corresponding PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in
place of the wrapper object and will co-exist with the slot. This is helpful because calls to PyCFunctions are
optimized more than wrapper object calls.
PyObject *PyCMethod_New(PyMethodDef *ml, PyObject *self, PyObject *module, PyTypeObject *cls)
Return value: New reference. Part of the Stable ABI since version 3.9. Turn ml into a Python callable object.
The caller must ensure that ml outlives the callable. Typically, ml is defined as a static variable.
The self parameter will be passed as the self argument to the C function in ml->ml_meth when invoked.
self can be NULL.
The callable object’s __module__ attribute can be set from the given module argument. module should be a
Python string, which will be used as name of the module the function is defined in. If unavailable, it can be set
to None or NULL.
Ver también:
function.__module__
The cls parameter will be passed as the defining_class argument to the C function. Must be set if
METH_METHOD is set on ml->ml_flags.
Added in version 3.9.
PyObject *PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module)
Return value: New reference. Part of the Stable ABI. Equivalent to PyCMethod_New(ml, self,
module, NULL).
PyObject *PyCFunction_New(PyMethodDef *ml, PyObject *self)
Return value: New reference. Part of the Stable ABI since version 3.4. Equivalent to PyCMethod_New(ml,
self, NULL, NULL).

258 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

12.2.3 Acceder a atributos de tipos de extensión

type PyMemberDef
Part of the Stable ABI (including all members). Structure which describes an attribute of a type which corres-
ponds to a C struct member. When defining a class, put a NULL-terminated array of these structures in the
tp_members slot.
Its fields are, in order:
const char *name
Name of the member. A NULL value marks the end of a PyMemberDef[] array.
The string should be static, no copy is made of it.
int type
The type of the member in the C struct. See Member types for the possible values.
Py_ssize_t offset
The offset in bytes that the member is located on the type’s object struct.
int flags
Zero or more of the Member flags, combined using bitwise OR.
const char *doc
The docstring, or NULL. The string should be static, no copy is made of it. Typically, it is defined using
PyDoc_STR.
By default (when flags is 0), members allow both read and write access. Use the Py_READONLY flag
for read-only access. Certain types, like Py_T_STRING, imply Py_READONLY. Only Py_T_OBJECT_EX
(and legacy T_OBJECT) members can be deleted.
For heap-allocated types (created using PyType_FromSpec() or similar), PyMemberDef may
contain a definition for the special member "__vectorcalloffset__", corresponding to
tp_vectorcall_offset in type objects. These must be defined with Py_T_PYSSIZET and
Py_READONLY, for example:

static PyMemberDef spam_type_members[] = {


{"__vectorcalloffset__", Py_T_PYSSIZET,
offsetof(Spam_object, vectorcall), Py_READONLY},
{NULL} /* Sentinel */
};

(You may need to #include <stddef.h> for offsetof().)


The legacy offsets tp_dictoffset and tp_weaklistoffset can be defined similarly using
"__dictoffset__" and "__weaklistoffset__" members, but extensions are strongly encouraged
to use Py_TPFLAGS_MANAGED_DICT and Py_TPFLAGS_MANAGED_WEAKREF instead.
Distinto en la versión 3.12: PyMemberDef is always available. Previously, it required including
"structmember.h".
PyObject *PyMember_GetOne(const char *obj_addr, struct PyMemberDef *m)
Part of the Stable ABI. Obtiene un atributo que pertenece al objeto en la dirección obj_addr. El atributo se
describe por PyMemberDef m. Retorna NULL en caso de error.
Distinto en la versión 3.12: PyMember_GetOne is always available. Previously, it required including
"structmember.h".
int PyMember_SetOne(char *obj_addr, struct PyMemberDef *m, PyObject *o)
Part of the Stable ABI. Establece un atributo que pertenece al objeto en la dirección obj_addr al objeto o. El
atributo a establecer se describe por PyMemberDef m. Retorna 0 si tiene éxito y un valor negativo si falla.
Distinto en la versión 3.12: PyMember_SetOne is always available. Previously, it required including
"structmember.h".

12.2. Estructuras de objetos comunes 259


The Python/C API, Versión 3.12.4

Member flags

The following flags can be used with PyMemberDef.flags:


Py_READONLY
Not writable.
Py_AUDIT_READ
Emit an object.__getattr__ audit event before reading.
Py_RELATIVE_OFFSET
Indicates that the offset of this PyMemberDef entry indicates an offset from the subclass-specific data,
rather than from PyObject.
Can only be used as part of Py_tp_members slot when creating a class using negative basicsize. It
is mandatory in that case.
This flag is only used in PyType_Slot. When setting tp_members during class creation, Python clears it
and sets PyMemberDef.offset to the offset from the PyObject struct.
Distinto en la versión 3.10: The RESTRICTED, READ_RESTRICTED and WRITE_RESTRICTED macros availa-
ble with #include "structmember.h" are deprecated. READ_RESTRICTED and RESTRICTED are equi-
valent to Py_AUDIT_READ; WRITE_RESTRICTED does nothing.
Distinto en la versión 3.12: The READONLY macro was renamed to Py_READONLY. The PY_AUDIT_READ macro
was renamed with the Py_ prefix. The new names are now always available. Previously, these required #include
"structmember.h". The header is still available and it provides the old names.

Member types

PyMemberDef.type can be one of the following macros corresponding to various C types. When the member is
accessed in Python, it will be converted to the equivalent Python type. When it is set from Python, it will be converted
back to the C type. If that is not possible, an exception such as TypeError or ValueError is raised.
Unless marked (D), attributes defined this way cannot be deleted using e.g. del or delattr().

260 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

Nombre de la macro Tipo C Python type


char int
Py_T_BYTE

short int
Py_T_SHORT

int int
Py_T_INT

long int
Py_T_LONG

long long int


Py_T_LONGLONG

unsigned char int


Py_T_UBYTE

unsigned int int


Py_T_UINT

unsigned short int


Py_T_USHORT

unsigned long int


Py_T_ULONG

unsigned long long int


Py_T_ULONGLONG

Py_ssize_t int
Py_T_PYSSIZET

float float
Py_T_FLOAT

double float
Py_T_DOUBLE

char (written as 0 or 1) bool


Py_T_BOOL

const char* (*) str (RO)


Py_T_STRING

const char[] (*) str (RO)


Py_T_STRING_INPLACE

char (0-127) str (**)


Py_T_CHAR

PyObject* object (D)


Py_T_OBJECT_EX

(*): Zero-terminated, UTF8-encoded C string. With Py_T_STRING the C representation is a pointer;


with Py_T_STRING_INPLACE the string is stored directly in the structure.

12.2. Estructuras de objetos comunes 261


The Python/C API, Versión 3.12.4

(**): String of length 1. Only ASCII is accepted.


(RO): Implies Py_READONLY.
(D): Can be deleted, in which case the pointer is set to NULL. Reading a NULL pointer raises
AttributeError.
Added in version 3.12: In previous versions, the macros were only available with #include "structmember.
h" and were named without the Py_ prefix (e.g. as T_INT). The header is still available and contains the old names,
along with the following deprecated types:
T_OBJECT
Like Py_T_OBJECT_EX, but NULL is converted to None. This results in surprising behavior in Python:
deleting the attribute effectively sets it to None.
T_NONE
Always None. Must be used with Py_READONLY.

Defining Getters and Setters

type PyGetSetDef
Part of the Stable ABI (including all members). Estructura para definir el acceso para un tipo como el de una
propiedad. Véase también la descripción de la ranura PyTypeObject.tp_getset.
const char *name
nombre del atributo
getter get
C function to get the attribute.
setter set
Optional C function to set or delete the attribute. If NULL, the attribute is read-only.
const char *doc
docstring opcional
void *closure
Optional user data pointer, providing additional data for getter and setter.
typedef PyObject *(*getter)(PyObject*, void*)
Part of the Stable ABI. The get function takes one PyObject* parameter (the instance) and a user data
pointer (the associated closure):
Debe retornar una nueva referencia en caso de éxito o NULL con una excepción establecida en caso de error.
typedef int (*setter)(PyObject*, PyObject*, void*)
Part of the Stable ABI. set functions take two PyObject* parameters (the instance and the value to be set)
and a user data pointer (the associated closure):
En caso de que el atributo deba suprimirse el segundo parámetro es NULL. Debe retornar 0 en caso de éxito o
-1 con una excepción explícita en caso de fallo.

262 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

12.3 Objetos tipo

Perhaps one of the most important structures of the Python object system is the structure that defines a new type: the
PyTypeObject structure. Type objects can be handled using any of the PyObject_* or PyType_* functions,
but do not offer much that’s interesting to most Python applications. These objects are fundamental to how objects
behave, so they are very important to the interpreter itself and to any extension module that implements new types.
Los objetos de tipo son bastante grandes en comparación con la mayoría de los tipos estándar. La razón del tamaño
es que cada objeto de tipo almacena una gran cantidad de valores, principalmente punteros de función C, cada uno
de los cuales implementa una pequeña parte de la funcionalidad del tipo. Los campos del objeto tipo se examinan en
detalle en esta sección. Los campos se describirán en el orden en que aparecen en la estructura.
Además de la siguiente referencia rápida, la sección Ejemplos proporciona una visión rápida del significado y uso de
PyTypeObject.

12.3.1 Referencia rápida

«ranuras tp» (tp slots)

Ranura Type métodos/atributos especiales In-


PyTypeObjectPágina 264, 1 for-
ma-
ciónPágina 264, 2
O T D I
<R> tp_name const char * __name__ X X
tp_basicsize Py_ssize_t X X X
tp_itemsize Py_ssize_t X X
tp_dealloc destructor X X X
tp_vectorcall_offset Py_ssize_t X X
(tp_getattr) getattrfunc __getattribute__, __getattr__ G
(tp_setattr) setattrfunc __setattr__, __delattr__ G
tp_as_async PyAsyncMethods * sub-ranuras (sub-slots) %
tp_repr reprfunc __repr__ X X X
tp_as_number PyNumberMethods * sub-ranuras (sub-slots) %
tp_as_sequence PySequenceMethods * sub-ranuras (sub-slots) %
tp_as_mapping PyMappingMethods * sub-ranuras (sub-slots) %
tp_hash hashfunc __hash__ X G
tp_call ternaryfunc __call__ X X
tp_str reprfunc __str__ X X
tp_getattro getattrofunc __getattribute__, __getattr__ X X G
tp_setattro setattrofunc __setattr__, __delattr__ X X G
tp_as_buffer PyBufferProcs * %
tp_flags unsigned long X X ?
tp_doc const char * __doc__ X X
tp_traverse traverseproc X G
tp_clear inquiry X G
tp_richcompare richcmpfunc __lt__, __le__, __eq__, __ne__, X G
__gt__, __ge__
(tp_weaklistoffset) Py_ssize_t X ?
tp_iter getiterfunc __iter__ X
tp_iternext iternextfunc __next__ X
tp_methods PyMethodDef [] X X
tp_members PyMemberDef [] X
tp_getset PyGetSetDef [] X X
tp_base PyTypeObject * __base__ X
continúe en la próxima página

12.3. Objetos tipo 263


The Python/C API, Versión 3.12.4

Tabla 1 – proviene de la página anterior


Ranura Type métodos/atributos especiales In-
PyTypeObjectPágina 264, 1 for-
ma-
ción2
O T D I
tp_dict PyObject * __dict__ ?
tp_descr_get descrgetfunc __get__ X
tp_descr_set descrsetfunc __set__, __delete__ X
(tp_dictoffset) Py_ssize_t X ?
tp_init initproc __init__ X X X
tp_alloc allocfunc X ? ?
tp_new newfunc __new__ X X ? ?
tp_free freefunc X X ? ?
tp_is_gc inquiry X X
<tp_bases> PyObject * __bases__ ~
<tp_mro> PyObject * __mro__ ~
[tp_cache] PyObject *
[tp_subclasses] void * __subclasses__
[tp_weaklist] PyObject *
(tp_del) destructor
[tp_version_tag] unsigned int
tp_finalize destructor __del__ X
tp_vectorcall vectorcallfunc
[tp_watched] unsigned char

sub-ranuras (sub-slots)

Ranuras (Slot) Type métodos especiales


am_await unaryfunc __await__
am_aiter unaryfunc __aiter__
am_anext unaryfunc __anext__
am_send sendfunc

nb_add binaryfunc __add__ __radd__


continúe en la próxima página
1 (): A slot name in parentheses indicates it is (effectively) deprecated.

<>: Names in angle brackets should be initially set to NULL and treated as read-only.
[]: Names in square brackets are for internal use only.
<R> (as a prefix) means the field is required (must be non-NULL).
2 Columnas:

«O»: set on PyBaseObject_Type


«T»: set on PyType_Type
«D»: por defecto (si la ranura está establecida como NULL)

X - PyType_Ready sets this value if it is NULL


~ - PyType_Ready always sets this value (it should be NULL)
? - PyType_Ready may set this value depending on other slots

Also see the inheritance column ("I").


«I»: herencia
X - type slot is inherited via *PyType_Ready* if defined with a *NULL* value
% - the slots of the sub-struct are inherited individually
G - inherited, but only in combination with other slots; see the slot's description
? - it's complicated; see the slot's description
Tenga en cuenta que algunos espacios se heredan efectivamente a través de la cadena de búsqueda de atributos normal.

264 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

Tabla 2 – proviene de la página anterior


Ranuras (Slot) Type métodos especiales
nb_inplace_add binaryfunc __iadd__
nb_subtract binaryfunc __sub__ __rsub__
nb_inplace_subtract binaryfunc __isub__
nb_multiply binaryfunc __mul__ __rmul__
nb_inplace_multiply binaryfunc __imul__
nb_remainder binaryfunc __mod__ __rmod__
nb_inplace_remainder binaryfunc __imod__
nb_divmod binaryfunc __divmod__ __rdiv-
mod__
nb_power ternaryfunc __pow__ __rpow__
nb_inplace_power ternaryfunc __ipow__
nb_negative unaryfunc __neg__
nb_positive unaryfunc __pos__
nb_absolute unaryfunc __abs__
nb_bool inquiry __bool__
nb_invert unaryfunc __invert__
nb_lshift binaryfunc __lshift__ __rlshift__
nb_inplace_lshift binaryfunc __ilshift__
nb_rshift binaryfunc __rshift__ __rrshift__
nb_inplace_rshift binaryfunc __irshift__
nb_and binaryfunc __and__ __rand__
nb_inplace_and binaryfunc __iand__
nb_xor binaryfunc __xor__ __rxor__
nb_inplace_xor binaryfunc __ixor__
nb_or binaryfunc __or__ __ror__
nb_inplace_or binaryfunc __ior__
nb_int unaryfunc __int__
nb_reserved void *
nb_float unaryfunc __float__
nb_floor_divide binaryfunc __floordiv__
nb_inplace_floor_divide binaryfunc __ifloordiv__
nb_true_divide binaryfunc __truediv__
nb_inplace_true_divide binaryfunc __itruediv__
nb_index unaryfunc __index__
nb_matrix_multiply binaryfunc __matmul__ __rmat-
mul__
nb_inplace_matrix_multiply binaryfunc __imatmul__

mp_length lenfunc __len__


mp_subscript binaryfunc __getitem__
mp_ass_subscript objobjargproc __setitem__, __deli-
tem__

sq_length lenfunc __len__


sq_concat binaryfunc __add__
sq_repeat ssizeargfunc __mul__
sq_item ssizeargfunc __getitem__
sq_ass_item ssizeobjargproc __setitem__ __deli-
tem__
sq_contains objobjproc __contains__
sq_inplace_concat binaryfunc __iadd__
sq_inplace_repeat ssizeargfunc __imul__

bf_getbuffer getbufferproc()
continúe en la próxima página

12.3. Objetos tipo 265


The Python/C API, Versión 3.12.4

Tabla 2 – proviene de la página anterior


Ranuras (Slot) Type métodos especiales
bf_releasebuffer releasebufferproc()

266 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

ranura de typedefs

typedef Tipos parámetros Tipo de retorno


allocfunc PyObject *
PyTypeObject *
Py_ssize_t

destructor PyObject * void


freefunc void * void
traverseproc int
PyObject *
visitproc
void *

newfunc PyObject *
PyObject *
PyObject *
PyObject *

initproc int
PyObject *
PyObject *
PyObject *

reprfunc PyObject * PyObject *


getattrfunc PyObject *
PyObject *
const char *

setattrfunc int
PyObject *
const char *
PyObject *

getattrofunc PyObject *
PyObject *
PyObject *

setattrofunc int
PyObject *
PyObject *
PyObject *

descrgetfunc PyObject *
PyObject *
PyObject *
PyObject *

descrsetfunc int
PyObject *
PyObject *
12.3. Objetos tipo 267
PyObject *

hashfunc PyObject * Py_hash_t


The Python/C API, Versión 3.12.4

Vea Tipo Ranura typedefs abajo para más detalles.

12.3.2 Definición de PyTypeObject

La definición de estructura para PyTypeObject se puede encontrar en Include/object.h. Por conveniencia


de referencia, esto repite la definición encontrada allí:

typedef struct _typeobject {


PyObject_VAR_HEAD
const char *tp_name; /* For printing, in format "<module>.<name>" */
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

/* Methods to implement standard operations */

destructor tp_dealloc;
Py_ssize_t tp_vectorcall_offset;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
or tp_reserved (Python 3) */
reprfunc tp_repr;

/* Method suites for standard classes */

PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;

/* More standard operations (here for binary compatibility) */

hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;

/* Functions to access object as input/output buffer */


PyBufferProcs *tp_as_buffer;

/* Flags to define presence of optional/expanded features */


unsigned long tp_flags;

const char *tp_doc; /* Documentation string */

/* Assigned meaning in release 2.0 */


/* call function for all accessible objects */
traverseproc tp_traverse;

/* delete references to contained objects */


inquiry tp_clear;

/* Assigned meaning in release 2.1 */


/* rich comparisons */
richcmpfunc tp_richcompare;

/* weak reference enabler */


Py_ssize_t tp_weaklistoffset;

/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
(continúe en la próxima página)

268 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

(proviene de la página anterior)

/* Attribute descriptor and subclassing stuff */


struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
// Strong reference on a heap type, borrowed reference on a static type
struct _typeobject *tp_base;
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
Py_ssize_t tp_dictoffset;
initproc tp_init;
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; /* Low-level free-memory routine */
inquiry tp_is_gc; /* For PyObject_IS_GC */
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;
destructor tp_del;

/* Type attribute cache version tag. Added in version 2.6 */


unsigned int tp_version_tag;

destructor tp_finalize;
vectorcallfunc tp_vectorcall;

/* bitset of which type-watchers care about this type */


unsigned char tp_watched;
} PyTypeObject;

12.3.3 Ranuras (Slots) PyObject

The type object structure extends the PyVarObject structure. The ob_size field is used for dynamic types (crea-
ted by type_new(), usually called from a class statement). Note that PyType_Type (the metatype) initializes
tp_itemsize, which means that its instances (i.e. type objects) must have the ob_size field.
Py_ssize_t PyObject.ob_refcnt
Part of the Stable ABI. This is the type object’s reference count, initialized to 1 by the
PyObject_HEAD_INIT macro. Note that for statically allocated type objects, the type’s instances
(objects whose ob_type points back to the type) do not count as references. But for dynamically allocated
type objects, the instances do count as references.
Herencia:
Este campo no es heredado por los subtipos.
PyTypeObject *PyObject.ob_type
Part of the Stable ABI. Este es el tipo del tipo, en otras palabras, su metatipo. Se inicializa mediante el ar-
gumento de la macro PyObject_HEAD_INIT, y su valor normalmente debería ser &PyType_Type. Sin
embargo, para los módulos de extensión cargables dinámicamente que deben ser utilizables en Windows (al
menos), el compilador se queja de que este no es un inicializador válido. Por lo tanto, la convención es pasar
NULL al macro PyObject_HEAD_INIT e inicializar este campo explícitamente al comienzo de la función
de inicialización del módulo, antes de hacer cualquier otra cosa. Esto normalmente se hace así:

Foo_Type.ob_type = &PyType_Type;

12.3. Objetos tipo 269


The Python/C API, Versión 3.12.4

This should be done before any instances of the type are created. PyType_Ready() checks if ob_type
is NULL, and if so, initializes it to the ob_type field of the base class. PyType_Ready() will not change
this field if it is non-zero.
Herencia:
Este campo es heredado por subtipos.
PyObject *PyObject._ob_next
PyObject *PyObject._ob_prev
Estos campos solo están presentes cuando se define la macro Py_TRACE_REFS (ver la opción
configure --with-trace-refs).
Their initialization to NULL is taken care of by the PyObject_HEAD_INIT macro. For statically allocated
objects, these fields always remain NULL. For dynamically allocated objects, these two fields are used to link
the object into a doubly linked list of all live objects on the heap.
Esto podría usarse para varios propósitos de depuración; actualmente, los únicos usos son la función sys.
getobjects() y para imprimir los objetos que aún están vivos al final de una ejecución cuando se establece
la variable de entorno PYTHONDUMPREFS.
Herencia:
Estos campos no son heredados por subtipos.

12.3.4 Ranuras PyVarObject

Py_ssize_t PyVarObject.ob_size
Part of the Stable ABI. Para objetos de tipo estáticamente asignados, debe inicializarse a cero. Para objetos de
tipo dinámicamente asignados, este campo tiene un significado interno especial.
Herencia:
Este campo no es heredado por los subtipos.

12.3.5 Ranuras PyTypeObject

Each slot has a section describing inheritance. If PyType_Ready() may set a value when the field is set to
NULL then there will also be a «Default» section. (Note that many fields set on PyBaseObject_Type and
PyType_Type effectively act as defaults.)
const char *PyTypeObject.tp_name
Pointer to a NUL-terminated string containing the name of the type. For types that are accessible as module
globals, the string should be the full module name, followed by a dot, followed by the type name; for built-in
types, it should be just the type name. If the module is a submodule of a package, the full package name is
part of the full module name. For example, a type named T defined in module M in subpackage Q in package
P should have the tp_name initializer "P.Q.M.T".
Para objetos de tipo dinámicamente asignados, éste debe ser sólo el nombre del tipo, y el nombre del módulo
almacenado explícitamente en el dict tipo que el valor de '__module__' clave.
Para objetos de tipo estáticamente asignados, el campo tp_name debe contener un punto. Todo lo que está antes
del último punto se hace accesible como el atributo __module__, y todo lo que está después del último punto
se hace accesible como el atributo __name__.
Si no hay ningún punto, todo el campo tp_name se hace accesible como el atributo __name__, y el atributo
__module__ no está definido (a menos que sea explícitamente establecido en el diccionario, como se explicó
anteriormente). Esto significa que su tipo será imposible de guardar como pickle. Además, no figurará en la
documentación del módulo creado con pydoc.
Este campo no debe ser NULL. Es el único campo obligatorio en PyTypeObject() (que no sea potencial-
mente tp_itemsize).

270 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

Herencia:
Este campo no es heredado por los subtipos.
Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize
Estos campos permiten calcular el tamaño en bytes de instancias del tipo.
Hay dos tipos de tipos: los tipos con instancias de longitud fija tienen un campo cero tp_itemsize, los
tipos con instancias de longitud variable tienen un campo distinto de cero tp_itemsize. Para un tipo con
instancias de longitud fija, todas las instancias tienen el mismo tamaño, dado en tp_basicsize.
For a type with variable-length instances, the instances must have an ob_size field, and the instance size
is tp_basicsize plus N times tp_itemsize, where N is the «length» of the object. The value of N
is typically stored in the instance’s ob_size field. There are exceptions: for example, ints use a negative
ob_size to indicate a negative number, and N is abs(ob_size) there. Also, the presence of an ob_size
field in the instance layout doesn’t mean that the instance structure is variable-length (for example, the structure
for the list type has fixed-length instances, yet those instances have a meaningful ob_size field).
The basic size includes the fields in the instance declared by the macro PyObject_HEAD or
PyObject_VAR_HEAD (whichever is used to declare the instance struct) and this in turn includes the
_ob_prev and _ob_next fields if they are present. This means that the only correct way to get an initializer
for the tp_basicsize is to use the sizeof operator on the struct used to declare the instance layout. The
basic size does not include the GC header size.
Una nota sobre la alineación: si los elementos variables requieren una alineación particular, esto debe
ser atendido por el valor de tp_basicsize. Ejemplo: supongamos que un tipo implementa un arreglo
de dobles (double). tp_itemsize es sizeof(double). Es responsabilidad del programador que
tp_basicsize es un múltiplo de sizeof(double) (suponiendo que este sea el requisito de alineación
para double).
Para cualquier tipo con instancias de longitud variable, este campo no debe ser NULL.
Herencia:
Estos campos se heredan por separado por subtipos. Si el tipo base tiene un miembro distinto de cero
tp_itemsize, generalmente no es seguro establecer tp_itemsize en un valor diferente de cero en un
subtipo ( aunque esto depende de la implementación del tipo base).
destructor PyTypeObject.tp_dealloc
Un puntero a la función destructor de instancias. Esta función debe definirse a menos que el tipo garantice que
sus instancias nunca se desasignarán (como es el caso de los singletons None y Ellipsis). La firma de la
función es:

void tp_dealloc(PyObject *self);

The destructor function is called by the Py_DECREF() and Py_XDECREF() macros when the new referen-
ce count is zero. At this point, the instance is still in existence, but there are no references to it. The destructor
function should free all references which the instance owns, free all memory buffers owned by the instance
(using the freeing function corresponding to the allocation function used to allocate the buffer), and call the
type’s tp_free function. If the type is not subtypable (doesn’t have the Py_TPFLAGS_BASETYPE flag
bit set), it is permissible to call the object deallocator directly instead of via tp_free. The object dealloca-
tor should be the one used to allocate the instance; this is normally PyObject_Del() if the instance was
allocated using PyObject_New or PyObject_NewVar, or PyObject_GC_Del() if the instance was
allocated using PyObject_GC_New or PyObject_GC_NewVar.
If the type supports garbage collection (has the Py_TPFLAGS_HAVE_GC flag bit set), the destructor should
call PyObject_GC_UnTrack() before clearing any member fields.

static void foo_dealloc(foo_object *self) {


PyObject_GC_UnTrack(self);
Py_CLEAR(self->ref);
(continúe en la próxima página)

12.3. Objetos tipo 271


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


Py_TYPE(self)->tp_free((PyObject *)self);
}

Finally, if the type is heap allocated (Py_TPFLAGS_HEAPTYPE), the deallocator should release the owned
reference to its type object (via Py_DECREF()) after calling the type deallocator. In order to avoid dangling
pointers, the recommended way to achieve this is:

static void foo_dealloc(foo_object *self) {


PyTypeObject *tp = Py_TYPE(self);
// free references and buffers here
tp->tp_free(self);
Py_DECREF(tp);
}

Herencia:
Este campo es heredado por subtipos.
Py_ssize_t PyTypeObject.tp_vectorcall_offset
Un desplazamiento opcional a una función por instancia que implementa la llamada al objeto usando vectorcall
protocol, una alternativa más eficiente del simple tp_call.
This field is only used if the flag Py_TPFLAGS_HAVE_VECTORCALL is set. If so, this must be a positive
integer containing the offset in the instance of a vectorcallfunc pointer.
The vectorcallfunc pointer may be NULL, in which case the instance behaves as if
Py_TPFLAGS_HAVE_VECTORCALL was not set: calling the instance falls back to tp_call.
Cualquier clase que establezca _Py_TPFLAGS_HAVE_VECTORCALL también debe establecer tp_call
y asegurarse de que su comportamiento sea coherente con la función vectorcallfunc. Esto se puede hacer con-
figurando tp_call en PyVectorcall_Call().
Distinto en la versión 3.8: Antes de la versión 3.8, este slot se llamaba tp_print. En Python 2.x, se usó para
imprimir en un archivo. En Python 3.0 a 3.7, no se usó.
Distinto en la versión 3.12: Before version 3.12, it was not recommended for mutable heap types to implement
the vectorcall protocol. When a user sets __call__ in Python code, only tp_call is updated, likely making
it inconsistent with the vectorcall function. Since 3.12, setting __call__ will disable vectorcall optimization
by clearing the Py_TPFLAGS_HAVE_VECTORCALL flag.
Herencia:
This field is always inherited. However, the Py_TPFLAGS_HAVE_VECTORCALL flag is not always inherited.
If it’s not set, then the subclass won’t use vectorcall, except when PyVectorcall_Call() is explicitly
called.
getattrfunc PyTypeObject.tp_getattr
Un puntero opcional a la función «obtener atributo cadena de caracteres» (get-attribute-string).
Este campo está en desuso. Cuando se define, debe apuntar a una función que actúe igual que la función
tp_getattro, pero tomando una cadena de caracteres C en lugar de un objeto de cadena Python para dar
el nombre del atributo.
Herencia:
Group: tp_getattr, tp_getattro
Este campo es heredado por los subtipos junto con tp_getattro: un subtipo hereda ambos tp_getattr
y tp_getattro de su base escriba cuando los subtipos tp_getattr y tp_getattro son ambos NULL.
setattrfunc PyTypeObject.tp_setattr
Un puntero opcional a la función para configurar y eliminar atributos.

272 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

Este campo está en desuso. Cuando se define, debe apuntar a una función que actúe igual que la función
tp_setattro, pero tomando una cadena de caracteres C en lugar de un objeto de cadena Python para dar
el nombre del atributo.
Herencia:
Group: tp_setattr, tp_setattro
Este campo es heredado por los subtipos junto con tp_setattro: un subtipo hereda ambos tp_setattr
y tp_setattro de su base escriba cuando los subtipos tp_setattr y tp_setattro son ambos NULL.
PyAsyncMethods *PyTypeObject.tp_as_async
Puntero a una estructura adicional que contiene campos relevantes solo para los objetos que implementan los
protocolos «esperable» (awaitable) y «iterador asíncrono» (asynchronous iterator) en el nivel C. Ver Estructuras
de objetos asíncronos para más detalles.
Added in version 3.5: Anteriormente conocidos como tp_compare y tp_reserved.
Herencia:
El campo tp_as_async no se hereda, pero los campos contenidos se heredan individualmente.
reprfunc PyTypeObject.tp_repr
Un puntero opcional a una función que implementa la función incorporada repr().
La firma es la misma que para PyObject_Repr():

PyObject *tp_repr(PyObject *self);

La función debe retornar una cadena de caracteres o un objeto Unicode. Idealmente, esta función debería
retornar una cadena que, cuando se pasa a eval(), dado un entorno adecuado, retorna un objeto con el
mismo valor. Si esto no es factible, debe retornar una cadena que comience con '<' y termine con '>' desde
la cual se puede deducir tanto el tipo como el valor del objeto.
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Cuando este campo no está configurado, se retorna una cadena de caracteres de la forma <%s object at
%p>, donde %s se reemplaza por el nombre del tipo y %p por dirección de memoria del objeto.
PyNumberMethods *PyTypeObject.tp_as_number
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el pro-
tocolo numérico. Estos campos están documentados en Estructuras de objetos de números.
Herencia:
El campo tp_as_number no se hereda, pero los campos contenidos se heredan individualmente.
PySequenceMethods *PyTypeObject.tp_as_sequence
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el pro-
tocolo de secuencia. Estos campos están documentados en estructuras de secuencia.
Herencia:
El campo tp_as_sequence no se hereda, pero los campos contenidos se heredan individualmente.
PyMappingMethods *PyTypeObject.tp_as_mapping
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el pro-
tocolo de mapeo. Estos campos están documentados en Estructuras de objetos mapeo.
Herencia:
El campo tp_as_mapping no se hereda, pero los campos contenidos se heredan individualmente.

12.3. Objetos tipo 273


The Python/C API, Versión 3.12.4

hashfunc PyTypeObject.tp_hash
Un puntero opcional a una función que implementa la función incorporada hash().
La firma es la misma que para PyObject_Hash():

Py_hash_t tp_hash(PyObject *);

El valor -1 no debe retornarse como un valor de retorno normal; Cuando se produce un error durante el cálculo
del valor hash, la función debe establecer una excepción y retornar -1.
When this field is not set (and tp_richcompare is not set), an attempt to take the hash of the object raises
TypeError. This is the same as setting it to PyObject_HashNotImplemented().
Este campo se puede establecer explícitamente en PyObject_HashNotImplemented() para bloquear
la herencia del método hash de un tipo primario. Esto se interpreta como el equivalente de __hash__ =
None en el nivel de Python, lo que hace que isinstance(o, collections.Hashable) retor-
ne correctamente False. Tenga en cuenta que lo contrario también es cierto: establecer __hash__ =
None en una clase en el nivel de Python dará como resultado que la ranura tp_hash se establezca en
PyObject_HashNotImplemented().
Herencia:
Group: tp_hash, tp_richcompare
Este campo es heredado por subtipos junto con tp_richcompare: un subtipo hereda ambos
tp_richcompare y tp_hash, cuando los subtipos tp_richcompare y tp_hash son ambos NULL.
ternaryfunc PyTypeObject.tp_call
Un puntero opcional a una función que implementa la llamada al objeto. Esto debería ser NULL si el objeto no
es invocable. La firma es la misma que para PyObject_Call():

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

Herencia:
Este campo es heredado por subtipos.
reprfunc PyTypeObject.tp_str
Un puntero opcional a una función que implementa la operación integrada str(). (Tenga en cuenta que str
es un tipo ahora, y str() llama al constructor para ese tipo. Este constructor llama a PyObject_Str()
para hacer el trabajo real, y PyObject_Str() llamará a este controlador.)
La firma es la misma que para PyObject_Str():

PyObject *tp_str(PyObject *self);

La función debe retornar una cadena de caracteres o un objeto Unicode. Debe ser una representación de cadena
«amigable» del objeto, ya que esta es la representación que será utilizada, entre otras cosas, por la función
print().
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Cuando este campo no está configurado, se llama a PyObject_Repr() para retornar una representación
de cadena de caracteres.
getattrofunc PyTypeObject.tp_getattro
Un puntero opcional a la función «obtener atributo» (get-attribute).
La firma es la misma que para PyObject_GetAttr():

PyObject *tp_getattro(PyObject *self, PyObject *attr);

274 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

Por lo general, es conveniente establecer este campo en PyObject_GenericGetAttr(), que implementa


la forma normal de buscar atributos de objeto.
Herencia:
Group: tp_getattr, tp_getattro
Este campo es heredado por los subtipos junto con tp_getattr: un subtipo hereda ambos tp_getattr y
tp_getattro de su base escriba cuando los subtipos tp_getattr y tp_getattro son ambos NULL.
Por defecto:
PyBaseObject_Type uses PyObject_GenericGetAttr().
setattrofunc PyTypeObject.tp_setattro
Un puntero opcional a la función para configurar y eliminar atributos.
La firma es la misma que para PyObject_SetAttr():

int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);

Además, se debe admitir la configuración de value en NULL para eliminar un atributo. Por lo general, es
conveniente establecer este campo en PyObject_GenericSetAttr(), que implementa la forma normal
de establecer los atributos del objeto.
Herencia:
Group: tp_setattr, tp_setattro
Los subtipos heredan este campo junto con tp_setattr: un subtipo hereda ambos tp_setattr y
tp_setattro de su base escriba cuando los subtipos tp_setattr y tp_setattro son ambos NULL.
Por defecto:
PyBaseObject_Type uses PyObject_GenericSetAttr().
PyBufferProcs *PyTypeObject.tp_as_buffer
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan la interfaz
del búfer. Estos campos están documentados en Estructuras de objetos búfer.
Herencia:
El campo tp_as_buffer no se hereda, pero los campos contenidos se heredan individualmente.
unsigned long PyTypeObject.tp_flags
Este campo es una máscara de bits de varias banderas. Algunas banderas indican semántica variante para ciertas
situaciones; otros se utilizan para indicar que ciertos campos en el tipo de objeto (o en las estructuras de ex-
tensión a las que se hace referencia a través de tp_as_number, tp_as_sequence, tp_as_mapping,
y tp_as_buffer) que históricamente no siempre estuvieron presentes son válidos; si dicho bit de bandera
está claro, no se debe acceder a los campos de tipo que protege y se debe considerar que tienen un valor cero
o NULL.
Herencia:
Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag
bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if
the extension structure is inherited, i.e. the base type’s value of the flag bit is copied into the subtype together
with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the
tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype
and the tp_traverse and tp_clear fields in the subtype exist and have NULL values. .. XXX are most
flag bits really inherited individually?
Por defecto:
PyBaseObject_Type uses Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE.
Máscaras de bits:

12.3. Objetos tipo 275


The Python/C API, Versión 3.12.4

Las siguientes máscaras de bits están definidas actualmente; estos se pueden unidos por OR usando el operador
| para formar el valor del campo tp_flags. El macro PyType_HasFeature() toma un tipo y un valor
de banderas, tp y f, y comprueba si tp->tp_flags & f no es cero.
Py_TPFLAGS_HEAPTYPE
This bit is set when the type object itself is allocated on the heap, for example, types created dynamically
using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference
to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when
an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the
instance’s ob_type gets INCREF’ed or DECREF’ed). Heap types should also support garbage collection
as they can form a reference cycle with their own module object.
Herencia:
???
Py_TPFLAGS_BASETYPE
Este bit se establece cuando el tipo se puede usar como el tipo base de otro tipo. Si este bit es claro, el
tipo no puede subtiparse (similar a una clase «final» en Java).
Herencia:
???
Py_TPFLAGS_READY
Este bit se establece cuando el objeto tipo ha sido completamente inicializado por PyType_Ready().
Herencia:
???
Py_TPFLAGS_READYING
Este bit se establece mientras PyType_Ready() está en el proceso de inicialización del objeto tipo.
Herencia:
???
Py_TPFLAGS_HAVE_GC
This bit is set when the object supports garbage collection. If this bit is set, instances must be created
using PyObject_GC_New and destroyed using PyObject_GC_Del(). More information in section
Apoyo a la recolección de basura cíclica. This bit also implies that the GC-related fields tp_traverse
and tp_clear are present in the type object.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear
fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and
tp_clear fields in the subtype exist and have NULL values.
Py_TPFLAGS_DEFAULT
This is a bitmask of all the bits that pertain to the existence of certain fields in
the type object and its extension structures. Currently, it includes the following bits:
Py_TPFLAGS_HAVE_STACKLESS_EXTENSION.
Herencia:
???
Py_TPFLAGS_METHOD_DESCRIPTOR
Este bit indica que los objetos se comportan como métodos independientes.
Si este indicador está configurado para type(meth), entonces:
• meth.__get__(obj, cls)(*args, **kwds) (con obj no None) debe ser equivalente
a meth(obj, *args, **kwds).

276 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

• meth.__get__(None, cls)(*args, **kwds) debe ser equivalente a meth(*args,


**kwds).
Este indicador (flag) permite una optimización para llamadas a métodos típicos como obj.meth():
evita crear un objeto temporal de «método vinculado» para obj.meth.
Added in version 3.8.
Herencia:
This flag is never inherited by types without the Py_TPFLAGS_IMMUTABLETYPE flag set. For exten-
sion types, it is inherited whenever tp_descr_get is inherited.
Py_TPFLAGS_MANAGED_DICT
This bit indicates that instances of the class have a __dict__ attribute, and that the space for the
dictionary is managed by the VM.
If this flag is set, Py_TPFLAGS_HAVE_GC should also be set.
Added in version 3.12.
Herencia:
This flag is inherited unless the tp_dictoffset field is set in a superclass.
Py_TPFLAGS_MANAGED_WEAKREF
This bit indicates that instances of the class should be weakly referenceable.
Added in version 3.12.
Herencia:
This flag is inherited unless the tp_weaklistoffset field is set in a superclass.
Py_TPFLAGS_ITEMS_AT_END
Only usable with variable-size types, i.e. ones with non-zero tp_itemsize.
Indicates that the variable-sized portion of an instance of this type is at the end of the instance’s memory
area, at an offset of Py_TYPE(obj)->tp_basicsize (which may be different in each subclass).
When setting this flag, be sure that all superclasses either use this memory layout, or are not variable-sized.
Python does not check this.
Added in version 3.12.
Herencia:
This flag is inherited.
Py_TPFLAGS_LONG_SUBCLASS

Py_TPFLAGS_LIST_SUBCLASS

Py_TPFLAGS_TUPLE_SUBCLASS

Py_TPFLAGS_BYTES_SUBCLASS

Py_TPFLAGS_UNICODE_SUBCLASS

Py_TPFLAGS_DICT_SUBCLASS

Py_TPFLAGS_BASE_EXC_SUBCLASS

Py_TPFLAGS_TYPE_SUBCLASS
Estas marcas son utilizadas por funciones como PyLong_Check() para determinar rápidamente si un
tipo es una subclase de un tipo incorporado; dichos controles específicos son más rápidos que un control
genérico, como PyObject_IsInstance(). Los tipos personalizados que heredan de los elementos
integrados deben tener su tp_flags configurado correctamente, o el código que interactúa con dichos
tipos se comportará de manera diferente dependiendo del tipo de verificación que se use.

12.3. Objetos tipo 277


The Python/C API, Versión 3.12.4

Py_TPFLAGS_HAVE_FINALIZE
Este bit se establece cuando la ranura tp_finalize está presente en la estructura de tipo.
Added in version 3.4.
Obsoleto desde la versión 3.8: Este indicador ya no es necesario, ya que el intérprete asume que: el espacio
tp_finalize siempre está presente en la estructura de tipos.
Py_TPFLAGS_HAVE_VECTORCALL
Este bit se establece cuando la clase implementa protocolo vectorcall. Consulte
tp_vectorcall_offset para obtener más detalles.
Herencia:
This bit is inherited if tp_call is also inherited.
Added in version 3.9.
Distinto en la versión 3.12: This flag is now removed from a class when the class’s __call__() method
is reassigned.
This flag can now be inherited by mutable classes.
Py_TPFLAGS_IMMUTABLETYPE
Este bit se establece para objetos de tipo que son inmutables: los atributos de tipo no se pueden establecer
ni eliminar.
PyType_Ready() aplica automáticamente este indicador a static types.
Herencia:
Este flag no se hereda.
Added in version 3.10.
Py_TPFLAGS_DISALLOW_INSTANTIATION
No permita la creación de instancias del tipo: establezca tp_new en NULL y no cree la clave __new__
en el diccionario de tipos.
La bandera debe establecerse antes de crear el tipo, no después. Por ejemplo, debe establecerse antes de
que se llame a PyType_Ready() en el tipo.
La bandera se establece automáticamente en static types si tp_base es NULL o
&PyBaseObject_Type y tp_new es NULL.
Herencia:
This flag is not inherited. However, subclasses will not be instantiable unless they provide a non-NULL
tp_new (which is only possible via the C API).

Nota: To disallow instantiating a class directly but allow instantiating its subclasses (e.g. for an abstract
base class), do not use this flag. Instead, make tp_new only succeed for subclasses.

Added in version 3.10.


Py_TPFLAGS_MAPPING
Este bit indica que las instancias de la clase pueden coincidir con los patrones de correspondencia cuando
se utilizan como sujeto de un bloque match. Se configura automáticamente al registrar o subclasificar
collections.abc.Mapping, y se desarma al registrar collections.abc.Sequence.

Nota: Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error


to enable both flags simultaneously.

Herencia:

278 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.


Ver también:
PEP 634 - Coincidencia de patrones estructurales: especificación
Added in version 3.10.
Py_TPFLAGS_SEQUENCE
Este bit indica que las instancias de la clase pueden coincidir con los patrones de secuencia cuando se
utilizan como sujeto de un bloque match. Se configura automáticamente al registrar o subclasificar
collections.abc.Sequence, y se desarma al registrar collections.abc.Mapping.

Nota: Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error


to enable both flags simultaneously.

Herencia:
This flag is inherited by types that do not already set Py_TPFLAGS_MAPPING.
Ver también:
PEP 634 - Coincidencia de patrones estructurales: especificación
Added in version 3.10.
Py_TPFLAGS_VALID_VERSION_TAG
Internal. Do not set or unset this flag. To indicate that a class has changed call PyType_Modified()

Advertencia: This flag is present in header files, but is an internal feature and should not be used. It
will be removed in a future version of CPython

const char *PyTypeObject.tp_doc


Un puntero opcional a una cadena de caracteres de C terminada en NULL que proporciona la cadena de docu-
mentación para este tipo de objeto. Esto se expone como el atributo __doc__ en el tipo y las instancias del
tipo.
Herencia:
Este campo es no heredado por los subtipos.
traverseproc PyTypeObject.tp_traverse
An optional pointer to a traversal function for the garbage collector. This is only used if the
Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:

int tp_traverse(PyObject *self, visitproc visit, void *arg);

Se puede encontrar más información sobre el esquema de recolección de basura de Python en la sección Apoyo
a la recolección de basura cíclica.
The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical imple-
mentation of a tp_traverse function simply calls Py_VISIT() on each of the instance’s members that
are Python objects that the instance owns. For example, this is function local_traverse() from the
_thread extension module:

static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
Py_VISIT(self->args);
Py_VISIT(self->kw);
Py_VISIT(self->dict);
(continúe en la próxima página)

12.3. Objetos tipo 279


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


return 0;
}

Tenga en cuenta que Py_VISIT() solo se llama a aquellos miembros que pueden participar en los ciclos de
referencia. Aunque también hay un miembro self->key, solo puede ser NULL o una cadena de caracteres
de Python y, por lo tanto, no puede ser parte de un ciclo de referencia.
Por otro lado, incluso si sabe que un miembro nunca puede ser parte de un ciclo, como ayuda para la depuración
puede visitarlo de todos modos solo para que la función get_referents() del módulo gc lo incluirá.

Advertencia: Al implementar tp_traverse, solo se deben visitar los miembros que tienen la instancia
owns (por tener referencias fuertes). Por ejemplo, si un objeto admite referencias débiles a través de la ranura
tp_weaklist, el puntero que respalda la lista vinculada (a lo que apunta tp_weaklist) no debe visitarse
ya que la instancia no posee directamente las referencias débiles a sí misma (la lista de referencias débiles
está ahí para respaldar la maquinaria de referencia débil, pero la instancia no tiene una fuerte referencia a
los elementos dentro de ella, ya que pueden eliminarse incluso si la instancia todavía está viva).

Tenga en cuenta que Py_VISIT() requiere los parámetros visit y arg para local_traverse() para
tener estos nombres específicos; no les llames de ninguna manera.
Las instancias de heap-allocated types contienen una referencia a su tipo. Por lo tanto, su función transver-
sal debe visitar Py_TYPE(self) o delegar esta responsabilidad llamando a tp_traverse de otro tipo
asignado al heap (como una superclase asignada al heap). Si no es así, es posible que el objeto de tipo no se
recolecte como basura.
Distinto en la versión 3.9: Se espera que los tipos asignados al heap visiten Py_TYPE(self) en
tp_traverse. En versiones anteriores de Python, debido al bug 40217, hacer esto puede provocar fallas en
las subclases.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the
flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.
inquiry PyTypeObject.tp_clear
An optional pointer to a clear function for the garbage collector. This is only used if the
Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:
int tp_clear(PyObject *);

La función miembro tp_clear se usa para romper los ciclos de referencia en la basura cíclica detectada
por el recolector de basura. En conjunto, todas las funciones tp_clear en el sistema deben combinarse para
romper todos los ciclos de referencia. Esto es sutil y, en caso de duda, proporcione una función tp_clear.
Por ejemplo, el tipo de tupla no implementa una función tp_clear, porque es posible demostrar que ningún
ciclo de referencia puede estar compuesto completamente de tuplas. Por lo tanto, las funciones tp_clear de
otros tipos deben ser suficientes para romper cualquier ciclo que contenga una tupla. Esto no es inmediatamente
obvio, y rara vez hay una buena razón para evitar la implementación de tp_clear.
Las implementaciones de tp_clear deberían descartar las referencias de la instancia a las de sus miembros
que pueden ser objetos de Python, y establecer sus punteros a esos miembros en NULL, como en el siguiente
ejemplo:
static int
local_clear(localobject *self)
{
Py_CLEAR(self->key);
Py_CLEAR(self->args);
Py_CLEAR(self->kw);
(continúe en la próxima página)

280 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


Py_CLEAR(self->dict);
return 0;
}

The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the contained
object must not be released (via Py_DECREF()) until after the pointer to the contained object is set to NULL.
This is because releasing the reference may cause the contained object to become trash, triggering a chain of
reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks,
associated with the contained object). If it’s possible for such code to reference self again, it’s important that
the pointer to the contained object be NULL at that time, so that self knows the contained object can no longer
be used. The Py_CLEAR() macro performs the operations in a safe order.
Tenga en cuenta que tp_clear no se llama siempre antes de que se desasigne una instancia. Por ejemplo,
cuando el recuento de referencias es suficiente para determinar que un objeto ya no se utiliza, el recolector de
basura cíclico no está involucrado y se llama directamente a tp_dealloc.
Debido a que el objetivo de tp_clear es romper los ciclos de referencia, no es necesario borrar objetos
contenidos como cadenas de caracteres de Python o enteros de Python, que no pueden participar en los ciclos
de referencia. Por otro lado, puede ser conveniente borrar todos los objetos Python contenidos y escribir la
función tp_dealloc para invocar tp_clear.
Se puede encontrar más información sobre el esquema de recolección de basura de Python en la sección Apoyo
a la recolección de basura cíclica.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit:
the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the
subtype.
richcmpfunc PyTypeObject.tp_richcompare
Un puntero opcional a la función de comparación enriquecida, cuya firma es:

PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);

Se garantiza que el primer parámetro será una instancia del tipo definido por PyTypeObject.
La función debería retornar el resultado de la comparación (generalmente Py_True o Py_False). Si la
comparación no está definida, debe retornar Py_NotImplemented, si se produce otro error, debe retornar
NULL y establecer una condición de excepción.
Las siguientes constantes se definen para ser utilizadas como el tercer argumento para tp_richcompare y
para PyObject_RichCompare():

12.3. Objetos tipo 281


The Python/C API, Versión 3.12.4

Constante Comparación
<
Py_LT

<=
Py_LE

==
Py_EQ

!=
Py_NE

>
Py_GT

>=
Py_GE

El siguiente macro está definido para facilitar la escritura de funciones de comparación enriquecidas:
Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)
Retorna Py_True o Py_False de la función, según el resultado de una comparación. VAL_A y
VAL_B deben ser ordenados por operadores de comparación C (por ejemplo, pueden ser enteros
o punto flotantes de C). El tercer argumento especifica la operación solicitada, como por ejemplo
PyObject_RichCompare().
The returned value is a new strong reference.
En caso de error, establece una excepción y retorna NULL de la función.
Added in version 3.7.
Herencia:
Group: tp_hash, tp_richcompare
Este campo es heredado por subtipos junto con tp_hash: un subtipo hereda tp_richcompare y
tp_hash cuando el subtipo tp_richcompare y tp_hash son ambos NULL.
Por defecto:
PyBaseObject_Type provides a tp_richcompare implementation, which may be inherited. However,
if only tp_hash is defined, not even the inherited function is used and instances of the type will not be able
to participate in any comparisons.
Py_ssize_t PyTypeObject.tp_weaklistoffset
While this field is still supported, Py_TPFLAGS_MANAGED_WEAKREF should be used instead, if at all pos-
sible.
If the instances of this type are weakly referenceable, this field is greater than zero and contains the offset in
the instance structure of the weak reference list head (ignoring the GC header, if present); this offset is used
by PyObject_ClearWeakRefs() and the PyWeakref_* functions. The instance structure needs to
include a field of type PyObject* which is initialized to NULL.
No confunda este campo con tp_weaklist; ese es el encabezado de la lista para referencias débiles al objeto
de tipo en sí.
It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_weaklist.
Herencia:

282 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

Este campo es heredado por subtipos, pero consulte las reglas que se enumeran a continuación. Un subtipo
puede anular este desplazamiento; Esto significa que el subtipo utiliza un encabezado de lista de referen-
cia débil diferente que el tipo base. Dado que el encabezado de la lista siempre se encuentra a través de
tp_weaklistoffset, esto no debería ser un problema.
Por defecto:
If the Py_TPFLAGS_MANAGED_WEAKREF bit is set in the tp_dict field, then tp_weaklistoffset
will be set to a negative value, to indicate that it is unsafe to use this field.
getiterfunc PyTypeObject.tp_iter
An optional pointer to a function that returns an iterator for the object. Its presence normally signals that the
instances of this type are iterable (although sequences may be iterable without this function).
Esta función tiene la misma firma que PyObject_GetIter():
PyObject *tp_iter(PyObject *self);

Herencia:
Este campo es heredado por subtipos.
iternextfunc PyTypeObject.tp_iternext
An optional pointer to a function that returns the next item in an iterator. The signature is:
PyObject *tp_iternext(PyObject *self);

Cuando el iterador está agotado, debe retornar NULL; a la excepción StopIteration puede o no estable-
cerse. Cuando se produce otro error, también debe retornar NULL. Su presencia indica que las instancias de
este tipo son iteradores.
Los tipos de iterador también deberían definir la función tp_iter, y esa función debería retornar la instancia
de iterador en sí (no una nueva instancia de iterador).
Esta función tiene la misma firma que PyIter_Next().
Herencia:
Este campo es heredado por subtipos.
struct PyMethodDef *PyTypeObject.tp_methods
Un puntero opcional a un arreglo estático terminado en NULL de estructuras PyMethodDef, declarando
métodos regulares de este tipo.
Para cada entrada en el arreglo, se agrega una entrada al diccionario del tipo (ver tp_dict a continuación)
que contiene un descriptor method.
Herencia:
Los subtipos no heredan este campo (los métodos se heredan mediante un mecanismo diferente).
struct PyMemberDef *PyTypeObject.tp_members
Un puntero opcional a un arreglo estático terminado en NULL de estructuras PyMemberDef, declarando
miembros de datos regulares (campos o ranuras) de instancias de este tipo.
Para cada entrada en el arreglo, se agrega una entrada al diccionario del tipo (ver tp_dict a continuación)
que contiene un descriptor member.
Herencia:
Los subtipos no heredan este campo (los miembros se heredan mediante un mecanismo diferente).
struct PyGetSetDef *PyTypeObject.tp_getset
Un puntero opcional a un arreglo estático terminado en NULL de estructuras PyGetSetDef, declarando
atributos calculados de instancias de este tipo.
Para cada entrada en el arreglo, se agrega una entrada al diccionario del tipo (ver tp_dict a continuación)
que contiene un descriptor getset.

12.3. Objetos tipo 283


The Python/C API, Versión 3.12.4

Herencia:
Este campo no es heredado por los subtipos (los atributos computados se heredan a través de un mecanismo
diferente).
PyTypeObject *PyTypeObject.tp_base
Un puntero opcional a un tipo base del que se heredan las propiedades de tipo. En este nivel, solo se admite
una herencia única; La herencia múltiple requiere la creación dinámica de un objeto tipo llamando al metatipo.

Nota: La inicialización de ranuras está sujeta a las reglas de inicialización de globales. C99 re-
quiere que los inicializadores sean «constantes de dirección». Los designadores de funciones como
PyType_GenericNew(), con conversión implícita a un puntero, son constantes de dirección C99 váli-
das.
However, the unary “&” operator applied to a non-static variable like PyBaseObject_Type is not required
to produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers are
strictly standard conforming in this particular behavior.
En consecuencia, tp_base debe establecerse en la función init del módulo de extensión.

Herencia:
Este campo no es heredado por los subtipos (obviamente).
Por defecto:
Este campo predeterminado es &PyBaseObject_Type (que para los programadores de Python se conoce
como el tipo objeto).
PyObject *PyTypeObject.tp_dict
El diccionario del tipo se almacena aquí por PyType_Ready().
This field should normally be initialized to NULL before PyType_Ready is called; it may also be initialized to
a dictionary containing initial attributes for the type. Once PyType_Ready() has initialized the type, extra
attributes for the type may be added to this dictionary only if they don’t correspond to overloaded operations
(like __add__()). Once initialization for the type has finished, this field should be treated as read-only.
Some types may not store their dictionary in this slot. Use PyType_GetDict() to retrieve the dictionary
for an arbitrary type.
Distinto en la versión 3.12: Internals detail: For static builtin types, this is always NULL. Instead, the dict for
such types is stored on PyInterpreterState. Use PyType_GetDict() to get the dict for an arbitrary
type.
Herencia:
Este campo no es heredado por los subtipos (aunque los atributos definidos aquí se heredan a través de un
mecanismo diferente).
Por defecto:
Si este campo es NULL, PyType_Ready() le asignará un nuevo diccionario.

Advertencia: No es seguro usar PyDict_SetItem() en o modificar de otra manera a tp_dict con


el diccionario C-API.

descrgetfunc PyTypeObject.tp_descr_get
Un puntero opcional a una función «obtener descriptor» (descriptor ger).
La firma de la función es:

PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);

284 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

Herencia:
Este campo es heredado por subtipos.
descrsetfunc PyTypeObject.tp_descr_set
Un puntero opcional a una función para configurar y eliminar el valor de un descriptor.
La firma de la función es:

int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);

El argumento value se establece a NULL para borrar el valor.


Herencia:
Este campo es heredado por subtipos.
Py_ssize_t PyTypeObject.tp_dictoffset
While this field is still supported, Py_TPFLAGS_MANAGED_DICT should be used instead, if at all possible.
Si las instancias de este tipo tienen un diccionario que contiene variables de instancia, este campo no es cero
y contiene el desplazamiento en las instancias del tipo del diccionario de variables de instancia; este desplaza-
miento es utilizado por PyObject_GenericGetAttr().
No confunda este campo con tp_dict; ese es el diccionario para los atributos del tipo de objeto en sí.
The value specifies the offset of the dictionary from the start of the instance structure.
El tp_dictoffset debe considerarse como de solo escritura. Para obtener el puntero al diccionario, lla-
me a PyObject_GenericGetDict(). Llamar a PyObject_GenericGetDict() puede necesitar
asignar memoria para el diccionario, por lo que puede ser más eficiente llamar a PyObject_GetAttr()
cuando se accede a un atributo en el objeto.
It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_dictoffset.
Herencia:
This field is inherited by subtypes. A subtype should not override this offset; doing so could be unsa-
fe, if C code tries to access the dictionary at the previous offset. To properly support inheritance, use
Py_TPFLAGS_MANAGED_DICT.
Por defecto:
This slot has no default. For static types, if the field is NULL then no __dict__ gets created for instances.
If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_dict field, then tp_dictoffset will be set
to -1, to indicate that it is unsafe to use this field.
initproc PyTypeObject.tp_init
Un puntero opcional a una función de inicialización de instancia.
This function corresponds to the __init__() method of classes. Like __init__(), it is possible to
create an instance without calling __init__(), and it is possible to reinitialize an instance by calling its
__init__() method again.
La firma de la función es:

int tp_init(PyObject *self, PyObject *args, PyObject *kwds);

The self argument is the instance to be initialized; the args and kwds arguments represent positional and keyword
arguments of the call to __init__().
La función tp_init, si no es NULL, se llama cuando una instancia se crea normalmente llamando a su tipo,
después de la función tp_new del tipo ha retornado una instancia del tipo. Si la función tp_new retorna
una instancia de otro tipo que no es un subtipo del tipo original, no se llama la función tp_init; if tp_new
retorna una instancia de un subtipo del tipo original, se llama al subtipo tp_init.
Retorna 0 en caso de éxito, -1 y establece una excepción en caso de error.

12.3. Objetos tipo 285


The Python/C API, Versión 3.12.4

Herencia:
Este campo es heredado por subtipos.
Por defecto:
Para tipos estáticos, este campo no tiene un valor predeterminado.
allocfunc PyTypeObject.tp_alloc
Un puntero opcional a una función de asignación de instancia.
La firma de la función es:

PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);

Herencia:
Este campo es heredado por subtipos estáticos, pero no por subtipos dinámicos (subtipos creados por una
declaración de clase).
Por defecto:
Para subtipos dinámicos, este campo siempre se establece en PyType_GenericAlloc(), para forzar una
estrategia de asignación de heap estándar.
For static subtypes, PyBaseObject_Type uses PyType_GenericAlloc(). That is the recommended
value for all statically defined types.
newfunc PyTypeObject.tp_new
Un puntero opcional a una función de creación de instancias.
La firma de la función es:

PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);

El argumento subtype es el tipo de objeto que se está creando; los argumentos args y kwds representan argu-
mentos posicionales y de palabras clave de la llamada al tipo. Tenga en cuenta que subtype no tiene que ser igual
al tipo cuya función tp_new es llamada; puede ser un subtipo de ese tipo (pero no un tipo no relacionado).
La función tp_new debería llamar a subtype->tp_alloc(subtype, nitems) para asignar espacio
para el objeto, y luego hacer solo la inicialización adicional que sea absolutamente necesaria. La inicialización
que se puede ignorar o repetir de forma segura debe colocarse en el controlador tp_init. Una buena regla
general es que para los tipos inmutables, toda la inicialización debe tener lugar en tp_new, mientras que para
los tipos mutables, la mayoría de las inicializaciones se deben diferir a tp_init.
Set the Py_TPFLAGS_DISALLOW_INSTANTIATION flag to disallow creating instances of the type in
Python.
Herencia:
Este campo se hereda por subtipos, excepto que no lo heredan tipos estáticos cuyo tp_base es NULL o
&PyBaseObject_Type.
Por defecto:
Para tipos estáticos, este campo no tiene ningún valor predeterminado. Esto significa que si la ranura se define
como NULL, no se puede llamar al tipo para crear nuevas instancias; presumiblemente hay alguna otra forma
de crear instancias, como una función de fábrica.
freefunc PyTypeObject.tp_free
Un puntero opcional a una función de desasignación de instancia. Su firma es:

void tp_free(void *self);

Un inicializador que es compatible con esta firma es PyObject_Free().


Herencia:

286 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

Este campo es heredado por subtipos estáticos, pero no por subtipos dinámicos (subtipos creados por una
declaración de clase)
Por defecto:
In dynamic subtypes, this field is set to a deallocator suitable to match PyType_GenericAlloc() and the
value of the Py_TPFLAGS_HAVE_GC flag bit.
For static subtypes, PyBaseObject_Type uses PyObject_Del().
inquiry PyTypeObject.tp_is_gc
Un puntero opcional a una función llamada por el recolector de basura.
The garbage collector needs to know whether a particular object is collectible or not. Normally, it is sufficient
to look at the object’s type’s tp_flags field, and check the Py_TPFLAGS_HAVE_GC flag bit. But some
types have a mixture of statically and dynamically allocated instances, and the statically allocated instances are
not collectible. Such types should define this function; it should return 1 for a collectible instance, and 0 for a
non-collectible instance. The signature is:

int tp_is_gc(PyObject *self);

(El único ejemplo de esto son los tipos en sí. El metatipo, PyType_Type, define esta función para distinguir
entre tipos estática y dinámicamente asignados.)
Herencia:
Este campo es heredado por subtipos.
Por defecto:
This slot has no default. If this field is NULL, Py_TPFLAGS_HAVE_GC is used as the functional equivalent.
PyObject *PyTypeObject.tp_bases
Tupla de tipos base.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
For dynamically created classes, the Py_tp_bases slot can be used instead of the bases argument of
PyType_FromSpecWithBases(). The argument form is preferred.

Advertencia: Multiple inheritance does not work well for statically defined types. If you set tp_bases
to a tuple, Python will not raise an error, but some slots will only be inherited from the first base.

Herencia:
Este campo no se hereda.
PyObject *PyTypeObject.tp_mro
Tupla que contiene el conjunto expandido de tipos base, comenzando con el tipo en sí y terminando con
object, en orden de resolución de método.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
Herencia:
Este campo no se hereda; se calcula fresco por PyType_Ready().
PyObject *PyTypeObject.tp_cache
No usado. Solo para uso interno.
Herencia:
Este campo no se hereda.

12.3. Objetos tipo 287


The Python/C API, Versión 3.12.4

void *PyTypeObject.tp_subclasses
A collection of subclasses. Internal use only. May be an invalid pointer.
To get a list of subclasses, call the Python method __subclasses__().
Distinto en la versión 3.12: For some types, this field does not hold a valid PyObject*. The type was changed
to void* to indicate this.
Herencia:
Este campo no se hereda.
PyObject *PyTypeObject.tp_weaklist
Cabecera de lista de referencia débil, para referencias débiles a este tipo de objeto. No heredado Solo para uso
interno.
Distinto en la versión 3.12: Internals detail: For the static builtin types this is always NULL, even if weakrefs
are added. Instead, the weakrefs for each are stored on PyInterpreterState. Use the public C-API or
the internal _PyObject_GET_WEAKREFS_LISTPTR() macro to avoid the distinction.
Herencia:
Este campo no se hereda.
destructor PyTypeObject.tp_del
Este campo está en desuso. Use tp_finalize en su lugar.
unsigned int PyTypeObject.tp_version_tag
Se usa para indexar en el caché de métodos. Solo para uso interno.
Herencia:
Este campo no se hereda.
destructor PyTypeObject.tp_finalize
Un puntero opcional a una función de finalización de instancia. Su firma es:

void tp_finalize(PyObject *self);

Si tp_finalize está configurado, el intérprete lo llama una vez cuando finaliza una instancia. Se llama
desde el recolector de basura (si la instancia es parte de un ciclo de referencia aislado) o justo antes de que el
objeto se desasigne. De cualquier manera, se garantiza que se invocará antes de intentar romper los ciclos de
referencia, asegurando que encuentre el objeto en un estado sano.
tp_finalize no debe mutar el estado de excepción actual; por lo tanto, una forma recomendada de escribir
un finalizador no trivial es:

static void
local_finalize(PyObject *self)
{
PyObject *error_type, *error_value, *error_traceback;

/* Save the current exception, if any. */


PyErr_Fetch(&error_type, &error_value, &error_traceback);

/* ... */

/* Restore the saved exception. */


PyErr_Restore(error_type, error_value, error_traceback);
}

Además, tenga en cuenta que, en un Python que ha recolectado basura, se puede llamar a tp_dealloc desde
cualquier hilo de Python, no solo el hilo que creó el objeto (si el objeto se convierte en parte de un ciclo de
conteo de referencias, ese ciclo puede ser recogido por una recolección de basura en cualquier hilo). Esto no
es un problema para las llamadas a la API de Python, ya que el hilo en el que se llama tp_dealloc será

288 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

el propietario del Bloqueo Global del Intérprete (GIL, por sus siglas en inglés Global Interpreter Lock). Sin
embargo, si el objeto que se destruye a su vez destruye objetos de alguna otra biblioteca C o C++, se debe tener
cuidado para garantizar que la destrucción de esos objetos en el hilo que se llama tp_dealloc no violará
ningún supuesto de la biblioteca.
Herencia:
Este campo es heredado por subtipos.
Added in version 3.4.
Distinto en la versión 3.8: Before version 3.8 it was necessary to set the Py_TPFLAGS_HAVE_FINALIZE
flags bit in order for this field to be used. This is no longer required.
Ver también:
«Finalización segura de objetos» (PEP 442)
vectorcallfunc PyTypeObject.tp_vectorcall
Vectorcall function to use for calls of this type object. In other words, it is used to implement vectorcall for
type.__call__. If tp_vectorcall is NULL, the default call implementation using __new__() and
__init__() is used.
Herencia:
Este campo nunca se hereda.
Added in version 3.9: (el campo existe desde 3.8 pero solo se usa desde 3.9)
unsigned char PyTypeObject.tp_watched
Internal. Do not use.
Added in version 3.12.

12.3.6 Tipos estáticos

Tradicionalmente, los tipos definidos en el código C son static, es decir, una estructura estática PyTypeObject se
define directamente en el código y se inicializa usando PyType_Ready().
Esto da como resultado tipos que están limitados en relación con los tipos definidos en Python:
• Los tipos estáticos están limitados a una base, es decir, no pueden usar herencia múltiple.
• Los objetos de tipo estático (pero no necesariamente sus instancias) son inmutables. No es posible agregar o
modificar los atributos del objeto tipo desde Python.
• Los objetos de tipo estático se comparten en sub intérpretes, por lo que no deben incluir ningún estado específico
del sub interpretador.
Also, since PyTypeObject is only part of the Limited API as an opaque struct, any extension modules using static
types must be compiled for a specific Python minor version.

12.3.7 Tipos Heap

An alternative to static types is heap-allocated types, or heap types for short, which correspond closely to classes created
by Python’s class statement. Heap types have the Py_TPFLAGS_HEAPTYPE flag set.
This is done by filling a PyType_Spec structure and calling PyType_FromSpec(),
PyType_FromSpecWithBases(), PyType_FromModuleAndSpec(), or
PyType_FromMetaclass().

12.3. Objetos tipo 289


The Python/C API, Versión 3.12.4

12.4 Estructuras de objetos de números

type PyNumberMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo numérico.
Cada función es utilizada por la función de un nombre similar documentado en la sección Protocolo de números.
Aquí está la definición de la estructura:

typedef struct {
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;
unaryfunc nb_negative;
unaryfunc nb_positive;
unaryfunc nb_absolute;
inquiry nb_bool;
unaryfunc nb_invert;
binaryfunc nb_lshift;
binaryfunc nb_rshift;
binaryfunc nb_and;
binaryfunc nb_xor;
binaryfunc nb_or;
unaryfunc nb_int;
void *nb_reserved;
unaryfunc nb_float;

binaryfunc nb_inplace_add;
binaryfunc nb_inplace_subtract;
binaryfunc nb_inplace_multiply;
binaryfunc nb_inplace_remainder;
ternaryfunc nb_inplace_power;
binaryfunc nb_inplace_lshift;
binaryfunc nb_inplace_rshift;
binaryfunc nb_inplace_and;
binaryfunc nb_inplace_xor;
binaryfunc nb_inplace_or;

binaryfunc nb_floor_divide;
binaryfunc nb_true_divide;
binaryfunc nb_inplace_floor_divide;
binaryfunc nb_inplace_true_divide;

unaryfunc nb_index;

binaryfunc nb_matrix_multiply;
binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;

Nota: Las funciones binarias y ternarias deben verificar el tipo de todos sus operandos e implementar las con-
versiones necesarias (al menos uno de los operandos es una instancia del tipo definido). Si la operación no está
definida para los operandos dados, las funciones binarias y ternarias deben retornar Py_NotImplemented,
si se produce otro error, deben retornar NULL y establecer una excepción.

Nota: The nb_reserved field should always be NULL. It was previously called nb_long, and was renamed
in Python 3.0.1.

290 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

binaryfunc PyNumberMethods.nb_add

binaryfunc PyNumberMethods.nb_subtract

binaryfunc PyNumberMethods.nb_multiply

binaryfunc PyNumberMethods.nb_remainder

binaryfunc PyNumberMethods.nb_divmod

ternaryfunc PyNumberMethods.nb_power

unaryfunc PyNumberMethods.nb_negative

unaryfunc PyNumberMethods.nb_positive

unaryfunc PyNumberMethods.nb_absolute

inquiry PyNumberMethods.nb_bool

unaryfunc PyNumberMethods.nb_invert

binaryfunc PyNumberMethods.nb_lshift

binaryfunc PyNumberMethods.nb_rshift

binaryfunc PyNumberMethods.nb_and

binaryfunc PyNumberMethods.nb_xor

binaryfunc PyNumberMethods.nb_or

unaryfunc PyNumberMethods.nb_int

void *PyNumberMethods.nb_reserved

unaryfunc PyNumberMethods.nb_float

binaryfunc PyNumberMethods.nb_inplace_add

binaryfunc PyNumberMethods.nb_inplace_subtract

binaryfunc PyNumberMethods.nb_inplace_multiply

binaryfunc PyNumberMethods.nb_inplace_remainder

ternaryfunc PyNumberMethods.nb_inplace_power

binaryfunc PyNumberMethods.nb_inplace_lshift

binaryfunc PyNumberMethods.nb_inplace_rshift

binaryfunc PyNumberMethods.nb_inplace_and

binaryfunc PyNumberMethods.nb_inplace_xor

binaryfunc PyNumberMethods.nb_inplace_or

binaryfunc PyNumberMethods.nb_floor_divide

binaryfunc PyNumberMethods.nb_true_divide

binaryfunc PyNumberMethods.nb_inplace_floor_divide

binaryfunc PyNumberMethods.nb_inplace_true_divide

12.4. Estructuras de objetos de números 291


The Python/C API, Versión 3.12.4

unaryfunc PyNumberMethods.nb_index

binaryfunc PyNumberMethods.nb_matrix_multiply

binaryfunc PyNumberMethods.nb_inplace_matrix_multiply

12.5 Estructuras de objetos mapeo

type PyMappingMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo de mapeo.
Tiene tres miembros:
lenfunc PyMappingMethods.mp_length
Esta función es utilizada por PyMapping_Size() y PyObject_Size(), y tiene la misma firma. Esta
ranura puede establecerse en NULL si el objeto no tiene una longitud definida.
binaryfunc PyMappingMethods.mp_subscript
Esta función es utilizada por PyObject_GetItem() y PySequence_GetSlice(), y tie-
ne la misma firma que PyObject_GetItem(). Este espacio debe llenarse para que la función
PyMapping_Check() retorna 1, de lo contrario puede ser NULL.
objobjargproc PyMappingMethods.mp_ass_subscript
This function is used by PyObject_SetItem(), PyObject_DelItem(),
PySequence_SetSlice() and PySequence_DelSlice(). It has the same signature as
PyObject_SetItem(), but v can also be set to NULL to delete an item. If this slot is NULL, the
object does not support item assignment and deletion.

12.6 Estructuras de objetos secuencia

type PySequenceMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo de se-
cuencia.
lenfunc PySequenceMethods.sq_length
Esta función es utilizada por PySequence_Size() y PyObject_Size(), y tiene la misma firma. Tam-
bién se usa para manejar índices negativos a través de los espacios sq_item y sq_ass_item.
binaryfunc PySequenceMethods.sq_concat
Esta función es utilizada por PySequence_Concat() y tiene la misma firma. También es utilizado por el
operador +, después de intentar la suma numérica a través de la ranura nb_add.
ssizeargfunc PySequenceMethods.sq_repeat
Esta función es utilizada por PySequence_Repeat() y tiene la misma firma. También es utilizado por el
operador *, después de intentar la multiplicación numérica a través de la ranura nb_multiply.
ssizeargfunc PySequenceMethods.sq_item
Esta función es utilizada por PySequence_GetItem() y tiene la misma firma. También es utilizado por
PyObject_GetItem(), después de intentar la suscripción a través de la ranura mp_subscript. Este
espacio debe llenarse para que la función PySequence_Check() retorna 1, de lo contrario puede ser
NULL.
Negative indexes are handled as follows: if the sq_length slot is filled, it is called and the sequence length is
used to compute a positive index which is passed to sq_item. If sq_length is NULL, the index is passed
as is to the function.

292 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

ssizeobjargproc PySequenceMethods.sq_ass_item
Esta función es utilizada por PySequence_SetItem() y tiene la misma firma. También lo usan
PyObject_SetItem() y PyObject_DelItem(), después de intentar la asignación y eliminación del
elemento a través de la ranura mp_ass_subscript. Este espacio puede dejarse en NULL si el objeto no
admite la asignación y eliminación de elementos.
objobjproc PySequenceMethods.sq_contains
Esta función puede ser utilizada por PySequence_Contains() y tiene la misma firma. Este espacio puede
dejarse en NULL, en este caso PySequence_Contains() simplemente atraviesa la secuencia hasta que
encuentra una coincidencia.
binaryfunc PySequenceMethods.sq_inplace_concat
Esta función es utilizada por PySequence_InPlaceConcat() y tiene la misma firma. Debe-
ría modificar su primer operando y retornarlo. Este espacio puede dejarse en NULL, en este caso
PySequence_InPlaceConcat() volverá a PySequence_Concat(). También es utilizado por
la asignación aumentada +=, después de intentar la suma numérica en el lugar a través de la ranura
nb_inplace_add.
ssizeargfunc PySequenceMethods.sq_inplace_repeat
Esta función es utilizada por PySequence_InPlaceRepeat() y tiene la misma firma. Debe-
ría modificar su primer operando y retornarlo. Este espacio puede dejarse en NULL, en este caso
PySequence_InPlaceRepeat() volverá a PySequence_Repeat(). También es utilizado por la
asignación aumentada *=, después de intentar la multiplicación numérica en el lugar a través de la ranura
nb_inplace_multiply.

12.7 Estructuras de objetos búfer

type PyBufferProcs
Esta estructura contiene punteros a las funciones requeridas por Buffer protocol. El protocolo define cómo un
objeto exportador puede exponer sus datos internos a objetos de consumo.
getbufferproc PyBufferProcs.bf_getbuffer
La firma de esta función es:

int (PyObject *exporter, Py_buffer *view, int flags);

Maneja una solicitud a exporter para completar view según lo especificado por flags. Excepto por el punto (3),
una implementación de esta función DEBE seguir estos pasos:
(1) Check if the request can be met. If not, raise BufferError, set view->obj to NULL and return -1.
(2) Rellene los campos solicitados.
(3) Incrementa un contador interno para el número de exportaciones (exports).
(4) Set view->obj to exporter and increment view->obj.
(5) Retorna 0.
Si exporter es parte de una cadena o árbol de proveedores de búfer, se pueden usar dos esquemas principales:
• Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference
to itself.
• Redirect: The buffer request is redirected to the root object of the tree. Here, view->obj will be a new
reference to the root object.
Los campos individuales de view se describen en la sección Estructura de búfer, las reglas sobre cómo debe
reaccionar un exportador a solicitudes específicas se encuentran en la sección Tipos de solicitud de búfer.

12.7. Estructuras de objetos búfer 293


The Python/C API, Versión 3.12.4

Toda la memoria señalada en la estructura Py_buffer pertenece al exportador y debe permanecer válida
hasta que no queden consumidores. format, shape, strides, suboffsets y internal son de solo
lectura para el consumidor.
PyBuffer_FillInfo() proporciona una manera fácil de exponer un búfer de bytes simple mientras se
trata correctamente con todos los tipos de solicitud.
PyObject_GetBuffer() es la interfaz para el consumidor que envuelve esta función.
releasebufferproc PyBufferProcs.bf_releasebuffer
La firma de esta función es:

void (PyObject *exporter, Py_buffer *view);

Maneja una solicitud para liberar los recursos del búfer. Si no es necesario liberar recursos,
PyBufferProcs.bf_releasebuffer puede ser NULL. De lo contrario, una implementación están-
dar de esta función tomará estos pasos opcionales:
(1) Disminuir un contador interno para el número de exportaciones.
(2) Si el contador es 0, libera toda la memoria asociada con view.
El exportador DEBE utilizar el campo internal para realizar un seguimiento de los recursos específicos del
búfer. Se garantiza que este campo permanecerá constante, mientras que un consumidor PUEDE pasar una
copia del búfer original como argumento view.
This function MUST NOT decrement view->obj, since that is done automatically in
PyBuffer_Release() (this scheme is useful for breaking reference cycles).
PyBuffer_Release() es la interfaz para el consumidor que envuelve esta función.

12.8 Estructuras de objetos asíncronos

Added in version 3.5.


type PyAsyncMethods
Esta estructura contiene punteros a las funciones requeridas para implementar objetos «esperable» (awaitable)
y «iterador asincrónico» (asynchronous iterator).
Aquí está la definición de la estructura:

typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
sendfunc am_send;
} PyAsyncMethods;

unaryfunc PyAsyncMethods.am_await
La firma de esta función es:

PyObject *am_await(PyObject *self);

The returned object must be an iterator, i.e. PyIter_Check() must return 1 for it.
Este espacio puede establecerse en NULL si un objeto no es awaitable.
unaryfunc PyAsyncMethods.am_aiter
La firma de esta función es:

PyObject *am_aiter(PyObject *self);

294 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

Must return an asynchronous iterator object. See __anext__() for details.


Este espacio puede establecerse en NULL si un objeto no implementa el protocolo de iteración asincrónica.
unaryfunc PyAsyncMethods.am_anext
La firma de esta función es:

PyObject *am_anext(PyObject *self);

Must return an awaitable object. See __anext__() for details. This slot may be set to NULL.
sendfunc PyAsyncMethods.am_send
La firma de esta función es:

PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);

Consulte PyIter_Send() para obtener más detalles. Esta ranura se puede establecer en NULL.
Added in version 3.10.

12.9 Tipo Ranura typedefs

typedef PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)


Part of the Stable ABI. The purpose of this function is to separate memory allocation from memory initia-
lization. It should return a pointer to a block of memory of adequate length for the instance, suitably alig-
ned, and initialized to zeros, but with ob_refcnt set to 1 and ob_type set to the type argument. If
the type’s tp_itemsize is non-zero, the object’s ob_size field should be initialized to nitems and the
length of the allocated memory block should be tp_basicsize + nitems*tp_itemsize, rounded
up to a multiple of sizeof(void*); otherwise, nitems is not used and the length of the block should be
tp_basicsize.
Esta función no debe hacer ninguna otra instancia de inicialización, ni siquiera para asignar memoria adicional;
eso debe ser realizado por tp_new.
typedef void (*destructor)(PyObject*)
Part of the Stable ABI.
typedef void (*freefunc)(void*)
Consulte tp_free.
typedef PyObject *(*newfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. Consulte tp_new.
typedef int (*initproc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. Consulte tp_init.
typedef PyObject *(*reprfunc)(PyObject*)
Part of the Stable ABI. Consulte tp_repr.
typedef PyObject *(*getattrfunc)(PyObject *self, char *attr)
Part of the Stable ABI. Retorna el valor del atributo nombrado para el objeto.
typedef int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
Part of the Stable ABI. Establece el valor del atributo nombrado para el objeto. El argumento del valor se
establece en NULL para eliminar el atributo.
typedef PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)
Part of the Stable ABI. Retorna el valor del atributo nombrado para el objeto.
Consulte tp_getattro.

12.9. Tipo Ranura typedefs 295


The Python/C API, Versión 3.12.4

typedef int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)


Part of the Stable ABI. Establece el valor del atributo nombrado para el objeto. El argumento del valor se
establece en NULL para eliminar el atributo.
Consulte tp_setattro.
typedef PyObject *(*descrgetfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. See tp_descr_get.
typedef int (*descrsetfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. See tp_descr_set.
typedef Py_hash_t (*hashfunc)(PyObject*)
Part of the Stable ABI. Consulte tp_hash.
typedef PyObject *(*richcmpfunc)(PyObject*, PyObject*, int)
Part of the Stable ABI. Consulte tp_richcompare.
typedef PyObject *(*getiterfunc)(PyObject*)
Part of the Stable ABI. Consulte tp_iter.
typedef PyObject *(*iternextfunc)(PyObject*)
Part of the Stable ABI. Consulte tp_iternext.
typedef Py_ssize_t (*lenfunc)(PyObject*)
Part of the Stable ABI.
typedef int (*getbufferproc)(PyObject*, Py_buffer*, int)
Part of the Stable ABI since version 3.12.
typedef void (*releasebufferproc)(PyObject*, Py_buffer*)
Part of the Stable ABI since version 3.12.
typedef PyObject *(*unaryfunc)(PyObject*)
Part of the Stable ABI.
typedef PyObject *(*binaryfunc)(PyObject*, PyObject*)
Part of the Stable ABI.
typedef PySendResult (*sendfunc)(PyObject*, PyObject*, PyObject**)
Consulte am_send.
typedef PyObject *(*ternaryfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.
typedef PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)
Part of the Stable ABI.
typedef int (*ssizeobjargproc)(PyObject*, Py_ssize_t, PyObject*)
Part of the Stable ABI.
typedef int (*objobjproc)(PyObject*, PyObject*)
Part of the Stable ABI.
typedef int (*objobjargproc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

296 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

12.10 Ejemplos

Los siguientes son ejemplos simples de definiciones de tipo Python. Incluyen el uso común que puede encontrar.
Algunos demuestran casos difíciles de esquina (corner cases). Para obtener más ejemplos, información práctica y un
tutorial, consulte «definiendo nuevos tipos» (defining-new-types) y «tópicos de nuevos tipos (new-types-topics).
Un tipo estático básico:
typedef struct {
PyObject_HEAD
const char *data;
} MyObject;

static PyTypeObject MyObject_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
.tp_basicsize = sizeof(MyObject),
.tp_doc = PyDoc_STR("My objects"),
.tp_new = myobj_new,
.tp_dealloc = (destructor)myobj_dealloc,
.tp_repr = (reprfunc)myobj_repr,
};

También puede encontrar código más antiguo (especialmente en la base de código CPython) con un inicializador más
detallado:
static PyTypeObject MyObject_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"mymod.MyObject", /* tp_name */
sizeof(MyObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)myobj_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
(reprfunc)myobj_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
PyDoc_STR("My objects"), /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(continúe en la próxima página)

12.10. Ejemplos 297


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


0, /* tp_init */
0, /* tp_alloc */
myobj_new, /* tp_new */
};

Un tipo que admite referencias débiles, instancias de diccionarios (dicts) y hashing:

typedef struct {
PyObject_HEAD
const char *data;
} MyObject;

static PyTypeObject MyObject_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
.tp_basicsize = sizeof(MyObject),
.tp_doc = PyDoc_STR("My objects"),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MANAGED_DICT |
Py_TPFLAGS_MANAGED_WEAKREF,
.tp_new = myobj_new,
.tp_traverse = (traverseproc)myobj_traverse,
.tp_clear = (inquiry)myobj_clear,
.tp_alloc = PyType_GenericNew,
.tp_dealloc = (destructor)myobj_dealloc,
.tp_repr = (reprfunc)myobj_repr,
.tp_hash = (hashfunc)myobj_hash,
.tp_richcompare = PyBaseObject_Type.tp_richcompare,
};

A str subclass that cannot be subclassed and cannot be called to create instances (e.g. uses a separate factory func)
using Py_TPFLAGS_DISALLOW_INSTANTIATION flag:

typedef struct {
PyUnicodeObject raw;
char *extra;
} MyStr;

static PyTypeObject MyStr_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyStr",
.tp_basicsize = sizeof(MyStr),
.tp_base = NULL, // set to &PyUnicode_Type in module init
.tp_doc = PyDoc_STR("my custom str"),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
.tp_repr = (reprfunc)myobj_repr,
};

El tipo estático más simple con instancias de longitud fija:

typedef struct {
PyObject_HEAD
} MyObject;

static PyTypeObject MyObject_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
};

El tipo estático más simple con instancias de longitud variable:

298 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

typedef struct {
PyObject_VAR_HEAD
const char *data[1];
} MyObject;

static PyTypeObject MyObject_Type = {


PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
.tp_basicsize = sizeof(MyObject) - sizeof(char *),
.tp_itemsize = sizeof(char *),
};

12.11 Apoyo a la recolección de basura cíclica

El soporte de Python para detectar y recolectar basura que involucra referencias circulares requiere el soporte de
tipos de objetos que son «contenedores» para otros objetos que también pueden ser contenedores. Los tipos que no
almacenan referencias a otros objetos, o que solo almacenan referencias a tipos atómicos (como números o cadenas),
no necesitan proporcionar ningún soporte explícito para la recolección de basura.
To create a container type, the tp_flags field of the type object must include the Py_TPFLAGS_HAVE_GC
and provide an implementation of the tp_traverse handler. If instances of the type are mutable, a tp_clear
implementation must also be provided.
Py_TPFLAGS_HAVE_GC
Los objetos con un tipo con este indicador establecido deben cumplir con las reglas documentadas aquí. Por
conveniencia, estos objetos se denominarán objetos contenedor.
Los constructores para tipos de contenedores deben cumplir con dos reglas:
1. The memory for the object must be allocated using PyObject_GC_New or PyObject_GC_NewVar.
2. Una vez que se inicializan todos los campos que pueden contener referencias a otros contenedores, debe llamar
a PyObject_GC_Track().
Del mismo modo, el desasignador (deallocator) para el objeto debe cumplir con un par similar de reglas:
1. Antes de invalidar los campos que se refieren a otros contenedores, debe llamarse
PyObject_GC_UnTrack().
2. La memoria del objeto debe ser desasignada (deallocated) usando PyObject_GC_Del().

Advertencia: Si un tipo añade el Py_TPFLAGS_HAVE_GC, entonces must implementar al menos un


manejado tp_traverse o usar explícitamente uno de su subclase o subclases.
When calling PyType_Ready() or some of the APIs that indirectly call it like
PyType_FromSpecWithBases() or PyType_FromSpec() the interpreter will automatically
populate the tp_flags, tp_traverse and tp_clear fields if the type inherits from a class that im-
plements the garbage collector protocol and the child class does not include the Py_TPFLAGS_HAVE_GC
flag.

PyObject_GC_New(TYPE, typeobj)
Analogous to PyObject_New but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
PyObject_GC_NewVar(TYPE, typeobj, size)
Analogous to PyObject_NewVar but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
PyObject *PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *type, size_t extra_size)

12.11. Apoyo a la recolección de basura cíclica 299


The Python/C API, Versión 3.12.4

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

Analogous to PyObject_GC_New but allocates extra_size bytes at the end of the object (at offset
tp_basicsize). The allocated memory is initialized to zeros, except for the Python object header.
The extra data will be deallocated with the object, but otherwise it is not managed by Python.

Advertencia: The function is marked as unstable because the final mechanism for reserving extra data after
an instance is not yet decided. For allocating a variable number of fields, prefer using PyVarObject and
tp_itemsize instead.

Added in version 3.12.


PyObject_GC_Resize(TYPE, op, newsize)
Resize an object allocated by PyObject_NewVar. Returns the resized object of type TYPE* (refers to any
C type) or NULL on failure.
op must be of type PyVarObject* and must not be tracked by the collector yet. newsize must be of type
Py_ssize_t.
void PyObject_GC_Track(PyObject *op)
Part of the Stable ABI. Agrega el objeto op al conjunto de objetos contenedor seguidos por el recolector de
basura. El recolector puede ejecutarse en momentos inesperados, por lo que los objetos deben ser válidos
durante el seguimiento. Esto debería llamarse una vez que todos los campos seguidos por tp_traverse se
vuelven válidos, generalmente cerca del final del constructor.
int PyObject_IS_GC(PyObject *obj)
Retorna un valor distinto de cero si el objeto implementa el protocolo del recolector de basura; de lo contrario,
retorna 0.
El recolector de basura no puede rastrear el objeto si esta función retorna 0.
int PyObject_GC_IsTracked(PyObject *op)
Part of the Stable ABI since version 3.9. Retorna 1 si el tipo de objeto de op implementa el protocolo GC y el
recolector de basura está rastreando op y 0 en caso contrario.
Esto es análogo a la función de Python gc.is_tracked().
Added in version 3.9.
int PyObject_GC_IsFinalized(PyObject *op)
Part of the Stable ABI since version 3.9. Retorna 1 si el tipo de objeto de op implementa el protocolo GC y op
ya ha sido finalizado por el recolector de basura y 0 en caso contrario.
Esto es análogo a la función de Python gc.is_finalized().
Added in version 3.9.
void PyObject_GC_Del(void *op)
Part of the Stable ABI. Releases memory allocated to an object using PyObject_GC_New or
PyObject_GC_NewVar.
void PyObject_GC_UnTrack(void *op)
Part of the Stable ABI. Elimina el objeto op del conjunto de objetos contenedor rastreados por el recolector de
basura. Tenga en cuenta que PyObject_GC_Track() puede ser llamado nuevamente en este objeto para
agregarlo nuevamente al conjunto de objetos rastreados. El desasignador (el manejador tp_dealloc) debería
llamarlo para el objeto antes de que cualquiera de los campos utilizados por el manejador tp_traverse no
sea válido.
Distinto en la versión 3.8: The _PyObject_GC_TRACK() and _PyObject_GC_UNTRACK() macros have
been removed from the public C API.

300 Capítulo 12. Soporte de implementación de objetos


The Python/C API, Versión 3.12.4

El manejador tp_traverse acepta un parámetro de función de este tipo:


typedef int (*visitproc)(PyObject *object, void *arg)
Part of the Stable ABI. Tipo de la función visitante que se pasa al manejador tp_traverse. La función debe
llamarse con un objeto para atravesar como object y el tercer parámetro para el manejador tp_traverse
como arg. El núcleo de Python utiliza varias funciones visitantes para implementar la detección de basura
cíclica; No se espera que los usuarios necesiten escribir sus propias funciones visitante.
El manejador tp_traverse debe tener el siguiente tipo:
typedef int (*traverseproc)(PyObject *self, visitproc visit, void *arg)
Part of the Stable ABI. Función transversal para un objeto contenedor. Las implementaciones deben llamar a la
función visit para cada objeto directamente contenido por self, siendo los parámetros a visit el objeto contenido
y el valor arg pasado al controlador. La función visit no debe llamarse con un argumento de objeto NULL. Si
visit retorna un valor distinto de cero, ese valor debe retornarse inmediatamente.
Para simplificar la escritura de los manejadores tp_traverse, se proporciona un macro a Py_VISIT(). Para
usar este macro, la implementación tp_traverse debe nombrar sus argumentos exactamente visit y arg:
void Py_VISIT(PyObject *o)
Si o no es NULL, llama a la devolución de llamada (callback) visit, con argumentos o y arg. Si visit retorna
un valor distinto de cero, lo retorna. Usando este macro, los manejadores tp_traverse tienen el siguiente
aspecto:

static int
my_traverse(Noddy *self, visitproc visit, void *arg)
{
Py_VISIT(self->foo);
Py_VISIT(self->bar);
return 0;
}

El manejador tp_clear debe ser del tipo query, o NULL si el objeto es inmutable.
typedef int (*inquiry)(PyObject *self)
Part of the Stable ABI. Descarta referencias que pueden haber creado ciclos de referencia. Los objetos inmu-
tables no tienen que definir este método ya que nunca pueden crear directamente ciclos de referencia. Tenga
en cuenta que el objeto aún debe ser válido después de llamar a este método (no solo llame a Py_DECREF()
en una referencia). El recolector de basura llamará a este método si detecta que este objeto está involucrado
en un ciclo de referencia.

12.11.1 Controlar el estado del recolector de basura

La C-API proporciona las siguientes funciones para controlar las ejecuciones de recolección de basura.
Py_ssize_t PyGC_Collect(void)
Part of the Stable ABI. Realiza una recolección de basura completa, si el recolector de basura está habilitado.
(Tenga en cuenta que gc.collect() lo ejecuta incondicionalmente).
Retorna el número de objetos recolectados e inalcanzables que no se pueden recolectar. Si el recolector de
basura está deshabilitado o ya está recolectando, retorna 0 inmediatamente. Los errores durante la recolección
de basura se pasan a sys.unraisablehook. Esta función no genera excepciones.
int PyGC_Enable(void)
Part of the Stable ABI since version 3.10. Habilita el recolector de basura: similar a gc.enable(). Retorna
el estado anterior, 0 para deshabilitado y 1 para habilitado.
Added in version 3.10.

12.11. Apoyo a la recolección de basura cíclica 301


The Python/C API, Versión 3.12.4

int PyGC_Disable(void)
Part of the Stable ABI since version 3.10. Deshabilita el recolector de basura: similar a gc.disable().
Retorna el estado anterior, 0 para deshabilitado y 1 para habilitado.
Added in version 3.10.
int PyGC_IsEnabled(void)
Part of the Stable ABI since version 3.10. Consulta el estado del recolector de basura: similar a gc.
isenabled(). Retorna el estado actual, 0 para deshabilitado y 1 para habilitado.
Added in version 3.10.

12.11.2 Querying Garbage Collector State

The C-API provides the following interface for querying information about the garbage collector.
void PyUnstable_GC_VisitObjects(gcvisitobjects_t callback, void *arg)

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

Run supplied callback on all live GC-capable objects. arg is passed through to all invocations of callback.

Advertencia: If new objects are (de)allocated by the callback it is undefined if they will be visited.
Garbage collection is disabled during operation. Explicitly running a collection in the callback may lead to
undefined behaviour e.g. visiting the same objects multiple times or not at all.

Added in version 3.12.


typedef int (*gcvisitobjects_t)(PyObject *object, void *arg)
Type of the visitor function to be passed to PyUnstable_GC_VisitObjects(). arg is the same as the
arg passed to PyUnstable_GC_VisitObjects. Return 0 to continue iteration, return 1 to stop iteration.
Other return values are reserved for now so behavior on returning anything else is undefined.
Added in version 3.12.

302 Capítulo 12. Soporte de implementación de objetos


CAPÍTULO 13

Versiones de API y ABI

CPython expone su número de versión en las siguientes macros. Tenga en cuenta que estos corresponden a la versión
con la que se construye el código, no necesariamente la versión utilizada en tiempo de ejecución.
Consulte Estabilidad de la API en C para obtener una discusión sobre la estabilidad de API y ABI en todas las
versiones.
PY_MAJOR_VERSION
El 3 en 3.4.1a2.
PY_MINOR_VERSION
El 4 en 3.4.1a2.
PY_MICRO_VERSION
El 1 en 3.4.1a2.
PY_RELEASE_LEVEL
La a en 3.4.1a2. Puede ser 0xA para la versión alfa, 0xB para la versión beta, 0xC para la versión candidata
o 0xF para la versión final.
PY_RELEASE_SERIAL
El 2 en 3.4.1a2, cero para lanzamientos finales.
PY_VERSION_HEX
El número de versión de Python codificado en un solo entero.
La información de la versión subyacente se puede encontrar tratándola como un número de 32 bits de la si-
guiente manera:

Bytes Bits (orden big-endian) Significado Valor para 3.4.1a2


1 1-8 PY_MAJOR_VERSION 0x03
2 9-16 PY_MINOR_VERSION 0x04
3 17-24 PY_MICRO_VERSION 0x01
4 25-28 PY_RELEASE_LEVEL 0xA
29-32 PY_RELEASE_SERIAL 0x2

Así, 3.4.1a2 es la hexadecimal 0x030401a2 y 3.10.0 es la hexadecimal 0x030a00f0.


Use this for numeric comparisons, e.g. #if PY_VERSION_HEX >= ....

303
The Python/C API, Versión 3.12.4

This version is also available via the symbol Py_Version.


const unsigned long Py_Version
Part of the Stable ABI since version 3.11. El número de versión de Python en tiempo de ejecución codificado
en un único entero constante, con el mismo formato que la macro PY_VERSION_HEX. Contiene la versión
de Python utilizada en tiempo de ejecución.
Added in version 3.11.
Todas las macros dadas se definen en Include/patchlevel.h.

304 Capítulo 13. Versiones de API y ABI


APÉNDICE A

Glosario

>>>
El prompt en el shell interactivo de Python por omisión. Frecuentemente vistos en ejemplos de código que
pueden ser ejecutados interactivamente en el intérprete.
...
Puede referirse a:
• El prompt en el shell interactivo de Python por omisión cuando se ingresa código para un bloque indentado
de código, y cuando se encuentra entre dos delimitadores que emparejan (paréntesis, corchetes, llaves o
comillas triples), o después de especificar un decorador.
• La constante incorporada Ellipsis.
2to3
Una herramienta que intenta convertir código de Python 2.x a Python 3.x arreglando la mayoría de las incom-
patibilidades que pueden ser detectadas analizando el código y recorriendo el árbol de análisis sintáctico.
2to3 está disponible en la biblioteca estándar como lib2to3; un punto de entrada independiente es provisto
como Tools/scripts/2to3. Vea 2to3-reference.
clase base abstracta
Las clases base abstractas (ABC, por sus siglas en inglés Abstract Base Class) complementan al duck-typing
brindando un forma de definir interfaces con técnicas como hasattr() que serían confusas o sutilmente
erróneas (por ejemplo con magic methods). Las ABC introduce subclases virtuales, las cuales son clases que
no heredan desde una clase pero aún así son reconocidas por isinstance() y issubclass(); vea la
documentación del módulo abc. Python viene con muchas ABC incorporadas para las estructuras de datos(
en el módulo collections.abc), números (en el módulo numbers ) , flujos de datos (en el módulo io
) , buscadores y cargadores de importaciones (en el módulo importlib.abc ) . Puede crear sus propios
ABCs con el módulo abc.
anotación
Una etiqueta asociada a una variable, atributo de clase, parámetro de función o valor de retorno, usado por
convención como un type hint.
Las anotaciones de variables no pueden ser accedidas en tiempo de ejecución, pero las anotaciones de variables
globales, atributos de clase, y funciones son almacenadas en el atributo especial __annotations__ de
módulos, clases y funciones, respectivamente.
Consulte variable annotation, function annotation, PEP 484 y PEP 526, que describen esta funcionalidad.
Consulte también annotations-howto para conocer las mejores prácticas sobre cómo trabajar con anotaciones.

305
The Python/C API, Versión 3.12.4

argumento
Un valor pasado a una function (o method) cuando se llama a la función. Hay dos clases de argumentos:
• argumento nombrado: es un argumento precedido por un identificador (por ejemplo, nombre=) en una
llamada a una función o pasado como valor en un diccionario precedido por **. Por ejemplo 3 y 5 son
argumentos nombrados en las llamadas a complex():

complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})

• argumento posicional son aquellos que no son nombrados. Los argumentos posicionales deben aparecer
al principio de una lista de argumentos o ser pasados como elementos de un iterable precedido por *. Por
ejemplo, 3 y 5 son argumentos posicionales en las siguientes llamadas:

complex(3, 5)
complex(*(3, 5))

Los argumentos son asignados a las variables locales en el cuerpo de la función. Vea en la sección calls las
reglas que rigen estas asignaciones. Sintácticamente, cualquier expresión puede ser usada para representar un
argumento; el valor evaluado es asignado a la variable local.
Vea también el parameter en el glosario, la pregunta frecuente la diferencia entre argumentos y parámetros, y
PEP 362.
administrador asincrónico de contexto
Un objeto que controla el entorno visible en un sentencia async with al definir los métodos
__aenter__() y __aexit__(). Introducido por PEP 492.
generador asincrónico
Una función que retorna un asynchronous generator iterator. Es similar a una función corrutina definida con
async def excepto que contiene expresiones yield para producir series de variables usadas en un ciclo
async for.
Usualmente se refiere a una función generadora asincrónica, pero puede referirse a un iterador generador
asincrónico en ciertos contextos. En aquellos casos en los que el significado no está claro, usar los términos
completos evita la ambigüedad.
Una función generadora asincrónica puede contener expresiones await así como sentencias async for, y
async with.
iterador generador asincrónico
Un objeto creado por una función asynchronous generator.
Este es un asynchronous iterator el cual cuando es llamado usa el método __anext__() retornando un
objeto a la espera (awaitable) el cual ejecutará el cuerpo de la función generadora asincrónica hasta la siguiente
expresión yield.
Cada yield suspende temporalmente el procesamiento, recordando el estado local de ejecución (incluyendo
a las variables locales y las sentencias try pendientes). Cuando el iterador del generador asincrónico vuelve
efectivamente con otro objeto a la espera (awaitable) retornado por el método __anext__(), retoma donde
lo dejó. Vea PEP 492 y PEP 525.
iterable asincrónico
Un objeto, que puede ser usado en una sentencia async for. Debe retornar un asynchronous iterator de su
método __aiter__(). Introducido por PEP 492.
iterador asincrónico
Un objeto que implementa los métodos __aiter__() y __anext__(). __anext__() debe retornar
un objeto awaitable. async for resuelve los esperables retornados por un método de iterador asincrónico
__anext__() hasta que lanza una excepción StopAsyncIteration. Introducido por PEP 492.
atributo
Un valor asociado a un objeto al que se suele hacer referencia por su nombre utilizando expresiones punteadas.
Por ejemplo, si un objeto o tiene un atributo a se referenciaría como o.a.

306 Apéndice A. Glosario


The Python/C API, Versión 3.12.4

Es posible dar a un objeto un atributo cuyo nombre no sea un identificador definido por identifiers, por ejemplo
usando setattr(), si el objeto lo permite. Dicho atributo no será accesible utilizando una expresión con
puntos, y en su lugar deberá ser recuperado con getattr().
a la espera
Un objeto que puede utilizarse en una expresión await. Puede ser una corutina o un objeto con un método
__await__(). Véase también PEP 492.
BDFL
Sigla de Benevolent Dictator For Life, benevolente dictador vitalicio, es decir Guido van Rossum, el creador de
Python.
archivo binario
A file object able to read and write bytes-like objects. Examples of binary files are files opened in binary
mode ('rb', 'wb' or 'rb+'), sys.stdin.buffer, sys.stdout.buffer, and instances of io.
BytesIO and gzip.GzipFile.
Vea también text file para un objeto archivo capaz de leer y escribir objetos str.
referencia prestada
En la API C de Python, una referencia prestada es una referencia a un objeto, donde el código usando el objeto
no posee la referencia. Se convierte en un puntero colgante si se destruye el objeto. Por ejemplo, una recolección
de basura puede eliminar el último strong reference del objeto y así destruirlo.
Se recomienda llamar a Py_INCREF() en la referencia prestada para convertirla en una referencia fuerte in
situ, excepto cuando el objeto no se puede destruir antes del último uso de la referencia prestada. La función
Py_NewRef() se puede utilizar para crear una nueva referencia fuerte.
objetos tipo binarios
Un objeto que soporta Protocolo búfer y puede exportar un búfer C-contiguous. Esto incluye todas los objetos
bytes, bytearray, y array.array, así como muchos objetos comunes memoryview. Los objetos
tipo binarios pueden ser usados para varias operaciones que usan datos binarios; éstas incluyen compresión,
salvar a archivos binarios, y enviarlos a través de un socket.
Algunas operaciones necesitan que los datos binarios sean mutables. La documentación frecuentemente se re-
fiere a éstos como «objetos tipo binario de lectura y escritura». Ejemplos de objetos de búfer mutables incluyen
a bytearray y memoryview de la bytearray. Otras operaciones que requieren datos binarios alma-
cenados en objetos inmutables («objetos tipo binario de sólo lectura»); ejemplos de éstos incluyen bytes y
memoryview del objeto bytes.
bytecode
El código fuente Python es compilado en bytecode, la representación interna de un programa python en el
intérprete CPython. El bytecode también es guardado en caché en los archivos .pyc de tal forma que ejecutar
el mismo archivo es más fácil la segunda vez (la recompilación desde el código fuente a bytecode puede ser
evitada). Este «lenguaje intermedio» deberá corren en una virtual machine que ejecute el código de máquina
correspondiente a cada bytecode. Note que los bytecodes no tienen como requisito trabajar en las diversas
máquina virtuales de Python, ni de ser estable entre versiones Python.
Una lista de las instrucciones en bytecode está disponible en la documentación de el módulo dis.
callable
Un callable es un objeto que puede ser llamado, posiblemente con un conjunto de argumentos (véase argument),
con la siguiente sintaxis:

callable(argument1, argument2, argumentN)

Una function, y por extensión un method, es un callable. Una instancia de una clase que implementa el método
__call__() también es un callable.
retrollamada
Una función de subrutina que se pasa como un argumento para ejecutarse en algún momento en el futuro.
clase
Una plantilla para crear objetos definidos por el usuario. Las definiciones de clase normalmente contienen
definiciones de métodos que operan una instancia de la clase.

307
The Python/C API, Versión 3.12.4

variable de clase
Una variable definida en una clase y prevista para ser modificada sólo a nivel de clase (es decir, no en una
instancia de la clase).
número complejo
Una extensión del sistema familiar de número reales en el cual los números son expresados como la suma
de una parte real y una parte imaginaria. Los números imaginarios son múltiplos de la unidad imaginaria (la
raíz cuadrada de -1), usualmente escrita como i en matemáticas o j en ingeniería. Python tiene soporte
incorporado para números complejos, los cuales son escritos con la notación mencionada al final.; la parte
imaginaria es escrita con un sufijo j, por ejemplo, 3+1j. Para tener acceso a los equivalentes complejos del
módulo math module, use cmath. El uso de números complejos es matemática bastante avanzada. Si no le
parecen necesarios, puede ignorarlos sin inconvenientes.
administrador de contextos
An object which controls the environment seen in a with statement by defining __enter__() and
__exit__() methods. See PEP 343.
variable de contexto
Una variable que puede tener diferentes valores dependiendo del contexto. Esto es similar a un almacenamiento
de hilo local Thread-Local Storage en el cual cada hilo de ejecución puede tener valores diferentes para una
variable. Sin embargo, con las variables de contexto, podría haber varios contextos en un hilo de ejecución
y el uso principal de las variables de contexto es mantener registro de las variables en tareas concurrentes
asíncronas. Vea contextvars.
contiguo
Un búfer es considerado contiguo con precisión si es C-contiguo o Fortran contiguo. Los búferes cero dimensio-
nales con C y Fortran contiguos. En los arreglos unidimensionales, los ítems deben ser dispuestos en memoria
uno siguiente al otro, ordenados por índices que comienzan en cero. En arreglos unidimensionales C-contiguos,
el último índice varía más velozmente en el orden de las direcciones de memoria. Sin embargo, en arreglos
Fortran contiguos, el primer índice vería más rápidamente.
corrutina
Las corrutinas son una forma más generalizadas de las subrutinas. A las subrutinas se ingresa por un punto y se
sale por otro punto. Las corrutinas pueden se iniciadas, finalizadas y reanudadas en muchos puntos diferentes.
Pueden ser implementadas con la sentencia async def. Vea además PEP 492.
función corrutina
Un función que retorna un objeto coroutine . Una función corrutina puede ser definida con la sentencia async
def, y puede contener las palabras claves await, async for, y async with. Las mismas son introdu-
cidas en PEP 492.
CPython
La implementación canónica del lenguaje de programación Python, como se distribuye en python.org. El tér-
mino «CPython» es usado cuando es necesario distinguir esta implementación de otras como Jython o IronPyt-
hon.
decorador
Una función que retorna otra función, usualmente aplicada como una función de transformación empleando la
sintaxis @envoltorio. Ejemplos comunes de decoradores son classmethod() y staticmethod().
La sintaxis del decorador es meramente azúcar sintáctico, las definiciones de las siguientes dos funciones son
semánticamente equivalentes:

def f(arg):
...
f = staticmethod(f)

@staticmethod
def f(arg):
...

El mismo concepto existe para clases, pero son menos usadas. Vea la documentación de function definitions y
class definitions para mayor detalle sobre decoradores.

308 Apéndice A. Glosario


The Python/C API, Versión 3.12.4

descriptor
Any object which defines the methods __get__(), __set__(), or __delete__(). When a class at-
tribute is a descriptor, its special binding behavior is triggered upon attribute lookup. Normally, using a.b to
get, set or delete an attribute looks up the object named b in the class dictionary for a, but if b is a descriptor,
the respective descriptor method gets called. Understanding descriptors is a key to a deep understanding of
Python because they are the basis for many features including functions, methods, properties, class methods,
static methods, and reference to super classes.
Para obtener más información sobre los métodos de los descriptores, consulte descriptors o Guía práctica de
uso de los descriptores.
diccionario
An associative array, where arbitrary keys are mapped to values. The keys can be any object with
__hash__() and __eq__() methods. Called a hash in Perl.
comprensión de diccionarios
Una forma compacta de procesar todos o parte de los elementos en un iterable y retornar un diccionario con los
resultados. results = {n: n ** 2 for n in range(10)} genera un diccionario que contiene la
clave n asignada al valor n ** 2. Ver comprehensions.
vista de diccionario
Los objetos retornados por los métodos dict.keys(), dict.values(), y dict.items() son lla-
mados vistas de diccionarios. Proveen una vista dinámica de las entradas de un diccionario, lo que significa que
cuando el diccionario cambia, la vista refleja éstos cambios. Para forzar a la vista de diccionario a convertirse
en una lista completa, use list(dictview). Vea dict-views.
docstring
A string literal which appears as the first expression in a class, function or module. While ignored when the
suite is executed, it is recognized by the compiler and put into the __doc__ attribute of the enclosing class,
function or module. Since it is available via introspection, it is the canonical place for documentation of the
object.
tipado de pato
Un estilo de programación que no revisa el tipo del objeto para determinar si tiene la interfaz correcta; en
vez de ello, el método o atributo es simplemente llamado o usado («Si se ve como un pato y grazna como un
pato, debe ser un pato»). Enfatizando las interfaces en vez de hacerlo con los tipos específicos, un código bien
diseñado pues tener mayor flexibilidad permitiendo la sustitución polimórfica. El tipado de pato duck-typing
evita usar pruebas llamando a type() o isinstance(). (Nota: si embargo, el tipado de pato puede ser
complementado con abstract base classes. En su lugar, generalmente pregunta con hasattr() o EAFP.
EAFP
Del inglés Easier to ask for forgiveness than permission, es más fácil pedir perdón que pedir permiso. Este estilo
de codificación común en Python asume la existencia de claves o atributos válidos y atrapa las excepciones si esta
suposición resulta falsa. Este estilo rápido y limpio está caracterizado por muchas sentencias try y except.
Esta técnica contrasta con estilo LBYL usual en otros lenguajes como C.
expresión
Una construcción sintáctica que puede ser evaluada, hasta dar un valor. En otras palabras, una expresión es
una acumulación de elementos de expresión tales como literales, nombres, accesos a atributos, operadores
o llamadas a funciones, todos ellos retornando valor. A diferencia de otros lenguajes, no toda la sintaxis del
lenguaje son expresiones. También hay statements que no pueden ser usadas como expresiones, como la while.
Las asignaciones también son sentencias, no expresiones.
módulo de extensión
Un módulo escrito en C o C++, usando la API para C de Python para interactuar con el núcleo y el código del
usuario.
f-string
Son llamadas f-strings las cadenas literales que usan el prefijo 'f' o 'F', que es una abreviatura para formatted
string literals. Vea también PEP 498.
objeto archivo
An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resour-
ce. Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type

309
The Python/C API, Versión 3.12.4

of storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes,
etc.). File objects are also called file-like objects or streams.
Existen tres categorías de objetos archivo: crudos raw archivos binarios, con búfer archivos binarios y archivos
de texto. Sus interfaces son definidas en el módulo io. La forma canónica de crear objetos archivo es usando
la función open().
objetos tipo archivo
Un sinónimo de file object.
codificación del sistema de archivos y manejador de errores
Controlador de errores y codificación utilizado por Python para decodificar bytes del sistema operativo y co-
dificar Unicode en el sistema operativo.
La codificación del sistema de archivos debe garantizar la decodificación exitosa de todos los bytes por debajo
de 128. Si la codificación del sistema de archivos no proporciona esta garantía, las funciones de API pueden
lanzar UnicodeError.
Las funciones sys.getfilesystemencoding() y sys.getfilesystemencodeerrors() se
pueden utilizar para obtener la codificación del sistema de archivos y el controlador de errores.
La codificación del sistema de archivos y el manejador de errores se configuran al inicio de Pyt-
hon mediante la función PyConfig_Read(): consulte los miembros filesystem_encoding y
filesystem_errors de PyConfig.
Vea también locale encoding.
buscador
Un objeto que trata de encontrar el loader para el módulo que está siendo importado.
There are two types of finder: meta path finders for use with sys.meta_path, and path entry finders for
use with sys.path_hooks.
See importsystem and importlib for much more detail.
división entera a la baja
Una división matemática que se redondea hacia el entero menor más cercano. El operador de la división entera
a la baja es //. Por ejemplo, la expresión 11 // 4 evalúa 2 a diferencia del 2.75 retornado por la verdadera
división de números flotantes. Note que (-11) // 4 es -3 porque es -2.75 redondeado para abajo. Ver
PEP 238.
función
Una serie de sentencias que retornan un valor al que las llama. También se le puede pasar cero o más argumentos
los cuales pueden ser usados en la ejecución de la misma. Vea también parameter, method, y la sección function.
anotación de función
Una annotation del parámetro de una función o un valor de retorno.
Las anotaciones de funciones son usadas frecuentemente para indicadores de tipo, por ejemplo, se espera que
una función tome dos argumentos de clase int y también se espera que retorne dos valores int:

def sum_two_numbers(a: int, b: int) -> int:


return a + b

La sintaxis de las anotaciones de funciones son explicadas en la sección function.


Consulte variable annotation y PEP 484, que describen esta funcionalidad. Consulte también annotations-
howto para conocer las mejores prácticas sobre cómo trabajar con anotaciones.
__future__
Un future statement, from __future__ import <feature>, indica al compilador que compile el
módulo actual utilizando una sintaxis o semántica que se convertirá en estándar en una versión futura de Pyt-
hon. El módulo __future__ documenta los posibles valores de feature. Al importar este módulo y evaluar
sus variables, puede ver cuándo se agregó por primera vez una nueva característica al lenguaje y cuándo se
convertirá (o se convirtió) en la predeterminada:

310 Apéndice A. Glosario


The Python/C API, Versión 3.12.4

>>> import __future__


>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

recolección de basura
El proceso de liberar la memoria de lo que ya no está en uso. Python realiza recolección de basura (garbage
collection) llevando la cuenta de las referencias, y el recogedor de basura cíclico es capaz de detectar y romper
las referencias cíclicas. El recogedor de basura puede ser controlado mediante el módulo gc .
generador
Una función que retorna un generator iterator. Luce como una función normal excepto que contiene la expresión
yield para producir series de valores utilizables en un bucle for o que pueden ser obtenidas una por una con
la función next().
Usualmente se refiere a una función generadora, pero puede referirse a un iterador generador en ciertos contex-
tos. En aquellos casos en los que el significado no está claro, usar los términos completos evita la ambigüedad.
iterador generador
Un objeto creado por una función generator.
Cada yield suspende temporalmente el procesamiento, recordando el estado de ejecución local (incluyendo
las variables locales y las sentencias try pendientes). Cuando el «iterador generado» vuelve, retoma donde ha
dejado, a diferencia de lo que ocurre con las funciones que comienzan nuevamente con cada invocación.
expresión generadora
Una expresión que retorna un iterador. Luce como una expresión normal seguida por la cláusula for definiendo
así una variable de bucle, un rango y una cláusula opcional if. La expresión combinada genera valores para la
función contenedora:

>>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81


285

función genérica
Una función compuesta de muchas funciones que implementan la misma operación para diferentes tipos. Qué
implementación deberá ser usada durante la llamada a la misma es determinado por el algoritmo de despacho.
Vea también la entrada de glosario single dispatch, el decorador functools.singledispatch(), y
PEP 443.
tipos genéricos
Un type que se puede parametrizar; normalmente un container class como list o dict. Usado para type
hints y annotations.
Para más detalles, véase generic alias types, PEP 483, PEP 484, PEP 585, y el módulo typing.
GIL
Vea global interpreter lock.
bloqueo global del intérprete
Mecanismo empleado por el intérprete CPython para asegurar que sólo un hilo ejecute el bytecode Python por
vez. Esto simplifica la implementación de CPython haciendo que el modelo de objetos (incluyendo algunos
críticos como dict) están implícitamente a salvo de acceso concurrente. Bloqueando el intérprete completo
se simplifica hacerlo multi-hilos, a costa de mucho del paralelismo ofrecido por las máquinas con múltiples
procesadores.
Sin embargo, algunos módulos de extensión, tanto estándar como de terceros, están diseñados para liberar el
GIL cuando se realizan tareas computacionalmente intensivas como la compresión o el hashing. Además, el
GIL siempre es liberado cuando se hace entrada/salida.
Esfuerzos previos hechos para crear un intérprete «sin hilos» (uno que bloquee los datos compartidos con una
granularidad mucho más fina) no han sido exitosos debido a que el rendimiento sufrió para el caso más común
de un solo procesador. Se cree que superar este problema de rendimiento haría la implementación mucho más
compleja y por tanto, más costosa de mantener.

311
The Python/C API, Versión 3.12.4

hash-based pyc
Un archivo cache de bytecode que usa el hash en vez de usar el tiempo de la última modificación del archivo
fuente correspondiente para determinar su validez. Vea pyc-invalidation.
hashable
An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__()
method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which
compare equal must have the same hash value.
Ser hashable hace a un objeto utilizable como clave de un diccionario y miembro de un set, porque éstas
estructuras de datos usan los valores de hash internamente.
La mayoría de los objetos inmutables incorporados en Python son hashables; los contenedores mutables (como
las listas o los diccionarios) no lo son; los contenedores inmutables (como tuplas y conjuntos frozensets) son
hashables si sus elementos son hashables . Los objetos que son instancias de clases definidas por el usuario son
hashables por defecto. Todos se comparan como desiguales (excepto consigo mismos), y su valor de hash está
derivado de su función id().
IDLE
Un Entorno Integrado de Desarrollo y Aprendizaje para Python. idle es un editor básico y un entorno de
intérprete que se incluye con la distribución estándar de Python.
inmutable
Un objeto con un valor fijo. Los objetos inmutables son números, cadenas y tuplas. Éstos objetos no pueden ser
alterados. Un nuevo objeto debe ser creado si un valor diferente ha de ser guardado. Juegan un rol importante
en lugares donde es necesario un valor de hash constante, por ejemplo como claves de un diccionario.
ruta de importación
Una lista de las ubicaciones (o entradas de ruta) que son revisadas por path based finder al importar módulos.
Durante la importación, ésta lista de localizaciones usualmente viene de sys.path, pero para los subpaquetes
también puede incluir al atributo __path__ del paquete padre.
importar
El proceso mediante el cual el código Python dentro de un módulo se hace alcanzable desde otro código Python
en otro módulo.
importador
Un objeto que buscan y lee un módulo; un objeto que es tanto finder como loader.
interactivo
Python tiene un intérprete interactivo, lo que significa que puede ingresar sentencias y expresiones en el prompt
del intérprete, ejecutarlos de inmediato y ver sus resultados. Sólo ejecute python sin argumentos (podría
seleccionarlo desde el menú principal de su computadora). Es una forma muy potente de probar nuevas ideas
o inspeccionar módulos y paquetes (recuerde help(x)).
interpretado
Python es un lenguaje interpretado, a diferencia de uno compilado, a pesar de que la distinción puede ser
difusa debido al compilador a bytecode. Esto significa que los archivos fuente pueden ser corridos directamente,
sin crear explícitamente un ejecutable que es corrido luego. Los lenguajes interpretados típicamente tienen
ciclos de desarrollo y depuración más cortos que los compilados, sin embargo sus programas suelen correr más
lentamente. Vea también interactive.
apagado del intérprete
Cuando se le solicita apagarse, el intérprete Python ingresa a un fase especial en la cual gradualmente libera to-
dos los recursos reservados, como módulos y varias estructuras internas críticas. También hace varias llamadas
al recolector de basura. Esto puede disparar la ejecución de código de destructores definidos por el usuario o
weakref callbacks. El código ejecutado durante la fase de apagado puede encontrar varias excepciones debido
a que los recursos que necesita pueden no funcionar más (ejemplos comunes son los módulos de bibliotecas o
los artefactos de advertencias warnings machinery)
La principal razón para el apagado del intérpreter es que el módulo __main__ o el script que estaba corriendo
termine su ejecución.

312 Apéndice A. Glosario


The Python/C API, Versión 3.12.4

iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such
as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes
you define with an __iter__() method or with a __getitem__() method that implements sequence
semantics.
Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(),
…). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator
for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not
necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for
you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator,
sequence, and generator.
iterador
An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing
it to the built-in function next()) return successive items in the stream. When no more data are available
a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any furt-
her calls to its __next__() method just raise StopIteration again. Iterators are required to have an
__iter__() method that returns the iterator object itself so every iterator is also iterable and may be used
in most places where other iterables are accepted. One notable exception is code which attempts multiple ite-
ration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the
iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted
iterator object used in the previous iteration pass, making it appear like an empty container.
Puede encontrar más información en typeiter.
Detalles de implementación de CPython: CPython does not consistently apply the requirement that an ite-
rator define __iter__().
función clave
Una función clave o una función de colación es un invocable que retorna un valor usado para el ordenamiento
o clasificación. Por ejemplo, locale.strxfrm() es usada para producir claves de ordenamiento que se
adaptan a las convenciones específicas de ordenamiento de un locale.
Cierta cantidad de herramientas de Python aceptan funciones clave para controlar como los elementos son
ordenados o agrupados. Incluyendo a min(), max(), sorted(), list.sort(), heapq.merge(),
heapq.nsmallest(), heapq.nlargest(), y itertools.groupby().
Hay varias formas de crear una función clave. Por ejemplo, el método str.lower() puede servir como
función clave para ordenamientos que no distingan mayúsculas de minúsculas. Como alternativa, una fun-
ción clave puede ser realizada con una expresión lambda como lambda r: (r[0], r[2]). Ade-
más, operator.attrgetter(), operator.itemgetter() y operator.methodcaller()
son tres constructores de funciones clave. Consulte Sorting HOW TO para ver ejemplos de cómo crear y utilizar
funciones clave.
argumento nombrado
Vea argument.
lambda
Una función anónima de una línea consistente en un sola expression que es evaluada cuando la función es
llamada. La sintaxis para crear una función lambda es lambda [parameters]: expression
LBYL
Del inglés Look before you leap, «mira antes de saltar». Es un estilo de codificación que prueba explícitamente
las condiciones previas antes de hacer llamadas o búsquedas. Este estilo contrasta con la manera EAFP y está
caracterizado por la presencia de muchas sentencias if.
En entornos multi-hilos, el método LBYL tiene el riesgo de introducir condiciones de carrera entre los hilos
que están «mirando» y los que están «saltando». Por ejemplo, el código, if key in mapping: return
mapping[key] puede fallar si otro hilo remueve key de mapping después del test, pero antes de retornar el
valor. Este problema puede ser resuelto usando bloqueos o empleando el método EAFP.
lista
A built-in Python sequence. Despite its name it is more akin to an array in other languages than to a linked list

313
The Python/C API, Versión 3.12.4

since access to elements is O(1).


comprensión de listas
Una forma compacta de procesar todos o parte de los elementos en una secuencia y retornar una lis-
ta como resultado. result = ['{:#04x}'.format(x) for x in range(256) if x % 2
== 0] genera una lista de cadenas conteniendo números hexadecimales (0x..) entre 0 y 255. La cláusula
if es opcional. Si es omitida, todos los elementos en range(256) son procesados.
cargador
Un objeto que carga un módulo. Debe definir el método llamado load_module(). Un cargador es normal-
mente retornados por un finder. Vea PEP 302 para detalles y importlib.abc.Loader para una abstract
base class.
codificación de la configuración regional
En Unix, es la codificación de la configuración regional LC_CTYPE. Se puede configurar con locale.
setlocale(locale.LC_CTYPE, new_locale).
En Windows, es la página de códigos ANSI (por ejemplo, "cp1252").
En Android y VxWorks, Python utiliza "utf-8" como codificación regional.
locale.getencoding() can be used to get the locale encoding.
Vea también filesystem encoding and error handler.
método mágico
Una manera informal de llamar a un special method.
mapeado
Un objeto contenedor que permite recupero de claves arbitrarias y que implementa los métodos espe-
cificados en la collections.abc.Mapping o collections.abc.MutableMapping abstract
base classes. Por ejemplo, dict, collections.defaultdict, collections.OrderedDict y
collections.Counter.
meta buscadores de ruta
Un finder retornado por una búsqueda de sys.meta_path. Los meta buscadores de ruta están relacionados
a buscadores de entradas de rutas, pero son algo diferente.
Vea en importlib.abc.MetaPathFinder los métodos que los meta buscadores de ruta implementan.
metaclase
La clase de una clase. Las definiciones de clases crean nombres de clase, un diccionario de clase, y una lista de
clases base. Las metaclases son responsables de tomar estos tres argumentos y crear la clase. La mayoría de los
objetos de un lenguaje de programación orientado a objetos provienen de una implementación por defecto. Lo
que hace a Python especial que es posible crear metaclases a medida. La mayoría de los usuario nunca necesi-
tarán esta herramienta, pero cuando la necesidad surge, las metaclases pueden brindar soluciones poderosas y
elegantes. Han sido usadas para loggear acceso de atributos, agregar seguridad a hilos, rastrear la creación de
objetos, implementar singletons, y muchas otras tareas.
Más información hallará en metaclasses.
método
Una función que es definida dentro del cuerpo de una clase. Si es llamada como un atributo de una instancia de
otra clase, el método tomará el objeto instanciado como su primer argument (el cual es usualmente denominado
self). Vea function y nested scope.
orden de resolución de métodos
Method Resolution Order is the order in which base classes are searched for a member during lookup. See
python_2.3_mro for details of the algorithm used by the Python interpreter since the 2.3 release.
módulo
Un objeto que sirve como unidad de organización del código Python. Los módulos tienen espacios de nombres
conteniendo objetos Python arbitrarios. Los módulos son cargados en Python por el proceso de importing.
Vea también package.

314 Apéndice A. Glosario


The Python/C API, Versión 3.12.4

especificador de módulo
Un espacio de nombres que contiene la información relacionada a la importación usada al leer un módulo. Una
instancia de importlib.machinery.ModuleSpec.
MRO
Vea method resolution order.
mutable
Los objetos mutables pueden cambiar su valor pero mantener su id(). Vea también immutable.
tupla nombrada
La denominación «tupla nombrada» se aplica a cualquier tipo o clase que hereda de una tupla y cuyos elementos
indexables son también accesibles usando atributos nombrados. Este tipo o clase puede tener además otras
capacidades.
Varios tipos incorporados son tuplas nombradas, incluyendo los valores retornados por time.localtime()
y os.stat(). Otro ejemplo es sys.float_info:

>>> sys.float_info[1] # indexed access


1024
>>> sys.float_info.max_exp # named field access
1024
>>> isinstance(sys.float_info, tuple) # kind of tuple
True

Some named tuples are built-in types (such as the above examples). Alternatively, a named tuple can be created
from a regular class definition that inherits from tuple and that defines named fields. Such a class can be
written by hand, or it can be created by inheriting typing.NamedTuple, or with the factory function
collections.namedtuple(). The latter techniques also add some extra methods that may not be found
in hand-written or built-in named tuples.
espacio de nombres
El lugar donde la variable es almacenada. Los espacios de nombres son implementados como diccionarios. Hay
espacio de nombre local, global, e incorporado así como espacios de nombres anidados en objetos (en méto-
dos). Los espacios de nombres soportan modularidad previniendo conflictos de nombramiento. Por ejemplo,
las funciones builtins.open y os.open() se distinguen por su espacio de nombres. Los espacios de
nombres también ayuda a la legibilidad y mantenibilidad dejando claro qué módulo implementa una función.
Por ejemplo, escribiendo random.seed() o itertools.islice() queda claro que éstas funciones
están implementadas en los módulos random y itertools, respectivamente.
paquete de espacios de nombres
Un PEP 420 package que sirve sólo para contener subpaquetes. Los paquetes de espacios de nombres pueden
no tener representación física, y específicamente se diferencian de los regular package porque no tienen un
archivo __init__.py.
Vea también module.
alcances anidados
La habilidad de referirse a una variable dentro de una definición encerrada. Por ejemplo, una función definida
dentro de otra función puede referir a variables en la función externa. Note que los alcances anidados por defecto
sólo funcionan para referencia y no para asignación. Las variables locales leen y escriben sólo en el alcance más
interno. De manera semejante, las variables globales pueden leer y escribir en el espacio de nombres global.
Con nonlocal se puede escribir en alcances exteriores.
clase de nuevo estilo
Old name for the flavor of classes now used for all class objects. In earlier Python versions, only
new-style classes could use Python’s newer, versatile features like __slots__, descriptors, properties,
__getattribute__(), class methods, and static methods.
objeto
Cualquier dato con estado (atributo o valor) y comportamiento definido (métodos). También es la más básica
clase base para cualquier new-style class.

315
The Python/C API, Versión 3.12.4

paquete
Un module Python que puede contener submódulos o recursivamente, subpaquetes. Técnicamente, un paquete
es un módulo Python con un atributo __path__.
Vea también regular package y namespace package.
parámetro
Una entidad nombrada en una definición de una function (o método) que especifica un argument (o en algunos
casos, varios argumentos) que la función puede aceptar. Existen cinco tipos de argumentos:
• posicional o nombrado: especifica un argumento que puede ser pasado tanto como posicional o como
nombrado. Este es el tipo por defecto de parámetro, como foo y bar en el siguiente ejemplo:

def func(foo, bar=None): ...

• sólo posicional: especifica un argumento que puede ser pasado sólo por posición. Los parámetros sólo
posicionales pueden ser definidos incluyendo un carácter / en la lista de parámetros de la función después
de ellos, como posonly1 y posonly2 en el ejemplo que sigue:

def func(posonly1, posonly2, /, positional_or_keyword): ...

• sólo nombrado: especifica un argumento que sólo puede ser pasado por nombre. Los parámetros sólo por
nombre pueden ser definidos incluyendo un parámetro posicional de una sola variable o un simple *`
antes de ellos en la lista de parámetros en la definición de la función, como kw_only1 y kw_only2 en el
ejemplo siguiente:

def func(arg, *, kw_only1, kw_only2): ...

• variable posicional: especifica una secuencia arbitraria de argumentos posicionales que pueden ser brin-
dados (además de cualquier argumento posicional aceptado por otros parámetros). Este parámetro puede
ser definido anteponiendo al nombre del parámetro *, como a args en el siguiente ejemplo:

def func(*args, **kwargs): ...

• variable nombrado: especifica que arbitrariamente muchos argumentos nombrados pueden ser brindados
(además de cualquier argumento nombrado ya aceptado por cualquier otro parámetro). Este parámetro
puede ser definido anteponiendo al nombre del parámetro con **, como kwargs en el ejemplo precedente.
Los parámetros puede especificar tanto argumentos opcionales como requeridos, así como valores por defecto
para algunos argumentos opcionales.
Vea también el glosario de argument, la pregunta respondida en la diferencia entre argumentos y parámetros,
la clase inspect.Parameter, la sección function , y PEP 362.
entrada de ruta
Una ubicación única en el import path que el path based finder consulta para encontrar los módulos a importar.
buscador de entradas de ruta
Un finder retornado por un invocable en sys.path_hooks (esto es, un path entry hook) que sabe cómo
localizar módulos dada una path entry.
Vea en importlib.abc.PathEntryFinder los métodos que los buscadores de entradas de ruta im-
plementan.
gancho a entrada de ruta
A callable on the sys.path_hooks list which returns a path entry finder if it knows how to find modules
on a specific path entry.
buscador basado en ruta
Uno de los meta buscadores de ruta por defecto que busca un import path para los módulos.
objeto tipo ruta
Un objeto que representa una ruta del sistema de archivos. Un objeto tipo ruta puede ser tanto una str como
un bytes representando una ruta, o un objeto que implementa el protocolo os.PathLike. Un objeto que
soporta el protocolo os.PathLike puede ser convertido a ruta del sistema de archivo de clase str o bytes

316 Apéndice A. Glosario


The Python/C API, Versión 3.12.4

usando la función os.fspath(); os.fsdecode() os.fsencode() pueden emplearse para garantizar


que retorne respectivamente str o bytes. Introducido por PEP 519.
PEP
Propuesta de mejora de Python, del inglés Python Enhancement Proposal. Un PEP es un documento de diseño
que brinda información a la comunidad Python, o describe una nueva capacidad para Python, sus procesos o
entorno. Los PEPs deberían dar una especificación técnica concisa y una fundamentación para las capacidades
propuestas.
Los PEPs tienen como propósito ser los mecanismos primarios para proponer nuevas y mayores capacidad,
para recoger la opinión de la comunidad sobre un tema, y para documentar las decisiones de diseño que se han
hecho en Python. El autor del PEP es el responsable de lograr consenso con la comunidad y documentar las
opiniones disidentes.
Vea PEP 1.
porción
Un conjunto de archivos en un único directorio (posiblemente guardo en un archivo comprimido zip) que
contribuye a un espacio de nombres de paquete, como está definido en PEP 420.
argumento posicional
Vea argument.
API provisional
Una API provisoria es aquella que deliberadamente fue excluida de las garantías de compatibilidad hacia atrás
de la biblioteca estándar. Aunque no se esperan cambios fundamentales en dichas interfaces, como están mar-
cadas como provisionales, los cambios incompatibles hacia atrás (incluso remover la misma interfaz) podrían
ocurrir si los desarrolladores principales lo estiman. Estos cambios no se hacen gratuitamente – solo ocurrirán
si fallas fundamentales y serias son descubiertas que no fueron vistas antes de la inclusión de la API.
Incluso para APIs provisorias, los cambios incompatibles hacia atrás son vistos como una «solución de último
recurso» - se intentará todo para encontrar una solución compatible hacia atrás para los problemas identificados.
Este proceso permite que la biblioteca estándar continúe evolucionando con el tiempo, sin bloquearse por
errores de diseño problemáticos por períodos extensos de tiempo. Vea PEP 411 para más detalles.
paquete provisorio
Vea provisional API.
Python 3000
Apodo para la fecha de lanzamiento de Python 3.x (acuñada en un tiempo cuando llegar a la versión 3 era algo
distante en el futuro.) También se lo abrevió como Py3k.
Pythónico
Una idea o pieza de código que sigue ajustadamente la convenciones idiomáticas comunes del lenguaje Python,
en vez de implementar código usando conceptos comunes a otros lenguajes. Por ejemplo, una convención
común en Python es hacer bucles sobre todos los elementos de un iterable con la sentencia for. Muchos otros
lenguajes no tienen este tipo de construcción, así que los que no están familiarizados con Python podrían usar
contadores numéricos:

for i in range(len(food)):
print(food[i])

En contraste, un método Pythónico más limpio:

for piece in food:


print(piece)

nombre calificado
Un nombre con puntos mostrando la ruta desde el alcance global del módulo a la clase, función o método
definido en dicho módulo, como se define en PEP 3155. Para las funciones o clases de más alto nivel, el
nombre calificado es el igual al nombre del objeto:

317
The Python/C API, Versión 3.12.4

>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'

Cuando es usado para referirse a los módulos, nombre completamente calificado significa la ruta con puntos
completo al módulo, incluyendo cualquier paquete padre, por ejemplo, email.mime.text:

>>> import email.mime.text


>>> email.mime.text.__name__
'email.mime.text'

contador de referencias
El número de referencias a un objeto. Cuando el contador de referencias de un objeto cae hasta cero, éste se
desaloja. Algunos objetos son «inmortales» y tienen recuentos de referencias que nunca se modifican, y por
lo tanto los objetos nunca son desalojan. El conteo de referencias generalmente no es visible para el código
Python, pero es un elemento clave de la implementación de CPython. Los programadores pueden llamar a la
función sys.getrefcount() para obtener el número de referencias de un objeto concreto.
paquete regular
Un package tradicional, como aquellos con un directorio conteniendo el archivo __init__.py.
Vea también namespace package.
__slots__
Es una declaración dentro de una clase que ahorra memoria predeclarando espacio para las atributos de la
instancia y eliminando diccionarios de la instancia. Aunque es popular, esta técnica es algo dificultosa de lograr
correctamente y es mejor reservarla para los casos raros en los que existen grandes cantidades de instancias en
aplicaciones con uso crítico de memoria.
secuencia
An iterable which supports efficient element access using integer indices via the __getitem__() spe-
cial method and defines a __len__() method that returns the length of the sequence. Some built-in se-
quence types are list, str, tuple, and bytes. Note that dict also supports __getitem__() and
__len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary immutable
keys rather than integers.
The collections.abc.Sequence abstract base class defines a much richer interface that goes be-
yond just __getitem__() and __len__(), adding count(), index(), __contains__(), and
__reversed__(). Types that implement this expanded interface can be registered explicitly using
register(). For more documentation on sequence methods generally, see Common Sequence Operations.
comprensión de conjuntos
Una forma compacta de procesar todos o parte de los elementos en un iterable y retornar un conjunto con los
resultados. results = {c for c in 'abracadabra' if c not in 'abc'} genera el con-
junto de cadenas {'r', 'd'}. Ver comprehensions.
despacho único
Una forma de despacho de una generic function donde la implementación es elegida a partir del tipo de un sólo
argumento.
rebanada
Un objeto que contiene una porción de una sequence. Una rebanada es creada usando la notación de suscripto,
[] con dos puntos entre los números cuando se ponen varios, como en nombre_variable[1:3:5]. La
notación con corchete (suscrito) usa internamente objetos slice.

318 Apéndice A. Glosario


The Python/C API, Versión 3.12.4

método especial
Un método que es llamado implícitamente por Python cuando ejecuta ciertas operaciones en un tipo, como la
adición. Estos métodos tienen nombres que comienzan y terminan con doble barra baja. Los métodos especiales
están documentados en specialnames.
sentencia
Una sentencia es parte de un conjunto (un «bloque» de código). Una sentencia tanto es una expression como
alguna de las varias sintaxis usando una palabra clave, como if, while o for.
static type checker
An external tool that reads Python code and analyzes it, looking for issues such as incorrect types. See also type
hints and the typing module.
referencia fuerte
En la API de C de Python, una referencia fuerte es una referencia a un objeto que es propiedad del código que
mantiene la referencia. La referencia fuerte se toma llamando a Py_INCREF() cuando se crea la referencia
y se libera con Py_DECREF() cuando se elimina la referencia.
La función Py_NewRef() se puede utilizar para crear una referencia fuerte a un objeto. Por lo general, se
debe llamar a la función Py_DECREF() en la referencia fuerte antes de salir del alcance de la referencia
fuerte, para evitar filtrar una referencia.
Consulte también borrowed reference.
codificación de texto
Una cadena de caracteres en Python es una secuencia de puntos de código Unicode (en el rango U+0000–
U+10FFFF). Para almacenar o transferir una cadena de caracteres, es necesario serializarla como una secuen-
cia de bytes.
La serialización de una cadena de caracteres en una secuencia de bytes se conoce como «codificación», y la
recreación de la cadena de caracteres a partir de la secuencia de bytes se conoce como «decodificación».
Existe una gran variedad de serializaciones de texto codecs, que se denominan colectivamente «codificaciones
de texto».
archivo de texto
Un file object capaz de leer y escribir objetos str. Frecuentemente, un archivo de texto también accede a
un flujo de datos binario y maneja automáticamente el text encoding. Ejemplos de archivos de texto que son
abiertos en modo texto ('r' o 'w'), sys.stdin, sys.stdout, y las instancias de io.StringIO.
Vea también binary file por objeto de archivos capaces de leer y escribir objeto tipo binario.
cadena con triple comilla
Una cadena que está enmarcada por tres instancias de comillas (») o apostrofes (“). Aunque no brindan nin-
guna funcionalidad que no está disponible usando cadenas con comillas simple, son útiles por varias razones.
Permiten incluir comillas simples o dobles sin escapar dentro de las cadenas y pueden abarcar múltiples líneas
sin el uso de caracteres de continuación, haciéndolas particularmente útiles para escribir docstrings.
tipo
El tipo de un objeto Python determina qué tipo de objeto es; cada objeto tiene un tipo. El tipo de un objeto
puede ser accedido por su atributo __class__ o puede ser conseguido usando type(obj).
alias de tipos
Un sinónimo para un tipo, creado al asignar un tipo a un identificador.
Los alias de tipos son útiles para simplificar los indicadores de tipo. Por ejemplo:

def remove_gray_shades(
colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass

podría ser más legible así:

Color = tuple[int, int, int]

(continúe en la próxima página)

319
The Python/C API, Versión 3.12.4

(proviene de la página anterior)


def remove_gray_shades(colors: list[Color]) -> list[Color]:
pass

Vea typing y PEP 484, que describen esta funcionalidad.


indicador de tipo
Una annotation que especifica el tipo esperado para una variable, un atributo de clase, un parámetro para una
función o un valor de retorno.
Type hints are optional and are not enforced by Python but they are useful to static type checkers. They can also
aid IDEs with code completion and refactoring.
Los indicadores de tipo de las variables globales, atributos de clase, y funciones, no de variables locales, pueden
ser accedidos usando typing.get_type_hints().
Vea typing y PEP 484, que describen esta funcionalidad.
saltos de líneas universales
Una manera de interpretar flujos de texto en la cual son reconocidos como finales de línea todas siguientes
formas: la convención de Unix para fin de línea '\n', la convención de Windows '\r\n', y la vieja con-
vención de Macintosh '\r'. Vea PEP 278 y PEP 3116, además de bytes.splitlines() para usos
adicionales.
anotación de variable
Una annotation de una variable o un atributo de clase.
Cuando se anota una variable o un atributo de clase, la asignación es opcional:

class C:
field: 'annotation'

Las anotaciones de variables son frecuentemente usadas para type hints: por ejemplo, se espera que esta variable
tenga valores de clase int:

count: int = 0

La sintaxis de la anotación de variables está explicada en la sección annassign.


Consulte function annotation, PEP 484 y PEP 526, que describen esta funcionalidad. Consulte también
annotations-howto para conocer las mejores prácticas sobre cómo trabajar con anotaciones.
entorno virtual
Un entorno cooperativamente aislado de ejecución que permite a los usuarios de Python y a las aplicaciones ins-
talar y actualizar paquetes de distribución de Python sin interferir con el comportamiento de otras aplicaciones
de Python en el mismo sistema.
Vea también venv.
máquina virtual
Una computadora definida enteramente por software. La máquina virtual de Python ejecuta el bytecode gene-
rado por el compilador de bytecode.
Zen de Python
Un listado de los principios de diseño y la filosofía de Python que son útiles para entender y usar el lenguaje.
El listado puede encontrarse ingresando «import this» en la consola interactiva.

320 Apéndice A. Glosario


APÉNDICE B

Acerca de estos documentos

Estos documentos son generados por reStructuredText desarrollado por Sphinx, un procesador de documentos espe-
cíficamente escrito para la documentación de Python.
El desarrollo de la documentación y su cadena de herramientas es un esfuerzo enteramente voluntario, al igual que
Python. Si tu quieres contribuir, por favor revisa la página reporting-bugs para más información de cómo hacerlo.
Los nuevos voluntarios son siempre bienvenidos!
Agradecemos a:
• Fred L. Drake, Jr., el creador original de la documentación del conjunto de herramientas de Python y escritor
de gran parte del contenido;
• el proyecto Docutils para creación de reStructuredText y la suite Docutils;
• Fredrik Lundh por su proyecto Referencia Alternativa de Python del que Sphinx obtuvo muchas buenas ideas.

B.1 Contribuidores de la documentación de Python

Muchas personas han contribuido para el lenguaje de Python, la librería estándar de Python, y la documentación de
Python. Revisa Misc/ACKS la distribución de Python para una lista parcial de contribuidores.
Es solamente con la aportación y contribuciones de la comunidad de Python que Python tiene tan fantástica docu-
mentación – Muchas gracias!

321
The Python/C API, Versión 3.12.4

322 Apéndice B. Acerca de estos documentos


APÉNDICE C

Historia y Licencia

C.1 Historia del software

Python fue creado a principios de la década de 1990 por Guido van Rossum en Stichting Mathematisch Centrum
(CWI, ver https://www.cwi.nl/) en los Países Bajos como sucesor de un idioma llamado ABC. Guido sigue siendo el
autor principal de Python, aunque incluye muchas contribuciones de otros.
En 1995, Guido continuó su trabajo en Python en la Corporation for National Research Initiatives (CNRI, consulte
https://www.cnri.reston.va.us/) en Reston, Virginia, donde lanzó varias versiones del software.
En mayo de 2000, Guido y el equipo de desarrollo central de Python se trasladaron a BeOpen.com para formar el
equipo de BeOpen PythonLabs. En octubre del mismo año, el equipo de PythonLabs se trasladó a Digital Creations
(ahora Zope Corporation; consulte https://www.zope.org/). En 2001, se formó la Python Software Foundation (PSF,
consulte https://www.python.org/psf/), una organización sin fines de lucro creada específicamente para poseer la
propiedad intelectual relacionada con Python. Zope Corporation es miembro patrocinador del PSF.
Todas las versiones de Python son de código abierto (consulte https://opensource.org/ para conocer la definición de
código abierto). Históricamente, la mayoría de las versiones de Python, pero no todas, también han sido compatibles
con GPL; la siguiente tabla resume las distintas versiones.

Lanzamiento Derivado de Año Dueño/a ¿compatible con GPL?


0.9.0 hasta 1.2 n/a 1991-1995 CWI sí
1.3 hasta 1.5.2 1.2 1995-1999 CNRI sí
1.6 1.5.2 2000 CNRI no
2.0 1.6 2000 BeOpen.com no
1.6.1 1.6 2001 CNRI no
2.1 2.0+1.6.1 2001 PSF no
2.0.1 2.0+1.6.1 2001 PSF sí
2.1.1 2.1+2.0.1 2001 PSF sí
2.1.2 2.1.1 2002 PSF sí
2.1.3 2.1.2 2002 PSF sí
2.2 y superior 2.1.1 2001-ahora PSF sí

Nota: Compatible con GPL no significa que estemos distribuyendo Python bajo la GPL. Todas las licencias de
Python, a diferencia de la GPL, le permiten distribuir una versión modificada sin que los cambios sean de código

323
The Python/C API, Versión 3.12.4

abierto. Las licencias compatibles con GPL permiten combinar Python con otro software que se publica bajo la GPL;
los otros no lo hacen.

Gracias a los muchos voluntarios externos que han trabajado bajo la dirección de Guido para hacer posibles estos
lanzamientos.

C.2 Términos y condiciones para acceder o usar Python

El software y la documentación de Python están sujetos a Acuerdo de licencia de PSF.


A partir de Python 3.8.6, los ejemplos, recetas y otros códigos de la documentación tienen licencia doble según el
Acuerdo de licencia de PSF y la Licencia BSD de cláusula cero.
Parte del software incorporado en Python está bajo diferentes licencias. Las licencias se enumeran con el código
correspondiente a esa licencia. Consulte Licencias y reconocimientos para software incorporado para obtener una lista
incompleta de estas licencias.

C.2.1 ACUERDO DE LICENCIA DE PSF PARA PYTHON | lanzamiento |

1. This LICENSE AGREEMENT is between the Python Software Foundation␣


,→("PSF"), and

the Individual or Organization ("Licensee") accessing and otherwise␣


,→using Python

3.12.4 software in source or binary form and its associated␣


,→documentation.

2. Subject to the terms and conditions of this License Agreement, PSF␣


,→hereby

grants Licensee a nonexclusive, royalty-free, world-wide license to␣


,→reproduce,

analyze, test, perform and/or display publicly, prepare derivative␣


,→works,

distribute, and otherwise use Python 3.12.4 alone or in any derivative


version, provided, however, that PSF's License Agreement and PSF's␣
,→notice of

copyright, i.e., "Copyright © 2001-2023 Python Software Foundation; All␣


,→Rights

Reserved" are retained in Python 3.12.4 alone or in any derivative␣


,→version

prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or


incorporates Python 3.12.4 or any part thereof, and wants to make the
derivative work available to others as provided herein, then Licensee␣
,→hereby

agrees to include in any such work a brief summary of the changes made␣
,→to Python

3.12.4.

4. PSF is making Python 3.12.4 available to Licensee on an "AS IS" basis.


PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY␣
,→OF

EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY␣


,→REPRESENTATION OR

WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR␣


,→THAT THE

324 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.12.4

USE OF PYTHON 3.12.4 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.12.4
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A␣
,→RESULT OF

MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.12.4, OR ANY␣


,→DERIVATIVE

THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material␣


,→breach of

its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any␣


,→relationship

of agency, partnership, or joint venture between PSF and Licensee. ␣


,→This License

Agreement does not grant permission to use PSF trademarks or trade name␣
,→in a

trademark sense to endorse or promote products or services of Licensee,␣


,→or any

third party.

8. By copying, installing or otherwise using Python 3.12.4, Licensee agrees


to be bound by the terms and conditions of this License Agreement.

C.2.2 ACUERDO DE LICENCIA DE BEOPEN.COM PARA PYTHON 2.0

ACUERDO DE LICENCIA DE CÓDIGO ABIERTO DE BEOPEN PYTHON VERSIÓN 1


1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
("Licensee") accessing and otherwise using this software in source or binary
form and its associated documentation ("the Software").

2. Subject to the terms and conditions of this BeOpen Python License Agreement,
BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
to reproduce, analyze, test, perform and/or display publicly, prepare derivative
works, distribute, and otherwise use the Software alone or in any derivative
version, provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.

3. BeOpen is making the Software available to Licensee on an "AS IS" basis.


BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
ADVISED OF THE POSSIBILITY THEREOF.

5. This License Agreement will automatically terminate upon a material breach of


its terms and conditions.

6. This License Agreement shall be governed by and interpreted in all respects


by the law of the State of California, excluding conflict of law provisions.
Nothing in this License Agreement shall be deemed to create any relationship of
(continúe en la próxima página)

C.2. Términos y condiciones para acceder o usar Python 325


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


agency, partnership, or joint venture between BeOpen and Licensee. This License
Agreement does not grant permission to use BeOpen trademarks or trade names in a
trademark sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the permissions
granted on that web page.

7. By copying, installing or otherwise using the software, Licensee agrees to be


bound by the terms and conditions of this License Agreement.

C.2.3 ACUERDO DE LICENCIA CNRI PARA PYTHON 1.6.1

1. This LICENSE AGREEMENT is between the Corporation for National Research


Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
("CNRI"), and the Individual or Organization ("Licensee") accessing and
otherwise using Python 1.6.1 software in source or binary form and its
associated documentation.

2. Subject to the terms and conditions of this License Agreement, CNRI hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
prepared by Licensee. Alternately, in lieu of CNRI's License Agreement,
Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
is made available subject to the terms and conditions in CNRI's License
Agreement. This Agreement together with Python 1.6.1 may be located on the
internet using the following unique, persistent identifier (known as a handle):
1895.22/1013. This Agreement may also be obtained from a proxy server on the
internet using the following URL: http://hdl.handle.net/1895.22/1013."

3. In the event Licensee prepares a derivative work that is based on or


incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
work available to others as provided herein, then Licensee hereby agrees to
include in any such work a brief summary of the changes made to Python 1.6.1.

4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI
MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of


its terms and conditions.

7. This License Agreement shall be governed by the federal intellectual property


law of the United States, including without limitation the federal copyright
law, and, to the extent such U.S. federal law does not apply, by the law of the
Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based on Python
1.6.1 that incorporate non-separable material that was previously distributed
under the GNU General Public License (GPL), the law of the Commonwealth of
(continúe en la próxima página)

326 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


Virginia shall govern this License Agreement only as to issues arising under or
with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in
this License Agreement shall be deemed to create any relationship of agency,
partnership, or joint venture between CNRI and Licensee. This License Agreement
does not grant permission to use CNRI trademarks or trade name in a trademark
sense to endorse or promote products or services of Licensee, or any third
party.

8. By clicking on the "ACCEPT" button where indicated, or by copying, installing


or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
conditions of this License Agreement.

C.2.4 ACUERDO DE LICENCIA CWI PARA PYTHON 0.9.0 HASTA 1.2

Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The


Netherlands. All rights reserved.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
publicity pertaining to distribution of the software without specific, written
prior permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS


SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

C.2.5 LICENCIA BSD DE CLÁUSULA CERO PARA CÓDIGO EN EL PYTHON |


lanzamiento | DOCUMENTACIÓN

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

C.2. Términos y condiciones para acceder o usar Python 327


The Python/C API, Versión 3.12.4

C.3 Licencias y reconocimientos para software incorporado

Esta sección es una lista incompleta, pero creciente, de licencias y reconocimientos para software de terceros incor-
porado en la distribución de Python.

C.3.1 Mersenne Twister

La extensión C _random subyacente al módulo random incluye código basado en una descarga de http://www.
math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html. Los siguientes son los comentarios textuales
del código original:

A C-program for MT19937, with initialization improved 2002/1/26.


Coded by Takuji Nishimura and Makoto Matsumoto.

Before using, initialize the state by using init_genrand(seed)


or init_by_array(init_key, key_length).

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,


All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright


notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. The names of its contributors may not be used to endorse or promote


products derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS


"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Any feedback is very welcome.


http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)

328 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.12.4

C.3.2 Sockets

El módulo socket usa las funciones, getaddrinfo(), y getnameinfo(), que están codificadas en archivos
fuente separados del Proyecto WIDE, http://www.wide.ad.jp /.

Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.


All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

C.3.3 Servicios de socket asincrónicos

Los módulos test.support.asynchat y test.support.asyncore contienen el siguiente aviso:

Copyright 1996 by Sam Rushing

All Rights Reserved

Permission to use, copy, modify, and distribute this software and


its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of Sam
Rushing not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,


INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

C.3. Licencias y reconocimientos para software incorporado 329


The Python/C API, Versión 3.12.4

C.3.4 Gestión de cookies

El módulo http.cookies contiene el siguiente aviso:

Copyright 2000 by Timothy O'Malley <[email protected]>

All Rights Reserved

Permission to use, copy, modify, and distribute this software


and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Timothy O'Malley not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS


SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

C.3.5 Seguimiento de ejecución

El módulo trace contiene el siguiente aviso:

portions copyright 2001, Autonomous Zones Industries, Inc., all rights...


err... reserved and offered to the public under the terms of the
Python 2.2 license.
Author: Zooko O'Whielacronx
http://zooko.com/
mailto:[email protected]

Copyright 2000, Mojam Media, Inc., all rights reserved.


Author: Skip Montanaro

Copyright 1999, Bioreason, Inc., all rights reserved.


Author: Andrew Dalke

Copyright 1995-1997, Automatrix, Inc., all rights reserved.


Author: Skip Montanaro

Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.

Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.

330 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.12.4

C.3.6 funciones UUencode y UUdecode

El módulo uu contiene el siguiente aviso:

Copyright 1994 by Lance Ellinghouse


Cathedral City, California Republic, United States of America.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Modified by Jack Jansen, CWI, July 1995:


- Use binascii module to do the actual line-by-line conversion
between ascii and binary. This results in a 1000-fold speedup. The C
version is still 5 times faster, though.
- Arguments more compliant with Python standard

C.3.7 Llamadas a procedimientos remotos XML

El módulo xmlrpc.client contiene el siguiente aviso:

The XML-RPC client interface is

Copyright (c) 1999-2002 by Secret Labs AB


Copyright (c) 1999-2002 by Fredrik Lundh

By obtaining, using, and/or copying this software and/or its


associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:

Permission to use, copy, modify, and distribute this software and


its associated documentation for any purpose and without fee is
hereby granted, provided that the above copyright notice appears in
all copies, and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Secret Labs AB or the author not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.

C.3. Licencias y reconocimientos para software incorporado 331


The Python/C API, Versión 3.12.4

C.3.8 test_epoll

El módulo test.test_epoll contiene el siguiente aviso:

Copyright (c) 2001-2006 Twisted Matrix Laboratories.

Permission is hereby granted, free of charge, to any person obtaining


a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be


included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,


EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

C.3.9 Seleccionar kqueue

El módulo select contiene el siguiente aviso para la interfaz kqueue:

Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

332 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.12.4

C.3.10 SipHash24

El archivo Python/pyhash.c contiene la implementación de Marek Majkowski del algoritmo SipHash24 de Dan
Bernstein. Contiene la siguiente nota:

<MIT License>
Copyright (c) 2013 Marek Majkowski <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy


of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</MIT License>

Original location:
https://github.com/majek/csiphash/

Solution inspired by code from:


Samuel Neves (supercop/crypto_auth/siphash24/little)
djb (supercop/crypto_auth/siphash24/little2)
Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)

C.3.11 strtod y dtoa

El archivo Python/dtoa.c, que proporciona las funciones de C dtoa y strtod para la conversión de dobles C hacia
y desde cadenas de caracteres, se deriva del archivo del mismo nombre por David M. Gay, actualmente disponible
en https://web.archive.org/web/20220517033456/http://www.netlib.org/fp/dtoa.c. El archivo original, recuperado el
16 de marzo de 2009, contiene el siguiente aviso de licencia y derechos de autor:

/****************************************************************
*
* The author of this software is David M. Gay.
*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
***************************************************************/

C.3. Licencias y reconocimientos para software incorporado 333


The Python/C API, Versión 3.12.4

C.3.12 OpenSSL

Los módulos hashlib, posix, ssl, crypt utilizan la biblioteca OpenSSL para un rendimiento adicional si el
sistema operativo la pone a disposición. Además, los instaladores de Windows y macOS para Python pueden incluir
una copia de las bibliotecas de OpenSSL, por lo que incluimos una copia de la licencia de OpenSSL aquí. Para la
version OpenSSL 3.0, y versiones posteriores derivadas, se aplica la Apache License v2:

Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by


the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity


exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.

"Object" form shall mean any form resulting from mechanical


transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or


Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object


form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including


the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
(continúe en la próxima página)

334 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity


on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of


this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of


this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the


Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:

(a) You must give any other recipients of the Work or


Derivative Works a copy of this License; and

(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and

(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and

(d) If the Work includes a "NOTICE" text file as part of its


distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
(continúe en la próxima página)

C.3. Licencias y reconocimientos para software incorporado 335


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.

You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,


any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or


agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,


whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing


the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

336 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.12.4

C.3.13 expat

La extensión pyexpat se construye usando una copia incluida de las fuentes de expatriados a menos que la cons-
trucción esté configurada --with-system-expat:

Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper

Permission is hereby granted, free of charge, to any person obtaining


a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,


EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

C.3.14 libffi

La extensión C _ctypes subyacente al módulo ctypes se construye usando una copia incluida de las fuentes de
libffi a menos que la construcción esté configurada --with-system-libffi:

Copyright (c) 1996-2008 Red Hat, Inc and others.

Permission is hereby granted, free of charge, to any person obtaining


a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,


EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

C.3. Licencias y reconocimientos para software incorporado 337


The Python/C API, Versión 3.12.4

C.3.15 zlib

La extensión zlib se crea utilizando una copia incluida de las fuentes de zlib si la versión de zlib encontrada en el
sistema es demasiado antigua para ser utilizada para la compilación:

Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler

This software is provided 'as-is', without any express or implied


warranty. In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,


including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.

2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.

3. This notice may not be removed or altered from any source distribution.

Jean-loup Gailly Mark Adler


[email protected] [email protected]

C.3.16 cfuhash

La implementación de la tabla hash utilizada por tracemalloc se basa en el proyecto cfuhash:

Copyright (c) 2005 Don Owens


All rights reserved.

This code is released under the BSD license:

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

* Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above


copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

* Neither the name of the author nor the names of its


contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS


"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
(continúe en la próxima página)

338 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.

C.3.17 libmpdec

La extension C _decimal subyacente al módulo decimal se construye usando una copia incluida de la biblioteca
libmpdec a menos que la construcción esté configurada --with-system-libmpdec:

Copyright (c) 2008-2020 Stefan Krah. All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright


notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

C.3.18 Conjunto de pruebas W3C C14N

El conjunto de pruebas C14N 2.0 en el paquete test (Lib/test/xmltestdata/c14n-20/) se recuperó


del sitio web de W3C en https://www.w3.org/TR/xml-c14n2-testcases/ y se distribuye bajo la licencia BSD de 3
cláusulas:

Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang),


All Rights Reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

* Redistributions of works must retain the original copyright notice,


this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the W3C nor the names of its contributors may be
used to endorse or promote products derived from this work without
specific prior written permission.
(continúe en la próxima página)

C.3. Licencias y reconocimientos para software incorporado 339


The Python/C API, Versión 3.12.4

(proviene de la página anterior)

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS


"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

C.3.19 Audioop

The audioop module uses the code base in g771.c file of the SoX project. https://sourceforge.net/projects/sox/files/
sox/12.17.7/sox-12.17.7.tar.gz
This source code is a product of Sun Microsystems, Inc. and is provided for unrestricted use. Users may
copy or modify this source code without charge.
SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLU-
DING THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICU-
LAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTI-
CE.
Sun source code is provided with no support and without any obligation on the part of Sun Microsystems,
Inc. to assist in its use, correction, modification or enhancement.
SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE INFRIN-
GEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE OR
ANY PART THEREOF.
In no event will Sun Microsystems, Inc. be liable for any lost revenue or profits or other special, indirect
and consequential damages, even if Sun has been advised of the possibility of such damages.
Sun Microsystems, Inc. 2550 Garcia Avenue Mountain View, California 94043

C.3.20 asyncio

Parts of the asyncio module are incorporated from uvloop 0.16, which is distributed under the MIT license:

Copyright (c) 2015-2021 MagicStack Inc. http://magic.io

Permission is hereby granted, free of charge, to any person obtaining


a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be


included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,


EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
(continúe en la próxima página)

340 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.12.4

(proviene de la página anterior)


LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

C.3. Licencias y reconocimientos para software incorporado 341


The Python/C API, Versión 3.12.4

342 Apéndice C. Historia y Licencia


APÉNDICE D

Derechos de autor

Python y esta documentación es:


Derechos de autor © 2001-2023 Python Software Foundation. Todos los derechos reservados.
Derechos de autor © 2000 BeOpen.com. Todos los derechos reservados.
Derechos de autor © 1995-2000 Corporation for National Research Initiatives. Todos los derechos reservados.
Derechos de autor © 1991-1995 Stichting Mathematisch Centrum. Todos los derechos reservados.

Consulte Historia y Licencia para obtener información completa sobre licencias y permisos.

343
The Python/C API, Versión 3.12.4

344 Apéndice D. Derechos de autor


Índice

No alfabético _PyObject_GetDictPtr (C function), 93


..., 305 _PyObject_New (C function), 253
2to3, 305 _PyObject_NewVar (C function), 253
>>>, 305 _PyTuple_Resize (C function), 152
__all__ (package variable), 70 _thread
__dict__ (module attribute), 169 module, 205
__doc__ (module attribute), 169
__file__ (module attribute), 169, 170
A
__future__, 310 a la espera, 307
__import__ abort (C function), 70
built-in function, 70 abs
__loader__ (module attribute), 169 built-in function, 102
__main__ administrador asincrónico de
module, 12, 197, 211, 212 contexto, 306
__name__ (module attribute), 169 administrador de contextos, 308
__package__ (module attribute), 169 alcances anidados, 315
__PYVENV_LAUNCHER__, 227, 232 alias de tipos, 319
__slots__, 318 allocfunc (C type), 295
_frozen (C struct), 73 anotación, 305
_inittab (C struct), 73 anotación de función, 310
_inittab.initfunc (C member), 74 anotación de variable, 320
_inittab.name (C member), 73 apagado del intérprete, 312
_Py_c_diff (C function), 129 API provisional, 317
_Py_c_neg (C function), 129 archivo binario, 307
_Py_c_pow (C function), 130 archivo de texto, 319
_Py_c_prod (C function), 129 argumento, 306
_Py_c_quot (C function), 130 argumento nombrado, 313
_Py_c_sum (C function), 129 argumento posicional, 317
_Py_InitializeMain (C function), 239 argv (in module sys), 201
_Py_NoneStruct (C var), 254 ascii
_PyBytes_Resize (C function), 133 built-in function, 93
_PyCFunctionFast (C type), 256 atributo, 306
_PyCFunctionFastWithKeywords (C type), 256
_PyCode_GetExtra (C function), 167 B
_PyCode_SetExtra (C function), 167 BDFL, 307
_PyEval_RequestCodeExtraIndex (C fun- binaryfunc (C type), 296
ction), 167 bloqueo global del intérprete, 311
_PyFrameEvalFunction (C type), 208 buffer interface
_PyInterpreterFrame (C struct), 184 (see buffer protocol), 108
_PyInterpreterState_GetEvalFrameFunc buffer object
(C function), 209 (see buffer protocol), 108
_PyInterpreterState_SetEvalFrameFunc buffer protocol, 108
(C function), 209 built-in function
__import__, 70

345
The Python/C API, Versión 3.12.4

abs, 102 contiguous, 111


ascii, 93 copyright (in module sys), 201
bytes, 94 corrutina, 308
classmethod, 258 CPython, 308
compile, 71
divmod, 102 D
float, 104 decorador, 308
hash, 94, 274 descrgetfunc (C type), 296
int, 104 descriptor, 309
len, 95, 104, 106, 153, 156, 159 descrsetfunc (C type), 296
pow, 102, 103 despacho único, 318
repr, 93, 273 destructor (C type), 295
staticmethod, 258 diccionario, 309
tuple, 105, 154 dictionary
type, 94 object, 155
builtins división entera a la baja, 310
module, 12, 197, 211, 212 divmod
buscador, 310 built-in function, 102
buscador basado en ruta, 316 docstring, 309
buscador de entradas de ruta, 316
bytearray E
object, 133 EAFP, 309
bytecode, 307 entorno virtual, 320
bytes entrada de ruta, 316
built-in function, 94 EOFError (built-in exception), 168
object, 131 espacio de nombres, 315
especificador de módulo, 315
C exc_info (in module sys), 11
cadena con triple comilla, 319 executable (in module sys), 200
callable, 307 exit (C function), 70
calloc (C function), 241 expresión, 309
Capsule expresión generadora, 311
object, 181
cargador, 314 F
C-contiguous, 111, 308 f-string, 309
clase, 307 file
clase base abstracta, 305 object, 168
clase de nuevo estilo, 315 float
classmethod built-in function, 104
built-in function, 258 floating point
cleanup functions, 70 object, 127
close (in module os), 212 Fortran contiguous, 111, 308
CO_FUTURE_DIVISION (C var), 45 free (C function), 241
code object, 164 freefunc (C type), 295
codificación de la configuración freeze utility, 73
regional, 314 frozenset
codificación de texto, 319 object, 158
codificación del sistema de archivos función, 310
y manejador de errores, 310 función clave, 313
compile función corrutina, 308
built-in function, 71 función genérica, 311
complex number function
object, 129 object, 160
comprensión de conjuntos, 318
comprensión de diccionarios, 309 G
comprensión de listas, 314 gancho a entrada de ruta, 316
contador de referencias, 318 gcvisitobjects_t (C type), 302
contiguo, 308 generador, 311

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

generador asincrónico, 306 LONG_MAX (C macro), 124


getattrfunc (C type), 295
getattrofunc (C type), 295 M
getbufferproc (C type), 296 magic
getiterfunc (C type), 296 método, 314
getter (C type), 262 main(), 198, 201
GIL, 311 malloc (C function), 241
global interpreter lock, 203 mapeado, 314
mapping
H object, 155
hash máquina virtual, 320
built-in function, 94, 274 memoryview
hash-based pyc, 312 object, 179
hashable, 312 meta buscadores de ruta, 314
hashfunc (C type), 296 metaclase, 314
METH_CLASS (C macro), 258
I METH_COEXIST (C macro), 258
IDLE, 312 METH_FASTCALL (C macro), 257
importador, 312 METH_KEYWORDS (C macro), 257
importar, 312 METH_METHOD (C macro), 257
incr_item(), 11, 12 METH_NOARGS (C macro), 257
indicador de tipo, 320 METH_O (C macro), 258
initproc (C type), 295 METH_STATIC (C macro), 258
inmutable, 312 METH_VARARGS (C macro), 257
inquiry (C type), 301 method
instancemethod object, 163
object, 162 MethodType (in module types), 160, 163
int método, 314
built-in function, 104 magic, 314
integer special, 319
object, 123 método especial, 319
interactivo, 312 método mágico, 314
interpretado, 312 module
interpreter lock, 203 __main__, 12, 197, 211, 212
iterable, 313 _thread, 205
iterable asincrónico, 306 builtins, 12, 197, 211, 212
iterador, 313 object, 169
iterador asincrónico, 306 search path, 12, 197, 200
iterador generador, 311 signal, 59
iterador generador asincrónico, 306 sys, 12, 197, 211, 212
iternextfunc (C type), 296 modules (in module sys), 70, 197
ModuleType (in module types), 169
K módulo, 314
KeyboardInterrupt (built-in exception), 59 módulo de extensión, 309
MRO, 315
L mutable, 315
lambda, 313
LBYL, 313
N
len newfunc (C type), 295
built-in function, 95, 104, 106, 153, 156, nombre calificado, 317
159 None
lenfunc (C type), 296 object, 123
list numeric
object, 153 object, 123
lista, 313 número complejo, 308
lock, interpreter, 203
long integer O
object, 123 object

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

bytearray, 133 Py_BLOCK_THREADS (C macro), 207


bytes, 131 Py_buffer (C type), 109
Capsule, 181 Py_buffer.buf (C member), 109
code, 164 Py_buffer.format (C member), 110
complex number, 129 Py_buffer.internal (C member), 110
dictionary, 155 Py_buffer.itemsize (C member), 109
file, 168 Py_buffer.len (C member), 109
floating point, 127 Py_buffer.ndim (C member), 110
frozenset, 158 Py_buffer.obj (C member), 109
function, 160 Py_buffer.readonly (C member), 109
instancemethod, 162 Py_buffer.shape (C member), 110
integer, 123 Py_buffer.strides (C member), 110
list, 153 Py_buffer.suboffsets (C member), 110
long integer, 123 Py_BuildValue (C function), 81
mapping, 155 Py_BytesMain (C function), 41
memoryview, 179 Py_BytesWarningFlag (C var), 194
method, 163 Py_CHARMASK (C macro), 5
module, 169 Py_CLEAR (C function), 48
None, 123 Py_CompileString (C function), 4345
numeric, 123 Py_CompileStringExFlags (C function), 44
sequence, 131 Py_CompileStringFlags (C function), 43
set, 158 Py_CompileStringObject (C function), 44
tuple, 151 Py_complex (C type), 129
type, 7, 117 Py_DEBUG (C macro), 13
objeto, 315 Py_DebugFlag (C var), 194
objeto archivo, 309 Py_DecodeLocale (C function), 66
objeto tipo ruta, 316 Py_DecRef (C function), 49
objetos tipo archivo, 310 Py_DECREF (C function), 7, 48
objetos tipo binarios, 307 Py_DEPRECATED (C macro), 5
objobjargproc (C type), 296 Py_DontWriteBytecodeFlag (C var), 194
objobjproc (C type), 296 Py_Ellipsis (C var), 179
orden de resolución de métodos, 314 Py_EncodeLocale (C function), 67
OverflowError (built-in exception), 124, 125 Py_END_ALLOW_THREADS (C macro), 203, 206
Py_EndInterpreter (C function), 212
P Py_EnterRecursiveCall (C function), 62
package variable Py_EQ (C macro), 282
__all__, 70 Py_eval_input (C var), 44
paquete, 316 Py_Exit (C function), 70
paquete de espacios de nombres, 315 Py_ExitStatusException (C function), 221
paquete provisorio, 317 Py_False (C var), 127
paquete regular, 318 Py_FatalError (C function), 70
parámetro, 316 Py_FatalError(), 201
path Py_FdIsInteractive (C function), 65
module search, 12, 197, 200 Py_file_input (C var), 44
PATH, 12 Py_Finalize (C function), 198
path (in module sys), 12, 197, 200 Py_FinalizeEx (C function), 70, 197, 212
PEP, 317 Py_FrozenFlag (C var), 195
platform (in module sys), 201 Py_GE (C macro), 282
porción, 317 Py_GenericAlias (C function), 191
pow Py_GenericAliasType (C var), 191
built-in function, 102, 103 Py_GetArgcArgv (C function), 239
Py_ABS (C macro), 5 Py_GetBuildInfo (C function), 201
Py_AddPendingCall (C function), 213 Py_GetCompiler (C function), 201
Py_ALWAYS_INLINE (C macro), 5 Py_GetCopyright (C function), 201
Py_AtExit (C function), 70 Py_GETENV (C macro), 5
Py_AUDIT_READ (C macro), 260 Py_GetExecPrefix (C function), 12, 199
Py_AuditHookFunction (C type), 70 Py_GetPath (C function), 12, 200
Py_BEGIN_ALLOW_THREADS (C macro), 203, 206 Py_GetPath(), 198, 200

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

Py_GetPlatform (C function), 201 Py_NoUserSiteDirectory (C var), 196


Py_GetPrefix (C function), 12, 199 Py_OptimizeFlag (C var), 196
Py_GetProgramFullPath (C function), 12, 200 Py_PreInitialize (C function), 224
Py_GetProgramName (C function), 199 Py_PreInitializeFromArgs (C function), 224
Py_GetPythonHome (C function), 202 Py_PreInitializeFromBytesArgs (C fun-
Py_GetVersion (C function), 200 ction), 224
Py_GT (C macro), 282 Py_PRINT_RAW (C macro), 91, 169
Py_hash_t (C type), 85 Py_QuietFlag (C var), 196
Py_HashRandomizationFlag (C var), 195 Py_READONLY (C macro), 260
Py_IgnoreEnvironmentFlag (C var), 195 Py_REFCNT (C function), 47
Py_IncRef (C function), 49 Py_RELATIVE_OFFSET (C macro), 260
Py_INCREF (C function), 7, 47 PY_RELEASE_LEVEL (C macro), 303
Py_Initialize (C function), 12, 197, 212 PY_RELEASE_SERIAL (C macro), 303
Py_Initialize(), 198 Py_ReprEnter (C function), 62
Py_InitializeEx (C function), 197 Py_ReprLeave (C function), 62
Py_InitializeFromConfig (C function), 235 Py_RETURN_FALSE (C macro), 127
Py_InspectFlag (C var), 195 Py_RETURN_NONE (C macro), 123
Py_InteractiveFlag (C var), 195 Py_RETURN_NOTIMPLEMENTED (C macro), 91
Py_Is (C function), 254 Py_RETURN_RICHCOMPARE (C macro), 282
Py_IS_TYPE (C function), 255 Py_RETURN_TRUE (C macro), 127
Py_IsFalse (C function), 255 Py_RunMain (C function), 239
Py_IsInitialized (C function), 13, 197 Py_SET_REFCNT (C function), 47
Py_IsNone (C function), 254 Py_SET_SIZE (C function), 255
Py_IsolatedFlag (C var), 195 Py_SET_TYPE (C function), 255
Py_IsTrue (C function), 255 Py_SetPath (C function), 200
Py_LE (C macro), 282 Py_SetPath(), 200
Py_LeaveRecursiveCall (C function), 62 Py_SetProgramName (C function), 12, 198
Py_LegacyWindowsFSEncodingFlag (C var), Py_SetProgramName(), 197, 199, 200
195 Py_SetPythonHome (C function), 202
Py_LegacyWindowsStdioFlag (C var), 196 Py_SETREF (C macro), 49
Py_LIMITED_API (C macro), 16 Py_SetStandardStreamEncoding (C function),
Py_LT (C macro), 282 198
Py_Main (C function), 41 Py_single_input (C var), 45
PY_MAJOR_VERSION (C macro), 303 Py_SIZE (C function), 255
Py_MAX (C macro), 5 Py_ssize_t (C type), 10
Py_MEMBER_SIZE (C macro), 5 PY_SSIZE_T_MAX (C macro), 125
PY_MICRO_VERSION (C macro), 303 Py_STRINGIFY (C macro), 6
Py_MIN (C macro), 5 Py_T_BOOL (C macro), 261
PY_MINOR_VERSION (C macro), 303 Py_T_BYTE (C macro), 261
Py_mod_create (C macro), 172 Py_T_CHAR (C macro), 261
Py_mod_exec (C macro), 173 Py_T_DOUBLE (C macro), 261
Py_mod_multiple_interpreters (C macro), Py_T_FLOAT (C macro), 261
173 Py_T_INT (C macro), 261
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED Py_T_LONG (C macro), 261
(C macro), 173 Py_T_LONGLONG (C macro), 261
Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED Py_T_OBJECT_EX (C macro), 261
(C macro), 173 Py_T_PYSSIZET (C macro), 261
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED Py_T_SHORT (C macro), 261
(C macro), 173 Py_T_STRING (C macro), 261
Py_NE (C macro), 282 Py_T_STRING_INPLACE (C macro), 261
Py_NewInterpreter (C function), 212 Py_T_UBYTE (C macro), 261
Py_NewInterpreterFromConfig (C function), Py_T_UINT (C macro), 261
211 Py_T_ULONG (C macro), 261
Py_NewRef (C function), 47 Py_T_ULONGLONG (C macro), 261
Py_NO_INLINE (C macro), 6 Py_T_USHORT (C macro), 261
Py_None (C var), 123 Py_TPFLAGS_BASE_EXC_SUBCLASS (C macro),
Py_NoSiteFlag (C var), 196 277
Py_NotImplemented (C var), 91 Py_TPFLAGS_BASETYPE (C macro), 276

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

Py_TPFLAGS_BYTES_SUBCLASS (C macro), 277 Py_UNICODE_TODIGIT (C function), 137


Py_TPFLAGS_DEFAULT (C macro), 276 Py_UNICODE_TOLOWER (C function), 137
Py_TPFLAGS_DICT_SUBCLASS (C macro), 277 Py_UNICODE_TONUMERIC (C function), 137
Py_TPFLAGS_DISALLOW_INSTANTIATION (C Py_UNICODE_TOTITLE (C function), 137
macro), 278 Py_UNICODE_TOUPPER (C function), 137
Py_TPFLAGS_HAVE_FINALIZE (C macro), 277 Py_UNREACHABLE (C macro), 6
Py_TPFLAGS_HAVE_GC (C macro), 276 Py_UNUSED (C macro), 6
Py_TPFLAGS_HAVE_VECTORCALL (C macro), 278 Py_VaBuildValue (C function), 83
Py_TPFLAGS_HEAPTYPE (C macro), 276 PY_VECTORCALL_ARGUMENTS_OFFSET (C ma-
Py_TPFLAGS_IMMUTABLETYPE (C macro), 278 cro), 97
Py_TPFLAGS_ITEMS_AT_END (C macro), 277 Py_VerboseFlag (C var), 197
Py_TPFLAGS_LIST_SUBCLASS (C macro), 277 Py_Version (C var), 304
Py_TPFLAGS_LONG_SUBCLASS (C macro), 277 PY_VERSION_HEX (C macro), 303
Py_TPFLAGS_MANAGED_DICT (C macro), 277 Py_VISIT (C function), 301
Py_TPFLAGS_MANAGED_WEAKREF (C macro), 277 Py_XDECREF (C function), 12, 48
Py_TPFLAGS_MAPPING (C macro), 278 Py_XINCREF (C function), 47
Py_TPFLAGS_METHOD_DESCRIPTOR (C macro), Py_XNewRef (C function), 48
276 Py_XSETREF (C macro), 49
Py_TPFLAGS_READY (C macro), 276 PyAIter_Check (C function), 107
Py_TPFLAGS_READYING (C macro), 276 PyAnySet_Check (C function), 159
Py_TPFLAGS_SEQUENCE (C macro), 279 PyAnySet_CheckExact (C function), 159
Py_TPFLAGS_TUPLE_SUBCLASS (C macro), 277 PyArg_Parse (C function), 80
Py_TPFLAGS_TYPE_SUBCLASS (C macro), 277 PyArg_ParseTuple (C function), 80
Py_TPFLAGS_UNICODE_SUBCLASS (C macro), PyArg_ParseTupleAndKeywords (C function),
277 80
Py_TPFLAGS_VALID_VERSION_TAG (C macro), PyArg_UnpackTuple (C function), 80
279 PyArg_ValidateKeywordArguments (C fun-
Py_tracefunc (C type), 214 ction), 80
Py_True (C var), 127 PyArg_VaParse (C function), 80
Py_tss_NEEDS_INIT (C macro), 216 PyArg_VaParseTupleAndKeywords (C fun-
Py_tss_t (C type), 216 ction), 80
Py_TYPE (C function), 255 PyASCIIObject (C type), 134
Py_UCS1 (C type), 134 PyAsyncMethods (C type), 294
Py_UCS2 (C type), 134 PyAsyncMethods.am_aiter (C member), 294
Py_UCS4 (C type), 134 PyAsyncMethods.am_anext (C member), 295
Py_uhash_t (C type), 85 PyAsyncMethods.am_await (C member), 294
Py_UNBLOCK_THREADS (C macro), 207 PyAsyncMethods.am_send (C member), 295
Py_UnbufferedStdioFlag (C var), 197 PyBool_Check (C function), 127
Py_UNICODE (C type), 134 PyBool_FromLong (C function), 127
Py_UNICODE_IS_HIGH_SURROGATE (C function), PyBool_Type (C var), 127
137 PyBUF_ANY_CONTIGUOUS (C macro), 112
Py_UNICODE_IS_LOW_SURROGATE (C function), PyBUF_C_CONTIGUOUS (C macro), 112
137 PyBUF_CONTIG (C macro), 112
Py_UNICODE_IS_SURROGATE (C function), 137 PyBUF_CONTIG_RO (C macro), 112
Py_UNICODE_ISALNUM (C function), 137 PyBUF_F_CONTIGUOUS (C macro), 112
Py_UNICODE_ISALPHA (C function), 136 PyBUF_FORMAT (C macro), 111
Py_UNICODE_ISDECIMAL (C function), 136 PyBUF_FULL (C macro), 112
Py_UNICODE_ISDIGIT (C function), 136 PyBUF_FULL_RO (C macro), 112
Py_UNICODE_ISLINEBREAK (C function), 136 PyBUF_INDIRECT (C macro), 111
Py_UNICODE_ISLOWER (C function), 136 PyBUF_MAX_NDIM (C macro), 110
Py_UNICODE_ISNUMERIC (C function), 136 PyBUF_ND (C macro), 111
Py_UNICODE_ISPRINTABLE (C function), 137 PyBUF_READ (C macro), 179
Py_UNICODE_ISSPACE (C function), 136 PyBUF_RECORDS (C macro), 112
Py_UNICODE_ISTITLE (C function), 136 PyBUF_RECORDS_RO (C macro), 112
Py_UNICODE_ISUPPER (C function), 136 PyBUF_SIMPLE (C macro), 111
Py_UNICODE_JOIN_SURROGATES (C function), PyBUF_STRIDED (C macro), 112
137 PyBUF_STRIDED_RO (C macro), 112
Py_UNICODE_TODECIMAL (C function), 137 PyBUF_STRIDES (C macro), 111

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

PyBUF_WRITABLE (C macro), 111 PyCapsule_New (C function), 181


PyBUF_WRITE (C macro), 179 PyCapsule_SetContext (C function), 182
PyBuffer_FillContiguousStrides (C fun- PyCapsule_SetDestructor (C function), 182
ction), 115 PyCapsule_SetName (C function), 182
PyBuffer_FillInfo (C function), 115 PyCapsule_SetPointer (C function), 182
PyBuffer_FromContiguous (C function), 114 PyCell_Check (C function), 163
PyBuffer_GetPointer (C function), 114 PyCell_Get (C function), 163
PyBuffer_IsContiguous (C function), 114 PyCell_GET (C function), 163
PyBuffer_Release (C function), 114 PyCell_New (C function), 163
PyBuffer_SizeFromFormat (C function), 114 PyCell_Set (C function), 164
PyBuffer_ToContiguous (C function), 114 PyCell_SET (C function), 164
PyBufferProcs (C type), 108, 293 PyCell_Type (C var), 163
PyBufferProcs.bf_getbuffer (C member), PyCellObject (C type), 163
293 PyCFunction (C type), 256
PyBufferProcs.bf_releasebuffer (C mem- PyCFunction_New (C function), 258
ber), 294 PyCFunction_NewEx (C function), 258
PyByteArray_AS_STRING (C function), 134 PyCFunctionWithKeywords (C type), 256
PyByteArray_AsString (C function), 133 PyCMethod (C type), 256
PyByteArray_Check (C function), 133 PyCMethod_New (C function), 258
PyByteArray_CheckExact (C function), 133 PyCode_Addr2Line (C function), 165
PyByteArray_Concat (C function), 133 PyCode_Addr2Location (C function), 165
PyByteArray_FromObject (C function), 133 PyCode_AddWatcher (C function), 166
PyByteArray_FromStringAndSize (C fun- PyCode_Check (C function), 164
ction), 133 PyCode_ClearWatcher (C function), 166
PyByteArray_GET_SIZE (C function), 134 PyCode_GetCellvars (C function), 165
PyByteArray_Resize (C function), 134 PyCode_GetCode (C function), 165
PyByteArray_Size (C function), 133 PyCode_GetFirstFree (C function), 164
PyByteArray_Type (C var), 133 PyCode_GetFreevars (C function), 166
PyByteArrayObject (C type), 133 PyCode_GetNumFree (C function), 164
PyBytes_AS_STRING (C function), 132 PyCode_GetVarnames (C function), 165
PyBytes_AsString (C function), 132 PyCode_New (C function), 164
PyBytes_AsStringAndSize (C function), 132 PyCode_NewEmpty (C function), 165
PyBytes_Check (C function), 131 PyCode_NewWithPosOnlyArgs (C function), 165
PyBytes_CheckExact (C function), 131 PyCode_Type (C var), 164
PyBytes_Concat (C function), 133 PyCode_WatchCallback (C type), 166
PyBytes_ConcatAndDel (C function), 133 PyCodec_BackslashReplaceErrors (C fun-
PyBytes_FromFormat (C function), 131 ction), 88
PyBytes_FromFormatV (C function), 132 PyCodec_Decode (C function), 86
PyBytes_FromObject (C function), 132 PyCodec_Decoder (C function), 87
PyBytes_FromString (C function), 131 PyCodec_Encode (C function), 86
PyBytes_FromStringAndSize (C function), 131 PyCodec_Encoder (C function), 87
PyBytes_GET_SIZE (C function), 132 PyCodec_IgnoreErrors (C function), 87
PyBytes_Size (C function), 132 PyCodec_IncrementalDecoder (C function), 87
PyBytes_Type (C var), 131 PyCodec_IncrementalEncoder (C function), 87
PyBytesObject (C type), 131 PyCodec_KnownEncoding (C function), 86
PyCallable_Check (C function), 101 PyCodec_LookupError (C function), 87
PyCallIter_Check (C function), 177 PyCodec_NameReplaceErrors (C function), 88
PyCallIter_New (C function), 177 PyCodec_Register (C function), 86
PyCallIter_Type (C var), 177 PyCodec_RegisterError (C function), 87
PyCapsule (C type), 181 PyCodec_ReplaceErrors (C function), 88
PyCapsule_CheckExact (C function), 181 PyCodec_StreamReader (C function), 87
PyCapsule_Destructor (C type), 181 PyCodec_StreamWriter (C function), 87
PyCapsule_GetContext (C function), 181 PyCodec_StrictErrors (C function), 87
PyCapsule_GetDestructor (C function), 181 PyCodec_Unregister (C function), 86
PyCapsule_GetName (C function), 182 PyCodec_XMLCharRefReplaceErrors (C fun-
PyCapsule_GetPointer (C function), 181 ction), 88
PyCapsule_Import (C function), 182 PyCodeEvent (C type), 166
PyCapsule_IsValid (C function), 182 PyCodeObject (C type), 164

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

PyCompactUnicodeObject (C type), 134 PyConfig.legacy_windows_stdio (C mem-


PyCompilerFlags (C struct), 45 ber), 230
PyCompilerFlags.cf_feature_version (C PyConfig.malloc_stats (C member), 230
member), 45 PyConfig.module_search_paths (C member),
PyCompilerFlags.cf_flags (C member), 45 231
PyComplex_AsCComplex (C function), 130 PyConfig.module_search_paths_set (C
PyComplex_Check (C function), 130 member), 231
PyComplex_CheckExact (C function), 130 PyConfig.optimization_level (C member),
PyComplex_FromCComplex (C function), 130 231
PyComplex_FromDoubles (C function), 130 PyConfig.orig_argv (C member), 231
PyComplex_ImagAsDouble (C function), 130 PyConfig.parse_argv (C member), 231
PyComplex_RealAsDouble (C function), 130 PyConfig.parser_debug (C member), 232
PyComplex_Type (C var), 130 PyConfig.pathconfig_warnings (C member),
PyComplexObject (C type), 130 232
PyConfig (C type), 225 PyConfig.perf_profiling (C member), 234
PyConfig_Clear (C function), 226 PyConfig.platlibdir (C member), 230
PyConfig_InitIsolatedConfig (C function), PyConfig.prefix (C member), 232
225 PyConfig.program_name (C member), 232
PyConfig_InitPythonConfig (C function), 225 PyConfig.pycache_prefix (C member), 232
PyConfig_Read (C function), 225 PyConfig.pythonpath_env (C member), 231
PyConfig_SetArgv (C function), 225 PyConfig.quiet (C member), 233
PyConfig_SetBytesArgv (C function), 225 PyConfig.run_command (C member), 233
PyConfig_SetBytesString (C function), 225 PyConfig.run_filename (C member), 233
PyConfig_SetString (C function), 225 PyConfig.run_module (C member), 233
PyConfig_SetWideStringList (C function), PyConfig.safe_path (C member), 226
225 PyConfig.show_ref_count (C member), 233
PyConfig.argv (C member), 226 PyConfig.site_import (C member), 233
PyConfig.base_exec_prefix (C member), 226 PyConfig.skip_source_first_line (C mem-
PyConfig.base_executable (C member), 226 ber), 233
PyConfig.base_prefix (C member), 227 PyConfig.stdio_encoding (C member), 233
PyConfig.buffered_stdio (C member), 227 PyConfig.stdio_errors (C member), 234
PyConfig.bytes_warning (C member), 227 PyConfig.tracemalloc (C member), 234
PyConfig.check_hash_pycs_mode (C mem- PyConfig.use_environment (C member), 234
ber), 227 PyConfig.use_hash_seed (C member), 229
PyConfig.code_debug_ranges (C member), PyConfig.user_site_directory (C member),
227 234
PyConfig.configure_c_stdio (C member), PyConfig.verbose (C member), 234
228 PyConfig.warn_default_encoding (C mem-
PyConfig.dev_mode (C member), 228 ber), 227
PyConfig.dump_refs (C member), 228 PyConfig.warnoptions (C member), 235
PyConfig.exec_prefix (C member), 228 PyConfig.write_bytecode (C member), 235
PyConfig.executable (C member), 228 PyConfig.xoptions (C member), 235
PyConfig.faulthandler (C member), 228 PyContext (C type), 186
PyConfig.filesystem_encoding (C member), PyContext_CheckExact (C function), 186
228 PyContext_Copy (C function), 186
PyConfig.filesystem_errors (C member), PyContext_CopyCurrent (C function), 186
229 PyContext_Enter (C function), 186
PyConfig.hash_seed (C member), 229 PyContext_Exit (C function), 186
PyConfig.home (C member), 229 PyContext_New (C function), 186
PyConfig.import_time (C member), 229 PyContext_Type (C var), 186
PyConfig.inspect (C member), 229 PyContextToken (C type), 186
PyConfig.install_signal_handlers (C PyContextToken_CheckExact (C function), 186
member), 229 PyContextToken_Type (C var), 186
PyConfig.int_max_str_digits (C member), PyContextVar (C type), 186
230 PyContextVar_CheckExact (C function), 186
PyConfig.interactive (C member), 230 PyContextVar_Get (C function), 187
PyConfig.isolated (C member), 230 PyContextVar_New (C function), 187
PyContextVar_Reset (C function), 187

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

PyContextVar_Set (C function), 187 PyDescr_IsData (C function), 177


PyContextVar_Type (C var), 186 PyDescr_NewClassMethod (C function), 177
PyCoro_CheckExact (C function), 185 PyDescr_NewGetSet (C function), 177
PyCoro_New (C function), 185 PyDescr_NewMember (C function), 177
PyCoro_Type (C var), 185 PyDescr_NewMethod (C function), 177
PyCoroObject (C type), 185 PyDescr_NewWrapper (C function), 177
PyDate_Check (C function), 188 PyDict_AddWatcher (C function), 157
PyDate_CheckExact (C function), 188 PyDict_Check (C function), 155
PyDate_FromDate (C function), 188 PyDict_CheckExact (C function), 155
PyDate_FromTimestamp (C function), 190 PyDict_Clear (C function), 155
PyDateTime_Check (C function), 188 PyDict_ClearWatcher (C function), 157
PyDateTime_CheckExact (C function), 188 PyDict_Contains (C function), 155
PyDateTime_Date (C type), 187 PyDict_Copy (C function), 155
PyDateTime_DATE_GET_FOLD (C function), 190 PyDict_DelItem (C function), 155
PyDateTime_DATE_GET_HOUR (C function), 189 PyDict_DelItemString (C function), 155
PyDateTime_DATE_GET_MICROSECOND (C fun- PyDict_GetItem (C function), 155
ction), 189 PyDict_GetItemString (C function), 156
PyDateTime_DATE_GET_MINUTE (C function), PyDict_GetItemWithError (C function), 156
189 PyDict_Items (C function), 156
PyDateTime_DATE_GET_SECOND (C function), PyDict_Keys (C function), 156
189 PyDict_Merge (C function), 157
PyDateTime_DATE_GET_TZINFO (C function), PyDict_MergeFromSeq2 (C function), 157
190 PyDict_New (C function), 155
PyDateTime_DateTime (C type), 187 PyDict_Next (C function), 156
PyDateTime_DateTimeType (C var), 187 PyDict_SetDefault (C function), 156
PyDateTime_DateType (C var), 187 PyDict_SetItem (C function), 155
PyDateTime_Delta (C type), 187 PyDict_SetItemString (C function), 155
PyDateTime_DELTA_GET_DAYS (C function), 190 PyDict_Size (C function), 156
PyDateTime_DELTA_GET_MICROSECONDS (C PyDict_Type (C var), 155
function), 190 PyDict_Unwatch (C function), 158
PyDateTime_DELTA_GET_SECONDS (C function), PyDict_Update (C function), 157
190 PyDict_Values (C function), 156
PyDateTime_DeltaType (C var), 187 PyDict_Watch (C function), 158
PyDateTime_FromDateAndTime (C function), PyDict_WatchCallback (C type), 158
188 PyDict_WatchEvent (C type), 158
PyDateTime_FromDateAndTimeAndFold (C PyDictObject (C type), 155
function), 189 PyDictProxy_New (C function), 155
PyDateTime_FromTimestamp (C function), 190 PyDoc_STR (C macro), 6
PyDateTime_GET_DAY (C function), 189 PyDoc_STRVAR (C macro), 6
PyDateTime_GET_MONTH (C function), 189 PyErr_BadArgument (C function), 53
PyDateTime_GET_YEAR (C function), 189 PyErr_BadInternalCall (C function), 54
PyDateTime_Time (C type), 187 PyErr_CheckSignals (C function), 59
PyDateTime_TIME_GET_FOLD (C function), 190 PyErr_Clear (C function), 10, 12, 51
PyDateTime_TIME_GET_HOUR (C function), 190 PyErr_DisplayException (C function), 52
PyDateTime_TIME_GET_MICROSECOND (C fun- PyErr_ExceptionMatches (C function), 12, 56
ction), 190 PyErr_Fetch (C function), 56
PyDateTime_TIME_GET_MINUTE (C function), PyErr_Format (C function), 52
190 PyErr_FormatV (C function), 52
PyDateTime_TIME_GET_SECOND (C function), PyErr_GetExcInfo (C function), 58
190 PyErr_GetHandledException (C function), 57
PyDateTime_TIME_GET_TZINFO (C function), PyErr_GetRaisedException (C function), 56
190 PyErr_GivenExceptionMatches (C function),
PyDateTime_TimeType (C var), 187 56
PyDateTime_TimeZone_UTC (C var), 188 PyErr_NewException (C function), 60
PyDateTime_TZInfoType (C var), 188 PyErr_NewExceptionWithDoc (C function), 60
PyDelta_Check (C function), 188 PyErr_NoMemory (C function), 53
PyDelta_CheckExact (C function), 188 PyErr_NormalizeException (C function), 57
PyDelta_FromDSU (C function), 189 PyErr_Occurred (C function), 10, 56

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

PyErr_Print (C function), 52 PyEval_ReleaseThread(), 205


PyErr_PrintEx (C function), 51 PyEval_RestoreThread (C function), 203, 205
PyErr_ResourceWarning (C function), 55 PyEval_RestoreThread(), 205
PyErr_Restore (C function), 57 PyEval_SaveThread (C function), 203, 205
PyErr_SetExcFromWindowsErr (C function), 53 PyEval_SaveThread(), 205
PyErr_SetExcFromWindowsErrWithFilename PyEval_SetProfile (C function), 215
(C function), 54 PyEval_SetProfileAllThreads (C function),
PyErr_SetExcFromWindowsErrWithFilenameObject 215
(C function), 54 PyEval_SetTrace (C function), 215
PyErr_SetExcFromWindowsErrWithFilenameObjects
PyEval_SetTraceAllThreads (C function), 215
(C function), 54 PyEval_ThreadsInitialized (C function), 205
PyErr_SetExcInfo (C function), 58 PyExc_ArithmeticError (C var), 63
PyErr_SetFromErrno (C function), 53 PyExc_AssertionError (C var), 63
PyErr_SetFromErrnoWithFilename (C fun- PyExc_AttributeError (C var), 63
ction), 53 PyExc_BaseException (C var), 63
PyErr_SetFromErrnoWithFilenameObject PyExc_BlockingIOError (C var), 63
(C function), 53 PyExc_BrokenPipeError (C var), 63
PyErr_SetFromErrnoWithFilenameObjects PyExc_BufferError (C var), 63
(C function), 53 PyExc_BytesWarning (C var), 64
PyErr_SetFromWindowsErr (C function), 53 PyExc_ChildProcessError (C var), 63
PyErr_SetFromWindowsErrWithFilename (C PyExc_ConnectionAbortedError (C var), 63
function), 53 PyExc_ConnectionError (C var), 63
PyErr_SetHandledException (C function), 58 PyExc_ConnectionRefusedError (C var), 63
PyErr_SetImportError (C function), 54 PyExc_ConnectionResetError (C var), 63
PyErr_SetImportErrorSubclass (C function), PyExc_DeprecationWarning (C var), 64
54 PyExc_EnvironmentError (C var), 64
PyErr_SetInterrupt (C function), 59 PyExc_EOFError (C var), 63
PyErr_SetInterruptEx (C function), 59 PyExc_Exception (C var), 63
PyErr_SetNone (C function), 52 PyExc_FileExistsError (C var), 63
PyErr_SetObject (C function), 52 PyExc_FileNotFoundError (C var), 63
PyErr_SetRaisedException (C function), 56 PyExc_FloatingPointError (C var), 63
PyErr_SetString (C function), 10, 52 PyExc_FutureWarning (C var), 64
PyErr_SyntaxLocation (C function), 54 PyExc_GeneratorExit (C var), 63
PyErr_SyntaxLocationEx (C function), 54 PyExc_ImportError (C var), 63
PyErr_SyntaxLocationObject (C function), 54 PyExc_ImportWarning (C var), 64
PyErr_WarnEx (C function), 55 PyExc_IndentationError (C var), 63
PyErr_WarnExplicit (C function), 55 PyExc_IndexError (C var), 63
PyErr_WarnExplicitObject (C function), 55 PyExc_InterruptedError (C var), 63
PyErr_WarnFormat (C function), 55 PyExc_IOError (C var), 64
PyErr_WriteUnraisable (C function), 52 PyExc_IsADirectoryError (C var), 63
PyEval_AcquireLock (C function), 209 PyExc_KeyboardInterrupt (C var), 63
PyEval_AcquireThread (C function), 209 PyExc_KeyError (C var), 63
PyEval_AcquireThread(), 205 PyExc_LookupError (C var), 63
PyEval_EvalCode (C function), 44 PyExc_MemoryError (C var), 63
PyEval_EvalCodeEx (C function), 44 PyExc_ModuleNotFoundError (C var), 63
PyEval_EvalFrame (C function), 44 PyExc_NameError (C var), 63
PyEval_EvalFrameEx (C function), 44 PyExc_NotADirectoryError (C var), 63
PyEval_GetBuiltins (C function), 86 PyExc_NotImplementedError (C var), 63
PyEval_GetFrame (C function), 86 PyExc_OSError (C var), 63
PyEval_GetFuncDesc (C function), 86 PyExc_OverflowError (C var), 63
PyEval_GetFuncName (C function), 86 PyExc_PendingDeprecationWarning (C var),
PyEval_GetGlobals (C function), 86 64
PyEval_GetLocals (C function), 86 PyExc_PermissionError (C var), 63
PyEval_InitThreads (C function), 205 PyExc_ProcessLookupError (C var), 63
PyEval_InitThreads(), 197 PyExc_RecursionError (C var), 63
PyEval_MergeCompilerFlags (C function), 44 PyExc_ReferenceError (C var), 63
PyEval_ReleaseLock (C function), 210 PyExc_ResourceWarning (C var), 64
PyEval_ReleaseThread (C function), 209 PyExc_RuntimeError (C var), 63

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

PyExc_RuntimeWarning (C var), 64 PyFrame_GetGlobals (C function), 183


PyExc_StopAsyncIteration (C var), 63 PyFrame_GetLasti (C function), 183
PyExc_StopIteration (C var), 63 PyFrame_GetLineNumber (C function), 184
PyExc_SyntaxError (C var), 63 PyFrame_GetLocals (C function), 184
PyExc_SyntaxWarning (C var), 64 PyFrame_GetVar (C function), 184
PyExc_SystemError (C var), 63 PyFrame_GetVarString (C function), 184
PyExc_SystemExit (C var), 63 PyFrame_Type (C var), 183
PyExc_TabError (C var), 63 PyFrameObject (C type), 183
PyExc_TimeoutError (C var), 63 PyFrozenSet_Check (C function), 159
PyExc_TypeError (C var), 63 PyFrozenSet_CheckExact (C function), 159
PyExc_UnboundLocalError (C var), 63 PyFrozenSet_New (C function), 159
PyExc_UnicodeDecodeError (C var), 63 PyFrozenSet_Type (C var), 159
PyExc_UnicodeEncodeError (C var), 63 PyFunction_AddWatcher (C function), 161
PyExc_UnicodeError (C var), 63 PyFunction_Check (C function), 160
PyExc_UnicodeTranslateError (C var), 63 PyFunction_ClearWatcher (C function), 161
PyExc_UnicodeWarning (C var), 64 PyFunction_GetAnnotations (C function), 161
PyExc_UserWarning (C var), 64 PyFunction_GetClosure (C function), 161
PyExc_ValueError (C var), 63 PyFunction_GetCode (C function), 161
PyExc_Warning (C var), 64 PyFunction_GetDefaults (C function), 161
PyExc_WindowsError (C var), 64 PyFunction_GetGlobals (C function), 161
PyExc_ZeroDivisionError (C var), 63 PyFunction_GetModule (C function), 161
PyException_GetArgs (C function), 60 PyFunction_New (C function), 160
PyException_GetCause (C function), 60 PyFunction_NewWithQualName (C function),
PyException_GetContext (C function), 60 160
PyException_GetTraceback (C function), 60 PyFunction_SetAnnotations (C function), 161
PyException_SetArgs (C function), 60 PyFunction_SetClosure (C function), 161
PyException_SetCause (C function), 60 PyFunction_SetDefaults (C function), 161
PyException_SetContext (C function), 60 PyFunction_SetVectorcall (C function), 161
PyException_SetTraceback (C function), 60 PyFunction_Type (C var), 160
PyFile_FromFd (C function), 168 PyFunction_WatchCallback (C type), 162
PyFile_GetLine (C function), 168 PyFunction_WatchEvent (C type), 162
PyFile_SetOpenCodeHook (C function), 168 PyFunctionObject (C type), 160
PyFile_SetOpenCodeHook.Py_OpenCodeHookFunction
PyGC_Collect (C function), 301
(C type), 168 PyGC_Disable (C function), 301
PyFile_WriteObject (C function), 169 PyGC_Enable (C function), 301
PyFile_WriteString (C function), 169 PyGC_IsEnabled (C function), 302
PyFloat_AS_DOUBLE (C function), 128 PyGen_Check (C function), 185
PyFloat_AsDouble (C function), 127 PyGen_CheckExact (C function), 185
PyFloat_Check (C function), 127 PyGen_New (C function), 185
PyFloat_CheckExact (C function), 127 PyGen_NewWithQualName (C function), 185
PyFloat_FromDouble (C function), 127 PyGen_Type (C var), 185
PyFloat_FromString (C function), 127 PyGenObject (C type), 185
PyFloat_GetInfo (C function), 128 PyGetSetDef (C type), 262
PyFloat_GetMax (C function), 128 PyGetSetDef.closure (C member), 262
PyFloat_GetMin (C function), 128 PyGetSetDef.doc (C member), 262
PyFloat_Pack2 (C function), 128 PyGetSetDef.get (C member), 262
PyFloat_Pack4 (C function), 128 PyGetSetDef.name (C member), 262
PyFloat_Pack8 (C function), 129 PyGetSetDef.set (C member), 262
PyFloat_Type (C var), 127 PyGILState_Check (C function), 206
PyFloat_Unpack2 (C function), 129 PyGILState_Ensure (C function), 206
PyFloat_Unpack4 (C function), 129 PyGILState_GetThisThreadState (C fun-
PyFloat_Unpack8 (C function), 129 ction), 206
PyFloatObject (C type), 127 PyGILState_Release (C function), 206
PyFrame_Check (C function), 183 PyHash_FuncDef (C type), 85
PyFrame_GetBack (C function), 183 PyHash_FuncDef.hash_bits (C member), 85
PyFrame_GetBuiltins (C function), 183 PyHash_FuncDef.name (C member), 85
PyFrame_GetCode (C function), 183 PyHash_FuncDef.seed_bits (C member), 85
PyFrame_GetGenerator (C function), 183 PyHash_GetFuncDef (C function), 85

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

PyImport_AddModule (C function), 71 PyInterpreterState_Delete (C function), 207


PyImport_AddModuleObject (C function), 71 PyInterpreterState_Get (C function), 208
PyImport_AppendInittab (C function), 73 PyInterpreterState_GetDict (C function),
PyImport_ExecCodeModule (C function), 71 208
PyImport_ExecCodeModuleEx (C function), 72 PyInterpreterState_GetID (C function), 208
PyImport_ExecCodeModuleObject (C fun- PyInterpreterState_Head (C function), 216
ction), 72 PyInterpreterState_Main (C function), 216
PyImport_ExecCodeModuleWithPathnames PyInterpreterState_New (C function), 207
(C function), 72 PyInterpreterState_Next (C function), 216
PyImport_ExtendInittab (C function), 74 PyInterpreterState_ThreadHead (C fun-
PyImport_FrozenModules (C var), 73 ction), 216
PyImport_GetImporter (C function), 73 PyIter_Check (C function), 107
PyImport_GetMagicNumber (C function), 72 PyIter_Next (C function), 107
PyImport_GetMagicTag (C function), 72 PyIter_Send (C function), 108
PyImport_GetModule (C function), 73 PyList_Append (C function), 154
PyImport_GetModuleDict (C function), 72 PyList_AsTuple (C function), 154
PyImport_Import (C function), 71 PyList_Check (C function), 153
PyImport_ImportFrozenModule (C function), PyList_CheckExact (C function), 153
73 PyList_GET_ITEM (C function), 154
PyImport_ImportFrozenModuleObject (C PyList_GET_SIZE (C function), 153
function), 73 PyList_GetItem (C function), 9, 154
PyImport_ImportModule (C function), 70 PyList_GetSlice (C function), 154
PyImport_ImportModuleEx (C function), 70 PyList_Insert (C function), 154
PyImport_ImportModuleLevel (C function), 71 PyList_New (C function), 153
PyImport_ImportModuleLevelObject (C PyList_Reverse (C function), 154
function), 71 PyList_SET_ITEM (C function), 154
PyImport_ImportModuleNoBlock (C function), PyList_SetItem (C function), 8, 154
70 PyList_SetSlice (C function), 154
PyImport_ReloadModule (C function), 71 PyList_Size (C function), 153
PyIndex_Check (C function), 104 PyList_Sort (C function), 154
PyInstanceMethod_Check (C function), 162 PyList_Type (C var), 153
PyInstanceMethod_Function (C function), 162 PyListObject (C type), 153
PyInstanceMethod_GET_FUNCTION (C fun- PyLong_AsDouble (C function), 126
ction), 162 PyLong_AsLong (C function), 124
PyInstanceMethod_New (C function), 162 PyLong_AsLongAndOverflow (C function), 124
PyInstanceMethod_Type (C var), 162 PyLong_AsLongLong (C function), 125
PyInterpreterConfig (C type), 210 PyLong_AsLongLongAndOverflow (C function),
PyInterpreterConfig_DEFAULT_GIL (C ma- 125
cro), 211 PyLong_AsSize_t (C function), 125
PyInterpreterConfig_OWN_GIL (C macro), PyLong_AsSsize_t (C function), 125
211 PyLong_AsUnsignedLong (C function), 125
PyInterpreterConfig_SHARED_GIL (C ma- PyLong_AsUnsignedLongLong (C function), 125
cro), 211 PyLong_AsUnsignedLongLongMask (C fun-
PyInterpreterConfig.allow_daemon_threads ction), 126
(C member), 211 PyLong_AsUnsignedLongMask (C function), 125
PyInterpreterConfig.allow_exec (C mem- PyLong_AsVoidPtr (C function), 126
ber), 210 PyLong_Check (C function), 123
PyInterpreterConfig.allow_fork (C mem- PyLong_CheckExact (C function), 123
ber), 210 PyLong_FromDouble (C function), 124
PyInterpreterConfig.allow_threads (C PyLong_FromLong (C function), 123
member), 211 PyLong_FromLongLong (C function), 124
PyInterpreterConfig.check_multi_interp_extensions
PyLong_FromSize_t (C function), 124
(C member), 211 PyLong_FromSsize_t (C function), 123
PyInterpreterConfig.gil (C member), 211 PyLong_FromString (C function), 124
PyInterpreterConfig.use_main_obmalloc PyLong_FromUnicodeObject (C function), 124
(C member), 210 PyLong_FromUnsignedLong (C function), 123
PyInterpreterState (C type), 205 PyLong_FromUnsignedLongLong (C function),
PyInterpreterState_Clear (C function), 207 124

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

PyLong_FromVoidPtr (C function), 124 PyMemberDef.doc (C member), 259


PyLong_Type (C var), 123 PyMemberDef.flags (C member), 259
PyLongObject (C type), 123 PyMemberDef.name (C member), 259
PyMapping_Check (C function), 106 PyMemberDef.offset (C member), 259
PyMapping_DelItem (C function), 106 PyMemberDef.type (C member), 259
PyMapping_DelItemString (C function), 106 PyMemoryView_Check (C function), 180
PyMapping_GetItemString (C function), 106 PyMemoryView_FromBuffer (C function), 179
PyMapping_HasKey (C function), 106 PyMemoryView_FromMemory (C function), 179
PyMapping_HasKeyString (C function), 107 PyMemoryView_FromObject (C function), 179
PyMapping_Items (C function), 107 PyMemoryView_GET_BASE (C function), 180
PyMapping_Keys (C function), 107 PyMemoryView_GET_BUFFER (C function), 180
PyMapping_Length (C function), 106 PyMemoryView_GetContiguous (C function),
PyMapping_SetItemString (C function), 106 179
PyMapping_Size (C function), 106 PyMethod_Check (C function), 163
PyMapping_Values (C function), 107 PyMethod_Function (C function), 163
PyMappingMethods (C type), 292 PyMethod_GET_FUNCTION (C function), 163
PyMappingMethods.mp_ass_subscript (C PyMethod_GET_SELF (C function), 163
member), 292 PyMethod_New (C function), 163
PyMappingMethods.mp_length (C member), PyMethod_Self (C function), 163
292 PyMethod_Type (C var), 163
PyMappingMethods.mp_subscript (C mem- PyMethodDef (C type), 256
ber), 292 PyMethodDef.ml_doc (C member), 257
PyMarshal_ReadLastObjectFromFile (C PyMethodDef.ml_flags (C member), 256
function), 74 PyMethodDef.ml_meth (C member), 256
PyMarshal_ReadLongFromFile (C function), 74 PyMethodDef.ml_name (C member), 256
PyMarshal_ReadObjectFromFile (C function), PyMODINIT_FUNC (C macro), 4
74 PyModule_AddFunctions (C function), 174
PyMarshal_ReadObjectFromString (C fun- PyModule_AddIntConstant (C function), 175
ction), 75 PyModule_AddIntMacro (C macro), 176
PyMarshal_ReadShortFromFile (C function), PyModule_AddObject (C function), 175
74 PyModule_AddObjectRef (C function), 174
PyMarshal_WriteLongToFile (C function), 74 PyModule_AddStringConstant (C function),
PyMarshal_WriteObjectToFile (C function), 176
74 PyModule_AddStringMacro (C macro), 176
PyMarshal_WriteObjectToString (C fun- PyModule_AddType (C function), 176
ction), 74 PyModule_Check (C function), 169
PyMem_Calloc (C function), 244 PyModule_CheckExact (C function), 169
PyMem_Del (C function), 244 PyModule_Create (C function), 171
PYMEM_DOMAIN_MEM (C macro), 247 PyModule_Create2 (C function), 171
PYMEM_DOMAIN_OBJ (C macro), 247 PyModule_ExecDef (C function), 174
PYMEM_DOMAIN_RAW (C macro), 246 PyModule_FromDefAndSpec (C function), 173
PyMem_Free (C function), 244 PyModule_FromDefAndSpec2 (C function), 173
PyMem_GetAllocator (C function), 247 PyModule_GetDef (C function), 170
PyMem_Malloc (C function), 243 PyModule_GetDict (C function), 169
PyMem_New (C macro), 244 PyModule_GetFilename (C function), 170
PyMem_RawCalloc (C function), 243 PyModule_GetFilenameObject (C function),
PyMem_RawFree (C function), 243 170
PyMem_RawMalloc (C function), 243 PyModule_GetName (C function), 169
PyMem_RawRealloc (C function), 243 PyModule_GetNameObject (C function), 169
PyMem_Realloc (C function), 244 PyModule_GetState (C function), 169
PyMem_Resize (C macro), 244 PyModule_New (C function), 169
PyMem_SetAllocator (C function), 247 PyModule_NewObject (C function), 169
PyMem_SetupDebugHooks (C function), 247 PyModule_SetDocString (C function), 174
PyMemAllocatorDomain (C type), 246 PyModule_Type (C var), 169
PyMemAllocatorEx (C type), 246 PyModuleDef (C type), 170
PyMember_GetOne (C function), 259 PyModuleDef_Init (C function), 172
PyMember_SetOne (C function), 259 PyModuleDef_Slot (C type), 172
PyMemberDef (C type), 259 PyModuleDef_Slot.slot (C member), 172

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

PyModuleDef_Slot.value (C member), 172 PyNumberMethods.nb_divmod (C member), 291


PyModuleDef.m_base (C member), 170 PyNumberMethods.nb_float (C member), 291
PyModuleDef.m_clear (C member), 171 PyNumberMethods.nb_floor_divide (C mem-
PyModuleDef.m_doc (C member), 170 ber), 291
PyModuleDef.m_free (C member), 171 PyNumberMethods.nb_index (C member), 291
PyModuleDef.m_methods (C member), 170 PyNumberMethods.nb_inplace_add (C mem-
PyModuleDef.m_name (C member), 170 ber), 291
PyModuleDef.m_size (C member), 170 PyNumberMethods.nb_inplace_and (C mem-
PyModuleDef.m_slots (C member), 171 ber), 291
PyModuleDef.m_slots.m_reload (C member), PyNumberMethods.nb_inplace_floor_divide
171 (C member), 291
PyModuleDef.m_traverse (C member), 171 PyNumberMethods.nb_inplace_lshift (C
PyNumber_Absolute (C function), 102 member), 291
PyNumber_Add (C function), 101 PyNumberMethods.nb_inplace_matrix_multiply
PyNumber_And (C function), 102 (C member), 292
PyNumber_AsSsize_t (C function), 104 PyNumberMethods.nb_inplace_multiply (C
PyNumber_Check (C function), 101 member), 291
PyNumber_Divmod (C function), 102 PyNumberMethods.nb_inplace_or (C mem-
PyNumber_Float (C function), 104 ber), 291
PyNumber_FloorDivide (C function), 101 PyNumberMethods.nb_inplace_power (C
PyNumber_Index (C function), 104 member), 291
PyNumber_InPlaceAdd (C function), 102 PyNumberMethods.nb_inplace_remainder
PyNumber_InPlaceAnd (C function), 103 (C member), 291
PyNumber_InPlaceFloorDivide (C function), PyNumberMethods.nb_inplace_rshift (C
103 member), 291
PyNumber_InPlaceLshift (C function), 103 PyNumberMethods.nb_inplace_subtract (C
PyNumber_InPlaceMatrixMultiply (C fun- member), 291
ction), 103 PyNumberMethods.nb_inplace_true_divide
PyNumber_InPlaceMultiply (C function), 102 (C member), 291
PyNumber_InPlaceOr (C function), 103 PyNumberMethods.nb_inplace_xor (C mem-
PyNumber_InPlacePower (C function), 103 ber), 291
PyNumber_InPlaceRemainder (C function), 103 PyNumberMethods.nb_int (C member), 291
PyNumber_InPlaceRshift (C function), 103 PyNumberMethods.nb_invert (C member), 291
PyNumber_InPlaceSubtract (C function), 102 PyNumberMethods.nb_lshift (C member), 291
PyNumber_InPlaceTrueDivide (C function), PyNumberMethods.nb_matrix_multiply (C
103 member), 292
PyNumber_InPlaceXor (C function), 103 PyNumberMethods.nb_multiply (C member),
PyNumber_Invert (C function), 102 291
PyNumber_Long (C function), 103 PyNumberMethods.nb_negative (C member),
PyNumber_Lshift (C function), 102 291
PyNumber_MatrixMultiply (C function), 101 PyNumberMethods.nb_or (C member), 291
PyNumber_Multiply (C function), 101 PyNumberMethods.nb_positive (C member),
PyNumber_Negative (C function), 102 291
PyNumber_Or (C function), 102 PyNumberMethods.nb_power (C member), 291
PyNumber_Positive (C function), 102 PyNumberMethods.nb_remainder (C member),
PyNumber_Power (C function), 102 291
PyNumber_Remainder (C function), 102 PyNumberMethods.nb_reserved (C member),
PyNumber_Rshift (C function), 102 291
PyNumber_Subtract (C function), 101 PyNumberMethods.nb_rshift (C member), 291
PyNumber_ToBase (C function), 104 PyNumberMethods.nb_subtract (C member),
PyNumber_TrueDivide (C function), 101 291
PyNumber_Xor (C function), 102 PyNumberMethods.nb_true_divide (C mem-
PyNumberMethods (C type), 290 ber), 291
PyNumberMethods.nb_absolute (C member), PyNumberMethods.nb_xor (C member), 291
291 PyObject (C type), 254
PyNumberMethods.nb_add (C member), 290 PyObject_AsCharBuffer (C function), 115
PyNumberMethods.nb_and (C member), 291 PyObject_ASCII (C function), 93
PyNumberMethods.nb_bool (C member), 291 PyObject_AsFileDescriptor (C function), 168

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

PyObject_AsReadBuffer (C function), 115 PyObject_IS_GC (C function), 300


PyObject_AsWriteBuffer (C function), 115 PyObject_IsInstance (C function), 94
PyObject_Bytes (C function), 93 PyObject_IsSubclass (C function), 94
PyObject_Call (C function), 99 PyObject_IsTrue (C function), 94
PyObject_CallFunction (C function), 99 PyObject_Length (C function), 95
PyObject_CallFunctionObjArgs (C function), PyObject_LengthHint (C function), 95
100 PyObject_Malloc (C function), 245
PyObject_CallMethod (C function), 100 PyObject_New (C macro), 253
PyObject_CallMethodNoArgs (C function), 100 PyObject_NewVar (C macro), 253
PyObject_CallMethodObjArgs (C function), PyObject_Not (C function), 94
100 PyObject._ob_next (C member), 270
PyObject_CallMethodOneArg (C function), 100 PyObject._ob_prev (C member), 270
PyObject_CallNoArgs (C function), 99 PyObject_Print (C function), 91
PyObject_CallObject (C function), 99 PyObject_Realloc (C function), 245
PyObject_Calloc (C function), 245 PyObject_Repr (C function), 93
PyObject_CallOneArg (C function), 99 PyObject_RichCompare (C function), 93
PyObject_CheckBuffer (C function), 114 PyObject_RichCompareBool (C function), 93
PyObject_CheckReadBuffer (C function), 115 PyObject_SetArenaAllocator (C function),
PyObject_ClearWeakRefs (C function), 180 250
PyObject_CopyData (C function), 114 PyObject_SetAttr (C function), 92
PyObject_Del (C function), 253 PyObject_SetAttrString (C function), 92
PyObject_DelAttr (C function), 92 PyObject_SetItem (C function), 95
PyObject_DelAttrString (C function), 92 PyObject_Size (C function), 95
PyObject_DelItem (C function), 95 PyObject_Str (C function), 93
PyObject_Dir (C function), 95 PyObject_Type (C function), 94
PyObject_Format (C function), 93 PyObject_TypeCheck (C function), 94
PyObject_Free (C function), 245 PyObject_VAR_HEAD (C macro), 254
PyObject_GC_Del (C function), 300 PyObject_Vectorcall (C function), 100
PyObject_GC_IsFinalized (C function), 300 PyObject_VectorcallDict (C function), 100
PyObject_GC_IsTracked (C function), 300 PyObject_VectorcallMethod (C function), 101
PyObject_GC_New (C macro), 299 PyObjectArenaAllocator (C type), 249
PyObject_GC_NewVar (C macro), 299 PyObject.ob_refcnt (C member), 269
PyObject_GC_Resize (C macro), 300 PyObject.ob_type (C member), 269
PyObject_GC_Track (C function), 300 PyOS_AfterFork (C function), 66
PyObject_GC_UnTrack (C function), 300 PyOS_AfterFork_Child (C function), 66
PyObject_GenericGetAttr (C function), 92 PyOS_AfterFork_Parent (C function), 65
PyObject_GenericGetDict (C function), 92 PyOS_BeforeFork (C function), 65
PyObject_GenericSetAttr (C function), 92 PyOS_CheckStack (C function), 66
PyObject_GenericSetDict (C function), 93 PyOS_double_to_string (C function), 84
PyObject_GetAIter (C function), 95 PyOS_FSPath (C function), 65
PyObject_GetArenaAllocator (C function), PyOS_getsig (C function), 66
249 PyOS_InputHook (C var), 43
PyObject_GetAttr (C function), 92 PyOS_ReadlineFunctionPointer (C var), 43
PyObject_GetAttrString (C function), 92 PyOS_setsig (C function), 66
PyObject_GetBuffer (C function), 114 PyOS_sighandler_t (C type), 66
PyObject_GetItem (C function), 95 PyOS_snprintf (C function), 83
PyObject_GetItemData (C function), 96 PyOS_stricmp (C function), 85
PyObject_GetIter (C function), 95 PyOS_string_to_double (C function), 84
PyObject_GetTypeData (C function), 95 PyOS_strnicmp (C function), 85
PyObject_HasAttr (C function), 91 PyOS_strtol (C function), 84
PyObject_HasAttrString (C function), 91 PyOS_strtoul (C function), 84
PyObject_Hash (C function), 94 PyOS_vsnprintf (C function), 83
PyObject_HashNotImplemented (C function), PyPreConfig (C type), 222
94 PyPreConfig_InitIsolatedConfig (C fun-
PyObject_HEAD (C macro), 254 ction), 222
PyObject_HEAD_INIT (C macro), 255 PyPreConfig_InitPythonConfig (C function),
PyObject_Init (C function), 253 222
PyObject_InitVar (C function), 253 PyPreConfig.allocator (C member), 222

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

PyPreConfig.coerce_c_locale (C member), PySequence_SetSlice (C function), 105


223 PySequence_Size (C function), 104
PyPreConfig.coerce_c_locale_warn (C PySequence_Tuple (C function), 105
member), 223 PySequenceMethods (C type), 292
PyPreConfig.configure_locale (C member), PySequenceMethods.sq_ass_item (C mem-
222 ber), 292
PyPreConfig.dev_mode (C member), 223 PySequenceMethods.sq_concat (C member),
PyPreConfig.isolated (C member), 223 292
PyPreConfig.legacy_windows_fs_encoding PySequenceMethods.sq_contains (C mem-
(C member), 223 ber), 293
PyPreConfig.parse_argv (C member), 223 PySequenceMethods.sq_inplace_concat (C
PyPreConfig.use_environment (C member), member), 293
223 PySequenceMethods.sq_inplace_repeat (C
PyPreConfig.utf8_mode (C member), 223 member), 293
PyProperty_Type (C var), 177 PySequenceMethods.sq_item (C member), 292
PyRun_AnyFile (C function), 41 PySequenceMethods.sq_length (C member),
PyRun_AnyFileEx (C function), 41 292
PyRun_AnyFileExFlags (C function), 42 PySequenceMethods.sq_repeat (C member),
PyRun_AnyFileFlags (C function), 41 292
PyRun_File (C function), 43 PySet_Add (C function), 160
PyRun_FileEx (C function), 43 PySet_Check (C function), 159
PyRun_FileExFlags (C function), 43 PySet_CheckExact (C function), 159
PyRun_FileFlags (C function), 43 PySet_Clear (C function), 160
PyRun_InteractiveLoop (C function), 42 PySet_Contains (C function), 160
PyRun_InteractiveLoopFlags (C function), 42 PySet_Discard (C function), 160
PyRun_InteractiveOne (C function), 42 PySet_GET_SIZE (C function), 159
PyRun_InteractiveOneFlags (C function), 42 PySet_New (C function), 159
PyRun_SimpleFile (C function), 42 PySet_Pop (C function), 160
PyRun_SimpleFileEx (C function), 42 PySet_Size (C function), 159
PyRun_SimpleFileExFlags (C function), 42 PySet_Type (C var), 159
PyRun_SimpleString (C function), 42 PySetObject (C type), 158
PyRun_SimpleStringFlags (C function), 42 PySignal_SetWakeupFd (C function), 59
PyRun_String (C function), 43 PySlice_AdjustIndices (C function), 179
PyRun_StringFlags (C function), 43 PySlice_Check (C function), 178
PySendResult (C type), 108 PySlice_GetIndices (C function), 178
PySeqIter_Check (C function), 177 PySlice_GetIndicesEx (C function), 178
PySeqIter_New (C function), 177 PySlice_New (C function), 178
PySeqIter_Type (C var), 177 PySlice_Type (C var), 178
PySequence_Check (C function), 104 PySlice_Unpack (C function), 178
PySequence_Concat (C function), 104 PyState_AddModule (C function), 176
PySequence_Contains (C function), 105 PyState_FindModule (C function), 176
PySequence_Count (C function), 105 PyState_RemoveModule (C function), 176
PySequence_DelItem (C function), 105 PyStatus (C type), 221
PySequence_DelSlice (C function), 105 PyStatus_Error (C function), 221
PySequence_Fast (C function), 105 PyStatus_Exception (C function), 221
PySequence_Fast_GET_ITEM (C function), 106 PyStatus_Exit (C function), 221
PySequence_Fast_GET_SIZE (C function), 106 PyStatus_IsError (C function), 221
PySequence_Fast_ITEMS (C function), 106 PyStatus_IsExit (C function), 221
PySequence_GetItem (C function), 9, 105 PyStatus_NoMemory (C function), 221
PySequence_GetSlice (C function), 105 PyStatus_Ok (C function), 221
PySequence_Index (C function), 105 PyStatus.err_msg (C member), 221
PySequence_InPlaceConcat (C function), 104 PyStatus.exitcode (C member), 221
PySequence_InPlaceRepeat (C function), 104 PyStatus.func (C member), 221
PySequence_ITEM (C function), 106 PyStructSequence_Desc (C type), 152
PySequence_Length (C function), 104 PyStructSequence_Desc.doc (C member), 152
PySequence_List (C function), 105 PyStructSequence_Desc.fields (C member),
PySequence_Repeat (C function), 104 152
PySequence_SetItem (C function), 105

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

PyStructSequence_Desc.n_in_sequence (C PEP 489, 173, 211


member), 152 PEP 492, 306308
PyStructSequence_Desc.name (C member), PEP 498, 309
152 PEP 519, 317
PyStructSequence_Field (C type), 152 PEP 523, 184, 209
PyStructSequence_Field.doc (C member), PEP 525, 306
152 PEP 526, 305, 320
PyStructSequence_Field.name (C member), PEP 528, 196, 230
152 PEP 529, 142, 196
PyStructSequence_GET_ITEM (C function), 153 PEP 538, 237
PyStructSequence_GetItem (C function), 153 PEP 539, 216
PyStructSequence_InitType (C function), 152 PEP 540, 237
PyStructSequence_InitType2 (C function), PEP 552, 228
152 PEP 554, 212
PyStructSequence_New (C function), 153 PEP 578, 70
PyStructSequence_NewType (C function), 152 PEP 585, 311
PyStructSequence_SET_ITEM (C function), 153 PEP 587, 219
PyStructSequence_SetItem (C function), 153 PEP 590, 96
PyStructSequence_UnnamedField (C var), PEP 623, 134
152 PEP 634, 279
PySys_AddAuditHook (C function), 69 PEP 3116, 320
PySys_AddWarnOption (C function), 68 PEP 3119, 94
PySys_AddWarnOptionUnicode (C function), 68 PEP 3121, 170
PySys_AddXOption (C function), 69 PEP 3147, 72
PySys_Audit (C function), 69 PEP 3151, 64
PySys_FormatStderr (C function), 69 PEP 3155, 317
PySys_FormatStdout (C function), 69 PYTHONCOERCECLOCALE, 237
PySys_GetObject (C function), 68 PYTHONDEBUG, 194, 232
PySys_GetXOptions (C function), 69 PYTHONDEVMODE, 228
PySys_ResetWarnOptions (C function), 68 PYTHONDONTWRITEBYTECODE, 194, 235
PySys_SetArgv (C function), 197, 202 PYTHONDUMPREFS, 228, 270
PySys_SetArgvEx (C function), 197, 201 PYTHONEXECUTABLE, 232
PySys_SetObject (C function), 68 PYTHONFAULTHANDLER, 228
PySys_SetPath (C function), 68 PYTHONHASHSEED, 195, 229
PySys_WriteStderr (C function), 68 PYTHONHOME, 12, 195, 202, 229
PySys_WriteStdout (C function), 68 Pythónico, 317
Python 3000, 317 PYTHONINSPECT, 195, 229
Python Enhancement Proposals PYTHONINTMAXSTRDIGITS, 230
PEP 1, 317 PYTHONIOENCODING, 198, 234
PEP 7, 3, 6, 7 PYTHONLEGACYWINDOWSFSENCODING, 196, 223
PEP 238, 45, 310 PYTHONLEGACYWINDOWSSTDIO, 196, 230
PEP 278, 320 PYTHONMALLOC, 242, 246, 248, 249
PEP 302, 314 PYTHONMALLOCSTATS, 230, 242
PEP 343, 308 PYTHONNODEBUGRANGES, 227
PEP 353, 10 PYTHONNOUSERSITE, 196, 234
PEP 362, 306, 316 PYTHONOPTIMIZE, 196, 231
PEP 383, 141, 142 PYTHONPATH, 12, 195, 231
PEP 387, 15 PYTHONPERFSUPPORT, 234
PEP 393, 134 PYTHONPLATLIBDIR, 231
PEP 411, 317 PYTHONPROFILEIMPORTTIME, 229
PEP 420, 315, 317 PYTHONPYCACHEPREFIX, 232
PEP 432, 239, 240 PYTHONSAFEPATH, 226
PEP 442, 289 PYTHONTRACEMALLOC, 234
PEP 443, 311 PYTHONUNBUFFERED, 197, 227
PEP 451, 172 PYTHONUTF8, 223, 237
PEP 456, 85 PYTHONVERBOSE, 197, 235
PEP 483, 311 PYTHONWARNINGS, 235
PEP 484, 305, 310, 311, 320 PyThread_create_key (C function), 218

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

PyThread_delete_key (C function), 218 PyTuple_SetItem (C function), 8, 151


PyThread_delete_key_value (C function), 218 PyTuple_Size (C function), 151
PyThread_get_key_value (C function), 218 PyTuple_Type (C var), 151
PyThread_ReInitTLS (C function), 218 PyTupleObject (C type), 151
PyThread_set_key_value (C function), 218 PyType_AddWatcher (C function), 118
PyThread_tss_alloc (C function), 217 PyType_Check (C function), 117
PyThread_tss_create (C function), 217 PyType_CheckExact (C function), 117
PyThread_tss_delete (C function), 217 PyType_ClearCache (C function), 117
PyThread_tss_free (C function), 217 PyType_ClearWatcher (C function), 118
PyThread_tss_get (C function), 217 PyType_FromMetaclass (C function), 120
PyThread_tss_is_created (C function), 217 PyType_FromModuleAndSpec (C function), 121
PyThread_tss_set (C function), 217 PyType_FromSpec (C function), 121
PyThreadState (C type), 203, 205 PyType_FromSpecWithBases (C function), 121
PyThreadState_Clear (C function), 207 PyType_GenericAlloc (C function), 119
PyThreadState_Delete (C function), 207 PyType_GenericNew (C function), 119
PyThreadState_DeleteCurrent (C function), PyType_GetDict (C function), 118
207 PyType_GetFlags (C function), 117
PyThreadState_EnterTracing (C function), PyType_GetModule (C function), 119
208 PyType_GetModuleByDef (C function), 120
PyThreadState_Get (C function), 205 PyType_GetModuleState (C function), 119
PyThreadState_GetDict (C function), 209 PyType_GetName (C function), 119
PyThreadState_GetFrame (C function), 207 PyType_GetQualName (C function), 119
PyThreadState_GetID (C function), 208 PyType_GetSlot (C function), 119
PyThreadState_GetInterpreter (C function), PyType_GetTypeDataSize (C function), 95
208 PyType_HasFeature (C function), 118
PyThreadState_LeaveTracing (C function), PyType_IS_GC (C function), 118
208 PyType_IsSubtype (C function), 118
PyThreadState_New (C function), 207 PyType_Modified (C function), 118
PyThreadState_Next (C function), 216 PyType_Ready (C function), 119
PyThreadState_SetAsyncExc (C function), 209 PyType_Slot (C type), 122
PyThreadState_Swap (C function), 205 PyType_Slot.pfunc (C member), 123
PyThreadState.interp (C member), 205 PyType_Slot.slot (C member), 122
PyTime_Check (C function), 188 PyType_Spec (C type), 121
PyTime_CheckExact (C function), 188 PyType_Spec.basicsize (C member), 121
PyTime_FromTime (C function), 189 PyType_Spec.flags (C member), 122
PyTime_FromTimeAndFold (C function), 189 PyType_Spec.itemsize (C member), 121
PyTimeZone_FromOffset (C function), 189 PyType_Spec.name (C member), 121
PyTimeZone_FromOffsetAndName (C function), PyType_Spec.slots (C member), 122
189 PyType_Type (C var), 117
PyTrace_C_CALL (C var), 215 PyType_Watch (C function), 118
PyTrace_C_EXCEPTION (C var), 215 PyType_WatchCallback (C type), 118
PyTrace_C_RETURN (C var), 215 PyTypeObject (C type), 117
PyTrace_CALL (C var), 214 PyTypeObject.tp_alloc (C member), 286
PyTrace_EXCEPTION (C var), 214 PyTypeObject.tp_as_async (C member), 273
PyTrace_LINE (C var), 214 PyTypeObject.tp_as_buffer (C member), 275
PyTrace_OPCODE (C var), 215 PyTypeObject.tp_as_mapping (C member),
PyTrace_RETURN (C var), 215 273
PyTraceMalloc_Track (C function), 250 PyTypeObject.tp_as_number (C member), 273
PyTraceMalloc_Untrack (C function), 250 PyTypeObject.tp_as_sequence (C member),
PyTuple_Check (C function), 151 273
PyTuple_CheckExact (C function), 151 PyTypeObject.tp_base (C member), 284
PyTuple_GET_ITEM (C function), 151 PyTypeObject.tp_bases (C member), 287
PyTuple_GET_SIZE (C function), 151 PyTypeObject.tp_basicsize (C member), 271
PyTuple_GetItem (C function), 151 PyTypeObject.tp_cache (C member), 287
PyTuple_GetSlice (C function), 151 PyTypeObject.tp_call (C member), 274
PyTuple_New (C function), 151 PyTypeObject.tp_clear (C member), 280
PyTuple_Pack (C function), 151 PyTypeObject.tp_dealloc (C member), 271
PyTuple_SET_ITEM (C function), 151 PyTypeObject.tp_del (C member), 288

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

PyTypeObject.tp_descr_get (C member), 284 PyUnicode_AsUCS4Copy (C function), 141


PyTypeObject.tp_descr_set (C member), 285 PyUnicode_AsUnicodeEscapeString (C fun-
PyTypeObject.tp_dict (C member), 284 ction), 147
PyTypeObject.tp_dictoffset (C member), PyUnicode_AsUTF8 (C function), 145
285 PyUnicode_AsUTF8AndSize (C function), 144
PyTypeObject.tp_doc (C member), 279 PyUnicode_AsUTF8String (C function), 144
PyTypeObject.tp_finalize (C member), 288 PyUnicode_AsUTF16String (C function), 146
PyTypeObject.tp_flags (C member), 275 PyUnicode_AsUTF32String (C function), 145
PyTypeObject.tp_free (C member), 286 PyUnicode_AsWideChar (C function), 143
PyTypeObject.tp_getattr (C member), 272 PyUnicode_AsWideCharString (C function),
PyTypeObject.tp_getattro (C member), 274 143
PyTypeObject.tp_getset (C member), 283 PyUnicode_Check (C function), 135
PyTypeObject.tp_hash (C member), 273 PyUnicode_CheckExact (C function), 135
PyTypeObject.tp_init (C member), 285 PyUnicode_Compare (C function), 150
PyTypeObject.tp_is_gc (C member), 287 PyUnicode_CompareWithASCIIString (C
PyTypeObject.tp_itemsize (C member), 271 function), 150
PyTypeObject.tp_iter (C member), 283 PyUnicode_Concat (C function), 149
PyTypeObject.tp_iternext (C member), 283 PyUnicode_Contains (C function), 150
PyTypeObject.tp_members (C member), 283 PyUnicode_CopyCharacters (C function), 140
PyTypeObject.tp_methods (C member), 283 PyUnicode_Count (C function), 150
PyTypeObject.tp_mro (C member), 287 PyUnicode_DATA (C function), 135
PyTypeObject.tp_name (C member), 270 PyUnicode_Decode (C function), 144
PyTypeObject.tp_new (C member), 286 PyUnicode_DecodeASCII (C function), 147
PyTypeObject.tp_repr (C member), 273 PyUnicode_DecodeCharmap (C function), 148
PyTypeObject.tp_richcompare (C member), PyUnicode_DecodeFSDefault (C function), 143
281 PyUnicode_DecodeFSDefaultAndSize (C
PyTypeObject.tp_setattr (C member), 272 function), 142
PyTypeObject.tp_setattro (C member), 275 PyUnicode_DecodeLatin1 (C function), 147
PyTypeObject.tp_str (C member), 274 PyUnicode_DecodeLocale (C function), 141
PyTypeObject.tp_subclasses (C member), PyUnicode_DecodeLocaleAndSize (C fun-
287 ction), 141
PyTypeObject.tp_traverse (C member), 279 PyUnicode_DecodeMBCS (C function), 148
PyTypeObject.tp_vectorcall (C member), PyUnicode_DecodeMBCSStateful (C function),
289 148
PyTypeObject.tp_vectorcall_offset (C PyUnicode_DecodeRawUnicodeEscape (C
member), 272 function), 147
PyTypeObject.tp_version_tag (C member), PyUnicode_DecodeUnicodeEscape (C fun-
288 ction), 147
PyTypeObject.tp_watched (C member), 289 PyUnicode_DecodeUTF7 (C function), 146
PyTypeObject.tp_weaklist (C member), 288 PyUnicode_DecodeUTF7Stateful (C function),
PyTypeObject.tp_weaklistoffset (C mem- 146
ber), 282 PyUnicode_DecodeUTF8 (C function), 144
PyTZInfo_Check (C function), 188 PyUnicode_DecodeUTF8Stateful (C function),
PyTZInfo_CheckExact (C function), 188 144
PyUnicode_1BYTE_DATA (C function), 135 PyUnicode_DecodeUTF16 (C function), 146
PyUnicode_1BYTE_KIND (C macro), 135 PyUnicode_DecodeUTF16Stateful (C fun-
PyUnicode_2BYTE_DATA (C function), 135 ction), 146
PyUnicode_2BYTE_KIND (C macro), 135 PyUnicode_DecodeUTF32 (C function), 145
PyUnicode_4BYTE_DATA (C function), 135 PyUnicode_DecodeUTF32Stateful (C fun-
PyUnicode_4BYTE_KIND (C macro), 135 ction), 145
PyUnicode_AsASCIIString (C function), 147 PyUnicode_EncodeCodePage (C function), 149
PyUnicode_AsCharmapString (C function), 148 PyUnicode_EncodeFSDefault (C function), 143
PyUnicode_AsEncodedString (C function), 144 PyUnicode_EncodeLocale (C function), 142
PyUnicode_AsLatin1String (C function), 147 PyUnicode_Fill (C function), 140
PyUnicode_AsMBCSString (C function), 148 PyUnicode_Find (C function), 149
PyUnicode_AsRawUnicodeEscapeString (C PyUnicode_FindChar (C function), 149
function), 147 PyUnicode_Format (C function), 150
PyUnicode_AsUCS4 (C function), 141

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

PyUnicode_FromEncodedObject (C function), PyUnicodeEncodeError_GetObject (C fun-


140 ction), 61
PyUnicode_FromFormat (C function), 138 PyUnicodeEncodeError_GetReason (C fun-
PyUnicode_FromFormatV (C function), 140 ction), 61
PyUnicode_FromKindAndData (C function), 138 PyUnicodeEncodeError_GetStart (C fun-
PyUnicode_FromObject (C function), 140 ction), 61
PyUnicode_FromString (C function), 138 PyUnicodeEncodeError_SetEnd (C function),
PyUnicode_FromStringAndSize (C function), 61
138 PyUnicodeEncodeError_SetReason (C fun-
PyUnicode_FromWideChar (C function), 143 ction), 62
PyUnicode_FSConverter (C function), 142 PyUnicodeEncodeError_SetStart (C fun-
PyUnicode_FSDecoder (C function), 142 ction), 61
PyUnicode_GET_LENGTH (C function), 135 PyUnicodeObject (C type), 134
PyUnicode_GetLength (C function), 140 PyUnicodeTranslateError_GetEnd (C fun-
PyUnicode_InternFromString (C function), ction), 61
150 PyUnicodeTranslateError_GetObject (C
PyUnicode_InternInPlace (C function), 150 function), 61
PyUnicode_IsIdentifier (C function), 136 PyUnicodeTranslateError_GetReason (C
PyUnicode_Join (C function), 149 function), 61
PyUnicode_KIND (C function), 135 PyUnicodeTranslateError_GetStart (C
PyUnicode_MAX_CHAR_VALUE (C function), 136 function), 61
PyUnicode_New (C function), 138 PyUnicodeTranslateError_SetEnd (C fun-
PyUnicode_READ (C function), 136 ction), 61
PyUnicode_READ_CHAR (C function), 136 PyUnicodeTranslateError_SetReason (C
PyUnicode_ReadChar (C function), 141 function), 62
PyUnicode_READY (C function), 135 PyUnicodeTranslateError_SetStart (C
PyUnicode_Replace (C function), 150 function), 61
PyUnicode_RichCompare (C function), 150 PyUnstable, 15
PyUnicode_Split (C function), 149 PyUnstable_Code_GetExtra (C function), 167
PyUnicode_Splitlines (C function), 149 PyUnstable_Code_New (C function), 164
PyUnicode_Substring (C function), 141 PyUnstable_Code_NewWithPosOnlyArgs (C
PyUnicode_Tailmatch (C function), 149 function), 164
PyUnicode_Translate (C function), 148 PyUnstable_Code_SetExtra (C function), 167
PyUnicode_Type (C var), 135 PyUnstable_Eval_RequestCodeExtraIndex
PyUnicode_WRITE (C function), 135 (C function), 167
PyUnicode_WriteChar (C function), 140 PyUnstable_Exc_PrepReraiseStar (C fun-
PyUnicodeDecodeError_Create (C function), ction), 60
61 PyUnstable_GC_VisitObjects (C function),
PyUnicodeDecodeError_GetEncoding (C 302
function), 61 PyUnstable_InterpreterFrame_GetCode (C
PyUnicodeDecodeError_GetEnd (C function), function), 184
61 PyUnstable_InterpreterFrame_GetLasti
PyUnicodeDecodeError_GetObject (C fun- (C function), 184
ction), 61 PyUnstable_InterpreterFrame_GetLine (C
PyUnicodeDecodeError_GetReason (C fun- function), 184
ction), 61 PyUnstable_Long_CompactValue (C function),
PyUnicodeDecodeError_GetStart (C fun- 126
ction), 61 PyUnstable_Long_IsCompact (C function), 126
PyUnicodeDecodeError_SetEnd (C function), PyUnstable_Object_GC_NewWithExtraData
61 (C function), 299
PyUnicodeDecodeError_SetReason (C fun- PyUnstable_PerfMapState_Fini (C function),
ction), 62 88
PyUnicodeDecodeError_SetStart (C fun- PyUnstable_PerfMapState_Init (C function),
ction), 61 88
PyUnicodeEncodeError_GetEncoding (C PyUnstable_Type_AssignVersionTag (C
function), 61 function), 120
PyUnicodeEncodeError_GetEnd (C function), PyUnstable_WritePerfMapEntry (C function),
61 88

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

PyVarObject (C type), 254 SIZE_MAX (C macro), 125


PyVarObject_HEAD_INIT (C macro), 255 special
PyVarObject.ob_size (C member), 270 método, 319
PyVectorcall_Call (C function), 98 ssizeargfunc (C type), 296
PyVectorcall_Function (C function), 98 ssizeobjargproc (C type), 296
PyVectorcall_NARGS (C function), 98 static type checker, 319
PyWeakref_Check (C function), 180 staticmethod
PyWeakref_CheckProxy (C function), 180 built-in function, 258
PyWeakref_CheckRef (C function), 180 stderr (in module sys), 211, 212
PyWeakref_GET_OBJECT (C function), 180 stdin
PyWeakref_GetObject (C function), 180 stdout sdterr, 198
PyWeakref_NewProxy (C function), 180 stdin (in module sys), 211, 212
PyWeakref_NewRef (C function), 180 stdout
PyWideStringList (C type), 220 sdterr, stdin, 198
PyWideStringList_Append (C function), 220 stdout (in module sys), 211, 212
PyWideStringList_Insert (C function), 220 strerror (C function), 53
PyWideStringList.items (C member), 220 string
PyWideStringList.length (C member), 220 PyObject_Str (C function), 93
PyWrapper_New (C function), 177 structmember.h, 262
sum_list(), 9
R sum_sequence(), 10, 11
READ_RESTRICTED (C macro), 260 sys
READONLY (C macro), 260 module, 12, 197, 211, 212
realloc (C function), 241 SystemError (built-in exception), 169, 170
rebanada, 318
recolección de basura, 311 T
referencia fuerte, 319 T_BOOL (C macro), 262
referencia prestada, 307 T_BYTE (C macro), 262
releasebufferproc (C type), 296 T_CHAR (C macro), 262
repr T_DOUBLE (C macro), 262
built-in function, 93, 273 T_FLOAT (C macro), 262
reprfunc (C type), 295 T_INT (C macro), 262
RESTRICTED (C macro), 260 T_LONG (C macro), 262
retrollamada, 307 T_LONGLONG (C macro), 262
richcmpfunc (C type), 296 T_NONE (C macro), 262
ruta de importación, 312 T_OBJECT (C macro), 262
T_OBJECT_EX (C macro), 262
S T_PYSSIZET (C macro), 262
saltos de líneas universales, 320 T_SHORT (C macro), 262
sdterr T_STRING (C macro), 262
stdin stdout, 198 T_STRING_INPLACE (C macro), 262
search T_UBYTE (C macro), 262
path, module, 12, 197, 200 T_UINT (C macro), 262
secuencia, 318 T_ULONG (C macro), 262
sendfunc (C type), 296 T_ULONGULONG (C macro), 262
sentencia, 319 T_USHORT (C macro), 262
sequence ternaryfunc (C type), 296
object, 131 tipado de pato, 309
set tipo, 319
object, 158 tipos genéricos, 311
set_all(), 9 traverseproc (C type), 301
setattrfunc (C type), 295 tupla nombrada, 315
setattrofunc (C type), 295 tuple
setswitchinterval (in module sys), 203 built-in function, 105, 154
setter (C type), 262 object, 151
SIGINT (C macro), 59 type
signal built-in function, 94
module, 59 object, 7, 117

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

U
ULONG_MAX (C macro), 125
unaryfunc (C type), 296
USE_STACKCHECK (C macro), 66

V
variable de clase, 308
variable de contexto, 308
variables de entorno
__PYVENV_LAUNCHER__, 227, 232
PATH, 12
PYTHONCOERCECLOCALE, 237
PYTHONDEBUG, 194, 232
PYTHONDEVMODE, 228
PYTHONDONTWRITEBYTECODE, 194, 235
PYTHONDUMPREFS, 228, 270
PYTHONEXECUTABLE, 232
PYTHONFAULTHANDLER, 228
PYTHONHASHSEED, 195, 229
PYTHONHOME, 12, 195, 202, 229
PYTHONINSPECT, 195, 229
PYTHONINTMAXSTRDIGITS, 230
PYTHONIOENCODING, 198, 234
PYTHONLEGACYWINDOWSFSENCODING, 196,
223
PYTHONLEGACYWINDOWSSTDIO, 196, 230
PYTHONMALLOC, 242, 246, 248, 249
PYTHONMALLOCSTATS, 230, 242
PYTHONNODEBUGRANGES, 227
PYTHONNOUSERSITE, 196, 234
PYTHONOPTIMIZE, 196, 231
PYTHONPATH, 12, 195, 231
PYTHONPERFSUPPORT, 234
PYTHONPLATLIBDIR, 231
PYTHONPROFILEIMPORTTIME, 229
PYTHONPYCACHEPREFIX, 232
PYTHONSAFEPATH, 226
PYTHONTRACEMALLOC, 234
PYTHONUNBUFFERED, 197, 227
PYTHONUTF8, 223, 237
PYTHONVERBOSE, 197, 235
PYTHONWARNINGS, 235
vectorcallfunc (C type), 97
version (in module sys), 200, 201
visitproc (C type), 301
vista de diccionario, 309

W
WRITE_RESTRICTED (C macro), 260

Z
Zen de Python, 320

366 Índice

También podría gustarte