0% encontró este documento útil (0 votos)
33 vistas401 páginas

C Api

Este documento describe la interfaz entre Python y C, permitiendo la integración de código C con Python. Explica conceptos como objetos, tipos, excepciones, manejo de memoria y más.

Cargado por

dvegaucentral
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)
33 vistas401 páginas

C Api

Este documento describe la interfaz entre Python y C, permitiendo la integración de código C con Python. Explica conceptos como objetos, tipos, excepciones, manejo de memoria y más.

Cargado por

dvegaucentral
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/ 401

The Python/C API

Versión 3.13.0a5

Guido van Rossum and the Python development team

marzo 16, 2024

Python Software Foundation


Email: [email protected]
Índice general

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

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

3 La capa de muy alto nivel 45

4 Conteo de referencias 51

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

i
6 Utilidades 71
6.1 Utilidades del sistema operativo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.2 Funciones del Sistema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.3 Control de procesos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.4 Importando módulos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.5 Soporte de empaquetado (marshalling) de datos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.6 Analizando argumentos y construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.6.1 Analizando argumentos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.6.2 Construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.7 Conversión y formato de cadenas de caracteres . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.8 PyHash API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.9 Reflexión . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.10 Registro de códec y funciones de soporte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
6.10.1 API de búsqueda de códec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.10.2 API de registro para controladores de errores de codificación Unicode . . . . . . . . . . . . . 95
6.11 PyTime C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.11.1 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.11.2 Clock Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.11.3 Conversion functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.12 Support for Perf Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

7 Capa de objetos abstractos 99


7.1 Protocolo de objeto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
7.2 Protocolo de llamada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
7.2.1 El protocolo tp_call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
7.2.2 El protocolo vectorcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
7.2.3 API para invocar objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
7.2.4 API de soporte de llamadas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
7.3 Protocolo de números . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
7.4 Protocolo de secuencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
7.5 Protocolo de mapeo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
7.6 Protocolo iterador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
7.7 Protocolo búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
7.7.1 Estructura de búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
7.7.2 Tipos de solicitud búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
7.7.3 Arreglos complejos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
7.7.4 Funciones relacionadas a búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

8 Capa de objetos concretos 127


8.1 Objetos fundamentales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.1.1 Objetos tipo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.1.2 El objeto None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.2 Objetos numéricos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
8.2.1 Objetos enteros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
8.2.2 Objetos booleanos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
8.2.3 Objetos de punto flotante . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
8.2.4 Objetos de números complejos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
8.3 Objetos de secuencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
8.3.1 Objetos bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
8.3.2 Objetos de arreglos de bytes (bytearrays) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
8.3.3 Objetos y códecs unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
8.3.4 Objetos tupla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
8.3.5 Objetos de secuencia de estructura . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
8.3.6 Objetos lista . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168

ii
8.4 Objetos contenedor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
8.4.1 Objetos diccionario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
8.4.2 Objetos conjunto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
8.5 Objetos de función . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.5.1 Objetos función . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.5.2 Objetos de método de instancia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
8.5.3 Objetos método . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.5.4 Objetos celda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.5.5 Objetos código . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
8.5.6 Extra information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
8.6 Otros objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.1 Objetos archivo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.2 Objetos módulo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
8.6.3 Objetos iteradores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
8.6.4 Objetos descriptores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
8.6.5 Objetos rebanada (slice) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
8.6.6 Objetos de vista de memoria (MemoryView) . . . . . . . . . . . . . . . . . . . . . . . . . . 197
8.6.7 Objetos de referencia débil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
8.6.8 Cápsulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
8.6.9 Objetos frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
8.6.10 Objetos generadores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
8.6.11 Objetos corrutina . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
8.6.12 Objetos de variables de contexto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
8.6.13 Objetos DateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
8.6.14 Objetos para indicaciones de tipado . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

9 Inicialización, finalización e hilos 211


9.1 Antes de la inicialización de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
9.2 Variables de configuración global . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
9.3 Inicializando y finalizando el intérprete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
9.4 Parámetros de todo el proceso . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
9.5 Estado del hilo y el bloqueo global del intérprete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
9.5.1 Liberando el GIL del código de extensión . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
9.5.2 Hilos creados sin Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
9.5.3 Precauciones sobre fork() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
9.5.4 API de alto nivel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
9.5.5 API de bajo nivel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
9.6 Soporte de subinterprete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
9.6.1 A Per-Interpreter GIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
9.6.2 Errores y advertencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
9.7 Notificaciones asincrónicas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
9.8 Perfilado y Rastreo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
9.9 Soporte avanzado del depurador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
9.10 Soporte de almacenamiento local de hilo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
9.10.1 API de almacenamiento específico de hilo (TSS, Thread Specific Storage) . . . . . . . . . . . 233
9.10.2 API de almacenamiento local de hilos (TLS, Thread Local Storage) . . . . . . . . . . . . . . 234

10 Configuración de inicialización de Python 237


10.1 Ejemplo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
10.2 PyWideStringList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
10.3 PyStatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
10.4 PyPreConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
10.5 Preinicialización de Python con PyPreConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
10.6 PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

iii
10.7 Inicialización con PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
10.8 Configuración aislada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
10.9 Configuración de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
10.10 Configuración de la ruta de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
10.11 Py_RunMain() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
10.12 Py_GetArgcArgv() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
10.13 API Provisional Privada de Inicialización Multifásica . . . . . . . . . . . . . . . . . . . . . . . . . . 259

11 Gestión de la memoria 261


11.1 Visión general . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
11.2 Dominios del asignador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
11.3 Interfaz de memoria sin procesar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
11.4 Interfaz de memoria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
11.5 Asignadores de objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
11.6 Asignadores de memoria predeterminados . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
11.7 Personalizar asignadores de memoria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
11.8 Configurar enlaces para detectar errores en las funciones del asignador de memoria de Python . . . . . 268
11.9 El asignador pymalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
11.9.1 Personalizar asignador de arena de pymalloc . . . . . . . . . . . . . . . . . . . . . . . . . . 270
11.10 The mimalloc allocator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
11.11 tracemalloc C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
11.12 Ejemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

12 Soporte de implementación de objetos 273


12.1 Asignación de objetos en el montículo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
12.2 Estructuras de objetos comunes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
12.2.1 Tipos objeto base y macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
12.2.2 Implementando funciones y métodos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
12.2.3 Acceder a atributos de tipos de extensión . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
12.3 Objetos tipo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
12.3.1 Referencia rápida . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
12.3.2 Definición de PyTypeObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
12.3.3 Ranuras (Slots) PyObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
12.3.4 Ranuras PyVarObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
12.3.5 Ranuras PyTypeObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
12.3.6 Tipos estáticos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
12.3.7 Tipos Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
12.4 Estructuras de objetos de números . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
12.5 Estructuras de objetos mapeo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
12.6 Estructuras de objetos secuencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
12.7 Estructuras de objetos búfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
12.8 Estructuras de objetos asíncronos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
12.9 Tipo Ranura typedefs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
12.10 Ejemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
12.11 Apoyo a la recolección de basura cíclica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
12.11.1 Controlar el estado del recolector de basura . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
12.11.2 Querying Garbage Collector State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325

13 Versiones de API y ABI 327

A Glosario 329

B Acerca de estos documentos 347


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

iv
C Historia y Licencia 349
C.1 Historia del software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
C.2 Términos y condiciones para acceder o usar Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
C.2.1 ACUERDO DE LICENCIA DE PSF PARA PYTHON | lanzamiento | . . . . . . . . . . . . 350
C.2.2 ACUERDO DE LICENCIA DE BEOPEN.COM PARA PYTHON 2.0 . . . . . . . . . . . . 351
C.2.3 ACUERDO DE LICENCIA CNRI PARA PYTHON 1.6.1 . . . . . . . . . . . . . . . . . . 352
C.2.4 ACUERDO DE LICENCIA CWI PARA PYTHON 0.9.0 HASTA 1.2 . . . . . . . . . . . . 353
C.2.5 LICENCIA BSD DE CLÁUSULA CERO PARA CÓDIGO EN EL PYTHON | lanzamiento
| DOCUMENTACIÓN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
C.3 Licencias y reconocimientos para software incorporado . . . . . . . . . . . . . . . . . . . . . . . . . 354
C.3.1 Mersenne Twister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
C.3.2 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
C.3.3 Servicios de socket asincrónicos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
C.3.4 Gestión de cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
C.3.5 Seguimiento de ejecución . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
C.3.6 funciones UUencode y UUdecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
C.3.7 Llamadas a procedimientos remotos XML . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
C.3.8 test_epoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
C.3.9 Seleccionar kqueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
C.3.10 SipHash24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
C.3.11 strtod y dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
C.3.18 Conjunto de pruebas W3C C14N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
C.3.19 mimalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
C.3.20 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
C.3.21 Global Unbounded Sequences (GUS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368

D Derechos de autor 369

Índice 371

v
vi
The Python/C API, Versión 3.13.0a5

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

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

2 Índice general
CAPÍTULO 1

Introducción

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

3
The Python/C API, Versión 3.13.0a5

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.

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 argumentos y
construyendo valores para obtener una descripción de este macro.

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

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

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

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

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 necesariamente
una lista completa.
PyMODINIT_FUNC
Declare an extension module PyInit initialization function. The function return type is PyObject*. The macro
declares any special linkage declarations required by the platform, and for C++ declares the function as extern
"C".
The initialization function must be named PyInit_name, where name is the name of the module, and should be
the only non-static item defined in the module file. Example:

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

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

Nuevo en la versión 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.

1.3. Macros útiles 5


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 3.3.
Py_MEMBER_SIZE(type, member)
Retorna el tamaño de una estructura (type) member en bytes.
Nuevo en la versión 3.6.
Py_MIN(x, y)
Retorna el valor mínimo entre x e y.
Nuevo en la versión 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; }

Nuevo en la versión 3.11.


Py_STRINGIFY(x)
Convierte x en una cadena de caracteres C. Por ejemplo, Py_STRINGIFY(123) retorna "123".
Nuevo en la versión 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().
Nuevo en la versión 3.7.

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

Py_UNUSED(arg)
Use esto para argumentos no utilizados en una definición de función para silenciar las advertencias del compilador.
Ejemplo: int func(int a, int Py_UNUSED(b)) {return a; }.
Nuevo en la versión 3.4.
PyDoc_STRVAR(name, str)
Crea una variable con el nombre name que se puede usar en docstrings. Si Python se construye sin docstrings, el
valor estará vacío.
Utilice PyDoc_STRVAR para que los docstrings admitan la construcción de Python sin docstrings, como se espe-
cifica en PEP 7.
Ejemplo:

PyDoc_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 deshabi-
litados.
Utilice PyDoc_STR al especificar docstrings para admitir la construcción de Python sin docstrings, como se espe-
cifica en PEP 7.
Ejemplo:

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. Objetos, tipos y conteos de referencias 7


The Python/C API, Versión 3.13.0a5

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.
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 reference»
means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership can also
be transferred, meaning that the code that receives ownership of the reference then becomes responsible for eventually
releasing it by calling Py_DECREF() or Py_XDECREF() when it’s no longer needed—or passing on this responsibility
(usually to its caller). When a function passes ownership of a reference on to its caller, the caller is said to receive a new
reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing needs to be done for a
borrowed reference.
Por el contrario, cuando una función de llamada pasa una referencia a un objeto, hay dos posibilidades: la función roba
una referencia al objeto, o no lo hace. Robar una referencia significa que cuando pasa una referencia a una función, esa
función asume que ahora posee esa referencia, y usted ya no es responsable de ella.

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

Pocas funciones roban referencias; las dos excepciones notables son PyList_SetItem() y PyTuple_SetItem(),
que roban una referencia al elemento (¡pero no a la tupla o lista en la que se coloca el elemento!). Estas funciones fueron
diseñadas para robar una referencia debido a un idioma común para poblar una tupla o lista con objetos recién creados;
por ejemplo, el código para crear la tupla (1, 2, "tres") podría verse así (olvidando el manejo de errores por el
momento; una mejor manera de codificar esto se muestra a continuación):

PyObject *t;

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

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

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 borro-
wing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding references
is much saner, since you don’t have to take a new reference just so you can give that reference away («have it be stolen»).
For example, this function sets all items of a list (actually, any mutable sequence) to a given item:

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

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

1.4. Objetos, tipos y conteos de referencias 9


The Python/C API, Versión 3.13.0a5

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

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

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

long
sum_sequence(PyObject *sequence)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
n = PySequence_Length(sequence);
if (n < 0)
return -1; /* Has no length */
for (i = 0; i < n; i++) {
item = PySequence_GetItem(sequence, i);
if (item == NULL)
return -1; /* Not a sequence, or other failure */
if (PyLong_Check(item)) {
value = PyLong_AsLong(item);
Py_DECREF(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
(continúe en la próxima página)

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

(proviene de la página anterior)


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 excepcio-
nes no manejadas se propagan automáticamente a la persona que llama, luego a la persona que llama, y así sucesivamente,
hasta que llegan al intérprete de nivel superior, donde se informan al usuario acompañado de un seguimiento de pila (stack
traceback).
Para los programadores de C, sin embargo, la comprobación de errores siempre tiene que ser explícita. Todas las fun-
ciones en la API Python/C pueden generar excepciones, a menos que se señale explícitamente en la documentación de
una función. En general, cuando una función encuentra un error, establece una excepción, descarta cualquier referencia
de objeto que posea y retorna un indicador de error. Si no se documenta lo contrario, este indicador es NULL o -1,
dependiendo del tipo de retorno de la función. Algunas funciones retornan un resultado booleano verdadero/falso, con
falso que indica un error. Muy pocas funciones no retornan ningún indicador de error explícito o tienen un valor de
retorno ambiguo, y requieren pruebas explícitas de errores con PyErr_Occurred(). Estas excepciones siempre se
documentan explícitamente.
El estado de excepción se mantiene en el almacenamiento por subproceso (esto es equivalente a usar el almacenamiento
global en una aplicación sin subprocesos). Un subproceso puede estar en uno de dos estados: se ha producido una excepción
o no. La función PyErr_Occurred() puede usarse para verificar esto: retorna una referencia prestada al objeto de
tipo de excepción cuando se produce una excepción, y NULL de lo contrario. Hay una serie de funciones para establecer
el estado de excepción: PyErr_SetString() es la función más común (aunque no la más general) para establecer el
estado de excepción, y PyErr_Clear() borra la excepción estado.
El estado de excepción completo consta de tres objetos (todos los cuales pueden ser NULL): el tipo de excepción, el
valor de excepción correspondiente y el rastreo. Estos tienen los mismos significados que el resultado de Python de sys.
exc_info(); sin embargo, no son lo mismo: los objetos Python representan la última excepción manejada por una
declaración de Python try … except, mientras que el estado de excepción de nivel C solo existe mientras se está
pasando una excepción entre las funciones de C hasta que llega al bucle principal del intérprete de código de bytes
(bytecode) de Python, que se encarga de transferirlo a sys.exc_info() y amigos.
Tenga en cuenta que a partir de Python 1.5, la forma preferida y segura de subprocesos para acceder al estado de excepción
desde el código de Python es llamar a la función sys.exc_info(), que retorna el estado de excepción por subproceso

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

para el código de Python. Además, la semántica de ambas formas de acceder al estado de excepción ha cambiado de
modo que una función que detecta una excepción guardará y restaurará el estado de excepción de su hilo para preservar
el estado de excepción de su llamador. Esto evita errores comunes en el código de manejo de excepciones causado por
una función de aspecto inocente que sobrescribe la excepción que se maneja; También reduce la extensión de vida útil a
menudo no deseada para los objetos a los que hacen referencia los marcos de pila en el rastreo.
Como principio general, una función que llama a otra función para realizar alguna tarea debe verificar si la función
llamada generó una excepción y, de ser así, pasar el estado de excepción a quien la llama (caller). Debe descartar cualquier
referencia de objeto que posea y retornar un indicador de error, pero no debe establecer otra excepción — que sobrescribirá
la excepción que se acaba de generar y perderá información importante sobre la causa exacta del error.
A simple example of detecting exceptions and passing them on is shown in the sum_sequence() example above. It so
happens that this example doesn’t need to clean up any owned references when it detects an error. The following example
function shows some error cleanup. First, to remind you why you like Python, we show the equivalent Python code:

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)
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 */
(continúe en la próxima página)

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

(proviene de la página anterior)

/* 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 ex-
tensión) del intérprete de Python es la inicialización, y posiblemente la finalización, del intérprete de Python. La mayor
parte de la funcionalidad del intérprete solo se puede usar después de que el intérprete se haya inicializado.
La función básica de inicialización es Py_Initialize(). Esto inicializa la tabla de módulos cargados y crea los
módulos fundamentales builtins, __main__, y sys. También inicializa la ruta de búsqueda del módulo (sys.
path).
Py_Initialize() no establece la «lista de argumentos de script» (sys.argv). Si esta variable es necesaria por el
código Python que se ejecutará más tarde, debe establecerse PyConfig.argv y PyConfig.parse_argv: consulte
Python Initialization Configuration.
En la mayoría de los sistemas (en particular, en Unix y Windows, aunque los detalles son ligeramente diferentes),
Py_Initialize() calcula la ruta de búsqueda del módulo basándose en su mejor estimación de la ubicación del
ejecutable del intérprete de Python estándar, suponiendo que la biblioteca de Python se encuentra en una ubicación fija
en relación con el ejecutable del intérprete de Python. En particular, busca un directorio llamado lib/pythonX.Y
relativo al directorio padre donde se encuentra el ejecutable llamado python en la ruta de búsqueda del comando shell
(la variable de entorno PATH).
Por ejemplo, si el ejecutable de Python se encuentra en /usr/local/bin/python, se supondrá que las bibliotecas
están en /usr/local/lib/pythonX.Y. (De hecho, esta ruta particular también es la ubicación «alternativa», uti-
lizada cuando no se encuentra un archivo ejecutable llamado python junto con PATH.) El usuario puede anular este
comportamiento configurando la variable de entorno PYTHONHOME, o inserte directorios adicionales delante de la ruta
estándar estableciendo PYTHONPATH.
The embedding application can steer the search by setting PyConfig.program_name before calling
Py_InitializeFromConfig(). Note that PYTHONHOME still overrides this and PYTHONPATH is still inser-
ted in front of the standard path. An application that requires total control has to provide its own implementation of
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), and Py_GetProgramFullPath() (all defi-
ned in Modules/getpath.c).
A veces, es deseable «no inicializar» Python. Por ejemplo, la aplicación puede querer comenzar de nuevo (hacer otra
llamada a Py_Initialize()) o la aplicación simplemente se hace con el uso de Python y quiere liberar memoria
asignada por Python. Esto se puede lograr llamando a Py_FinalizeEx(). La función Py_IsInitialized()
retorna verdadero si Python se encuentra actualmente en el estado inicializado. Se proporciona más información sobre
estas funciones en un capítulo posterior. Tenga en cuenta que Py_FinalizeEx() no libera toda la memoria asignada

1.6. Integración de Python 13


The Python/C API, Versión 3.13.0a5

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 adicionales,
véase compilaciones de depuración.
Definiendo Py_TRACE_REFS habilita el rastreo de referencias (véase la opción configure
--with-trace-refs). Cuando se define, se mantiene una lista circular doblemente vinculada de objetos ac-
tivos al agregar dos campos adicionales a cada PyObject. También se realiza un seguimiento de las asignaciones
totales. Al salir, se imprimen todas las referencias existentes. (En modo interactivo, esto sucede después de cada
declaración ejecutada por el intérprete).
Consulte Misc/SpecialBuilds.txt en la distribución fuente de Python para obtener información más detallada.

14 Capítulo 1. Introducción
CAPÍTULO 2

Estabilidad de la API en C

Unless documented otherwise, Python’s C API is covered by the Backwards Compatibility Policy, PEP 387. Most changes
to it are source-compatible (typically by only adding new API). Changing existing API or removing API is only done after
a deprecation period or to fix serious issues.
CPython’s Application Binary Interface (ABI) is forward- and backwards-compatible across a minor release (if these are
compiled the same way; see Consideraciones de la plataforma below). So, code compiled for Python 3.10.0 will work on
3.10.8 and vice versa, but will need to be compiled separately for 3.9.x and 3.11.x.
There are two tiers of C API with different stability expectations:
• Unstable API, may change in minor versions without a deprecation period. It is marked by the PyUnstable
prefix in names.
• Limited API, is compatible across several minor releases. When Py_LIMITED_API is defined, only this subset
is exposed from Python.h.
These are discussed in more detail below.
Names prefixed by an underscore, such as _Py_InternalState, are private API that can change without notice even
in patch releases. If you need to use this API, consider reaching out to CPython developers to discuss adding public API
for your use case.

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.13.0a5

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 ejem-
plo, 0x030A0000 para Python 3.10) para tener estabilidad cuando se compila con futuras versiones de Python.
También se puede definir Py_LIMITED_API con 3. Esto funciona igual que 0x03020000 (Python 3.2, la
función que introdujo la API limitada).

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 biblio-
teca específica de la versión como python39.dll.
En algunas plataformas, Python buscará y cargará archivos de bibliotecas compartidas con el nombre de la etiqueta abi3
(por ejemplo, mymodule.abi3.so). No comprueba si tales extensiones se ajustan a una ABI estable. El usuario (o sus
herramientas de empaquetado) necesitan asegurarse que, por ejemplo, las extensiones que se crean con la API limitada
3.10+ no estén instaladas para versiones inferiores de Python.
Todas las funciones de la ABI estable se presentan como funciones en la biblioteca compartida de Python, no sólo como
macros. Esto las hace utilizables desde lenguajes que no usan el preprocesador de C.

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 estructuras de datos
de Python, pero posiblemente reduzca el rendimiento.

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


The Python/C API, Versión 3.13.0a5

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.

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 prefe-
riblemente compilar con la versión más baja.
También recomendamos revisar la documentación de todas las API usadas para verificar si es parte explícitamente de la
API limitada. Aunque se defina Py_LIMITED_API, algunas declaraciones privadas se exponen por razones técnicas (o
incluso involuntariamente, como errores).
También tome en cuenta que la API limitada no necesariamente es estable: compilar con Py_LIMITED_API con Python
3.8 significa que la extensión se ejecutará con Python 3.12, pero no necesariamente compilará con Python 3.12. En
particular, las partes de la API limitada se pueden quedar obsoletas y eliminarse, siempre que la ABI estable permanezca
estable.

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

2.3. Consideraciones de la plataforma 17


The Python/C API, Versión 3.13.0a5

• PyArg_ParseTupleAndKeywords()
• PyArg_UnpackTuple()
• PyArg_VaParse()
• PyArg_VaParseTupleAndKeywords()
• PyArg_ValidateKeywordArguments()
• PyBaseObject_Type
• PyBool_FromLong()
• PyBool_Type
• PyBuffer_FillContiguousStrides()
• PyBuffer_FillInfo()
• PyBuffer_FromContiguous()
• PyBuffer_GetPointer()
• PyBuffer_IsContiguous()
• PyBuffer_Release()
• PyBuffer_SizeFromFormat()
• PyBuffer_ToContiguous()
• PyByteArrayIter_Type
• PyByteArray_AsString()
• PyByteArray_Concat()
• PyByteArray_FromObject()
• PyByteArray_FromStringAndSize()
• PyByteArray_Resize()
• PyByteArray_Size()
• PyByteArray_Type
• PyBytesIter_Type
• PyBytes_AsString()
• PyBytes_AsStringAndSize()
• PyBytes_Concat()
• PyBytes_ConcatAndDel()
• PyBytes_DecodeEscape()
• PyBytes_FromFormat()
• PyBytes_FromFormatV()
• PyBytes_FromObject()
• PyBytes_FromString()
• PyBytes_FromStringAndSize()
• PyBytes_Repr()

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


The Python/C API, Versión 3.13.0a5

• PyBytes_Size()
• PyBytes_Type
• PyCFunction
• PyCFunctionFast
• PyCFunctionFastWithKeywords
• PyCFunctionWithKeywords
• PyCFunction_GetFlags()
• PyCFunction_GetFunction()
• PyCFunction_GetSelf()
• PyCFunction_New()
• PyCFunction_NewEx()
• PyCFunction_Type
• PyCMethod_New()
• PyCallIter_New()
• PyCallIter_Type
• PyCallable_Check()
• PyCapsule_Destructor
• PyCapsule_GetContext()
• PyCapsule_GetDestructor()
• PyCapsule_GetName()
• PyCapsule_GetPointer()
• PyCapsule_Import()
• PyCapsule_IsValid()
• PyCapsule_New()
• PyCapsule_SetContext()
• PyCapsule_SetDestructor()
• PyCapsule_SetName()
• PyCapsule_SetPointer()
• PyCapsule_Type
• PyClassMethodDescr_Type
• PyCodec_BackslashReplaceErrors()
• PyCodec_Decode()
• PyCodec_Decoder()
• PyCodec_Encode()
• PyCodec_Encoder()
• PyCodec_IgnoreErrors()

2.4. Contenido de la API limitada 19


The Python/C API, Versión 3.13.0a5

• PyCodec_IncrementalDecoder()
• PyCodec_IncrementalEncoder()
• PyCodec_KnownEncoding()
• PyCodec_LookupError()
• PyCodec_NameReplaceErrors()
• PyCodec_Register()
• PyCodec_RegisterError()
• PyCodec_ReplaceErrors()
• PyCodec_StreamReader()
• PyCodec_StreamWriter()
• PyCodec_StrictErrors()
• PyCodec_Unregister()
• PyCodec_XMLCharRefReplaceErrors()
• PyComplex_FromDoubles()
• PyComplex_ImagAsDouble()
• PyComplex_RealAsDouble()
• PyComplex_Type
• PyDescr_NewClassMethod()
• PyDescr_NewGetSet()
• PyDescr_NewMember()
• PyDescr_NewMethod()
• PyDictItems_Type
• PyDictIterItem_Type
• PyDictIterKey_Type
• PyDictIterValue_Type
• PyDictKeys_Type
• PyDictProxy_New()
• PyDictProxy_Type
• PyDictRevIterItem_Type
• PyDictRevIterKey_Type
• PyDictRevIterValue_Type
• PyDictValues_Type
• PyDict_Clear()
• PyDict_Contains()
• PyDict_Copy()
• PyDict_DelItem()

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


The Python/C API, Versión 3.13.0a5

• PyDict_DelItemString()
• PyDict_GetItem()
• PyDict_GetItemRef()
• PyDict_GetItemString()
• PyDict_GetItemStringRef()
• PyDict_GetItemWithError()
• PyDict_Items()
• PyDict_Keys()
• PyDict_Merge()
• PyDict_MergeFromSeq2()
• PyDict_New()
• PyDict_Next()
• PyDict_SetItem()
• PyDict_SetItemString()
• PyDict_Size()
• PyDict_Type
• PyDict_Update()
• PyDict_Values()
• PyEllipsis_Type
• PyEnum_Type
• PyErr_BadArgument()
• PyErr_BadInternalCall()
• PyErr_CheckSignals()
• PyErr_Clear()
• PyErr_Display()
• PyErr_DisplayException()
• PyErr_ExceptionMatches()
• PyErr_Fetch()
• PyErr_Format()
• PyErr_FormatV()
• PyErr_GetExcInfo()
• PyErr_GetHandledException()
• PyErr_GetRaisedException()
• PyErr_GivenExceptionMatches()
• PyErr_NewException()
• PyErr_NewExceptionWithDoc()

2.4. Contenido de la API limitada 21


The Python/C API, Versión 3.13.0a5

• PyErr_NoMemory()
• PyErr_NormalizeException()
• PyErr_Occurred()
• PyErr_Print()
• PyErr_PrintEx()
• PyErr_ProgramText()
• PyErr_ResourceWarning()
• PyErr_Restore()
• PyErr_SetExcFromWindowsErr()
• PyErr_SetExcFromWindowsErrWithFilename()
• PyErr_SetExcFromWindowsErrWithFilenameObject()
• PyErr_SetExcFromWindowsErrWithFilenameObjects()
• PyErr_SetExcInfo()
• PyErr_SetFromErrno()
• PyErr_SetFromErrnoWithFilename()
• PyErr_SetFromErrnoWithFilenameObject()
• PyErr_SetFromErrnoWithFilenameObjects()
• PyErr_SetFromWindowsErr()
• PyErr_SetFromWindowsErrWithFilename()
• PyErr_SetHandledException()
• PyErr_SetImportError()
• PyErr_SetImportErrorSubclass()
• PyErr_SetInterrupt()
• PyErr_SetInterruptEx()
• PyErr_SetNone()
• PyErr_SetObject()
• PyErr_SetRaisedException()
• PyErr_SetString()
• PyErr_SyntaxLocation()
• PyErr_SyntaxLocationEx()
• PyErr_WarnEx()
• PyErr_WarnExplicit()
• PyErr_WarnFormat()
• PyErr_WriteUnraisable()
• PyEval_AcquireThread()
• PyEval_EvalCode()

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


The Python/C API, Versión 3.13.0a5

• PyEval_EvalCodeEx()
• PyEval_EvalFrame()
• PyEval_EvalFrameEx()
• PyEval_GetBuiltins()
• PyEval_GetFrame()
• PyEval_GetFuncDesc()
• PyEval_GetFuncName()
• PyEval_GetGlobals()
• PyEval_GetLocals()
• PyEval_ReleaseThread()
• PyEval_RestoreThread()
• PyEval_SaveThread()
• PyExc_ArithmeticError
• PyExc_AssertionError
• PyExc_AttributeError
• PyExc_BaseException
• PyExc_BaseExceptionGroup
• PyExc_BlockingIOError
• PyExc_BrokenPipeError
• PyExc_BufferError
• PyExc_BytesWarning
• PyExc_ChildProcessError
• PyExc_ConnectionAbortedError
• PyExc_ConnectionError
• PyExc_ConnectionRefusedError
• PyExc_ConnectionResetError
• PyExc_DeprecationWarning
• PyExc_EOFError
• PyExc_EncodingWarning
• PyExc_EnvironmentError
• PyExc_Exception
• PyExc_FileExistsError
• PyExc_FileNotFoundError
• PyExc_FloatingPointError
• PyExc_FutureWarning
• PyExc_GeneratorExit

2.4. Contenido de la API limitada 23


The Python/C API, Versión 3.13.0a5

• PyExc_IOError
• PyExc_ImportError
• PyExc_ImportWarning
• PyExc_IncompleteInputError
• PyExc_IndentationError
• PyExc_IndexError
• PyExc_InterruptedError
• PyExc_IsADirectoryError
• PyExc_KeyError
• PyExc_KeyboardInterrupt
• PyExc_LookupError
• PyExc_MemoryError
• PyExc_ModuleNotFoundError
• PyExc_NameError
• PyExc_NotADirectoryError
• PyExc_NotImplementedError
• PyExc_OSError
• PyExc_OverflowError
• PyExc_PendingDeprecationWarning
• PyExc_PermissionError
• PyExc_ProcessLookupError
• PyExc_RecursionError
• PyExc_ReferenceError
• PyExc_ResourceWarning
• PyExc_RuntimeError
• PyExc_RuntimeWarning
• PyExc_StopAsyncIteration
• PyExc_StopIteration
• PyExc_SyntaxError
• PyExc_SyntaxWarning
• PyExc_SystemError
• PyExc_SystemExit
• PyExc_TabError
• PyExc_TimeoutError
• PyExc_TypeError
• PyExc_UnboundLocalError

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


The Python/C API, Versión 3.13.0a5

• PyExc_UnicodeDecodeError
• PyExc_UnicodeEncodeError
• PyExc_UnicodeError
• PyExc_UnicodeTranslateError
• PyExc_UnicodeWarning
• PyExc_UserWarning
• PyExc_ValueError
• PyExc_Warning
• PyExc_WindowsError
• PyExc_ZeroDivisionError
• PyExceptionClass_Name()
• PyException_GetArgs()
• PyException_GetCause()
• PyException_GetContext()
• PyException_GetTraceback()
• PyException_SetArgs()
• PyException_SetCause()
• PyException_SetContext()
• PyException_SetTraceback()
• PyFile_FromFd()
• PyFile_GetLine()
• PyFile_WriteObject()
• PyFile_WriteString()
• PyFilter_Type
• PyFloat_AsDouble()
• PyFloat_FromDouble()
• PyFloat_FromString()
• PyFloat_GetInfo()
• PyFloat_GetMax()
• PyFloat_GetMin()
• PyFloat_Type
• PyFrameObject
• PyFrame_GetCode()
• PyFrame_GetLineNumber()
• PyFrozenSet_New()
• PyFrozenSet_Type

2.4. Contenido de la API limitada 25


The Python/C API, Versión 3.13.0a5

• PyGC_Collect()
• PyGC_Disable()
• PyGC_Enable()
• PyGC_IsEnabled()
• PyGILState_Ensure()
• PyGILState_GetThisThreadState()
• PyGILState_Release()
• PyGILState_STATE
• PyGetSetDef
• PyGetSetDescr_Type
• PyImport_AddModule()
• PyImport_AddModuleObject()
• PyImport_AddModuleRef()
• PyImport_AppendInittab()
• PyImport_ExecCodeModule()
• PyImport_ExecCodeModuleEx()
• PyImport_ExecCodeModuleObject()
• PyImport_ExecCodeModuleWithPathnames()
• PyImport_GetImporter()
• PyImport_GetMagicNumber()
• PyImport_GetMagicTag()
• PyImport_GetModule()
• PyImport_GetModuleDict()
• PyImport_Import()
• PyImport_ImportFrozenModule()
• PyImport_ImportFrozenModuleObject()
• PyImport_ImportModule()
• PyImport_ImportModuleLevel()
• PyImport_ImportModuleLevelObject()
• PyImport_ImportModuleNoBlock()
• PyImport_ReloadModule()
• PyIndex_Check()
• PyInterpreterState
• PyInterpreterState_Clear()
• PyInterpreterState_Delete()
• PyInterpreterState_Get()

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


The Python/C API, Versión 3.13.0a5

• PyInterpreterState_GetDict()
• PyInterpreterState_GetID()
• PyInterpreterState_New()
• PyIter_Check()
• PyIter_Next()
• PyIter_Send()
• PyListIter_Type
• PyListRevIter_Type
• PyList_Append()
• PyList_AsTuple()
• PyList_GetItem()
• PyList_GetItemRef()
• PyList_GetSlice()
• PyList_Insert()
• PyList_New()
• PyList_Reverse()
• PyList_SetItem()
• PyList_SetSlice()
• PyList_Size()
• PyList_Sort()
• PyList_Type
• PyLongObject
• PyLongRangeIter_Type
• PyLong_AsDouble()
• PyLong_AsInt()
• PyLong_AsLong()
• PyLong_AsLongAndOverflow()
• PyLong_AsLongLong()
• PyLong_AsLongLongAndOverflow()
• PyLong_AsSize_t()
• PyLong_AsSsize_t()
• PyLong_AsUnsignedLong()
• PyLong_AsUnsignedLongLong()
• PyLong_AsUnsignedLongLongMask()
• PyLong_AsUnsignedLongMask()
• PyLong_AsVoidPtr()

2.4. Contenido de la API limitada 27


The Python/C API, Versión 3.13.0a5

• PyLong_FromDouble()
• PyLong_FromLong()
• PyLong_FromLongLong()
• PyLong_FromSize_t()
• PyLong_FromSsize_t()
• PyLong_FromString()
• PyLong_FromUnsignedLong()
• PyLong_FromUnsignedLongLong()
• PyLong_FromVoidPtr()
• PyLong_GetInfo()
• PyLong_Type
• PyMap_Type
• PyMapping_Check()
• PyMapping_GetItemString()
• PyMapping_GetOptionalItem()
• PyMapping_GetOptionalItemString()
• PyMapping_HasKey()
• PyMapping_HasKeyString()
• PyMapping_HasKeyStringWithError()
• PyMapping_HasKeyWithError()
• PyMapping_Items()
• PyMapping_Keys()
• PyMapping_Length()
• PyMapping_SetItemString()
• PyMapping_Size()
• PyMapping_Values()
• PyMem_Calloc()
• PyMem_Free()
• PyMem_Malloc()
• PyMem_RawCalloc()
• PyMem_RawFree()
• PyMem_RawMalloc()
• PyMem_RawRealloc()
• PyMem_Realloc()
• PyMemberDef
• PyMemberDescr_Type

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


The Python/C API, Versión 3.13.0a5

• PyMember_GetOne()
• PyMember_SetOne()
• PyMemoryView_FromBuffer()
• PyMemoryView_FromMemory()
• PyMemoryView_FromObject()
• PyMemoryView_GetContiguous()
• PyMemoryView_Type
• PyMethodDef
• PyMethodDescr_Type
• PyModuleDef
• PyModuleDef_Base
• PyModuleDef_Init()
• PyModuleDef_Type
• PyModule_Add()
• PyModule_AddFunctions()
• PyModule_AddIntConstant()
• PyModule_AddObject()
• PyModule_AddObjectRef()
• PyModule_AddStringConstant()
• PyModule_AddType()
• PyModule_Create2()
• PyModule_ExecDef()
• PyModule_FromDefAndSpec2()
• PyModule_GetDef()
• PyModule_GetDict()
• PyModule_GetFilename()
• PyModule_GetFilenameObject()
• PyModule_GetName()
• PyModule_GetNameObject()
• PyModule_GetState()
• PyModule_New()
• PyModule_NewObject()
• PyModule_SetDocString()
• PyModule_Type
• PyNumber_Absolute()
• PyNumber_Add()

2.4. Contenido de la API limitada 29


The Python/C API, Versión 3.13.0a5

• PyNumber_And()
• PyNumber_AsSsize_t()
• PyNumber_Check()
• PyNumber_Divmod()
• PyNumber_Float()
• PyNumber_FloorDivide()
• PyNumber_InPlaceAdd()
• PyNumber_InPlaceAnd()
• PyNumber_InPlaceFloorDivide()
• PyNumber_InPlaceLshift()
• PyNumber_InPlaceMatrixMultiply()
• PyNumber_InPlaceMultiply()
• PyNumber_InPlaceOr()
• PyNumber_InPlacePower()
• PyNumber_InPlaceRemainder()
• PyNumber_InPlaceRshift()
• PyNumber_InPlaceSubtract()
• PyNumber_InPlaceTrueDivide()
• PyNumber_InPlaceXor()
• PyNumber_Index()
• PyNumber_Invert()
• PyNumber_Long()
• PyNumber_Lshift()
• PyNumber_MatrixMultiply()
• PyNumber_Multiply()
• PyNumber_Negative()
• PyNumber_Or()
• PyNumber_Positive()
• PyNumber_Power()
• PyNumber_Remainder()
• PyNumber_Rshift()
• PyNumber_Subtract()
• PyNumber_ToBase()
• PyNumber_TrueDivide()
• PyNumber_Xor()
• PyOS_AfterFork()

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


The Python/C API, Versión 3.13.0a5

• PyOS_AfterFork_Child()
• PyOS_AfterFork_Parent()
• PyOS_BeforeFork()
• PyOS_CheckStack()
• PyOS_FSPath()
• PyOS_InputHook
• PyOS_InterruptOccurred()
• PyOS_double_to_string()
• PyOS_getsig()
• PyOS_mystricmp()
• PyOS_mystrnicmp()
• PyOS_setsig()
• PyOS_sighandler_t
• PyOS_snprintf()
• PyOS_string_to_double()
• PyOS_strtol()
• PyOS_strtoul()
• PyOS_vsnprintf()
• PyObject
• PyObject.ob_refcnt
• PyObject.ob_type
• PyObject_ASCII()
• PyObject_AsFileDescriptor()
• PyObject_Bytes()
• PyObject_Call()
• PyObject_CallFunction()
• PyObject_CallFunctionObjArgs()
• PyObject_CallMethod()
• PyObject_CallMethodObjArgs()
• PyObject_CallNoArgs()
• PyObject_CallObject()
• PyObject_Calloc()
• PyObject_CheckBuffer()
• PyObject_ClearWeakRefs()
• PyObject_CopyData()
• PyObject_DelAttr()

2.4. Contenido de la API limitada 31


The Python/C API, Versión 3.13.0a5

• PyObject_DelAttrString()
• PyObject_DelItem()
• PyObject_DelItemString()
• PyObject_Dir()
• PyObject_Format()
• PyObject_Free()
• PyObject_GC_Del()
• PyObject_GC_IsFinalized()
• PyObject_GC_IsTracked()
• PyObject_GC_Track()
• PyObject_GC_UnTrack()
• PyObject_GenericGetAttr()
• PyObject_GenericGetDict()
• PyObject_GenericSetAttr()
• PyObject_GenericSetDict()
• PyObject_GetAIter()
• PyObject_GetAttr()
• PyObject_GetAttrString()
• PyObject_GetBuffer()
• PyObject_GetItem()
• PyObject_GetIter()
• PyObject_GetOptionalAttr()
• PyObject_GetOptionalAttrString()
• PyObject_GetTypeData()
• PyObject_HasAttr()
• PyObject_HasAttrString()
• PyObject_HasAttrStringWithError()
• PyObject_HasAttrWithError()
• PyObject_Hash()
• PyObject_HashNotImplemented()
• PyObject_Init()
• PyObject_InitVar()
• PyObject_IsInstance()
• PyObject_IsSubclass()
• PyObject_IsTrue()
• PyObject_Length()

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


The Python/C API, Versión 3.13.0a5

• PyObject_Malloc()
• PyObject_Not()
• PyObject_Realloc()
• PyObject_Repr()
• PyObject_RichCompare()
• PyObject_RichCompareBool()
• PyObject_SelfIter()
• PyObject_SetAttr()
• PyObject_SetAttrString()
• PyObject_SetItem()
• PyObject_Size()
• PyObject_Str()
• PyObject_Type()
• PyObject_Vectorcall()
• PyObject_VectorcallMethod()
• PyProperty_Type
• PyRangeIter_Type
• PyRange_Type
• PyReversed_Type
• PySeqIter_New()
• PySeqIter_Type
• PySequence_Check()
• PySequence_Concat()
• PySequence_Contains()
• PySequence_Count()
• PySequence_DelItem()
• PySequence_DelSlice()
• PySequence_Fast()
• PySequence_GetItem()
• PySequence_GetSlice()
• PySequence_In()
• PySequence_InPlaceConcat()
• PySequence_InPlaceRepeat()
• PySequence_Index()
• PySequence_Length()
• PySequence_List()

2.4. Contenido de la API limitada 33


The Python/C API, Versión 3.13.0a5

• PySequence_Repeat()
• PySequence_SetItem()
• PySequence_SetSlice()
• PySequence_Size()
• PySequence_Tuple()
• PySetIter_Type
• PySet_Add()
• PySet_Clear()
• PySet_Contains()
• PySet_Discard()
• PySet_New()
• PySet_Pop()
• PySet_Size()
• PySet_Type
• PySlice_AdjustIndices()
• PySlice_GetIndices()
• PySlice_GetIndicesEx()
• PySlice_New()
• PySlice_Type
• PySlice_Unpack()
• PyState_AddModule()
• PyState_FindModule()
• PyState_RemoveModule()
• PyStructSequence_Desc
• PyStructSequence_Field
• PyStructSequence_GetItem()
• PyStructSequence_New()
• PyStructSequence_NewType()
• PyStructSequence_SetItem()
• PyStructSequence_UnnamedField
• PySuper_Type
• PySys_Audit()
• PySys_AuditTuple()
• PySys_FormatStderr()
• PySys_FormatStdout()
• PySys_GetObject()

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


The Python/C API, Versión 3.13.0a5

• PySys_GetXOptions()
• PySys_ResetWarnOptions()
• PySys_SetObject()
• PySys_WriteStderr()
• PySys_WriteStdout()
• PyThreadState
• PyThreadState_Clear()
• PyThreadState_Delete()
• PyThreadState_Get()
• PyThreadState_GetDict()
• PyThreadState_GetFrame()
• PyThreadState_GetID()
• PyThreadState_GetInterpreter()
• PyThreadState_New()
• PyThreadState_SetAsyncExc()
• PyThreadState_Swap()
• PyThread_GetInfo()
• PyThread_ReInitTLS()
• PyThread_acquire_lock()
• PyThread_acquire_lock_timed()
• PyThread_allocate_lock()
• PyThread_create_key()
• PyThread_delete_key()
• PyThread_delete_key_value()
• PyThread_exit_thread()
• PyThread_free_lock()
• PyThread_get_key_value()
• PyThread_get_stacksize()
• PyThread_get_thread_ident()
• PyThread_get_thread_native_id()
• PyThread_init_thread()
• PyThread_release_lock()
• PyThread_set_key_value()
• PyThread_set_stacksize()
• PyThread_start_new_thread()
• PyThread_tss_alloc()

2.4. Contenido de la API limitada 35


The Python/C API, Versión 3.13.0a5

• PyThread_tss_create()
• PyThread_tss_delete()
• PyThread_tss_free()
• PyThread_tss_get()
• PyThread_tss_is_created()
• PyThread_tss_set()
• PyTraceBack_Here()
• PyTraceBack_Print()
• PyTraceBack_Type
• PyTupleIter_Type
• PyTuple_GetItem()
• PyTuple_GetSlice()
• PyTuple_New()
• PyTuple_Pack()
• PyTuple_SetItem()
• PyTuple_Size()
• PyTuple_Type
• PyTypeObject
• PyType_ClearCache()
• PyType_FromMetaclass()
• PyType_FromModuleAndSpec()
• PyType_FromSpec()
• PyType_FromSpecWithBases()
• PyType_GenericAlloc()
• PyType_GenericNew()
• PyType_GetFlags()
• PyType_GetFullyQualifiedName()
• PyType_GetModule()
• PyType_GetModuleName()
• PyType_GetModuleState()
• PyType_GetName()
• PyType_GetQualName()
• PyType_GetSlot()
• PyType_GetTypeDataSize()
• PyType_IsSubtype()
• PyType_Modified()

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


The Python/C API, Versión 3.13.0a5

• PyType_Ready()
• PyType_Slot
• PyType_Spec
• PyType_Type
• PyUnicodeDecodeError_Create()
• PyUnicodeDecodeError_GetEncoding()
• PyUnicodeDecodeError_GetEnd()
• PyUnicodeDecodeError_GetObject()
• PyUnicodeDecodeError_GetReason()
• PyUnicodeDecodeError_GetStart()
• PyUnicodeDecodeError_SetEnd()
• PyUnicodeDecodeError_SetReason()
• PyUnicodeDecodeError_SetStart()
• PyUnicodeEncodeError_GetEncoding()
• PyUnicodeEncodeError_GetEnd()
• PyUnicodeEncodeError_GetObject()
• PyUnicodeEncodeError_GetReason()
• PyUnicodeEncodeError_GetStart()
• PyUnicodeEncodeError_SetEnd()
• PyUnicodeEncodeError_SetReason()
• PyUnicodeEncodeError_SetStart()
• PyUnicodeIter_Type
• PyUnicodeTranslateError_GetEnd()
• PyUnicodeTranslateError_GetObject()
• PyUnicodeTranslateError_GetReason()
• PyUnicodeTranslateError_GetStart()
• PyUnicodeTranslateError_SetEnd()
• PyUnicodeTranslateError_SetReason()
• PyUnicodeTranslateError_SetStart()
• PyUnicode_Append()
• PyUnicode_AppendAndDel()
• PyUnicode_AsASCIIString()
• PyUnicode_AsCharmapString()
• PyUnicode_AsDecodedObject()
• PyUnicode_AsDecodedUnicode()
• PyUnicode_AsEncodedObject()

2.4. Contenido de la API limitada 37


The Python/C API, Versión 3.13.0a5

• PyUnicode_AsEncodedString()
• PyUnicode_AsEncodedUnicode()
• PyUnicode_AsLatin1String()
• PyUnicode_AsMBCSString()
• PyUnicode_AsRawUnicodeEscapeString()
• PyUnicode_AsUCS4()
• PyUnicode_AsUCS4Copy()
• PyUnicode_AsUTF16String()
• PyUnicode_AsUTF32String()
• PyUnicode_AsUTF8AndSize()
• PyUnicode_AsUTF8String()
• PyUnicode_AsUnicodeEscapeString()
• PyUnicode_AsWideChar()
• PyUnicode_AsWideCharString()
• PyUnicode_BuildEncodingMap()
• PyUnicode_Compare()
• PyUnicode_CompareWithASCIIString()
• PyUnicode_Concat()
• PyUnicode_Contains()
• PyUnicode_Count()
• PyUnicode_Decode()
• PyUnicode_DecodeASCII()
• PyUnicode_DecodeCharmap()
• PyUnicode_DecodeCodePageStateful()
• PyUnicode_DecodeFSDefault()
• PyUnicode_DecodeFSDefaultAndSize()
• PyUnicode_DecodeLatin1()
• PyUnicode_DecodeLocale()
• PyUnicode_DecodeLocaleAndSize()
• PyUnicode_DecodeMBCS()
• PyUnicode_DecodeMBCSStateful()
• PyUnicode_DecodeRawUnicodeEscape()
• PyUnicode_DecodeUTF16()
• PyUnicode_DecodeUTF16Stateful()
• PyUnicode_DecodeUTF32()
• PyUnicode_DecodeUTF32Stateful()

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


The Python/C API, Versión 3.13.0a5

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

2.4. Contenido de la API limitada 39


The Python/C API, Versión 3.13.0a5

• PyUnicode_Split()
• PyUnicode_Splitlines()
• PyUnicode_Substring()
• PyUnicode_Tailmatch()
• PyUnicode_Translate()
• PyUnicode_Type
• PyUnicode_WriteChar()
• PyVarObject
• PyVarObject.ob_base
• PyVarObject.ob_size
• PyVectorcall_Call()
• PyVectorcall_NARGS()
• PyWeakReference
• PyWeakref_GetObject()
• PyWeakref_GetRef()
• PyWeakref_NewProxy()
• PyWeakref_NewRef()
• PyWrapperDescr_Type
• PyWrapper_New()
• PyZip_Type
• Py_AddPendingCall()
• Py_AtExit()
• Py_BEGIN_ALLOW_THREADS
• Py_BLOCK_THREADS
• Py_BuildValue()
• Py_BytesMain()
• Py_CompileString()
• Py_DecRef()
• Py_DecodeLocale()
• Py_END_ALLOW_THREADS
• Py_EncodeLocale()
• Py_EndInterpreter()
• Py_EnterRecursiveCall()
• Py_Exit()
• Py_FatalError()
• Py_FileSystemDefaultEncodeErrors

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


The Python/C API, Versión 3.13.0a5

• Py_FileSystemDefaultEncoding
• Py_Finalize()
• Py_FinalizeEx()
• Py_GenericAlias()
• Py_GenericAliasType
• Py_GetBuildInfo()
• Py_GetCompiler()
• Py_GetCopyright()
• Py_GetExecPrefix()
• Py_GetPath()
• Py_GetPlatform()
• Py_GetPrefix()
• Py_GetProgramFullPath()
• Py_GetProgramName()
• Py_GetPythonHome()
• Py_GetRecursionLimit()
• Py_GetVersion()
• Py_HasFileSystemDefaultEncoding
• Py_IncRef()
• Py_Initialize()
• Py_InitializeEx()
• Py_Is()
• Py_IsFalse()
• Py_IsFinalizing()
• Py_IsInitialized()
• Py_IsNone()
• Py_IsTrue()
• Py_LeaveRecursiveCall()
• Py_Main()
• Py_MakePendingCalls()
• Py_NewInterpreter()
• Py_NewRef()
• Py_ReprEnter()
• Py_ReprLeave()
• Py_SetRecursionLimit()
• Py_UCS4

2.4. Contenido de la API limitada 41


The Python/C API, Versión 3.13.0a5

• Py_UNBLOCK_THREADS
• Py_UTF8Mode
• Py_VaBuildValue()
• Py_Version
• Py_XNewRef()
• Py_buffer
• Py_intptr_t
• Py_ssize_t
• Py_uintptr_t
• allocfunc
• binaryfunc
• descrgetfunc
• descrsetfunc
• destructor
• getattrfunc
• getattrofunc
• getbufferproc
• getiterfunc
• getter
• hashfunc
• initproc
• inquiry
• iternextfunc
• lenfunc
• newfunc
• objobjargproc
• objobjproc
• releasebufferproc
• reprfunc
• richcmpfunc
• setattrfunc
• setattrofunc
• setter
• ssizeargfunc
• ssizeobjargproc
• ssizessizeargfunc

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


The Python/C API, Versión 3.13.0a5

• ssizessizeobjargproc
• symtable
• ternaryfunc
• traverseproc
• unaryfunc
• vectorcallfunc
• visitproc

2.4. Contenido de la API limitada 43


The Python/C API, Versión 3.13.0a5

44 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 care-
fully is that the FILE structure for different C libraries can be different and incompatible. Under Windows (at least),
it is possible for dynamically linked extensions to actually use different libraries, so care should be taken that FILE*
parameters are only passed to these functions if it is certain that they were created by the same library that the Python
runtime is using.
int Py_Main(int argc, wchar_t **argv)
Part of the Stable ABI. El programa principal para el intérprete estándar. Está disponible para programas que
incorporan Python. Los parámetros argc y argv deben prepararse exactamente como los que se pasan a la función
main() de un programa en C (convertido a wchar_t de acuerdo con la configuración regional del usuario). Es
importante tener en cuenta que la lista de argumentos puede ser modificada (pero el contenido de las cadenas de
caracteres señaladas por la lista de argumentos no lo es). El valor de retorno será 0 si el intérprete acaba normalmente
(es decir, sin excepción), 1 si el intérprete acaba debido a una excepción, o 2 si la lista de parámetros no representa
una línea de comando Python válida.
Note that if an otherwise unhandled SystemExit is raised, this function will not return 1, but exit the process,
as long as PyConfig.inspect is zero.
int Py_BytesMain(int argc, char **argv)
Part of the Stable ABI since version 3.8. Similar a Py_Main() pero argv es un arreglo de cadenas de caracteres
de bytes.
Nuevo en la versión 3.8.
int PyRun_AnyFile(FILE *fp, const char *filename)
Esta es una interfaz simplificada para PyRun_AnyFileExFlags() más abajo, dejando closeit establecido a 0
y flags establecido a NULL.

45
The Python/C API, Versión 3.13.0a5

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.
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), re-
turn the value of PyRun_InteractiveLoop(), otherwise return the result of PyRun_SimpleFile().
filename is decoded from the filesystem encoding (sys.getfilesystemencoding()). If filena-
me 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 establecido
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 establecido
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 lugar 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 con-
trario, 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 estable-
cido 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).

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


The Python/C API, Versión 3.13.0a5

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


Esta es una interfaz simplificada para PyRun_InteractiveLoopFlags() más abajo, dejando flags esta-
blecido 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.
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 diccionario; 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.

47
The Python/C API, Versión 3.13.0a5

PyObject *PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int
closeit, PyCompilerFlags *flags)
Return value: New reference. Similar a PyRun_StringFlags(), pero el código fuente de Python se lee
de fp en lugar de una cadena de caracteres en memoria. filename debe ser el nombre del fichero, es decodi-
ficado desde el filesystem encoding and error handler. Si closeit es verdadero, el fichero se cierra antes de que
PyRun_FileExFlags() retorne.
PyObject *Py_CompileString(const char *str, const char *filename, int start)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz simplificada para
Py_CompileStringFlags() más abajo, dejando flags establecido a NULL.
PyObject *Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)
Return value: New reference. Esta es una interfaz simplificada para Py_CompileStringExFlags() más aba-
jo, con optimize establecido a -1.
PyObject *Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int
optimize)
Return value: New reference. Parse and compile the Python source code in str, returning the resulting code object.
The start token is given by start; this can be used to constrain the code which can be compiled and should be
Py_eval_input, Py_file_input, or Py_single_input. The filename specified by filename is used
to construct the code object and may appear in tracebacks or SyntaxError exception messages. This returns
NULL if the code cannot be parsed or compiled.
El número entero optimize especifica el nivel de optimización del compilador; un valor de -1 selecciona el nivel
de optimización del intérprete como se indica en las opciones -O. Los niveles explícitos son 0 (sin optimización;
__debug__ es verdadero), 1 (los asserts se eliminan, __debug__ es falso) o 2 (los docstrings también se
eliminan) )
Nuevo en la versión 3.4.
PyObject *Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags,
int optimize)
Return value: New reference. Como Py_CompileStringObject(), pero filename es una cadena de bytes
decodificada a partir del manejador de codificación y errores del sistema de archivos.
Nuevo en la versión 3.2.
PyObject *PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz simplificada para
PyEval_EvalCodeEx(), con solo el objeto de código y las variables globales y locales. Los otros ar-
gumentos están establecidos en NULL.
PyObject *PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int
argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int
defcount, PyObject *kwdefs, PyObject *closure)
Return value: New reference. Part of the Stable ABI. Evaluar un objeto de código precompilado, dado un entorno
particular para su evaluación. Este entorno consta de un diccionario de variables globales, un objeto de mapeo
de variables locales, arreglos de argumentos, palabras clave y valores predeterminados, un diccionario de valores
predeterminados para argumentos keyword-only y una tupla de cierre de células.
PyObject *PyEval_EvalFrame(PyFrameObject *f)
Return value: New reference. Part of the Stable ABI. Evaluar un marco de ejecución. Esta es una interfaz simplificada
para PyEval_EvalFrameEx(), para compatibilidad con versiones anteriores.
PyObject *PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Return value: New reference. Part of the Stable ABI. Esta es la función principal sin barnizar de la interpretación de
Python. El objeto de código asociado con el marco de ejecución del marco f se ejecuta, interpretando el código de

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


The Python/C API, Versión 3.13.0a5

bytes y ejecutando llamadas según sea necesario. El parámetro adicional throwflag se puede ignorar por lo general;
si es verdadero, entonces se lanza una excepción de inmediato; esto se usa para los métodos throw() de objetos
generadores.
Distinto en la versión 3.4: Esta función ahora incluye una afirmación de depuración para ayudar a garantizar que
no descarte silenciosamente una excepción activa.
int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Esta función cambia los flags del marco de evaluación actual, y retorna verdad (true) en caso de éxito, falso (false)
en caso de fallo.
int Py_eval_input
El símbolo de inicio de la gramática de Python para expresiones aisladas; para usar con Py_CompileString().
int Py_file_input
El símbolo de inicio de la gramática de Python para secuencias de declaración leídos desde un archivo u otra fuente;
para usar con Py_CompileString(). Este es el símbolo usado cuando se compile un código fuente en Python
arbitrariamente largo.
int Py_single_input
El símbolo de inicio de la gramática de Python para una declaración única; para usar con
Py_CompileString(). Este es el símbolo usado para el bucle interactivo del intérprete.
struct PyCompilerFlags
Esta es la estructura usada para contener los flags del compilador. En casos donde el código es sólo compilado,
es pasado como int flags, y en casos donde el código es ejecutado, es pasado como PyCompilerFlags
*flags. En este caso, from __future__ import puede modificar los flags.
Whenever PyCompilerFlags *flags is NULL, cf_flags is treated as equal to 0, and any modification
due to from __future__ import is discarded.
int cf_flags
Flags del compilador.
int cf_feature_version
cf_feature_version es la versión menor de Python. Debe ser inicializado a PY_MINOR_VERSION.
The field is ignored by default, it is used if and only if PyCF_ONLY_AST flag is set in cf_flags.
Distinto en la versión 3.8: Agregado el campo cf_feature_version.
int CO_FUTURE_DIVISION
Este bit puede ser configurado en flags para causar que un operador de división / sea interpretado como una
«división real» de acuerdo a PEP 238.

49
The Python/C API, Versión 3.13.0a5

50 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 exam-
ple, some objects are immortal and have a very high refcount that does not reflect the actual number of references.
Consequently, do not rely on the returned value to be accurate, other than a value of 0 or 1.
Use the Py_SET_REFCNT() function to set an object reference count.
Distinto en la versión 3.10: Py_REFCNT() is changed to the inline static function.
Distinto en la versión 3.11: The parameter type is no longer const PyObject*.
void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)
Set the object o reference counter to refcnt.
On Python build with Free Threading, if refcnt is larger than UINT32_MAX, the object is made immortal.
This function has no effect on immortal objects.
Nuevo en la versión 3.9.
Distinto en la versión 3.12: Immortal objects are not modified.
void Py_INCREF(PyObject *o)
Indicate taking a new strong reference to object o, indicating it is in use and should not be destroyed.
This function has no effect on immortal objects.
Esta función se usa generalmente para convertir un borrowed reference en un strong reference en su lugar. La función
Py_NewRef() se puede utilizar para crear un nuevo strong reference.
When done using the object, release is by calling Py_DECREF().
El objeto no debe ser NULL; si no está seguro de que no sea NULL, use Py_XINCREF().
Do not expect this function to actually modify o in any way. For at least some objects, this function has no effect.

51
The Python/C API, Versión 3.13.0a5

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


Nuevo en la versión 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.
Nuevo en la versión 3.10.
void Py_DECREF(PyObject *o)
Release a strong reference to object o, indicating the reference is no longer used.
This function has no effect on immortal objects.
Once the last strong reference is released (i.e. the object’s reference count reaches 0), the object’s type’s deallocation
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.

52 Capítulo 4. Conteo de referencias


The Python/C API, Versión 3.13.0a5

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.
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.
Nuevo en la versión 3.6.
Distinto en la versión 3.12: The macro arguments are now only evaluated once. If an argument has side effects,
these are no longer duplicated.
Py_XSETREF(dst, src)
Variant of Py_SETREF macro that uses Py_XDECREF() instead of Py_DECREF().
Nuevo en la versión 3.6.
Distinto en la versión 3.12: The macro arguments are now only evaluated once. If an argument has side effects,
these are no longer duplicated.

53
The Python/C API, Versión 3.13.0a5

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

Nota: El indicador de error es no el resultado de sys.exc_info(). El primero corresponde a una excepción que aún
no se detecta (y, por lo tanto, todavía se está propagando), mientras que el segundo retorna una excepción después de que
se detecta (y, por lo tanto, ha dejado de propagarse).

55
The Python/C API, Versión 3.13.0a5

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.
Llame a esta función solo cuando el indicador de error está configurado. De lo contrario, provocará un error fatal!
If set_sys_last_vars is nonzero, the variable sys.last_exc is set to the printed exception. For backwards com-
patibility, the deprecated variables sys.last_type, sys.last_value and sys.last_traceback are
also set to the type, value and traceback of this exception, respectively.
Distinto en la versión 3.12: The setting of sys.last_exc was added.
void PyErr_Print()
Part of the Stable ABI. Alias para PyErr_PrintEx(1).
void PyErr_WriteUnraisable(PyObject *obj)
Part of the Stable ABI. Llama sys.unraisablehook() utilizando la excepción actual y el argumento obj.
This utility function prints a warning message to sys.stderr when an exception has been set but it is impos-
sible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs in an
__del__() method.
The function is called with a single argument obj that identifies the context in which the unraisable exception
occurred. If possible, the repr of obj will be printed in the warning message. If obj is NULL, only the traceback is
printed.
Se debe establecer una excepción al llamar a esta función.
Distinto en la versión 3.4: Print a traceback. Print only traceback if obj is NULL.
Distinto en la versión 3.8: Use sys.unraisablehook().
void PyErr_FormatUnraisable(const char *format, ...)
Similar to PyErr_WriteUnraisable(), but the format and subsequent parame-
ters help format the warning message; they have the same meaning and values as in
PyUnicode_FromFormat(). PyErr_WriteUnraisable(obj) is roughtly equivalent to
PyErr_FormatUnraisable("Exception ignored in: %R", obj). If format is NULL, only the
traceback is printed.
Nuevo en la versión 3.13.
void PyErr_DisplayException(PyObject *exc)
Part of the Stable ABI since version 3.12. Print the standard traceback display of exc to sys.stderr, including
chained exceptions and notes.
Nuevo en la versión 3.12.

56 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.13.0a5

5.2 Lanzando excepciones

Estas funciones lo ayudan a configurar el indicador de error del hilo actual. Por conveniencia, algunas de estas funciones
siempre retornarán un puntero NULL para usar en una declaración return.
void PyErr_SetString(PyObject *type, const char *message)
Part of the Stable ABI. This is the most common way to set the error indicator. The first argument specifies the
exception type; it is normally one of the standard exceptions, e.g. PyExc_RuntimeError. You need not create
a new strong reference to it (e.g. with Py_INCREF()). The second argument is an error message; it is decoded
from 'utf-8'.
void PyErr_SetObject(PyObject *type, PyObject *value)
Part of the Stable ABI. Esta función es similar a PyErr_SetString() pero le permite especificar un objeto
Python arbitrario para el «valor» de la excepción.
PyObject *PyErr_Format(PyObject *exception, const char *format, ...)
Return value: Always NULL. Part of the Stable ABI. Esta función establece el indicador de error y retorna NULL.
exception debe ser una clase de excepción Python. El format y los parámetros posteriores ayudan a formatear el
mensaje de error; tienen el mismo significado y valores que en PyUnicode_FromFormat(). format es una
cadena de caracteres codificada en ASCII.
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Return value: Always NULL. Part of the Stable ABI since version 3.5. Igual que PyErr_Format(), pero tomando
un argumento va_list en lugar de un número variable de argumentos.
Nuevo en la versión 3.5.
void PyErr_SetNone(PyObject *type)
Part of the Stable ABI. Esta es una abreviatura de PyErr_SetObject(type, Py_None).
int PyErr_BadArgument()
Part of the Stable ABI. Esta es una abreviatura de PyErr_SetString(PyExc_TypeError, message),
donde message indica que se invocó una operación incorporada con un argumento ilegal. Es principalmente para
uso interno.
PyObject *PyErr_NoMemory()
Return value: Always NULL. Part of the Stable ABI. Esta es una abreviatura de
PyErr_SetNone(PyExc_MemoryError); retorna NULL para que una función de asignación de ob-
jetos pueda escribir return PyErr_NoMemory(); cuando se queda sin memoria.
PyObject *PyErr_SetFromErrno(PyObject *type)
Return value: Always NULL. Part of the Stable ABI. This is a convenience function to raise an exception when a C
library function has returned an error and set the C variable errno. It constructs a tuple object whose first item is
the integer errno value and whose second item is the corresponding error message (gotten from strerror()),
and then calls PyErr_SetObject(type, object). On Unix, when the errno value is EINTR, indicating
an interrupted system call, this calls PyErr_CheckSignals(), and if that set the error indicator, leaves it
set to that. The function always returns NULL, so a wrapper function around a system call can write return
PyErr_SetFromErrno(type); when the system call returns an error.
PyObject *PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)
Return value: Always NULL. Part of the Stable ABI. Similar to PyErr_SetFromErrno(), with the additional
behavior that if filenameObject is not NULL, it is passed to the constructor of type as a third parameter. In the case
of OSError exception, this is used to define the filename attribute of the exception instance.
PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject,
PyObject *filenameObject2)

5.2. Lanzando excepciones 57


The Python/C API, Versión 3.13.0a5

Return value: Always NULL. Part of the Stable ABI since version 3.7. Similar a
PyErr_SetFromErrnoWithFilenameObject(), pero toma un segundo objeto de nombre de ar-
chivo, para lanzar errores cuando falla una función que toma dos nombres de archivo.
Nuevo en la versión 3.4.
PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
Return value: Always NULL. Part of the Stable ABI. Similar a PyErr_SetFromErrnoWithFilenameObject(),
pero el nombre del archivo se da como una cadena de caracteres de C. filename se decodifica a partir de la
codificación de filesystem encoding and error handler.
PyObject *PyErr_SetFromWindowsErr(int ierr)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. This is a convenience function
to raise WindowsError. If called with ierr of 0, the error code returned by a call to GetLastError()
is used instead. It calls the Win32 function FormatMessage() to retrieve the Windows description of error
code given by ierr or GetLastError(), then it constructs a tuple object whose first item is the ierr value
and whose second item is the corresponding error message (gotten from FormatMessage()), and then calls
PyErr_SetObject(PyExc_WindowsError, object). This function always returns NULL.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a
PyErr_SetFromWindowsErr(), con un parámetro adicional que especifica el tipo de excepción que
se lanzará.
Disponibilidad: Windows.
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar to
PyErr_SetFromWindowsErr(), with the additional behavior that if filename is not NULL, it is deco-
ded from the filesystem encoding (os.fsdecode()) and passed to the constructor of OSError as a third
parameter to be used to define the filename attribute of the exception instance.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject
*filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar to
PyErr_SetExcFromWindowsErr(), with the additional behavior that if filename is not NULL, it is
passed to the constructor of OSError as a third parameter to be used to define the filename attribute of the
exception instance.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject
*filename, PyObject *filename2)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a
PyErr_SetExcFromWindowsErrWithFilenameObject(), pero acepta un segundo objeto de
nombre de archivo.
Disponibilidad: Windows.
Nuevo en la versión 3.4.
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a

58 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 3.2.
void PyErr_SyntaxLocation(const char *filename, int lineno)
Part of the Stable ABI. Como PyErr_SyntaxLocationEx(), pero se omite el parámetro col_offset.
void PyErr_BadInternalCall()
Part of the Stable ABI. Esta es una abreviatura de PyErr_SetString(PyExc_SystemError,
message), donde message indica que se invocó una operación interna (por ejemplo, una función de Python/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.

5.3. Emitir advertencias 59


The Python/C API, Versión 3.13.0a5

Las categorías de advertencia deben ser subclases de PyExc_Warning; PyExc_Warning es una subclase de
PyExc_Exception; la categoría de advertencia predeterminada es PyExc_RuntimeWarning. Las catego-
rías de advertencia estándar de Python están disponibles como variables globales cuyos nombres se enumeran en
Categorías de advertencia estándar.
Para obtener información sobre el control de advertencia, consulte la documentación del módulo warnings y la
opción -W en la documentación de la línea de comandos. No hay API de C para el control de advertencia.
int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno,
PyObject *module, PyObject *registry)
Emite un mensaje de advertencia con control explícito sobre todos los atributos de advertencia. Este es un conte-
nedor sencillo alrededor de la función Python warnings.warn_explicit(); consulte allí para obtener más
información. Los argumentos module y registry pueden establecerse en NULL para obtener el efecto predetermi-
nado que se describe allí.
Nuevo en la versión 3.4.
int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char
*module, PyObject *registry)
Part of the Stable ABI. Similar a PyErr_WarnExplicitObject() excepto que message y module son cade-
nas codificadas UTF-8, y filename se decodifica de filesystem encoding and error handler.
int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI. Función similar a PyErr_WarnEx(), pero usa PyUnicode_FromFormat() para
formatear el mensaje de advertencia. format es una cadena de caracteres codificada en ASCII.
Nuevo en la versión 3.2.
int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI since version 3.6. Function similar to PyErr_WarnFormat(), but category is
ResourceWarning and it passes source to warnings.WarningMessage.
Nuevo en la versión 3.6.

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 acceso a la memoria
si no se ha producido ninguna excepción.

60 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 3.12.
void PyErr_SetRaisedException(PyObject *exc)
Part of the Stable ABI since version 3.12. Set exc as the exception currently being raised, clearing the existing
exception if one is set.

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

Nuevo en la versión 3.12.


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á confi-
gurado, 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);


}

5.4. Consultando el indicador de error 61


The Python/C API, Versión 3.13.0a5

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 tem-
porarily. 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 norma-
lizados», 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 lanzada. Retorna
una nueva referencia a la excepción o NULL. No modifica el estado de excepción del intérprete.

Nota: Esta función normalmente no es utilizada por el código que quiere manejar excepciones. En cam-
bio, se puede usar cuando el código necesita guardar y restaurar el estado de excepción temporalmente. Use
PyErr_SetHandledException() para restaurar o borrar el estado de excepción.

Nuevo en la versión 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.

Nuevo en la versión 3.11.

62 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.13.0a5

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 re-
cientemente. Retorna nuevas referencias para los tres objetos, cualquiera de los cuales puede ser NULL. No modi-
fica 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.

Nuevo en la versión 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.

Nuevo en la versión 3.3.


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

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 inmediatamente (de
modo que es posible que otras señales pendientes no se hayan manejado todavía: estarán en la siguiente invocación
de PyErr_CheckSignals()).
Si la función se llama desde un hilo no principal, o bajo un intérprete de Python no principal, no hace nada y
devuelve 0.
Esta función se puede llamar mediante un código C de ejecución prolongada que quiere ser interrumpible por las
peticiones del usuario (como presionar Ctrl-C).

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

5.5. Manejo de señal 63


The Python/C API, Versión 3.13.0a5

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.

Nuevo en la versión 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.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.

64 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.13.0a5

Nuevo en la versión 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.
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.
Nuevo en la versión 3.12.

5.7. Objetos excepción 65


The Python/C API, Versión 3.13.0a5

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

66 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.13.0a5

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 funciones facilitan
esta funcionalidad. Efectivamente, estos son los C equivalentes a reprlib.recursive_repr().
int Py_ReprEnter(PyObject *object)
Part of the Stable ABI. Llamado al comienzo de la implementación tp_repr para detectar ciclos.
Si el objeto ya ha sido procesado, la función retorna un entero positivo. En ese caso, la implementación tp_repr
debería retornar un objeto de cadena que indique un ciclo. Como ejemplos, los objetos dict retornan {...} y
los objetos list retornan [...].
La función retornará un entero negativo si se alcanza el límite de recursión. En ese caso, la implementación
tp_repr normalmente debería retornar NULL.
De lo contrario, la función retorna cero y la implementación tp_repr puede continuar normalmente.
void Py_ReprLeave(PyObject *object)
Part of the Stable ABI. Termina a Py_ReprEnter(). Se debe llamar una vez por cada invocación de
Py_ReprEnter() que retorna cero.

5.9. Control de recursión 67


The Python/C API, Versión 3.13.0a5

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 69, 1
PyExc_Exception Exception
Página 69, 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_ConnectionResetErrorConnectionResetError
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 69, 1
PyExc_LookupError LookupError
PyExc_MemoryError MemoryError
PyExc_ModuleNotFoundError ModuleNotFoundError
PyExc_NameError NameError
PyExc_NotADirectoryError NotADirectoryError
PyExc_NotImplementedError NotImplementedError
Página 69, 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
continúe en la próxima página

68 Capítulo 5. Manejo de excepciones


The Python/C API, Versión 3.13.0a5

Tabla 1 – proviene de la página anterior


Nombre en C Nombre en Python Notas
PyExc_TimeoutError TimeoutError
PyExc_TypeError TypeError
PyExc_UnboundLocalError UnboundLocalError
PyExc_UnicodeDecodeError UnicodeDecodeError
PyExc_UnicodeEncodeError UnicodeEncodeError
PyExc_UnicodeError UnicodeError
PyExc_UnicodeTranslateError
UnicodeTranslateError
PyExc_ValueError ValueError
PyExc_ZeroDivisionError ZeroDivisionError

Nuevo en la versión 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.
Nuevo en la versión 3.5: PyExc_StopAsyncIteration y PyExc_RecursionError.
Nuevo en la versión 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:
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.

5.11. Categorías de advertencia estándar 69


The Python/C API, Versión 3.13.0a5

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

Nuevo en la versión 3.2: PyExc_ResourceWarning.


Notas:

3 Esta es una clase base para otras categorías de advertencia estándar.

70 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.
Nuevo en la versión 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 function 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().

Nuevo en la versión 3.7.

71
The Python/C API, Versión 3.13.0a5

void PyOS_AfterFork_Parent()
Part of the Stable ABI on platforms with fork() since version 3.7. Función para actualizar algún estado interno
después de una bifurcación de proceso. Se debe invocar desde el proceso principal después de llamar a fork() o
cualquier función similar que clone el proceso actual, independientemente de si la clonación del proceso fue exitosa.
Solo disponible en sistemas donde fork() está definido.

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

Nuevo en la versión 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érprete
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 posibilidad 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().

Nuevo en la versión 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 bifur-
cació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.

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

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

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

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

Ver también:
Las funciones PyUnicode_EncodeFSDefault() y PyUnicode_EncodeLocale().
Nuevo en la versión 3.5.

6.1. Utilidades del sistema operativo 73


The Python/C API, Versión 3.13.0a5

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.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().
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Clear sys.warnoptions and warnings.
filters instead.
void PySys_WriteStdout(const char *format, ...)
Part of the Stable ABI. Escribe la cadena de caracteres de salida descrita por format en sys.stdout. No se
lanzan excepciones, incluso si se produce el truncamiento (ver más abajo).
format debe limitar el tamaño total de la cadena de caracteres de salida formateada a 1000 bytes o menos; después
de 1000 bytes, la cadena de caracteres de salida se trunca. En particular, esto significa que no deben existir formatos
«%s» sin restricciones; estos deben limitarse usando «%.<N>s» donde <N> es un número decimal calculado de
modo que <N> más el tamaño máximo de otro texto formateado no exceda los 1000 bytes. También tenga cuidado
con «%f», que puede imprimir cientos de dígitos para números muy grandes.
Si ocurre un problema, o sys.stdout no está configurado, el mensaje formateado se escribe en el real (nivel C)
stdout.
void PySys_WriteStderr(const char *format, ...)
Part of the Stable ABI. Como PySys_WriteStdout(), pero escribe a sys.stderr o stderr en su lugar.
void PySys_FormatStdout(const char *format, ...)
Part of the Stable ABI. Función similar a PySys_WriteStdout() pero formatea el mensaje usando
PyUnicode_FromFormatV() y no trunca el mensaje a una longitud arbitraria.
Nuevo en la versión 3.2.
void PySys_FormatStderr(const char *format, ...)
Part of the Stable ABI. Como PySys_FormatStdout(), pero escribe a sys.stderr o stderr en su lugar.
Nuevo en la versión 3.2.
PyObject *PySys_GetXOptions()
Return value: Borrowed reference. Part of the Stable ABI since version 3.7. Retorna el diccionario actual de opciones
-X, de manera similar a sys._xoptions. En caso de error, se retorna NULL y se establece una excepción.
Nuevo en la versión 3.2.

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

int PySys_Audit(const char *event, const char *format, ...)


Part of the Stable ABI since version 3.13. Lanza un evento de auditoría con cualquier gancho activo. Retorna cero
para el éxito y no cero con una excepción establecida en caso de error.
The event string argument must not be NULL.
If any hooks have been added, format and other arguments will be used to construct a tuple to pass. Apart from N,
the same format characters as used in Py_BuildValue() are available. If the built value is not a tuple, it will
be added into a single-element tuple.
The N format option must not be used. It consumes a reference, but since there is no way to know whether arguments
to this function will be consumed, using it may cause reference leaks.
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.
See also PySys_AuditTuple().
Nuevo en la versión 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_AuditTuple(const char *event, PyObject *args)
Part of the Stable ABI since version 3.13. Similar to PySys_Audit(), but pass arguments as a Python object.
args must be a tuple. To pass no arguments, args can be NULL.
Nuevo en la versión 3.13.
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.
Ver PEP 578 para una descripción detallada de la auditoría. Las funciones en el tiempo de ejecución y la biblio-
teca 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() or
PySys_AuditTuple(). args is guaranteed to be a PyTupleObject. userData is the argument passed
to PySys_AddAuditHook().
Nuevo en la versión 3.8.

6.2. Funciones del Sistema 75


The Python/C API, Versión 3.13.0a5

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.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Use PyImport_ImportModule() instead.
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__().
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().

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

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 describe mejor ha-
ciendo 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.
Nuevo en la versión 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_AddModuleRef(const char *name)
Return value: New reference. Part of the Stable ABI since version 3.13. Return the module object corresponding to
a module name.
The name argument may be of the form package.module. First check the modules dictionary if there’s one
there, and if not, create a new one and insert it in the modules dictionary.
Return a strong reference to the module on success. Return NULL with an exception set on failure.
The module name name is decoded from UTF-8.
This function does not load or import the module; if the module wasn’t already loaded, you will get an empty module
object. Use PyImport_ImportModule() or one of its variants to import a module. Package structures implied
by a dotted name for name are not created if not already present.
Nuevo en la versión 3.13.
PyObject *PyImport_AddModuleObject(PyObject *name)
Return value: Borrowed reference. Part of the Stable ABI since version 3.7. Similar to
PyImport_AddModuleRef(), but return a borrowed reference and name is a Python str object.
Nuevo en la versión 3.3.
PyObject *PyImport_AddModule(const char *name)
Return value: Borrowed reference. Part of the Stable ABI. Similar to PyImport_AddModuleRef(), but return
a borrowed reference.

6.4. Importando módulos 77


The Python/C API, Versión 3.13.0a5

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 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.
Nuevo en la versión 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.
Nuevo en la versión 3.2.
Distinto en la versión 3.3: Uses imp.source_from_cache() in calculating the source path if only the byte-
code 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.

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

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.
Nuevo en la versión 3.2.
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.
Nuevo en la versión 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ó).
Nuevo en la versión 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.

6.4. Importando módulos 79


The Python/C API, Versión 3.13.0a5

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 contenedor
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 inicializació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:
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 (marshalled)
de value. version indica el formato del archivo.
Las siguientes funciones permiten volver a leer los valores empaquetados (marshalled).

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

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.
PyObject *PyMarshal_ReadLastObjectFromFile(FILE *file)
Return value: New reference. Retorna un objeto Python del flujo de datos FILE* abierto para lectura. A diferencia
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 formato que se utilizan para contarle a la función sobre los
argumentos esperados. Las cadenas de caracteres de formato utilizan la misma sintaxis para cada una de estas funciones.

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.

6.6. Analizando argumentos y construyendo valores 81


The Python/C API, Versión 3.13.0a5

Cadena de caracteres y búferes

Nota: On Python 3.12 and older, the macro PY_SSIZE_T_CLEAN must be defined before including Python.h to
use all # variants of formats (s#, y#, etc.) explained below. This is not necessary on Python 3.13 and later.

Estos formatos permiten acceder a un objeto como un bloque contiguo de memoria. Usted no tiene que proporcionar
almacenamiento en bruto para el Unicode o área de bytes retornada.
A menos que se indique lo contrario, los búferes no son terminados en NULL (NUL-terminated).
There are three ways strings and buffers can be converted to C:
• Formats such as y* and s* fill a Py_buffer structure. This locks the underlying buffer so that the caller can
subsequently use the buffer even inside a Py_BEGIN_ALLOW_THREADS block without the risk of mutable da-
ta being resized or destroyed. As a result, you have to call PyBuffer_Release() after you have finished
processing the data (or in any early abort case).
• The es, es#, et and et# formats allocate the result buffer. You have to call PyMem_Free() after you have
finished processing the data (or in any early abort case).
• Other formats take a str or a read-only bytes-like object, such as bytes, and provide a const char * pointer
to its buffer. In this case the buffer is «borrowed»: it is managed by the corresponding Python object, and shares
the lifetime of this object. You won’t have to release any memory yourself.
To ensure that the underlying buffer may be safely borrowed, the object’s PyBufferProcs.
bf_releasebuffer field must be NULL. This disallows common mutable objects such as bytearray, but
also some read-only objects such as memoryview of bytes.
Besides this bf_releasebuffer requirement, there is no check to verify whether the input object is immutable
(e.g. whether it would honor a request for a writable buffer, or whether another thread can mutate the data).
s (str) [const char *]
Convierte un objeto Unicode a un puntero C a una cadena de caracteres. Un puntero a una cadena de caracteres
existente se almacena en la variable puntero del carácter cuya dirección se pasa. La cadena de caracteres en C es
terminada en NULL. La cadena de caracteres de Python no debe contener puntos de código incrustado nulos; si
lo hace, se lanza una excepción ValueError. Los objetos Unicode se convierten en cadenas de caracteres de C
utilizando codificación 'utf-8'. Si esta conversión fallase lanza un UnicodeError.

Nota: Este formato no acepta objetos de tipo bytes. Si desea aceptar los caminos del sistema de archivos y con-
vertirlos en cadenas de caracteres C, es preferible utilizar el formato O& con PyUnicode_FSConverter()
como convertidor.

Distinto en la versión 3.5: Anteriormente, TypeError se lanzó cuando se encontraron puntos de código nulos
incrustados en la cadena de caracteres de Python.
s* (str o bytes-like object) [Py_buffer]
Este formato acepta objetos Unicode, así como objetos de tipo bytes. Llena una estructura Py_buffer propor-
cionada por la persona que llama. En este caso la cadena de caracteres de C resultante puede contener bytes NUL
embebidos. Los objetos Unicode se convierten en cadenas de caracteres C utilizando codificación 'utf-8'.
s# (str, bytes-like object de sólo lectura) [const char *, Py_ssize_t]
Like s*, except that it provides a borrowed buffer. The result is stored into two C variables, the first one a pointer
to a C string, the second one its length. The string may contain embedded null bytes. Unicode objects are converted
to C strings using 'utf-8' encoding.
z (str o None) [const char *]
Como s, pero el objeto Python también puede ser None, en cuyo caso el puntero C se establece en NULL.

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

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 recomendada
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.
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 estructura
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.

6.6. Analizando argumentos y construyendo valores 83


The Python/C API, Versión 3.13.0a5

It requires three arguments. The first is only used as input, and must be a const char* which points to the name
of an encoding as a NUL-terminated string, or NULL, in which case 'utf-8' encoding is used. An exception is
raised if the named encoding is not known to Python. The second argument must be a char**; the value of the
pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the
encoding specified by the first argument. The third argument must be a pointer to an integer; the referenced integer
will be set to the number of bytes in the output buffer.
Hay dos modos de operación:
Si *buffer señala un puntero NULL, la función asignará un búfer del tamaño necesario, copiará los datos codifica-
dos en este búfer y configurará *buffer para hacer referencia al almacenamiento recién asignado. Quien llama es
responsable de llamar a PyMem_Free() para liberar el búfer asignado después del uso.
Si *buffer apunta a un puntero no NULL (un búfer ya asignado), PyArg_ParseTuple() usará esta ubicación
como el búfer e interpretará el valor inicial de *buffer_length como el tamaño del búfer. Luego copiará los da-
tos codificados en el búfer y los terminará en NUL. Si el búfer no es lo suficientemente grande, se establecerá a
ValueError.
En ambos casos, *buffer_length se establece a la longitud de los datos codificados sin el byte NUL final.
et# (str, bytes o bytearray) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
Igual que es#, excepto que los objetos de cadena de caracteres de bytes se pasan sin recodificarlos. En cambio,
la implementación supone que el objeto de cadena de caracteres de bytes utiliza la codificación que se pasa como
parámetro.
Distinto en la versión 3.12: u, u#, Z, and Z# are removed because they used a legacy Py_UNICODE* representation.

Números

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.

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

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 actual object
that was passed. A new strong reference to the object is not created (i.e. its reference count is not increased). The
pointer stored is not NULL.
O! (object) [typeobject, PyObject *]
Store a Python object in a C object pointer. This is similar to O, but takes two C arguments: the first is the address
of a Python type object, the second is the address of the C variable (of type PyObject*) into which the object
pointer is stored. If the Python object does not have the required type, TypeError is raised.
O& (object) [converter, anything]
Convert a Python object to a C variable through a converter function. This takes two arguments: the first is a function,
the second is the address of a C variable (of arbitrary type), converted to void*. The converter function in turn is
called as follows:

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 argumento
finalmente falla, dando al convertidor la oportunidad de liberar cualquier memoria que ya haya asignado. En esta
segunda llamada, el parámetro object será NULL; address tendrá el mismo valor que en la llamada original.
Distinto en la versión 3.1: Py_CLEANUP_SUPPORTED fue agregada.
p (bool) [int]
Prueba el valor pasado por verdad (un booleano predicado p) y convierte el resultado a su valor entero C verdade-
ro/falso entero equivalente. Establece int en 1 si la expresión era verdadera y 0 si era falsa. Esto acepta cualquier
valor válido de Python. Consulte truth para obtener más información sobre cómo Python prueba los valores por
verdad.
Nuevo en la versión 3.3.
(items) (tuple) [matching-items]
El objeto debe ser una secuencia de Python cuya longitud es el número de unidades de formato en items. Los
argumentos C deben corresponder a las unidades de formato individuales en items. Las unidades de formato para
secuencias pueden estar anidadas.

6.6. Analizando argumentos y construyendo valores 85


The Python/C API, Versión 3.13.0a5

It is possible to pass «long» integers (integers whose value exceeds the platform’s LONG_MAX) however no proper range
checking is done — the most significant bits are silently truncated when the receiving field is too small to receive the value
(actually, the semantics are inherited from downcasts in C — your mileage may vary).
Algunos otros caracteres tienen un significado en una cadena de formato. Esto puede no ocurrir dentro de paréntesis
anidados. Son:
|
Indica que los argumentos restantes en la lista de argumentos de Python son opcionales. Las variables C corres-
pondientes a argumentos opcionales deben inicializarse a su valor predeterminado — cuando no se especifica un
argumento opcional, PyArg_ParseTuple() no toca el contenido de las variables C correspondientes.
$
PyArg_ParseTupleAndKeywords() solamente: indica que los argumentos restantes en la lista de argumen-
tos de Python son solo palabras clave. Actualmente, todos los argumentos de solo palabras clave también deben
ser argumentos opcionales, por lo que | siempre debe especificarse antes de $ en la cadena de formato.
Nuevo en la versión 3.3.
:
La lista de unidades de formato termina aquí; la cadena después de los dos puntos se usa como el nombre de la
función en los mensajes de error (el «valor asociado» de la excepción que PyArg_ParseTuple() lanza).
;
La lista de unidades de formato termina aquí; la cadena después del punto y coma se usa como mensaje de error en
lugar de del mensaje de error predeterminado. : y ; se excluyen mutuamente.
Note that any Python object references which are provided to the caller are borrowed references; do not release them (i.e.
do not decrement their reference count)!
Los argumentos adicionales pasados a estas funciones deben ser direcciones de variables cuyo tipo está determinado por
la cadena de formato; Estos se utilizan para almacenar valores de la tupla de entrada. Hay algunos casos, como se describe
en la lista de unidades de formato anterior, donde estos parámetros se utilizan como valores de entrada; deben coincidir
con lo especificado para la unidad de formato correspondiente en ese caso.
For the conversion to succeed, the arg object must match the format and the format must be exhausted. On success,
the PyArg_Parse* functions return true, otherwise they return false and raise an appropriate exception. When the
PyArg_Parse* functions fail due to conversion failure in one of the format units, the variables at the addresses corres-
ponding to that and the following format units are left untouched.

Funciones API

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 *const
*keywords, ...)
Part of the Stable ABI. Parse the parameters of a function that takes both positional and keyword parameters into
local variables. The keywords argument is a NULL-terminated array of keyword parameter names specified as null-
terminated ASCII or UTF-8 encoded C strings. Empty names denote positional-only parameters. Returns true on
success; on failure, it returns false and raises the appropriate exception.

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

Nota: The keywords parameter declaration is char *const* in C and const char *const* in C++.
This can be overridden with the PY_CXX_CONST macro.

Distinto en la versión 3.6: Soporte agregado para sólo parámetros posicionales.


Distinto en la versión 3.13: The keywords parameter has now type char *const* in C and const char
*const* in C++, instead of char**. Added support for non-ASCII keyword parameter names.
int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *const
*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.
Nuevo en la versión 3.2.
int PyArg_Parse(PyObject *args, const char *format, ...)
Part of the Stable ABI. Parse the parameter of a function that takes a single positional parameter into a local variable.
Returns true on success; on failure, it returns false and raises the appropriate exception.
Example:
// Function using METH_O calling convention
static PyObject*
my_function(PyObject *module, PyObject *arg)
{
int value;
if (!PyArg_Parse(arg, "i:my_function", &value)) {
return NULL;
}
// ... use value ...
}

int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
Part of the Stable ABI. A simpler form of parameter retrieval which does not use a format string to specify
the types of the arguments. Functions which use this method to retrieve their parameters should be declared as
METH_VARARGS in function or method tables. The tuple containing the actual parameters should be passed as
args; it must actually be a tuple. The length of the tuple must be at least min and no more than max; min and
max may be equal. Additional arguments must be passed to the function, each of which should be a pointer to a
PyObject* variable; these will be filled in with the values from args; they will contain borrowed references. The
variables which correspond to optional parameters not given by args will not be filled in; these should be initialized
by the caller. This function returns true on success and false if args is not a tuple or contains the wrong number of
elements; an exception will be set if there was a failure.
This is an example of the use of this function, taken from the sources for the _weakref helper module for weak
references:
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
(continúe en la próxima página)

6.6. Analizando argumentos y construyendo valores 87


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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)

PY_CXX_CONST
The value to be inserted, if any, before char *const* in the keywords parameter declaration of
PyArg_ParseTupleAndKeywords() and PyArg_VaParseTupleAndKeywords(). Default empty
for C and const for C++ (const char *const*). To override, define it to the desired value before inclu-
ding Python.h.
Nuevo en la versión 3.13.

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.

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

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

6.6. Analizando argumentos y construyendo valores 89


The Python/C API, Versión 3.13.0a5

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 incremented
by one). If the object passed in is a NULL pointer, it is assumed that this was caused because the 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).

90 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5

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 (including
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 (excluyendo
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.
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).
Nuevo en la versión 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).
Nuevo en la versión 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

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


The Python/C API, Versión 3.13.0a5

NULL retorna Py_HUGE_VAL (con un signo apropiado) y no establece ninguna excepción. De lo contrario,
overflow_exception debe apuntar a un objeto excepción de Python; lanza esa excepción y retorna -1.
0. En ambos casos, configura *endptr para que apunte al primer carácter después del valor convertido.
Si se produce algún otro error durante la conversión (por ejemplo, un error de falta de memoria), establece la
excepción Python adecuada y retorna -1.0.
Nuevo en la versión 3.1.
char *PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)
Part of the Stable ABI. Convert a double val to a string using supplied format_code, precision, and flags.
format_code debe ser uno de 'e', 'E', 'f', 'F', 'g', 'G' or 'r'. Para 'r', la precision suministrada debe
ser 0 y se ignora. El código de formato 'r' especifica el formato estándar repr().
flags puede ser cero o más de los valores Py_DTSF_SIGN, Py_DTSF_ADD_DOT_0, o Py_DTSF_ALT, unidos
por or (or-ed) juntos:
• Py_DTSF_SIGN significa preceder siempre a la cadena de caracteres retornada con un carácter de signo,
incluso si val no es negativo.
• Py_DTSF_ADD_DOT_0 significa asegurarse de que la cadena de caracteres retornada no se verá como un
número entero.
• Py_DTSF_ALT significa aplicar reglas de formato «alternativas». Consulte la documentación del especifi-
cador PyOS_snprintf() '#' para obtener más detalles.
Si ptype no es NULL, el valor al que apunta se establecerá en uno de Py_DTST_FINITE, Py_DTST_INFINITE
o Py_DTST_NAN, lo que significa que val es un número finito, un número infinito o no es un número, respectiva-
mente.
El valor de retorno es un puntero a buffer con la cadena de caracteres convertida o NULL si la conversión falla. La
persona que llama es responsable de liberar la cadena de caracteres retornada llamando a PyMem_Free().
Nuevo en la versión 3.1.
int PyOS_stricmp(const char *s1, const char *s2)
Case insensitive comparison of strings. The function works almost identically to strcmp() except that it ignores
the case.
int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size)
Case insensitive comparison of strings. The function works almost identically to strncmp() except that it ignores
the case.

6.8 PyHash API

See also the PyTypeObject.tp_hash member and numeric-hash.


type Py_hash_t
Hash value type: signed integer.
Nuevo en la versión 3.2.
type Py_uhash_t
Hash value type: unsigned integer.
Nuevo en la versión 3.2.

92 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5

PyHASH_MODULUS
The Mersenne prime P = 2**n -1, used for numeric hash scheme.
Nuevo en la versión 3.13.
PyHASH_BITS
The exponent n of P in PyHASH_MODULUS.
Nuevo en la versión 3.13.
PyHASH_INF
The hash value returned for a positive infinity.
Nuevo en la versión 3.13.
PyHASH_IMAG
The multiplier used for the imaginary part of a complex number.
Nuevo en la versión 3.13.
type PyHash_FuncDef
Hash function definition used by PyHash_GetFuncDef().
const char *name
Hash function name (UTF-8 encoded string).
const int hash_bits
Internal size of the hash value in bits.
const int seed_bits
Size of seed input in bits.
Nuevo en la versión 3.4.
PyHash_FuncDef *PyHash_GetFuncDef(void)
Get the hash function definition.
Ver también:
PEP 456 «Secure and interchangeable hash algorithm».
Nuevo en la versión 3.4.
Py_hash_t Py_HashPointer(const void *ptr)
Hash a pointer value: process the pointer value as an integer (cast it to uintptr_t internally). The pointer is not
dereferenced.
The function cannot fail: it cannot return -1.
Nuevo en la versión 3.13.

6.9 Reflexión

PyObject *PyEval_GetBuiltins(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las construcciones en el marco
de ejecución actual, o el intérprete del estado del hilo si no se está ejecutando ningún marco actualmente.

6.9. Reflexión 93
The Python/C API, Versión 3.13.0a5

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

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.
Nuevo en la versión 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.
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.

94 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5

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 pro-
blemática de caracteres o bytes y su desplazamiento en la cadena original (consulte Objetos unicode de excepción
para funciones para extraer esta información). La devolución de llamada debe lanzar la excepción dada o retor-
nar 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.
PyObject *PyCodec_IgnoreErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Ignora el error Unicode, omitiendo la entrada defectuosa.

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


The Python/C API, Versión 3.13.0a5

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{...}.
Nuevo en la versión 3.5.

6.11 PyTime C API

Nuevo en la versión 3.13.


The clock C API provides access to system clocks. It is similar to the Python time module.
For C API related to the datetime module, see Objetos DateTime.

6.11.1 Types

type PyTime_t
A timestamp or duration in nanoseconds, represented as a signed 64-bit integer.
The reference point for timestamps depends on the clock used. For example, PyTime_Time() returns times-
tamps relative to the UNIX epoch.
The supported range is around [-292.3 years; +292.3 years]. Using the Unix epoch (January 1st, 1970) as reference,
the supported date range is around [1677-09-21; 2262-04-11]. The exact limits are exposed as constants:
PyTime_t PyTime_MIN
Minimum value of PyTime_t.
PyTime_t PyTime_MAX
Maximum value of PyTime_t.

6.11.2 Clock Functions

The following functions take a pointer to a PyTime_t that they set to the value of a particular clock. Details of each
clock are given in the documentation of the corresponding Python function.
The functions return 0 on success, or -1 (with an exception set) on failure.
On integer overflow, they set the PyExc_OverflowError exception and set *result to the value clamped to the
[PyTime_MIN; PyTime_MAX] range. (On current systems, integer overflows are likely caused by misconfigured
system time.)
As any other C API (unless otherwise specified), the functions must be called with the GIL held.

96 Capítulo 6. Utilidades
The Python/C API, Versión 3.13.0a5

int PyTime_Monotonic(PyTime_t *result)


Read the monotonic clock. See time.monotonic() for important details on this clock.
int PyTime_PerfCounter(PyTime_t *result)
Read the performance counter. See time.perf_counter() for important details on this clock.
int PyTime_Time(PyTime_t *result)
Read the “wall clock” time. See time.time() for details important on this clock.

6.11.3 Conversion functions

double PyTime_AsSecondsDouble(PyTime_t t)
Convert a timestamp to a number of seconds as a C double.
The function cannot fail, but note that double has limited accuracy for large values.

6.12 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 documen-
tation of the Linux Perf tool.
In Python, these helper APIs can be used by libraries and features that rely on generating machine code on the fly.
Note that holding the Global Interpreter Lock (GIL) is not required for these APIs.
int PyUnstable_PerfMapState_Init(void)

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()). Normally, there’s
no need to call this explicitly; just use PyUnstable_WritePerfMapEntry() and it will initialize the state
on first call.
Returns 0 on success, -1 on failure to create/open the perf map file, or -2 on failure to create a lock. Check
errno for more information about the cause of a failure.
int PyUnstable_WritePerfMapEntry(const void *code_addr, unsigned int code_size, const char
*entry_name)

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.

6.12. Support for Perf Maps 97


The Python/C API, Versión 3.13.0a5

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.

98 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 combinación
de tipos dada.
Py_RETURN_NOTIMPLEMENTED
Properly handle returning Py_NotImplemented from within a C function (that is, create a new strong reference
to NotImplemented and return it).
Py_PRINT_RAW
Flag to be used with multiple functions that print the object (like PyObject_Print() and
PyFile_WriteObject()). If passed, these function would use the str() of the object instead of
the repr().
int PyObject_Print(PyObject *o, FILE *fp, int flags)
Print an object o, on file fp. Returns -1 on error. The flags argument is used to enable certain printing options. The
only option currently supported is Py_PRINT_RAW; if given, the str() of the object is written instead of the
repr().
int PyObject_HasAttrWithError(PyObject *o, const char *attr_name)
Part of the Stable ABI since version 3.13. Returns 1 if o has the attribute attr_name, and 0 otherwise. This is
equivalent to the Python expression hasattr(o, attr_name). On failure, return -1.
Nuevo en la versión 3.13.

99
The Python/C API, Versión 3.13.0a5

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


Part of the Stable ABI since version 3.13. This is the same as PyObject_HasAttrWithError(), but
attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
Nuevo en la versión 3.13.
int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
Part of the Stable ABI. Returns 1 if o has the attribute attr_name, and 0 otherwise. This function always succeeds.

Nota: Exceptions that occur when this calls __getattr__() and __getattribute__() met-
hods are silently ignored. For proper error handling, use PyObject_HasAttrWithError(),
PyObject_GetOptionalAttr() or PyObject_GetAttr() instead.

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_HasAttrStringWithError(), PyObject_GetOptionalAttrString() or
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.
If the missing attribute should not be treated as a failure, you can use PyObject_GetOptionalAttr()
instead.
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*.
If the missing attribute should not be treated as a failure, you can use
PyObject_GetOptionalAttrString() instead.
int PyObject_GetOptionalAttr(PyObject *obj, PyObject *attr_name, PyObject **result);
Part of the Stable ABI since version 3.13. Variant of PyObject_GetAttr() which doesn’t raise
AttributeError if the attribute is not found.
If the attribute is found, return 1 and set *result to a new strong reference to the attribute. If the attribute is not found,
return 0 and set *result to NULL; the AttributeError is silenced. If an error other than AttributeError
is raised, return -1 and set *result to NULL.
Nuevo en la versión 3.13.
int PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject **result);
Part of the Stable ABI since version 3.13. This is the same as PyObject_GetOptionalAttr(), but attr_name
is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
Nuevo en la versión 3.13.
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,

100 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

así como un atributo en el objeto __ dict__ (si está presente). Como se describe en descriptors, los descriptores
de datos tienen preferencia sobre los atributos de instancia, mientras que los descriptores que no son de datos no lo
hacen. De lo contrario, se lanza un AttributeError.
int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)
Part of the Stable ABI. Establece el valor del atributo llamado attr_name, para el objeto o, en el valor v. Lanza
una excepción y retorna -1 en caso de falla; retorna 0 en caso de éxito. Este es el equivalente de la declaración de
Python o.attr_name = v.
Si v es NULL, el atributo se elimina. Este comportamiento está deprecado en favor de usar
PyObject_DelAttr(), pero por el momento no hay planes de quitarlo.
int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)
Part of the Stable ABI. This is the same as PyObject_SetAttr(), but attr_name is specified as a const
char* UTF-8 encoded bytes string, rather than a PyObject*.
Si v es NULL, el atributo se elimina, sin embargo, esta característica está deprecada en favor de usar
PyObject_DelAttrString().
int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)
Part of the Stable ABI. Establecimiento de atributo genérico y función de eliminación que está destinada a colocarse
en la ranura de un objeto tipo tp_setattro. Busca un descriptor de datos en el diccionario de clases en el MRO
del objeto y, si se encuentra, tiene preferencia sobre la configuración o eliminación del atributo en el diccionario de
instancias. De lo contrario, el atributo se establece o elimina en el objeto __dict__ (si está presente). En caso de
éxito, se retorna 0; de lo contrario, se lanza un AttributeError y se retorna -1.
int PyObject_DelAttr(PyObject *o, PyObject *attr_name)
Part of the Stable ABI since version 3.13. Elimina el atributo llamado attr_name, para el objeto o. Retorna -1 en
caso de falla. Este es el equivalente de la declaración de Python del o.attr_name.
int PyObject_DelAttrString(PyObject *o, const char *attr_name)
Part of the Stable ABI since version 3.13. This is the same as PyObject_DelAttr(), but attr_name is specified
as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
PyObject *PyObject_GenericGetDict(PyObject *o, void *context)
Return value: New reference. Part of the Stable ABI since version 3.10. Una implementación genérica para obtener
un descriptor __dict__. Crea el diccionario si es necesario.
Esta función también puede ser llamada para obtener el __dict__ del objeto o. Se pasa context igual a NULL
cuando se lo llama. Dado que esta función puede necesitar asignar memoria para el diccionario, puede ser más
eficiente llamar a PyObject_GetAttr() para acceder a un atributo del objeto.
En caso de fallo, retorna NULL con una excepción establecida.
Nuevo en la versión 3.3.
int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
Part of the Stable ABI since version 3.7. Una implementación genérica para el creador de un descriptor __dict__.
Esta implementación no permite que se elimine el diccionario.
Nuevo en la versión 3.3.
PyObject **_PyObject_GetDictPtr(PyObject *obj)
Retorna un puntero al __dict__ del objeto obj. Si no hay __dict__, retorna NULL sin establecer una excepción.
Esta función puede necesitar asignar memoria para el diccionario, por lo que puede ser más eficiente llamar a
PyObject_GetAttr() para acceder a un atributo del objeto.

7.1. Protocolo de objeto 101


The Python/C API, Versión 3.13.0a5

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

102 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

Si cls tiene un método __subclasscheck__(), se llamará para determinar el estado de la subclase como se
describe en PEP 3119. De lo contrario, derived es una subclase de cls si es una subclase directa o indirecta, es
decir, contenida en cls.__ mro__.
Normally only class objects, i.e. instances of type or a derived class, are considered classes. However, objects can
override this by having a __bases__ attribute (which must be a tuple of base classes).
int PyObject_IsInstance(PyObject *inst, PyObject *cls)
Part of the Stable ABI. Retorna 1 si inst es una instancia de la clase cls o una subclase de cls, o 0 si no. En caso de
error, retorna -1 y establece una excepción.
Si cls es una tupla, la verificación se realizará con cada entrada en cls. El resultado será 1 cuando al menos una de
las verificaciones retorne 1, de lo contrario será 0.
Si cls tiene un método __instancecheck__(), se llamará para determinar el estado de la subclase como se
describe en PEP 3119. De lo contrario, inst es una instancia de cls si su clase es una subclase de cls.
An instance inst can override what is considered its class by having a __class__ attribute.
An object cls can override if it is considered a class, and what its base classes are, by having a __bases__ attribute
(which must be a tuple of base classes).
Py_hash_t PyObject_Hash(PyObject *o)
Part of the Stable ABI. Calcula y retorna el valor hash de un objeto o. En caso de fallo, retorna -1. Este es el
equivalente de la expresión de Python hash(o).
Distinto en la versión 3.2: El tipo de retorno ahora es Py_hash_t. Este es un entero con signo del mismo tamaño
que Py_ssize_t.
Py_hash_t PyObject_HashNotImplemented(PyObject *o)
Part of the Stable ABI. Set a TypeError indicating that type(o) is not hashable and return -1. This function
receives special treatment when stored in a tp_hash slot, allowing a type to explicitly indicate to the interpreter
that it is not hashable.
int PyObject_IsTrue(PyObject *o)
Part of the Stable ABI. Retorna 1 si el objeto o se considera verdadero y 0 en caso contrario. Esto es equivalente a
la expresión de Python not not o. En caso de error, retorna -1.
int PyObject_Not(PyObject *o)
Part of the Stable ABI. Retorna 0 si el objeto o se considera verdadero, y 1 de lo contrario. Esto es equivalente a
la expresión de Python not o. En caso de error, retorna -1.
PyObject *PyObject_Type(PyObject *o)
Return value: New reference. Part of the Stable ABI. When o is non-NULL, returns a type object corresponding to
the object type of object o. On failure, raises SystemError and returns NULL. This is equivalent to the Python
expression type(o). This function creates a new strong reference to the return value. There’s really no reason to
use this function instead of the Py_TYPE() function, which returns a pointer of type PyTypeObject*, except
when a new strong reference is needed.
int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)
Retorna un valor no-nulo si el objeto o es de tipo type o un subtipo de type, y 0 en cualquier otro caso. Ninguno de
los dos parámetros debe ser NULL.
Py_ssize_t PyObject_Size(PyObject *o)
Py_ssize_t PyObject_Length(PyObject *o)
Part of the Stable ABI. Retorna la longitud del objeto o. Si el objeto o proporciona los protocolos de secuencia y
mapeo, se retorna la longitud de la secuencia. En caso de error, se retorna -1. Este es el equivalente a la expresión
de Python len(o).

7.1. Protocolo de objeto 103


The Python/C API, Versión 3.13.0a5

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).
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 3.12.
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.
Nuevo en la versión 3.12.

104 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 3.12.
int PyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg)
Visit the managed dictionary of obj.
This function must only be called in a traverse function of the type which has the Py_TPFLAGS_MANAGED_DICT
flag set.
Nuevo en la versión 3.13.
void PyObject_ClearManagedDict(PyObject *obj)
Clear the managed dictionary of obj.
This function must only be called in a traverse function of the type which has the Py_TPFLAGS_MANAGED_DICT
flag set.
Nuevo en la versión 3.13.

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

Nuevo en la versión 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. Ademá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:

7.2. Protocolo de llamada 105


The Python/C API, Versión 3.13.0a5

Advertencia: Una clase que admita vectorcall debe también implementar tp_call con la misma semántica.

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

Control de recursión

Cuando se usa tp_call, los destinatarios no necesitan preocuparse por recursividad: CPython usa
Py_EnterRecursiveCall() y Py_LeaveRecursiveCall() para llamadas realizadas usando tp_call.
Por eficiencia, este no es el caso de las llamadas realizadas mediante vectorcall: el destinatario de la llamada debe utilizar
Py_EnterRecursiveCall y Py_LeaveRecursiveCall si es necesario.

106 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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 argu-
mentos. Actualmente equivalente a:

(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)

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

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.

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

7.2. Protocolo de llamada 107


The Python/C API, Versión 3.13.0a5

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 argu-
mento.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Nuevo en la versión 3.9.
PyObject *PyObject_CallOneArg(PyObject *callable, PyObject *arg)
Return value: New reference. Llama a un objeto de Python invocable callable con exactamente 1 argumento posi-
cional 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.
Nuevo en la versión 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 alternative.
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 *.

108 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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 argumentos.
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.
Nuevo en la versión 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().

7.2. Protocolo de llamada 109


The Python/C API, Versión 3.13.0a5

If the object has the Py_TPFLAGS_METHOD_DESCRIPTOR feature, this will call the unbound method object
with the full args vector as arguments.
Retorna el resultado de la llamada en caso de éxito o lanza una excepción y retorna NULL en caso de error.
Nuevo en la versión 3.9.

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.
Nuevo en la versión 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 matemá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 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.

110 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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.

7.3. Protocolo de números 111


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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.

112 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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.
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 raise 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 clipped 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.

7.4. Protocolo de secuencia 113


The Python/C API, Versión 3.13.0a5

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

114 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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.
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 otherwise.
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*.

7.5. Protocolo de mapeo 115


The Python/C API, Versión 3.13.0a5

int PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result)


Part of the Stable ABI since version 3.13. Variant of PyObject_GetItem() which doesn’t raise KeyError
if the key is not found.
If the key is found, return 1 and set *result to a new strong reference to the corresponding value. If the key is not
found, return 0 and set *result to NULL; the KeyError is silenced. If an error other than KeyError is raised,
return -1 and set *result to NULL.
Nuevo en la versión 3.13.
int PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result)
Part of the Stable ABI since version 3.13. This is the same as PyMapping_GetOptionalItem(), but key is
specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
Nuevo en la versión 3.13.
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_HasKeyWithError(PyObject *o, PyObject *key)
Part of the Stable ABI since version 3.13. Return 1 if the mapping object has the key key and 0 otherwise. This is
equivalent to the Python expression key in o. On failure, return -1.
Nuevo en la versión 3.13.
int PyMapping_HasKeyStringWithError(PyObject *o, const char *key)
Part of the Stable ABI since version 3.13. This is the same as PyMapping_HasKeyWithError(), but key is
specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
Nuevo en la versión 3.13.
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.

Nota: Exceptions which occur when this calls __getitem__() method are silently ignored. For pro-
per error handling, use PyMapping_HasKeyWithError(), PyMapping_GetOptionalItem() or
PyObject_GetItem() instead.

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_HasKeyStringWithError(),
PyMapping_GetOptionalItemString() or PyMapping_GetItemString() instead.

116 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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 */
}

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


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

Py_DECREF(iterator);

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

7.6. Protocolo iterador 117


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


/* propagate error */
}
else {
/* continue doing useful work */
}

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

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

118 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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 ubicación
dentro del bloque de memoria física subyacente del exportador. Por ejemplo, con negativo strides el valor
puede apuntar al final del bloque de memoria.
Para arreglos contiguous, el valor apunta al comienzo del bloque de memoria.
PyObject *obj
A new reference to the exporting object. The reference is owned by the consumer and automatically released
(i.e. reference count decremented) and set to NULL by PyBuffer_Release(). The field is the equivalent
of the return value of any standard C-API function.
Como un caso especial, para los búferes temporary que están envueltos por
PyMemoryView_FromBuffer() o PyBuffer_FillInfo() este campo es NULL. En gene-
ral, los objetos de exportación NO DEBEN usar este esquema.
Py_ssize_t len
product(shape) * itemize. Para arreglos contiguos, esta es la longitud del bloque de memoria sub-
yacente. Para arreglos no contiguos, es la longitud que tendría la estructura lógica si se copiara en una repre-
sentación contigua.
Accede a ((char *)buf)[0] hasta ((char *)buf)[len-1] solo es válido si el búfer se ha
obtenido mediante una solicitud que garantiza la contigüidad. En la mayoría de los casos, dicha solicitud será
PyBUF_SIMPLE o PyBUF_WRITABLE.
int readonly
Un indicador de si el búfer es de solo lectura. Este campo está controlado por el indicador
PyBUF_WRITABLE.
Py_ssize_t itemsize
Tamaño del elemento en bytes de un solo elemento. Igual que el valor de struct.calcsize() invocado
en valores no NULL format.
Excepción importante: si un consumidor solicita un búfer sin el indicador PyBUF_FORMAT, format se
establecerá en NULL, pero itemsize todavía tiene el valor para el formato original.
Si shape está presente, la igualdad product(shape) * itemsize == len aún se mantiene y el
consumidor puede usar itemsize para navegar el búfer.
Si shape es NULL como resultado de un PyBUF_SIMPLE o un PyBUF_WRITABLE, el consumidor debe
ignorar itemsize y asume itemsize == 1.

7.7. Protocolo búfer 119


The Python/C API, Versión 3.13.0a5

const char *format


Una cadena de caracteres terminada en NUL en sintaxis de estilo del modulo struct que describe el con-
tenido de un solo elemento. Si esto es NULL, se supone "B" (bytes sin signo).
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 atenció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 gene-
ralmente 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.

120 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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ástica-
mente, el consumidor usa el argumento flags para especificar el tipo de búfer exacto que puede manejar.
All Py_buffer fields are unambiguously defined by the request type.

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

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 121


The Python/C API, Versión 3.13.0a5

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 an-
terior. Por conveniencia, el protocolo de memoria intermedia proporciona combinaciones de uso frecuente como indica-
dores únicos.
En la siguiente tabla U significa contigüidad indefinida. El consumidor tendría que llamar a
PyBuffer_IsContiguous() para determinar la contigüidad.

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

122 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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 consumidor
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 expor-
tador 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:

7.7. Protocolo búfer 123


The Python/C API, Versión 3.13.0a5

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];
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 consumidor
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 ex-
ception and return -1.
Nuevo en la versión 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.

124 Capítulo 7. Capa de objetos abstractos


The Python/C API, Versión 3.13.0a5

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

7.7. Protocolo búfer 125


The Python/C API, Versión 3.13.0a5

126 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 inco-
rrecto no es una buena idea; si recibe un objeto de un programa Python y no está seguro de que tenga el tipo correc-
to, primero debe realizar una verificación de tipo; por ejemplo, para verificar que un objeto es un diccionario, utilice
PyDict_Check(). El capítulo está estructurado como el «árbol genealógico» de los tipos de objetos Python.

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

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.

127
The Python/C API, Versión 3.13.0a5

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.
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.
Nuevo en la versión 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 neces-
sary 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.
Nuevo en la versión 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.
Nuevo en la versión 3.12.
int PyType_ClearWatcher(int watcher_id)
Clear watcher identified by watcher_id (previously returned from PyType_AddWatcher()). Return 0 on suc-
cess, -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().
Nuevo en la versión 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 whenever
PyType_Modified() reports a change to type. (The callback may be called only once for a series of conse-
cutive 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().
Nuevo en la versión 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.
Nuevo en la versión 3.12.

128 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
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 parents.
On the contrary, if the type being created does include Py_TPFLAGS_HAVE_GC in its flags then it must imple-
ment the GC protocol itself by at least implementing the tp_traverse handle.

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.
Nuevo en la versión 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.
Nuevo en la versión 3.11.
PyObject *PyType_GetFullyQualifiedName(PyTypeObject *type)
Part of the Stable ABI since version 3.13. Return the type’s fully qualified name. Equivalent to f"{type.
__module__}.{type.__qualname__}", or type.__qualname__ if type.__module__ is not a
string or is equal to "builtins".
Nuevo en la versión 3.13.
PyObject *PyType_GetModuleName(PyTypeObject *type)
Part of the Stable ABI since version 3.13. Return the type’s module name. Equivalent to getting the type.
__module__ attribute.
Nuevo en la versión 3.13.

8.1. Objetos fundamentales 129


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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.
Nuevo en la versión 3.9.
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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 3.12.

130 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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 compatibility,
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:
• __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.
Nuevo en la versión 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).
Nuevo en la versión 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).
Nuevo en la versión 3.3.

8.1. Objetos fundamentales 131


The Python/C API, Versión 3.13.0a5

Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the provided base classes.
Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
PyObject *PyType_FromSpec(PyType_Spec *spec)
Return value: New reference. Part of the Stable ABI. Equivalent to PyType_FromMetaclass(NULL, NULL,
spec, NULL).
Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the base classes provided
in Py_tp_base[s] slots. Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
type PyType_Spec
Part of the Stable ABI (including all members). Estructura que define el comportamiento de un tipo.
const char *name
Nombre del tipo, utilizado para establecer PyTypeObject.tp_name.
int basicsize
If positive, specifies the size of the instance in bytes. It is used to set PyTypeObject.tp_basicsize.
If zero, specifies that tp_basicsize should be inherited.
If negative, the absolute value specifies how much space instances of the class need in addition to the su-
perclass. Use PyObject_GetTypeData() to get a pointer to subclass-specific memory reserved this
way.
Distinto en la versión 3.12: Previously, this field could not be negative.
int itemsize
Size of one element of a variable-size type, in bytes. Used to set PyTypeObject.tp_itemsize. See
tp_itemsize documentation for caveats.
If zero, tp_itemsize is inherited. Extending arbitrary variable-sized classes is dangerous, since some
types use a fixed offset for variable-sized memory, which can then overlap fixed-sized memory used by a
subclass. To help prevent mistakes, inheriting itemsize is only possible in the following situations:
• The base is not variable-sized (its tp_itemsize).
• The requested PyType_Spec.basicsize is positive, suggesting that the memory layout of the base
class is known.
• The requested PyType_Spec.basicsize is zero, suggesting that the subclass does not access the
instance’s memory directly.
• With the Py_TPFLAGS_ITEMS_AT_END flag.
unsigned int flags
Banderas (flags) del tipo, que se usan para establecer PyTypeObject.tp_flags.
Si el indicador Py_TPFLAGS_HEAPTYPE no está establecido, PyType_FromSpecWithBases() lo
establece automáticamente.
PyType_Slot *slots
Arreglo de estructuras PyType_Slot. Terminado por el valor de ranura especial {0, NULL}.
Each slot ID should be specified at most once.

132 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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 pos-
sible)
• tp_dictoffset (use Py_TPFLAGS_MANAGED_DICT instead if possible)
• tp_vectorcall_offset (use "__vectorcalloffset__" in PyMember-
Def)
If it is not possible to switch to a MANAGED flag (for example, for vectorcall or to sup-
port Python older than 3.12), specify the offset in Py_tp_members. See PyMemberDef
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.
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 limi-
ted 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.1. Objetos fundamentales 133


The Python/C API, Versión 3.13.0a5

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 siem-
pre finaliza con éxito.
int PyLong_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyLongObject, pero no un subtipo de PyLongObject. Esta función
siempre finaliza con éxito.
PyObject *PyLong_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde v, o NULL
en caso de error.
The current implementation keeps an array of integer objects for all integers between -5 and 256. When you
create an int in that range you actually just get back a reference to the existing object.
PyObject *PyLong_FromUnsignedLong(unsigned long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C unsigned
long, or NULL on failure.
PyObject *PyLong_FromSsize_t(Py_ssize_t v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde un C
Py_ssize_t, o NULL en caso de error.
PyObject *PyLong_FromSize_t(size_t v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde un C
size_t, o NULL en caso de error.
PyObject *PyLong_FromLongLong(long long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C long long,
or NULL on failure.
PyObject *PyLong_FromUnsignedLongLong(unsigned long long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C unsigned
long long, or NULL on failure.
PyObject *PyLong_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto PyLongObject de la parte entera
de v, o NULL en caso de error.

134 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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().
PyObject *PyLong_FromNativeBytes(const void *buffer, size_t n_bytes, int endianness)
Create a Python integer from the value contained in the first n_bytes of buffer, interpreted as a two’s-complement
signed number.
endianness may be passed -1 for the native endian that CPython was compiled with, or else 0 for big endian and
1 for little.
Nuevo en la versión 3.13.
PyObject *PyLong_FromUnsignedNativeBytes(const void *buffer, size_t n_bytes, int endianness)
Create a Python integer from the value contained in the first n_bytes of buffer, interpreted as an unsigned number.
endianness may be passed -1 for the native endian that CPython was compiled with, or else 0 for big endian and
1 for little.
Nuevo en la versión 3.13.
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__().
int PyLong_AsInt(PyObject *obj)
Part of the Stable ABI since version 3.13. Similar to PyLong_AsLong(), but store the result in a C int instead
of a C long.
Nuevo en la versión 3.13.

8.2. Objetos numéricos 135


The Python/C API, Versión 3.13.0a5

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.
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.
Nuevo en la versión 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.

136 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
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.
Py_ssize_t PyLong_AsNativeBytes(PyObject *pylong, void *buffer, Py_ssize_t n_bytes, int endianness)
Copy the Python integer value to a native buffer of size n_bytes:

int32_t value;
Py_ssize_t bytes = PyLong_AsNativeBits(pylong, &value, sizeof(value), -1);
if (bytes < 0) {
// A Python exception was set with the reason.
return NULL;
}
else if (bytes <= (Py_ssize_t)sizeof(value)) {
// Success!
(continúe en la próxima página)

8.2. Objetos numéricos 137


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


}
else {
// Overflow occurred, but 'value' contains the truncated
// lowest bits of pylong.
}

The above example may look similar to PyLong_As* but instead fills in a specific caller defined type and never
raises an error about of the int pylong’s value regardless of n_bytes or the returned byte count.
To get at the entire potentially big Python value, this can be used to reserve enough space and copy it:

// Ask how much space we need.


Py_ssize_t expected = PyLong_AsNativeBits(pylong, NULL, 0, -1);
if (expected < 0) {
// A Python exception was set with the reason.
return NULL;
}
assert(expected != 0); // Impossible per the API definition.
uint8_t *bignum = malloc(expected);
if (!bignum) {
PyErr_SetString(PyExc_MemoryError, "bignum malloc failed.");
return NULL;
}
// Safely get the entire value.
Py_ssize_t bytes = PyLong_AsNativeBits(pylong, bignum, expected, -1);
if (bytes < 0) { // Exception set.
free(bignum);
return NULL;
}
else if (bytes > expected) { // Be safe, should not be possible.
PyErr_SetString(PyExc_RuntimeError,
"Unexpected bignum truncation after a size check.");
free(bignum);
return NULL;
}
// The expected success given the above pre-check.
// ... use bignum ...
free(bignum);

endianness may be passed -1 for the native endian that CPython was compiled with, or 0 for big endian and 1 for
little.
Returns -1 with an exception raised if pylong cannot be interpreted as an integer. Otherwise, return the size of the
buffer required to store the value. If this is equal to or less than n_bytes, the entire value was copied. 0 will never
be returned.
Unless an exception is raised, all n_bytes of the buffer will always be written. In the case of truncation, as many of
the lowest bits of the value as could fit are written. This allows the caller to ignore all non-negative results if the
intent is to match the typical behavior of a C-style downcast. No exception is set on truncation.
Values are always copied as two’s-complement and sufficient buffer will be requested to include a sign bit. For
example, this may cause an value that fits into 8 bytes when treated as unsigned to request 9 bytes, even though
all eight bytes were copied into the buffer. What has been omitted is the zero sign bit – redundant if the caller’s
intention is to treat the value as unsigned.
Passing zero to n_bytes will return the size of a buffer that would be large enough to hold the value. This may be
larger than technically necessary, but not unreasonably so.

138 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

Nota: Passing n_bytes=0 to this function is not an accurate way to determine the bit length of a value.

Nuevo en la versión 3.13.


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

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.

8.2. Objetos numéricos 139


The Python/C API, Versión 3.13.0a5

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

140 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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 pueden
empaquetar todos los valores; en plataformas que no son IEEE con menos precisión o con un rango dinámico más pequeño,
no se pueden desempaquetar todos los valores. Lo que sucede en tales casos es en parte accidental (desafortunadamente).
Nuevo en la versión 3.11.

Funciones de Empaquetado

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

Funciones de Desempaquetado

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

8.2. Objetos numéricos 141


The Python/C API, Versión 3.13.0a5

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

142 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
If op is not a Python complex number object but has a __complex__() method, this method will first be
called to convert op to a Python complex number object. If __complex__() is not defined then it falls back to
call PyFloat_AsDouble() and returns its result. Upon failure, this method returns -1.0, so one should call
PyErr_Occurred() to check for errors.
Distinto en la versión 3.13: Use __complex__() if available.
double PyComplex_ImagAsDouble(PyObject *op)
Part of the Stable ABI. Return the imaginary part of op as a C double.
If op is not a Python complex number object but has a __complex__() method, this method will first be called
to convert op to a Python complex number object. If __complex__() is not defined then it falls back to call
PyFloat_AsDouble() and returns 0.0 on success. Upon failure, this method returns -1.0, so one should
call PyErr_Occurred() to check for errors.
Distinto en la versión 3.13: Use __complex__() if available.
Py_complex PyComplex_AsCComplex(PyObject *op)
Retorna el valor Py_complex del número complejo op.
If op is not a Python complex number object but has a __complex__() method, this method will first be
called to convert op to a Python complex number object. If __complex__() is not defined then it falls back to
__float__(). If __float__() is not defined then it falls back to __index__(). Upon failure, this method
returns -1.0 as a real value.
Distinto en la versión 3.8: Use __index__() if available.

8.2. Objetos numéricos 143


The Python/C API, Versión 3.13.0a5

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:

144 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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 145, 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 implementa
el protocolo de búfer.
Py_ssize_t PyBytes_Size(PyObject *o)
Part of the Stable ABI. Retorna la longitud de los bytes en el objeto bytes o.
Py_ssize_t PyBytes_GET_SIZE(PyObject *o)
Forma macro de PyBytes_Size() pero sin verificación de errores.
char *PyBytes_AsString(PyObject *o)
Part of the Stable ABI. Retorna un puntero al contenido de o. El puntero se refiere al búfer interno de o, que
consiste en len(o) + 1 bytes. El último byte en el búfer siempre es nulo, independientemente de si hay otros
bytes nulos. Los datos no deben modificarse de ninguna manera, a menos que el objeto se haya creado usando
PyBytes_FromStringAndSize(NULL, size). No debe ser desasignado. Si o no es un objeto de bytes
en absoluto, PyBytes_AsString() retorna NULL y lanza un TypeError.
char *PyBytes_AS_STRING(PyObject *string)
Forma macro de PyBytes_AsString() pero sin verificación de errores.
int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
Part of the Stable ABI. Return the null-terminated contents of the object obj through the output variables buffer
and length. Returns 0 on success.
Si length es NULL, el objeto bytes no puede contener bytes nulos incrustados; en caso contrario, la función retorna
-1 y se lanza un ValueError.
El búfer se refiere a un búfer interno de obj, que incluye un byte nulo adicional al final (no está considerado
en length). Los datos no deben modificarse de ninguna manera, a menos que el objeto se haya creado usando
1 Para especificadores de enteros (d, u, ld, lu, zd, zu, i, x): el indicador de conversión 0 tiene efecto incluso cuando se proporciona una precisión.

8.3. Objetos de secuencia 145


The Python/C API, Versión 3.13.0a5

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 incrustados
en el objeto bytes.
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.

146 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
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 re-
presentaciones, para permitir el manejo del rango completo de caracteres Unicode mientras se mantiene la eficiencia de
memoria. Hay casos especiales para cadenas de caracteres donde todos los puntos de código están por debajo de 128,
256 o 65536; de lo contrario, los puntos de código deben estar por debajo de 1114112 (que es el rango completo de
Unicode).
UTF-8 representation is created on demand and cached in the Unicode object.

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

8.3. Objetos de secuencia 147


The Python/C API, Versión 3.13.0a5

Tipo unicode

Estos son los tipos básicos de objetos Unicode utilizados para la implementación de Unicode en Python:
type Py_UCS4
type Py_UCS2
type Py_UCS1
Part of the Stable ABI. Estos tipos son definiciones de tipo (typedefs) para los tipos “enteros sin signo” (unsigned
int) lo suficientemente anchos como para contener caracteres de 32 bits, 16 bits y 8 bits, respectivamente. Cuando
se trate con caracteres Unicode individuales, use Py_UCS4.
Nuevo en la versión 3.3.
type Py_UNICODE
This is a typedef of wchar_t, which is a 16-bit type or 32-bit type depending on the platform.
Distinto en la versión 3.3: En versiones anteriores, este era un tipo de 16 bits o de 32 bits, dependiendo de si
seleccionó una versión Unicode «estrecha» o «amplia» de Python en el momento de la compilación.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15.
type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject
Estos subtipos de PyObject representan un objeto Python Unicode. En casi todos los casos, no deben usar-
se directamente, ya que todas las funciones API que se ocupan de objetos Unicode toman y retornan punteros
PyObject.
Nuevo en la versión 3.3.
PyTypeObject PyUnicode_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo Python Unicode. Está expuesto al
código de Python como str.
The following APIs are C macros and static inlined functions for fast checks and access to internal read-only data of
Unicode objects:
int PyUnicode_Check(PyObject *obj)
Return true if the object obj is a Unicode object or an instance of a Unicode subtype. This function always succeeds.
int PyUnicode_CheckExact(PyObject *obj)
Return true if the object obj is a Unicode object, but not an instance of a subtype. This function always succeeds.
int PyUnicode_READY(PyObject *unicode)
Returns 0. This API is kept only for backward compatibility.
Nuevo en la versión 3.3.
Obsoleto desde la versión 3.10: This API does nothing since Python 3.12.
Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)
Return the length of the Unicode string, in code points. unicode has to be a Unicode object in the «canonical»
representation (not checked).
Nuevo en la versión 3.3.
Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *unicode)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *unicode)

148 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 3.3.
PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND
Retorna los valores de la macro PyUnicode_KIND().
Nuevo en la versión 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 Unicode
object uses to store its data. unicode has to be a Unicode object in the «canonical» representation (not checked).
Nuevo en la versión 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» representation
(not checked).
Nuevo en la versión 3.3.
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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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.

8.3. Objetos de secuencia 149


The Python/C API, Versión 3.13.0a5

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.
int Py_UNICODE_ISALPHA(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter alfabético.
int Py_UNICODE_ISALNUM(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter alfanumérico.
int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter imprimible. Los caracteres no imprimibles son aquellos definidos
en la base de datos de caracteres Unicode como «Otro» o «Separador», excepto el espacio ASCII (0x20) que se
considera imprimible. (Tenga en cuenta que los caracteres imprimibles en este contexto son aquellos a los que no se
debe escapar cuando repr() se invoca en una cadena de caracteres. No tiene relación con el manejo de cadenas
de caracteres escritas en sys.stdout o sys.stderr.)
Estas API se pueden usar para conversiones caracteres rápidas y directos:
Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)
Retorna el carácter ch convertido a minúsculas.
Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)
Retorna el carácter ch convertido a mayúsculas.
Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)
Retorna el carácter ch convertido a formato de título (titlecase).
int Py_UNICODE_TODECIMAL(Py_UCS4 ch)
Return the character ch converted to a decimal positive integer. Return -1 if this is not possible. This function does
not raise exceptions.

150 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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

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.
Nuevo en la versión 3.3.
PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
Return value: New reference. Crea un nuevo objeto Unicode con el tipo kind dado (los valores posibles son
PyUnicode_1BYTE_KIND etc., según lo retornado por PyUnicode_KIND()). El búfer debe apuntar a un
vector (array) de tamaño unidades de 1, 2 o 4 bytes por carácter, según el tipo.
Si es necesario, la entrada buffer se copia y se transforma en la representación canónica. Por ejemplo, si el buffer
es una cadena de caracteres UCS4 (PyUnicode_4BYTE_KIND) y consta solo de puntos de código en el rango
UCS1, se transformará en UCS1 (PyUnicode_1BYTE_KIND).
Nuevo en la versión 3.3.
PyObject *PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from the char buffer str. The bytes
will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. The return value might be a
shared object, i.e. modification of the data is not allowed.
This function raises SystemError when:
• size < 0,
• str is NULL and size > 0

8.3. Objetos de secuencia 151


The Python/C API, Versión 3.13.0a5

Distinto en la versión 3.12: str == NULL with size > 0 is not allowed anymore.
PyObject *PyUnicode_FromString(const char *str)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from a UTF-8 encoded null-terminated
char buffer str.
PyObject *PyUnicode_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI. Take a C printf()-style format string and a variable number
of arguments, calculate the size of the resulting Python Unicode string and return a string with the values formatted
into it. The variable arguments must be C types and must correspond exactly to the format characters in the format
ASCII-encoded string.
A conversion specifier contains two or more characters and has the following components, which must occur in this
order:
1. The '%' character, which marks the start of the specifier.
2. Conversion flags (optional), which affect the result of some conversion types.
3. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is given in the next ar-
gument, which must be of type int, and the object to convert comes after the minimum field width and
optional precision.
4. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the
actual precision is given in the next argument, which must be of type int, and the value to convert comes
after the precision.
5. Length modifier (optional).
6. Conversion type.
The conversion flag characters are:

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

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

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

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

152 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

Con- Tipo Comentario


version
Speci-
fier
% n/a The literal % character.
d, i Specified by the length The decimal representation of a signed C integer.
modifier
u Specified by the length The decimal representation of an unsigned C integer.
modifier
o Specified by the length The octal representation of an unsigned C integer.
modifier
x Specified by the length The hexadecimal representation of an unsigned C integer (lowercase).
modifier
X Specified by the length The hexadecimal representation of an unsigned C integer (uppercase).
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 lite-
ral 0x regardless of what the platform’s printf yields.
A PyObject* El resultado de llamar ascii().
U PyObject* Un objeto unicode.
V PyObject*, const Un objeto Unicode (que puede ser NULL) y un arreglo de caracteres de C
char* or const terminada en nulo como segundo parámetro (que se utilizará, si el primer
wchar_t* 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* 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.

8.3. Objetos de secuencia 153


The Python/C API, Versión 3.13.0a5

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 predetermi-
nados (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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 3.3.
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 ha-
berse 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).
Nuevo en la versión 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.
Nuevo en la versión 3.3.

154 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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 maneja-
dores de errores admitidos son "estricto" y "subrogateescape" (PEP 383). El decodificador usa el
controlador de errores "estricto" si errors es NULL. str debe terminar con un carácter nulo pero no puede
contener caracteres nulos incrustados.
Use PyUnicode_DecodeFSDefaultAndSize() to decode a string from the filesystem encoding and error
handler.
Esta función ignora el modo Python UTF-8.
Ver también:
La función Py_DecodeLocale().
Nuevo en la versión 3.3.
Distinto en la versión 3.7: La función ahora también usa la codificación de configuración regional actual para el
controlador de errores subrogateescape, excepto en Android. Anteriormente, Py_DecodeLocale() se
usaba para el subrogateescape, y la codificación local actual se usaba para estricto.
PyObject *PyUnicode_DecodeLocale(const char *str, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7. Similar to
PyUnicode_DecodeLocaleAndSize(), but compute the string length using strlen().
Nuevo en la versión 3.3.
PyObject *PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7. Codifica un objeto Unicode UTF-8 en
Android y VxWorks, o en la codificación local actual en otras plataformas. Los manejadores de errores admiti-
dos son "estricto" y "subrogateescape" (PEP 383). El codificador utiliza el controlador de errores
"estricto" si errors es NULL. Retorna un objeto bytes. unicode no puede contener caracteres nulos incrus-
tados.
Use PyUnicode_EncodeFSDefault() to encode a string to the filesystem encoding and error handler.

8.3. Objetos de secuencia 155


The Python/C API, Versión 3.13.0a5

Esta función ignora el modo Python UTF-8.


Ver también:
La función Py_EncodeLocale().
Nuevo en la versión 3.3.
Distinto en la versión 3.7: La función ahora también usa la codificación de configuración regional actual para el
controlador de errores subrogateescape, excepto en Android. Anteriormente, Py_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.
Nuevo en la versión 3.1.
Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).
Para decodificar nombres de archivo a str durante el análisis de argumentos, se debe usar el convertidor "O&", pasando
PyUnicode_FSDecoder() como la función de conversión:
int PyUnicode_FSDecoder(PyObject *obj, void *result)
Part of the Stable ABI. ParseTuple converter: decode bytes objects – obtained either directly or indirectly through
the os.PathLike interface – to str using PyUnicode_DecodeFSDefaultAndSize(); str objects are
output as-is. result must be a PyUnicodeObject* which must be released when it is no longer used.
Nuevo en la versión 3.2.
Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).
PyObject *PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Decodifica una cadena desde el codificador de sistema de
archivos y gestor de errores.
If you need to decode a string from the current locale encoding, use
PyUnicode_DecodeLocaleAndSize().
Ver también:
La función Py_DecodeLocale().
Distinto en la versión 3.6: The filesystem error handler is now used.
PyObject *PyUnicode_DecodeFSDefault(const char *str)
Return value: New reference. Part of the Stable ABI. Decodifica una cadena terminada en nulo desde el codificador
de sistema de archivos y gestor de errores.
If the string length is known, use PyUnicode_DecodeFSDefaultAndSize().
Distinto en la versión 3.6: The filesystem error handler is now used.

156 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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().
Nuevo en la versión 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.
Nuevo en la versión 3.2.
Distinto en la versión 3.7: Raises a ValueError if size is NULL and the wchar_t* string contains null charac-
ters.

8.3. Objetos de secuencia 157


The Python/C API, Versión 3.13.0a5

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.

158 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
On error, set an exception, set size to -1 (if it’s not NULL) and return NULL.
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.
Nuevo en la versión 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.
Nuevo en la versión 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 cuatro)
como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se almacenará
en consumed.

8.3. Objetos de secuencia 159


The Python/C API, Versión 3.13.0a5

PyObject *PyUnicode_AsUTF32String(PyObject *unicode)


Return value: New reference. Part of the Stable ABI. Retorna una cadena de bytes de Python usando la codificació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.

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 sustituto
dividido) como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se
almacenará en consumed.
PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Retorna una cadena de bytes de Python usando la codificación
UTF-16 en orden de bytes nativo. La cadena siempre comienza con una marca BOM. El manejo de errores es
«estricto». Retorna NULL si el códec provocó una excepción.

Códecs UTF-7

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)

160 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF7(). Si consumed no es NULL, las secciones UTF-7 base-64 incompletas no se tra-
tarán como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se
almacenará en consumed.

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 resul-
tado como un objeto de bytes Python. El manejo de errores es «estricto». Retorna NULL si el códec provocó una
excepción.

8.3. Objetos de secuencia 161


The Python/C API, Versión 3.13.0a5

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.

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

162 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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 consu-
med es NULL, se comporta como PyUnicode_DecodeMBCS(). Si consumed no es NULL,
PyUnicode_DecodeMBCSStateful() no decodificará el byte inicial y el número de bytes que se
han decodificado se almacenará en consumed.
PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Codifica un objeto Unicode
usando MBCS y retorna el resultado como un objeto de bytes de Python. El manejo de errores es «estricto».
Retorna NULL si el códec provocó una excepción.
PyObject *PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Encode the Unicode object using
the specified code page and return a Python bytes object. Return NULL if an exception was raised by the codec.
Use CP_ACP code page to get the MBCS encoder.
Nuevo en la versión 3.3.

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.

8.3. Objetos de secuencia 163


The Python/C API, Versión 3.13.0a5

Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
Part of the Stable ABI. Return 1 if substr matches unicode[start:end] at the given tail end (direction ==
-1 means to do a prefix match, direction == 1 a suffix match), 0 otherwise. Return -1 if an error occurred.
Py_ssize_t PyUnicode_Find(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI. Return the first position of substr in unicode[start:end] using the given direction
(direction == 1 means to do a forward search, direction == -1 a backward search). The return value is the index
of the first match; a value of -1 indicates that no match was found, and -2 indicates that an error occurred and an
exception has been set.
Py_ssize_t PyUnicode_FindChar(PyObject *unicode, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction)
Part of the Stable ABI since version 3.7. Return the first position of the character ch in unicode[start:end]
using the given direction (direction == 1 means to do a forward search, direction == -1 a backward search). The
return value is the index of the first match; a value of -1 indicates that no match was found, and -2 indicates that
an error occurred and an exception has been set.
Nuevo en la versión 3.3.
Distinto en la versión 3.7: start and end are now adjusted to behave like unicode[start:end].
Py_ssize_t PyUnicode_Count(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
Part of the Stable ABI. Return the number of non-overlapping occurrences of substr in unicode[start:end].
Return -1 if an error occurred.
PyObject *PyUnicode_Replace(PyObject *unicode, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)
Return value: New reference. Part of the Stable ABI. Replace at most maxcount occurrences of substr in unicode
with replstr and return the resulting Unicode object. maxcount == -1 means replace all occurrences.
int PyUnicode_Compare(PyObject *left, PyObject *right)
Part of the Stable ABI. Compara dos cadenas de caracteres y retorna -1, 0, 1 para menor que, igual y mayor que,
respectivamente.
Esta función retorna -1 en caso de falla, por lo que se debe llamar a PyErr_Occurred() para verificar si hay
errores.
int PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *string, Py_ssize_t size)
Part of the Stable ABI since version 3.13. Compare a Unicode object with a char buffer which is interpreted as
being UTF-8 or ASCII encoded and return true (1) if they are equal, or false (0) otherwise. If the Unicode object
contains surrogate characters or the C string is not valid UTF-8, false (0) is returned.
Esta función no lanza excepciones.
Nuevo en la versión 3.13.
int PyUnicode_EqualToUTF8(PyObject *unicode, const char *string)
Part of the Stable ABI since version 3.13. Similar to PyUnicode_EqualToUTF8AndSize(), but compute
string length using strlen(). If the Unicode object contains null characters, false (0) is returned.
Nuevo en la versión 3.13.
int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
Part of the Stable ABI. Compare a Unicode object, unicode, with string and return -1, 0, 1 for less than, equal,
and greater than, respectively. It is best to pass only ASCII-encoded strings, but the function interprets the input
string as ISO-8859-1 if it contains non-ASCII characters.
Esta función no lanza excepciones.

164 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.

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.

8.3. Objetos de secuencia 165


The Python/C API, Versión 3.13.0a5

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ñalada
por p. Si pos es negativo o está fuera de los límites, retorna NULL y establece una excepción IndexError.
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.
Bounds checking is performed as an assertion if Python is built in debug mode or with assertions.

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

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.

166 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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

8.3. Objetos de secuencia 167


The Python/C API, Versión 3.13.0a5

PyObject *PyStructSequence_GetItem(PyObject *p, Py_ssize_t pos)


Return value: Borrowed reference. Part of the Stable ABI. Return the object at position pos in the struct sequence
pointed to by p.
Bounds checking is performed as an assertion if Python is built in debug mode or with assertions.
PyObject *PyStructSequence_GET_ITEM(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Alias to PyStructSequence_GetItem().
Distinto en la versión 3.13: Now implemented as an alias to PyStructSequence_GetItem().
void PyStructSequence_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Part of the Stable ABI. 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.
Bounds checking is performed as an assertion if Python is built in debug mode or with assertions.

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

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


Alias to PyStructSequence_SetItem().
Distinto en la versión 3.13: Now implemented as an alias to PyStructSequence_SetItem().

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.

168 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

Py_ssize_t PyList_GET_SIZE(PyObject *list)


Similar to PyList_Size(), but without error checking.
PyObject *PyList_GetItemRef(PyObject *list, Py_ssize_t index)
Return value: New reference. Part of the Stable ABI since version 3.13. Return the object at position index in the list
pointed to by list. The position must be non-negative; indexing from the end of the list is not supported. If index is
out of bounds (<0 or >=len(list)), return NULL and set an IndexError exception.
Nuevo en la versión 3.13.
PyObject *PyList_GetItem(PyObject *list, Py_ssize_t index)
Return value: Borrowed reference. Part of the Stable ABI. Like PyList_GetItemRef(), but returns a borrowed
reference instead of a strong reference.
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 com-
pletar nuevas listas donde no hay contenido anterior.
Bounds checking is performed as an assertion if Python is built in debug mode or with assertions.

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

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

8.3. Objetos de secuencia 169


The Python/C API, Versión 3.13.0a5

int PyList_Extend(PyObject *list, PyObject *iterable)


Extend list with the contents of iterable. This is the same as PyList_SetSlice(list,
PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, iterable) and analogous to list.extend(iterable)
or list += iterable.
Raise an exception and return -1 if list is not a list object. Return 0 on success.
Nuevo en la versión 3.13.
int PyList_Clear(PyObject *list)
Remove all items from list. This is the same as PyList_SetSlice(list, 0, PY_SSIZE_T_MAX,
NULL) and analogous to list.clear() or del list[:].
Raise an exception and return -1 if list is not a list object. Return 0 on success.
Nuevo en la versión 3.13.
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).

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.

170 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
int PyDict_ContainsString(PyObject *p, const char *key)
This is the same as PyDict_Contains(), but key is specified as a const char* UTF-8 encoded bytes
string, rather than a PyObject*.
Nuevo en la versión 3.13.
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*.
int PyDict_GetItemRef(PyObject *p, PyObject *key, PyObject **result)
Part of the Stable ABI since version 3.13. Return a new strong reference to the object from dictionary p which has
a key key:
• If the key is present, set *result to a new strong reference to the value and return 1.
• If the key is missing, set *result to NULL and return 0.
• On error, raise an exception and return -1.
Nuevo en la versión 3.13.
See also the PyObject_GetItem() function.
PyObject *PyDict_GetItem(PyObject *p, PyObject *key)
Return value: Borrowed reference. Part of the Stable ABI. Return a borrowed reference to the object from dictionary
p which has a key key. Return NULL if the key key is missing without setting an exception.

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.

8.4. Objetos contenedor 171


The Python/C API, Versión 3.13.0a5

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 tem-
porary str object are silently ignored. Prefer using the PyDict_GetItemWithError() function with your
own PyUnicode_FromString() key instead.

int PyDict_GetItemStringRef(PyObject *p, const char *key, PyObject **result)


Part of the Stable ABI since version 3.13. Similar than PyDict_GetItemRef(), but key is specified as a const
char* UTF-8 encoded bytes string, rather than a PyObject*.
Nuevo en la versión 3.13.
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á presente,
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.
Nuevo en la versión 3.4.
int PyDict_SetDefaultRef(PyObject *p, PyObject *key, PyObject *default_value, PyObject **result)
Inserts default_value into the dictionary p with a key of key if the key is not already present in the dictionary. If
result is not NULL, then *result is set to a strong reference to either default_value, if the key was not present, or
the existing value, if key was already present in the dictionary. Returns 1 if the key was present and default_value
was not inserted, or 0 if the key was not present and default_value was inserted. On failure, returns -1, sets an
exception, and sets *result to NULL.
For clarity: if you have a strong reference to default_value before calling this function, then after it returns, you
hold a strong reference to both default_value and *result (if it’s not NULL). These may refer to the same object: in
that case you hold two separate references to it. .. versionadded:: 3.13
int PyDict_Pop(PyObject *p, PyObject *key, PyObject **result)
Remove key from dictionary p and optionally return the removed value. Do not raise KeyError if the key missing.
• If the key is present, set *result to a new reference to the removed value if result is not NULL, and return 1.
• If the key is missing, set *result to NULL if result is not NULL, and return 0.
• On error, raise an exception and return -1.
This is similar to dict.pop(), but without the default value and not raising KeyError if the key missing.
Nuevo en la versión 3.13.
int PyDict_PopString(PyObject *p, const char *key, PyObject **result)
Similar to PyDict_Pop(), but key is specified as a const char* UTF-8 encoded bytes string, rather than a
PyObject*.
Nuevo en la versión 3.13.

172 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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:
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

8.4. Objetos contenedor 173


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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.)
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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

174 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

for key. If event is PyDict_EVENT_DELETED, key is being deleted from the dictionary and new_value will be
NULL.
PyDict_EVENT_CLONED occurs when dict was previously empty and another dict is merged into it. To maintain
efficiency of this operation, per-key PyDict_EVENT_ADDED events are not issued in this case; instead a single
PyDict_EVENT_CLONED is issued, and key will be the source dictionary.
The callback may inspect but must not modify dict; doing so could have unpredictable effects, including infinite
recursion. Do not trigger Python code execution in the callback, as it could modify the dict as a side effect.
If event is PyDict_EVENT_DEALLOCATED, taking a new reference in the callback to the about-to-be-destroyed
dictionary will resurrect it and prevent it from being freed at this time. When the resurrected object is destroyed
later, any watcher callbacks active at that time will be called again.
Callbacks occur before the notified modification to dict takes place, so the prior state of dict can be inspected.
If the callback sets an exception, it must return -1; this exception will be printed as an unraisable exception using
PyErr_WriteUnraisable(). Otherwise it should return 0.
There may already be a pending exception set on entry to the callback. In this case, the callback should return 0
with the same exception still set. This means the callback may not call any other API that can set an exception
unless it saves and clears the exception state first, and restores it before returning.
Nuevo en la versión 3.12.

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 (incluyendo PyObject_CallMethod(),
PyObject_RichCompareBool(), PyObject_Hash(), PyObject_Repr(), PyObject_IsTrue(),
PyObject_Print(), y PyObject_GetIter()) o el protocolo numérico abstracto (inclu-
yendo PyNumber_And(), PyNumber_Subtract(), PyNumber_Or(), PyNumber_Xor(),
PyNumber_InPlaceAnd(), PyNumber_InPlaceSubtract(), PyNumber_InPlaceOr(), y
PyNumber_InPlaceXor()).
type PySetObject
Este subtipo de PyObject se utiliza para mantener los datos internos de los objetos set y frozenset. Es
como un PyDictObject en el sentido de que tiene un tamaño fijo para los conjuntos pequeños (muy parecido al
almacenamiento de tuplas) y apuntará a un bloque de memoria separado y de tamaño variable para los conjuntos de
tamaño medio y grande (muy parecido al almacenamiento de listas). Ninguno de los campos de esta estructura debe
considerarse público y todos están sujetos a cambios. Todo el acceso debe hacerse a través de la API documentada
en lugar de manipular los valores de la estructura.
PyTypeObject PySet_Type
Part of the Stable ABI. Esta es una instancia de PyTypeObject que representa el tipo Python set.
PyTypeObject PyFrozenSet_Type
Part of the Stable ABI. Esta es una instancia de PyTypeObject que representa el tipo Python frozenset.
Los siguientes macros de comprobación de tipos funcionan en punteros a cualquier objeto de Python. Del mismo modo,
las funciones del constructor funcionan con cualquier objeto Python iterable.
int PySet_Check(PyObject *p)
Retorna verdadero si p es un objeto set o una instancia de un subtipo. Esta función siempre finaliza con éxito.
int PyFrozenSet_Check(PyObject *p)
Retorna verdadero si p es un objeto frozenset o una instancia de un subtipo. Esta función siempre finaliza con
éxito.

8.4. Objetos contenedor 175


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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 retor-
nados 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 subtipos.
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.
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 frozen-
sets. 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

176 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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 programadores
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.
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__ attri-
bute is set to the same value as the code object’s co_qualname field.
Nuevo en la versión 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.

8.5. Objetos de función 177


The Python/C API, Versión 3.13.0a5

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!
Nuevo en la versión 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.
Nuevo en la versión 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.)
Nuevo en la versión 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
Nuevo en la versión 3.12.
typedef int (*PyFunction_WatchCallback)(PyFunction_WatchEvent event, PyFunctionObject *func, PyObject
*new_value)
Type of a function watcher callback function.

178 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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 com-
probación de errores.

8.5. Objetos de función 179


The Python/C API, Versión 3.13.0a5

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.

180 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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 deprecated,
but will remain available until the signature changes again.

8.5. Objetos de función 181


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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 de-
precated, 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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 3.11.

182 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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.
Nuevo en la versión 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 excep-
tion.
Nuevo en la versión 3.12.
int PyCode_ClearWatcher(int watcher_id)
Clear watcher identified by watcher_id previously returned from PyCode_AddWatcher() for the current inter-
preter. Return 0 on success, or -1 and set an exception on error (e.g. if the given watcher_id was never registered.)
Nuevo en la versión 3.12.
type PyCodeEvent
Enumeration of possible code object watcher events: - PY_CODE_EVENT_CREATE -
PY_CODE_EVENT_DESTROY
Nuevo en la versión 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. Otherwise,
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.
Nuevo en la versión 3.12.

8.5. Objetos de función 183


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 3.6: as _PyEval_RequestCodeExtraIndex
Distinto en la versión 3.12: Renamed to PyUnstable_Eval_RequestCodeExtraIndex. The old private
name is deprecated, but will be available until the API changes.
int PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)

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.
Nuevo en la versión 3.6: as _PyCode_GetExtra
Distinto en la versión 3.12: Renamed to PyUnstable_Code_GetExtra. The old private name is deprecated,
but will be available until the API changes.
int PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)

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.
Nuevo en la versión 3.6: as _PyCode_SetExtra
Distinto en la versión 3.12: Renamed to PyUnstable_Code_SetExtra. The old private name is deprecated,
but will be available until the API changes.

184 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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 controlador
proporcionado.
The handler is a function of type:
typedef PyObject *(*Py_OpenCodeHookFunction)(PyObject*, void*)
Equivalent of PyObject *(*)(PyObject *path, void *userData), where path is guaran-
teed 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 ejecu-
ción a menos que se sepa que están congelados o disponibles en sys.modules.

8.6. Otros objetos 185


The Python/C API, Versión 3.13.0a5

Una vez que se ha establecido un hook, no se puede quitar ni reemplazar, y luego llamadas a
PyFile_SetOpenCodeHook() fallarán. En caso de error, la función retorna -1 y establece una excepción
si el intérprete se ha inicializado.
Es seguro llamar a esta función antes de Py_Initialize().
Genera un evento de auditoría setopencodehook sin argumentos.
Nuevo en la versión 3.8.
int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
Part of the Stable ABI. Write object obj to file object p. The only supported flag for flags is Py_PRINT_RAW;
if given, the str() of the object is written instead of the repr(). Return 0 on success or -1 on failure; the
appropriate exception will be set.
int PyFile_WriteString(const char *s, PyObject *p)
Part of the Stable ABI. Escribe la cadena s en el objeto archivo p. Retorna 0 en caso de éxito o -1 en caso de error;
se establecerá la excepción apropiada.

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ódulo con el
atributo __name__ establecido en name. Los atributos del módulo __name__, __doc__, __package__, y
__loader__ se completan (todos menos __name__ están configurados en None); quien llama es responsable
de proporcionar un atributo __file__.
Nuevo en la versión 3.3.
Distinto en la versión 3.4: __package__ y __loader__ están configurados en None.
PyObject *PyModule_New(const char *name)
Return value: New reference. Part of the Stable ABI. Similar a PyModule_NewObject(), pero el nombre es
una cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
PyObject *PyModule_GetDict(PyObject *module)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto del diccionario que implementa el
espacio de nombres de module; este objeto es el mismo que el atributo __dict__ del objeto módulo. Si module
no es un objeto módulo (o un subtipo de un objeto de módulo), se lanza SystemError y se retorna NULL.
It is recommended extensions use other PyModule_* and PyObject_* functions rather than directly manipu-
late a module’s __dict__.

186 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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'.
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.
Nuevo en la versión 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 unencodable
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 infor-
mación necesaria para crear un objeto módulo. Por lo general, solo hay una variable estáticamente inicializada de
este tipo para cada módulo.
PyModuleDef_Base m_base
Always initialize this member to PyModuleDef_HEAD_INIT.
const char *m_name
Nombre para el nuevo módulo.
const char *m_doc
Docstring para el módulo; por lo general, se usa una variable docstring creada con PyDoc_STRVAR.

8.6. Otros objetos 187


The Python/C API, Versión 3.13.0a5

Py_ssize_t m_size
El estado del módulo se puede mantener en un área de memoria por módulo que se puede recuperar con
PyModule_GetState(), en lugar de en globales estáticos. Esto hace que los módulos sean seguros para
su uso en múltiples sub-interpretadores.
This memory area is allocated based on m_size on module creation, and freed when the module object is
deallocated, after the m_free function has been called, if present.
Establecer m_size en -1 significa que el módulo no admite sub-interpretadores, porque tiene un estado
global.
Establecerlo en un valor no negativo significa que el módulo se puede reinicializar y especifica la cantidad
adicional de memoria que requiere para su estado. Se requiere m_size no negativo para la inicialización de
múltiples fases.
Ver PEP 3121 para más detalles.
PyMethodDef *m_methods
Un puntero a una tabla de funciones de nivel de módulo, descrito por valores PyMethodDef. Puede ser
NULL si no hay funciones presentes.
PyModuleDef_Slot *m_slots
Un conjunto de definiciones de ranura para la inicialización de múltiples fases, terminadas por una entrada
{0, NULL}. Cuando se utiliza la inicialización monofásica, m_slots debe ser NULL.
Distinto en la versión 3.5: Antes de la versión 3.5, este miembro siempre estaba configurado en NULL y se
definía como:
inquiry m_reload

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

188 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.

Inicialización monofásica

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

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

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

Inicialización multifase

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

8.6. Otros objetos 189


The Python/C API, Versión 3.13.0a5

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

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

Si se especifican varias ranuras Py_mod_exec, se procesan en el orden en que aparecen en el arreglo m_slots.
Py_mod_multiple_interpreters
Specifies one of the following values:
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
The module does not support being imported in subinterpreters.
Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
The module supports being imported in subinterpreters, but only when they share the main interpreter’s GIL.
(See isolating-extensions-howto.)
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
The module supports being imported in subinterpreters, even when they have their own GIL. (See isolating-
extensions-howto.)
This slot determines whether or not importing this module in a subinterpreter will fail.
Multiple Py_mod_multiple_interpreters slots may not be specified in one module definition.

190 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

If Py_mod_multiple_interpreters is not specified, the import machinery defaults to


Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED.
Nuevo en la versión 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 ModuleSpec spec. This
behaves like PyModule_FromDefAndSpec2() with module_api_version set to PYTHON_API_VERSION.
Nuevo en la versión 3.5.
PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)
Return value: New reference. Part of the Stable ABI since version 3.7. Create a new module object, given the
definition in def and the ModuleSpec spec, assuming the API version module_api_version. If that version does
not match the version of the running interpreter, a RuntimeWarning is emitted.

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

Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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 modu-
le. 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.
Nuevo en la versión 3.5.

8.6. Otros objetos 191


The Python/C API, Versión 3.13.0a5

Funciones de soporte

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

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

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

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

Note que Py_XDECREF() debería ser usado en vez de Py_DECREF() en este caso, ya que obj puede ser NULL.
Nuevo en la versión 3.10.
int PyModule_Add(PyObject *module, const char *name, PyObject *value)
Part of the Stable ABI since version 3.13. Similar to PyModule_AddObjectRef(), but «steals» a reference
to value. It can be called with a result of function that returns a new reference without bothering to check its result
or even saving it to a variable.
Ejemplo de uso

if (PyModule_Add(module, "spam", PyBytes_FromString(value)) < 0) {


goto error;
}

Nuevo en la versión 3.13.


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

192 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

The new PyModule_Add() or PyModule_AddObjectRef() functions are recommended, since it is easy


to introduce reference leaks by misusing the PyModule_AddObject() function.

Nota: Unlike other functions that steal references, PyModule_AddObject() only releases the reference to
value on success.
This means that its return value must be checked, and calling code must Py_XDECREF() value manually on error.

Ejemplo de uso

PyObject *obj = PyBytes_FromString(value);


if (PyModule_AddObject(module, "spam", obj) < 0) {
// If 'obj' is not NULL and PyModule_AddObject() failed,
// 'obj' strong reference must be deleted with Py_XDECREF().
// If 'obj' is NULL, Py_XDECREF() does nothing.
Py_XDECREF(obj);
goto error;
}
// PyModule_AddObject() stole a reference to obj:
// Py_XDECREF(obj) is not needed here.

Obsoleto desde la versión 3.13: PyModule_AddObject() is soft deprecated.


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 inter-
namente 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.
Nuevo en la versión 3.9.

8.6. Otros objetos 193


The Python/C API, Versión 3.13.0a5

Búsqueda de módulos

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

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 secuencia
general, seq. La iteración termina cuando la secuencia lanza IndexError para la operación de suscripción.

194 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.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 dados. Los
parámetros start, stop y step se utilizan como los valores de los atributos del objeto rebanada de los mismos nombres.
Cualquiera de los valores puede ser NULL, en cuyo caso se usará None para el atributo correspondiente. Retorna
NULL si no se puedo asignar el nuevo objeto.

8.6. Otros objetos 195


The Python/C API, Versión 3.13.0a5

int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
Part of the Stable ABI. Recupera los índices start, stop y step del objeto rebanada slice, suponiendo una secuencia
de longitud length. Trata los índices mayores que length como errores.
Returns 0 on success and -1 on error with no exception set (unless one of the indices was not None and failed to
be converted to an integer, in which case -1 is returned with an exception set).
Probablemente no quiera usar esta función.
Distinto en la versión 3.2: El tipo de parámetro para el parámetro slice era PySliceObject* antes.
int PySlice_GetIndicesEx(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t
*step, Py_ssize_t *slicelength)
Part of the Stable ABI. Reemplazo utilizable para PySlice_GetIndices(). Recupera los índices de start,
stop, y step del objeto rebanada slice asumiendo una secuencia de longitud length, y almacena la longitud de la
rebanada en slicelength. Los índices fuera de los límites se recortan de manera coherente con el manejo de sectores
normales.
Retorna 0 en caso de éxito y -1 en caso de error con excepción establecida.

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

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.
int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
Part of the Stable ABI since version 3.7. Extrae los miembros de datos start, stop, y step de un objeto rebanada co-
mo enteros en C. Reduce silenciosamente los valores mayores que PY_SSIZE_T_MAX a PY_SSIZE_T_MAX,
aumenta silenciosamente los valores start y stop inferiores a PY_SSIZE_T_MIN a PY_SSIZE_T_MIN, y silen-
ciosamente aumenta los valores de step a menos de -PY_SSE a -PY_SSIZE_T_MAX.
Retorna -1 en caso de error, 0 en caso de éxito.
Nuevo en la versión 3.6.1.
Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)
Part of the Stable ABI since version 3.7. Ajusta los índices de corte de inicio/fin asumiendo una secuencia de la
longitud especificada. Los índices fuera de los límites se recortan de manera coherente con el manejo de sectores
normales.

196 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

Retorna la longitud de la rebanada. Siempre exitoso. No llama al código de Python.


Nuevo en la versión 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.
Nuevo en la versión 3.3.
PyObject *PyMemoryView_FromBuffer(const Py_buffer *view)
Return value: New reference. Part of the Stable ABI since version 3.11. Crea un objeto de vista de
memoria que ajuste la estructura de búfer dada view. Para memorias intermedias de bytes simples,
PyMemoryView_FromMemory() es la función preferida.
PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
Return value: New reference. Part of the Stable ABI. Crea un objeto de vista de memoria memoryview para un
fragmento de memoria contiguo (contiguous, en order “C” o “F” de Fortran) desde un objeto que define la interfaz
del búfer. Si la memoria es contigua, el objeto de vista de memoria apunta a la memoria original. De lo contrario,
se realiza una copia y la vista de memoria apunta a un nuevo objeto de bytes.
buffertype can be one of PyBUF_READ or PyBUF_WRITE.
int PyMemoryView_Check(PyObject *obj)
Retorna verdadero si el objeto obj es un objeto de vista de memoria. Actualmente no está permitido crear subclases
de memoryview. Esta función siempre finaliza con éxito.
Py_buffer *PyMemoryView_GET_BUFFER(PyObject *mview)
Retorna un puntero a la copia privada de la vista de memoria del búfer del exportador. mview debe ser una instancia
de memoryview; este macro no verifica su tipo, debe hacerlo usted mismo o correrá el riesgo de fallas.

8.6. Otros objetos 197


The Python/C API, Versión 3.13.0a5

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 implementan
directamente referencias débiles. El primero es un objeto con referencia simple, y el segundo actúa como un proxy del
objeto original tanto como pueda.
int PyWeakref_Check(PyObject *ob)
Return non-zero if ob is either a reference or proxy object. This function always succeeds.
int PyWeakref_CheckRef(PyObject *ob)
Return non-zero if ob is a reference object. This function always succeeds.
int PyWeakref_CheckProxy(PyObject *ob)
Return non-zero if ob is a proxy object. This function always succeeds.
PyObject *PyWeakref_NewRef(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference object for the object ob. This will
always return a new reference, but is not guaranteed to create a new object; an existing reference object may be
returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage
collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be
None or NULL. If ob is not a weakly referencable object, or if callback is not callable, None, or NULL, this will
return NULL and raise TypeError.
PyObject *PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference proxy object for the object ob. This
will always return a new reference, but is not guaranteed to create a new object; an existing proxy object may be
returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage
collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be
None or NULL. If ob is not a weakly referencable object, or if callback is not callable, None, or NULL, this will
return NULL and raise TypeError.
int PyWeakref_GetRef(PyObject *ref, PyObject **pobj)
Part of the Stable ABI since version 3.13. Get a strong reference to the referenced object from a weak reference,
ref, into *pobj.
• On success, set *pobj to a new strong reference to the referenced object and return 1.
• If the reference is dead, set *pobj to NULL and return 0.
• On error, raise an exception and return -1.
Nuevo en la versión 3.13.
PyObject *PyWeakref_GetObject(PyObject *ref)
Return value: Borrowed reference. Part of the Stable ABI. Return a borrowed reference to the referenced object
from a weak reference, ref. If the referent is no longer live, returns Py_None.

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

198 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Use PyWeakref_GetRef() instead.
PyObject *PyWeakref_GET_OBJECT(PyObject *ref)
Return value: Borrowed reference. Similar to PyWeakref_GetObject(), but does no error checking.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Use PyWeakref_GetRef() instead.
void PyObject_ClearWeakRefs(PyObject *object)
Part of the Stable ABI. This function is called by the tp_dealloc handler to clear weak references.
This iterates through the weak references for object and calls callbacks for those references which have one. It
returns when all callbacks have been attempted.

8.6.8 Cápsulas

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

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

8.6. Otros objetos 199


The Python/C API, Versión 3.13.0a5

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.
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 excep-
ció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.

200 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.

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.
Nuevo en la versión 3.9.
PyObject *PyFrame_GetBuiltins(PyFrameObject *frame)
Get the frame’s f_builtins attribute.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Nuevo en la versión 3.11.
PyCodeObject *PyFrame_GetCode(PyFrameObject *frame)
Part of the Stable ABI since version 3.10. Obtenga el código frame.
Retorna un strong reference.
El resultado (frame code) no puede ser NULL.
Nuevo en la versión 3.9.
PyObject *PyFrame_GetGenerator(PyFrameObject *frame)
Obtiene el generador, rutina o generador asíncrono al que pertenece este frame, o NULL si este frame no es pro-
piedad de un generador. No lanza una excepción, incluso si el valor de retorno es NULL.
Retorna un strong reference, o NULL.
Nuevo en la versión 3.11.

8.6. Otros objetos 201


The Python/C API, Versión 3.13.0a5

PyObject *PyFrame_GetGlobals(PyFrameObject *frame)


Get the frame’s f_globals attribute.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Nuevo en la versión 3.11.
int PyFrame_GetLasti(PyFrameObject *frame)
Get the frame’s f_lasti attribute.
Retorna -1 si frame.f_lasti es None.
Nuevo en la versión 3.11.
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.
Nuevo en la versión 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.
Nuevo en la versión 3.12.
PyObject *PyFrame_GetLocals(PyFrameObject *frame)
Get the frame’s f_locals attribute (dict).
Retorna un strong reference.
Nuevo en la versión 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.
Nuevo en la versión 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.

Nuevo en la versión 3.12.

202 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.


Nuevo en la versión 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.


Nuevo en la versión 3.12.

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 referencia
a frame es robada por esta función. El argumento no debe ser NULL.
PyObject *PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname)
Return value: New reference. Crea y retorna un nuevo objeto generador basado en el objeto frame, con __name__
y __qualname__ establecido en name y qualname. Una referencia a frame es robada por esta función. El argu-
mento frame no debe ser NULL.

8.6.11 Objetos corrutina

Nuevo en la versión 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.

8.6. Otros objetos 203


The Python/C API, Versión 3.13.0a5

PyTypeObject PyCoro_Type
El tipo de objeto correspondiente a los objetos corrutina.
int PyCoro_CheckExact(PyObject *ob)
Retorna verdadero si el tipo de ob es PyCoro_Type; ob no debe ser NULL. Esta función siempre finaliza con
éxito.
PyObject *PyCoro_New(PyFrameObject *frame, PyObject *name, PyObject *qualname)
Return value: New reference. Crea y retorna un nuevo objeto corrutina basado en el objeto frame, con __name__
y __qualname__ establecido en name y qualname. Una referencia a frame es robada por esta función. El argu-
mento frame no debe ser NULL.

8.6.12 Objetos de variables de contexto

Nuevo en la versión 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:

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

204 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
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. Otros objetos 205


The Python/C API, Versión 3.13.0a5

8.6.13 Objetos DateTime

Various date and time objects are supplied by the datetime module. Before using any of these functions, the hea-
der file datetime.h must be included in your source (note that this is not included by Python.h), and the macro
PyDateTime_IMPORT must be invoked, usually as part of the module initialisation function. The macro puts a pointer
to a C structure into a static variable, PyDateTimeAPI, that is used by the following macros.
type PyDateTime_Date
This subtype of PyObject represents a Python date object.
type PyDateTime_DateTime
This subtype of PyObject represents a Python datetime object.
type PyDateTime_Time
This subtype of PyObject represents a Python time object.
type PyDateTime_Delta
This subtype of PyObject represents the difference between two datetime values.
PyTypeObject PyDateTime_DateType
This instance of PyTypeObject represents the Python date type; it is the same object as datetime.date in
the Python layer.
PyTypeObject PyDateTime_DateTimeType
This instance of PyTypeObject represents the Python datetime type; it is the same object as datetime.
datetime in the Python layer.
PyTypeObject PyDateTime_TimeType
This instance of PyTypeObject represents the Python time type; it is the same object as datetime.time in
the Python layer.
PyTypeObject PyDateTime_DeltaType
This instance of PyTypeObject represents Python type for the difference between two datetime values; it is the
same object as datetime.timedelta in the Python layer.
PyTypeObject PyDateTime_TZInfoType
This instance of PyTypeObject represents the Python time zone info type; it is the same object as datetime.
tzinfo in the Python layer.
Macro para acceder al singleton UTC:
PyObject *PyDateTime_TimeZone_UTC
Retorna la zona horaria singleton que representa UTC, el mismo objeto que datetime.timezone.utc.
Nuevo en la versión 3.7.
Macros de verificación de tipo:
int PyDate_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DateType or a subtype of PyDateTime_DateType. ob must not
be NULL. This function always succeeds.
int PyDate_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_DateType. ob no debe ser NULL. Esta función siempre finaliza
con éxito.
int PyDateTime_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DateTimeType or a subtype of PyDateTime_DateTimeType.
ob must not be NULL. This function always succeeds.

206 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
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.
Nuevo en la versión 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 segundo
y doblez especificados.
Nuevo en la versión 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.

8.6. Otros objetos 207


The Python/C API, Versión 3.13.0a5

PyObject *PyTimeZone_FromOffset(PyObject *offset)


Return value: New reference. Retorna un objeto datetime.timezone con un desplazamiento fijo sin nombre
representado por el argumento offset.
Nuevo en la versión 3.7.
PyObject *PyTimeZone_FromOffsetAndName(PyObject *offset, PyObject *name)
Return value: New reference. Retorna un objeto datetime.timezone con un desplazamiento fijo representado
por el argumento offset y con tzname name.
Nuevo en la versión 3.7.
Macros to extract fields from date objects. The argument must be an instance of PyDateTime_Date, including sub-
classes (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, in-
cluding 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.
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.
Nuevo en la versión 3.6.
PyObject *PyDateTime_DATE_GET_TZINFO(PyDateTime_DateTime *o)
Retorna el tzinfo (que puede ser None).
Nuevo en la versión 3.10.
Macros to extract fields from time objects. The argument must be an instance of PyDateTime_Time, including sub-
classes. 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.

208 Capítulo 8. Capa de objetos concretos


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 3.6.
PyObject *PyDateTime_TIME_GET_TZINFO(PyDateTime_Time *o)
Retorna el tzinfo (que puede ser None).
Nuevo en la versión 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.
Nuevo en la versión 3.3.
int PyDateTime_DELTA_GET_SECONDS(PyDateTime_Delta *o)
Retorna el número de segundos, como un int de 0 a 86399.
Nuevo en la versión 3.3.
int PyDateTime_DELTA_GET_MICROSECONDS(PyDateTime_Delta *o)
Retorna el número de micro segundos, como un int de 0 a 999999.
Nuevo en la versión 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 argu-
mentos 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().

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:

8.6. Otros objetos 209


The Python/C API, Versión 3.13.0a5

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

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

210 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()
– PySys_ResetWarnOptions()
• Funciones informativas:
– Py_IsInitialized()
– PyMem_GetAllocator()
– PyObject_GetArenaAllocator()
– Py_GetBuildInfo()
– Py_GetCompiler()
– Py_GetCopyright()

211
The Python/C API, Versión 3.13.0a5

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

Nota: The following functions should not be called before Py_Initialize(): Py_EncodeLocale(),
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), Py_GetProgramFullPath(),
Py_GetPythonHome(), and Py_GetProgramName().

9.2 Variables de configuración global

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

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


The Python/C API, Versión 3.13.0a5

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

9.2. Variables de configuración global 213


The Python/C API, Versión 3.13.0a5

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

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


The Python/C API, Versión 3.13.0a5

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

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.
This initializes the table of loaded modules (sys.modules), and creates the fundamental modules builtins,
__main__ and sys. It also initializes the module search path (sys.path). It does not set sys.argv; use the
new PyConfig API of the Python Initialization Configuration for that. This is a no-op when called for a second
time (without calling Py_FinalizeEx() first). There is no return value; it is a fatal error if the initialization
fails.
Use the Py_InitializeFromConfig() function to customize the Python Initialization Configuration.

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

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.

9.3. Inicializando y finalizando el intérprete 215


The Python/C API, Versión 3.13.0a5

int Py_IsInitialized()
Part of the Stable ABI. Retorna verdadero (distinto de cero) cuando el intérprete de Python se ha inicializado, falso
(cero) si no. Después de que se llama a Py_FinalizeEx(), esto retorna falso hasta que Py_Initialize()
se llama de nuevo.
int Py_IsFinalizing()
Part of the Stable ABI since version 3.13. Return true (non-zero) if the main Python interpreter is shutting down.
Return false (zero) otherwise.
Nuevo en la versión 3.13.
int Py_FinalizeEx()
Part of the Stable ABI since version 3.6. Deshace todas las inicializaciones realizadas por Py_Initialize()
y el uso posterior de las funciones de Python/C API, y destruye todos los sub-intérpretes (ver
Py_NewInterpreter() a continuación) que se crearon y aún no se destruyeron desde el última llamada a
Py_Initialize(). Idealmente, esto libera toda la memoria asignada por el intérprete de Python. Este es un
no-op cuando se llama por segunda vez (sin llamar a Py_Initialize() nuevamente primero). Normalmente
el valor de retorno es 0. Si hubo errores durante la finalización (lavado de datos almacenados en el búfer), se retorna
-1.
Esta función se proporciona por varias razones. Una aplicación de incrustación puede querer reiniciar Python sin
tener que reiniciar la aplicación misma. Una aplicación que ha cargado el intérprete de Python desde una biblioteca
cargable dinámicamente (o DLL) puede querer liberar toda la memoria asignada por Python antes de descargar la
DLL. Durante una búsqueda de pérdidas de memoria en una aplicación, un desarrollador puede querer liberar toda
la memoria asignada por Python antes de salir de la aplicación.
Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause
destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules. Dy-
namically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by
the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references
between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions
may not work properly if their initialization routine is called more than once; this can happen if an application calls
Py_Initialize() and Py_FinalizeEx() more than once.
Genera un evento de auditoría cpython._PySys_ClearAuditHooks sin argumentos.
Nuevo en la versión 3.6.
void Py_Finalize()
Part of the Stable ABI. Esta es una versión compatible con versiones anteriores de Py_FinalizeEx() que
ignora el valor de retorno.

9.4 Parámetros de todo el proceso

wchar_t *Py_GetProgramName()
Part of the Stable ABI. Return the program name set with PyConfig.program_name, or the default. The
returned string points into static storage; the caller should not modify its value.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.executable instead.

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


The Python/C API, Versión 3.13.0a5

wchar_t *Py_GetPrefix()
Part of the Stable ABI. Return the prefix for installed platform-independent files. This is derived through a number
of complicated rules from the program name set with PyConfig.program_name and some environment va-
riables; for example, if the program name is '/usr/local/bin/python', the prefix is '/usr/local'.
The returned string points into static storage; the caller should not modify its value. This corresponds to the prefix
variable in the top-level Makefile and the --prefix argument to the configure script at build time. The
value is available to Python code as sys.prefix. It is only useful on Unix. See also the next function.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.prefix instead.
wchar_t *Py_GetExecPrefix()
Part of the Stable ABI. Return the exec-prefix for installed platform-dependent files. This is derived through a
number of complicated rules from the program name set with PyConfig.program_name and some envi-
ronment variables; for example, if the program name is '/usr/local/bin/python', the exec-prefix is '/
usr/local'. The returned string points into static storage; the caller should not modify its value. This corres-
ponds to the exec_prefix variable in the top-level Makefile and the --exec-prefix argument to the
configure script at build time. The value is available to Python code as sys.exec_prefix. It is only useful
on Unix.
Antecedentes: el prefijo exec difiere del prefijo cuando los archivos dependientes de la plataforma (como ejecutables
y bibliotecas compartidas) se instalan en un árbol de directorios diferente. En una instalación típica, los archivos
dependientes de la plataforma pueden instalarse en el subárbol /usr/local/plat mientras que la plataforma
independiente puede instalarse en /usr/local.
En términos generales, una plataforma es una combinación de familias de hardware y software, por ejemplo, las
máquinas Sparc que ejecutan el sistema operativo Solaris 2.x se consideran la misma plataforma, pero las máquinas
Intel que ejecutan Solaris 2.x son otra plataforma, y las máquinas Intel que ejecutan Linux son otra plataforma
más. Las diferentes revisiones importantes del mismo sistema operativo generalmente también forman plataformas
diferentes. Los sistemas operativos que no son Unix son una historia diferente; Las estrategias de instalación en esos
sistemas son tan diferentes que el prefijo y el prefijo exec no tienen sentido y se configuran en la cadena vacía.
Tenga en cuenta que los archivos de bytecode compilados de Python son independientes de la plataforma (¡pero
no independientes de la versión de Python con la que fueron compilados!).
Los administradores de sistemas sabrán cómo configurar los programas mount o automount para compartir
/usr/local entre plataformas mientras que /usr/local/plat sea un sistema de archivos diferente para
cada plataforma.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.exec_prefix instead.
wchar_t *Py_GetProgramFullPath()
Part of the Stable ABI. Return the full program name of the Python executable; this is computed as a side-effect
of deriving the default module search path from the program name (set by PyConfig.program_name). The
returned string points into static storage; the caller should not modify its value. The value is available to Python
code as sys.executable.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.

9.4. Parámetros de todo el proceso 217


The Python/C API, Versión 3.13.0a5

Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.executable instead.
wchar_t *Py_GetPath()
Part of the Stable ABI. Return the default module search path; this is computed from the program name (set
by PyConfig.program_name) and some environment variables. The returned string consists of a series of
directory names separated by a platform dependent delimiter character. The delimiter character is ':' on Unix
and macOS, ';' on Windows. The returned string points into static storage; the caller should not modify its value.
The list sys.path is initialized with this value on interpreter startup; it can be (and usually is) modified later to
change the search path for loading modules.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get sys.path instead.
const char *Py_GetVersion()
Part of the Stable ABI. Retorna la versión de este intérprete de Python. Esta es una cadena de caracteres que se
parece a

"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.
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:

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


The Python/C API, Versión 3.13.0a5

"#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.
wchar_t *Py_GetPythonHome()
Part of the Stable ABI. Return the default «home», that is, the value set by PyConfig.home, or the value of the
PYTHONHOME environment variable if it is set.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(), de lo
contrario retornará NULL.
Obsoleto desde la versión 3.13, se eliminará en la versión 3.15: Get PyConfig.home or PYTHONHOME envi-
ronment variable instead.

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

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:

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


The Python/C API, Versión 3.13.0a5

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.2 Hilos creados sin Python

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

PyGILState_STATE gstate;
gstate = PyGILState_Ensure();

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

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


The Python/C API, Versión 3.13.0a5

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 limpiar-
se correctamente, lo que os.fork() lo hace. Esto significa finalizar todos los demás objetos PyThreadState que
pertenecen al intérprete actual y todos los demás objetos PyInterpreterState. Debido a esto y a la naturaleza es-
pecial del intérprete «principal», fork() solo debería llamarse en el hilo «principal» de ese intérprete, donde el CPython
global el tiempo de ejecución se inicializó originalmente. La única excepción es si exec() se llamará inmediatamente
después.

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

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


The Python/C API, Versión 3.13.0a5

interpreter is in process of being finalized before calling this function to avoid unwanted termination.

PyThreadState *PyThreadState_Get()
Part of the Stable ABI. Retorna el estado actual del hilo. Se debe mantener el bloqueo global del intérprete. Cuando
el estado actual del hilo es NULL, esto genera un error fatal (por lo que la persona que llama no necesita verificar
NULL).
See also PyThreadState_GetUnchecked().
PyThreadState *PyThreadState_GetUnchecked()
Similar to PyThreadState_Get(), but don’t kill the process with a fatal error if it is NULL. The caller is
responsible to check if the result is NULL.
Nuevo en la versión 3.13: In Python 3.5 to 3.12, the function was private and known as
_PyThreadState_UncheckedGet().
PyThreadState *PyThreadState_Swap(PyThreadState *tstate)
Part of the Stable ABI. Cambia el estado del hilo actual con el estado del hilo dado por el argumento tstate, que
puede ser NULL. El bloqueo global del intérprete debe mantenerse y no se libera.
Las siguientes funciones utilizan almacenamiento local de hilos y no son compatibles con subinterpretes:
PyGILState_STATE PyGILState_Ensure()
Part of the Stable ABI. Asegúrese de que el subproceso actual esté listo para llamar a la API de Python C, inde-
pendientemente del estado actual de Python o del bloqueo global del intérprete. Esto se puede invocar tantas veces
como lo desee un subproceso siempre que cada llamada coincida con una llamada a PyGILState_Release().
En general, se pueden usar otras API relacionadas con subprocesos entre PyGILState_Ensure() y
PyGILState_Release() invoca siempre que el estado del subproceso se restablezca a su estado an-
terior antes del Release(). Por ejemplo, el uso normal de las macros Py_BEGIN_ALLOW_THREADS y
Py_END_ALLOW_THREADS es aceptable.
El valor de retorno es un «identificador» opaco al estado del hilo cuando PyGILState_Ensure() fue lla-
mado, y debe pasarse a PyGILState_Release() para asegurar que Python se deje en el mismo estado.
Aunque las llamadas recursivas están permitidas, estos identificadores no pueden compartirse; cada llamada única
a PyGILState_Ensure() debe guardar el identificador para su llamada a PyGILState_Release().
Cuando la función regrese, el hilo actual contendrá el GIL y podrá llamar a código arbitrario de Python. El fracaso
es un error fatal.

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

void PyGILState_Release(PyGILState_STATE)
Part of the Stable ABI. Libera cualquier recurso previamente adquirido. Después de esta llamada, el estado de
Python será el mismo que antes de la llamada correspondiente PyGILState_Ensure() (pero en general este
estado será desconocido para la persona que llama, de ahí el uso de la API GILState).
Cada llamada a PyGILState_Ensure() debe coincidir con una llamada a PyGILState_Release() en
el mismo hilo.
PyThreadState *PyGILState_GetThisThreadState()
Part of the Stable ABI. Obtenga el estado actual del hilo para este hilo. Puede retornar NULL si no se ha utilizado
la API GILState en el hilo actual. Tenga en cuenta que el subproceso principal siempre tiene dicho estado de
subproceso, incluso si no se ha realizado una llamada de estado de subproceso automático en el subproceso principal.
Esta es principalmente una función auxiliar y de diagnóstico.

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


The Python/C API, Versión 3.13.0a5

int PyGILState_Check()
Retorna 1 si el hilo actual mantiene el GIL y 0 de lo contrario. Esta función se puede llamar desde cualquier hilo
en cualquier momento. Solo si se ha inicializado el hilo de Python y actualmente mantiene el GIL, retornará 1. Esta
es principalmente una función auxiliar y de diagnóstico. Puede ser útil, por ejemplo, en contextos de devolución
de llamada o funciones de asignación de memoria cuando saber que el GIL está bloqueado puede permitir que la
persona que llama realice acciones confidenciales o se comporte de otra manera de manera diferente.
Nuevo en la versión 3.4.
Las siguientes macros se usan normalmente sin punto y coma final; busque, por ejemplo, el uso en la distribución fuente
de Python.
Py_BEGIN_ALLOW_THREADS
Part of the Stable ABI. Esta macro se expande a {PyThreadState *_save; _save =
PyEval_SaveThread();. Tenga en cuenta que contiene una llave de apertura; debe coincidir con la
siguiente macro Py_END_ALLOW_THREADS. Ver arriba para una discusión más detallada de esta macro.
Py_END_ALLOW_THREADS
Part of the Stable ABI. Esta macro se expande a PyEval_RestoreThread(_save); }. Tenga en cuenta
que contiene una llave de cierre; debe coincidir con una macro anterior Py_BEGIN_ALLOW_THREADS. Ver
arriba para una discusión más detallada de esta macro.
Py_BLOCK_THREADS
Part of the Stable ABI. Esta macro se expande a PyEval_RestoreThread(_save);: es equivalente a
Py_END_ALLOW_THREADS sin la llave de cierre.
Py_UNBLOCK_THREADS
Part of the Stable ABI. Esta macro se expande a _save = PyEval_SaveThread();: es equivalente a
Py_BEGIN_ALLOW_THREADS sin la llave de apertura y la declaración de variable.

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.

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


The Python/C API, Versión 3.13.0a5

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. Ante-
riormente, 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
inté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().
tstate no debe ser NULL.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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().
Nuevo en la versión 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().
Nuevo en la versión 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.

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


The Python/C API, Versión 3.13.0a5

La persona que llama debe retener el GIL.


Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 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.
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».
Nuevo en la versión 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».
Nuevo en la versión 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.

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


The Python/C API, Versión 3.13.0a5

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

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 mien-
tras 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.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érpre-
te de Python en un proceso. A diferencia de los subinterpretes, el intérprete principal tiene responsabilidades globales
de proceso únicas, como el manejo de señales. También es responsable de la ejecución durante la inicialización del
tiempo de ejecución y generalmente es el intérprete activo durante la finalización del tiempo de ejecución. La función
PyInterpreterState_Main() retorna un puntero a su estado.
Puede cambiar entre subinterpretes utilizando la función PyThreadState_Swap(). Puede crearlos y destruirlos
utilizando las siguientes funciones:
type PyInterpreterConfig
Structure containing most parameters to configure a sub-interpreter. Its values are used only in
Py_NewInterpreterFromConfig() and never modified by the runtime.
Nuevo en la versión 3.12.
Structure fields:
int use_main_obmalloc
If this is 0 then the sub-interpreter will use its own «object» allocator state. Otherwise it will use (share) the
main interpreter’s.
If this is 0 then check_multi_interp_extensions must be 1 (non-zero). If this is 1 then gil must
not be PyInterpreterConfig_OWN_GIL.

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


The Python/C API, Versión 3.13.0a5

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

9.6. Soporte de subinterprete 227


The Python/C API, Versión 3.13.0a5

will be released. When the function returns, the new interpreter’s GIL will be held by the current thread and the
previously interpreter’s GIL will remain released here.
Nuevo en la versión 3.12.
Sub-interpreters are most effective when isolated from each other, with certain functionality restricted:

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

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

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


The Python/C API, Versión 3.13.0a5

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

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 usuario entre
los subinterpretes, ya que las operaciones de importación ejecutadas por dichos objetos pueden afectar el diccionario
(sub-) intérprete incorrecto de los módulos cargados. Es igualmente importante evitar compartir objetos desde los que se
pueda acceder a lo anterior.
También tenga en cuenta que la combinación de esta funcionalidad con PyGILState_* APIs es delicada, porque estas
APIs suponen una biyección entre los estados de hilo de Python e hilos a nivel del sistema operativo, una suposición rota por
la presencia de subinterpretes. Se recomienda encarecidamente que no cambie los subinterpretes entre un par de llamadas
coincidentes PyGILState_Ensure() y PyGILState_Release(). Además, las extensiones (como ctypes)
que usan estas APIs para permitir la llamada de código Python desde hilos no creados por Python probablemente se
rompan cuando se usan subinterpretes.

9.6. Soporte de subinterprete 229


The Python/C API, Versión 3.13.0a5

9.7 Notificaciones asincrónicas

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

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

Nuevo en la versión 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:

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


The Python/C API, Versión 3.13.0a5

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
line-number event is being reported. It may be disabled for a frame by setting f_trace_lines to 0 on that
frame.
int PyTrace_RETURN
El valor para el parámetro what para Py_tracefunc funciona cuando una llamada está por regresar.
int PyTrace_C_CALL
El valor del parámetro what para Py_tracefunc funciona cuando una función C está a punto de ser invocada.
int PyTrace_C_EXCEPTION
El valor del parámetro what para funciones Py_tracefunc cuando una función C ha lanzado una excepción.
int PyTrace_C_RETURN
El valor del parámetro what para Py_tracefunc funciona cuando una función C ha retornado.
int PyTrace_OPCODE
The value for the what parameter to Py_tracefunc functions (but not profiling functions) when a new op-
code is about to be executed. This event is not emitted by default: it must be explicitly requested by setting
f_trace_opcodes to 1 on the frame.
void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
Set the profiler function to func. The obj parameter is passed to the function as its first parameter, and may be
any Python object, or NULL. If the profile function needs to maintain state, using a different value for obj for each
thread provides a convenient and thread-safe place to store it. The profile function is called for all monitored events
except PyTrace_LINE PyTrace_OPCODE and PyTrace_EXCEPTION.
Consulte también la función sys.setprofile().
La persona que llama debe mantener el GIL.

9.8. Perfilado y Rastreo 231


The Python/C API, Versión 3.13.0a5

void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)


Like PyEval_SetProfile() but sets the profile function in all running threads belonging to the current in-
terpreter 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.
Nuevo en la versión 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 function 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 parameter.
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 inter-
preter 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.
Nuevo en la versión 3.12.

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.

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


The Python/C API, Versión 3.13.0a5

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*. De-
be 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.
Nuevo en la versión 3.7.
Ver también:
«Una nueva C-API para Thread-Local Storage en CPython» (PEP 539)
type Py_tss_t
Esta estructura de datos representa el estado de una clave del hilo, cuya definición puede depender de la imple-
mentación de TLS subyacente, y tiene un campo interno que representa el estado de inicialización de la clave. No
hay miembros públicos en esta estructura.
Cuando Py_LIMITED_API no está definido, la asignación estática de este tipo por Py_tss_NEEDS_INIT está
permitida.
Py_tss_NEEDS_INIT
Esta macro se expande al inicializador para variables Py_tss_t. Tenga en cuenta que esta macro no se definirá
con Py_LIMITED_API.

Asignación dinámica

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

9.10. Soporte de almacenamiento local de hilo 233


The Python/C API, Versión 3.13.0a5

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

Métodos

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

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 mane-
ra que no se puede transmitir de forma segura a int. En tales plataformas, PyThread_create_key() regresará
inmediatamente con un estado de falla, y las otras funciones TLS serán no operativas en tales plataformas.

Debido al problema de compatibilidad mencionado anteriormente, esta versión de la API no debe usarse en código nuevo.

int PyThread_create_key()
Part of the Stable ABI.
void PyThread_delete_key(int key)
Part of the Stable ABI.

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


The Python/C API, Versión 3.13.0a5

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.

9.10. Soporte de almacenamiento local de hilo 235


The Python/C API, Versión 3.13.0a5

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


CAPÍTULO 10

Configuración de inicialización de Python

Nuevo en la versión 3.8.


Python se puede inicializar con Py_InitializeFromConfig() y la estructura PyConfig. Se puede preinicializar
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.


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

237
The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


Implicitly preinitialize Python (in isolated mode). */
status = PyConfig_SetBytesArgv(&config, argc, argv);
if (PyStatus_Exception(status)) {
goto exception;
}

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.

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


The Python/C API, Versión 3.13.0a5

10.3 PyStatus

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

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

Ejemplo:

10.3. PyStatus 239


The Python/C API, Versión 3.13.0a5

PyStatus alloc(void **ptr, size_t size)


{
*ptr = PyMem_RawMalloc(size);
if (*ptr == NULL) {
return PyStatus_NoMemory();
}
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 predetermi-
nados)
• PYMEM_ALLOCATOR_DEFAULT (1): asignadores de memoria predeterminados.
• PYMEM_ALLOCATOR_DEBUG (2): asignadores de memoria predeterminados con ganchos de depura-
ción.
• PYMEM_ALLOCATOR_MALLOC (3): usa malloc() de la biblioteca C.
• PYMEM_ALLOCATOR_MALLOC_DEBUG (4): fuerza el uso de malloc() con ganchos de depuración.
• PYMEM_ALLOCATOR_PYMALLOC (5): asignador de memoria pymalloc de Python
• PYMEM_ALLOCATOR_PYMALLOC_DEBUG (6): asignador de memoria pymalloc de Python con gan-
chos de depuración.
• PYMEM_ALLOCATOR_MIMALLOC (6): use mimalloc, a fast malloc replacement.
• PYMEM_ALLOCATOR_MIMALLOC_DEBUG (7): use mimalloc, a fast malloc replacement with de-
bug hooks.

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


The Python/C API, Versión 3.13.0a5

PYMEM_ALLOCATOR_PYMALLOC y PYMEM_ALLOCATOR_PYMALLOC_DEBUG no son compatibles si


Python es configurado usando --without-pymalloc.
PYMEM_ALLOCATOR_MIMALLOC and PYMEM_ALLOCATOR_MIMALLOC_DEBUG are not supported if
Python is configured using --without-mimalloc or if the underlying atomic support isn’t avai-
lable.
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.
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() ana-
lizan 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.

10.4. PyPreConfig 241


The Python/C API, Versión 3.13.0a5

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.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 puede llamar antes
Py_PreInitialize() si PyPreConfig.allocator está configurado en PYMEM_ALLOCATOR_NOT_SET.
Las funciones de asignación de memoria de Python como PyMem_RawMalloc() no deben usarse antes de la preini-
cialización de Python, mientras que llamar directamente a malloc() y free() siempre es seguro. No se debe llamar
a Py_DecodeLocale() antes de la preinicialización de Python.

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


The Python/C API, Versión 3.13.0a5

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

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.

10.6. PyConfig 243


The Python/C API, Versión 3.13.0a5

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 argumentos de Python se
eliminan de PyConfig.argv, analizar los argumentos dos veces analizaría las opciones de la aplicación
como opciones de Python.
Preinicializa Python si es necesario.
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 pre-
inicialización de Python (PyPreConfig) se basa en PyConfig. Si se ajustan los campos de configuració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
Set sys.argv command line arguments based on argv. These parameters are similar to those passed to
the program’s main() function with the difference that the first entry should refer to the script file to be
executed rather than the executable hosting the Python interpreter. If there isn’t a script that will be run, the
first entry in argv can be an empty string.
Configure parse_argv en 1 para analizar argv de la misma manera que Python normal analiza los ar-
gumentos de la línea de comandos de Python y luego quita los argumentos de Python de argv.

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


The Python/C API, Versión 3.13.0a5

Si argv está vacío, se agrega una cadena vacía para garantizar que sys.argv siempre exista y nunca esté
vacío.
Valor predeterminado: NULL.
Consulte también el miembro orig_argv.
int safe_path
Si es igual a cero, Py_RunMain() agrega una ruta potencialmente insegura a sys.path al inicio:
• Si argv[0] es igual a L"-m" (python -m module), añade el directorio de trabajo actual.
• If running a script (python script.py), prepend the script’s directory. If it’s a symbolic link, re-
solve symbolic links.
• En caso contrario (python -c code and python), añade una cadena vacía, que significa el direc-
torio de trabajo actual.
Set to 1 by the -P command line option and the PYTHONSAFEPATH environment variable.
Default: 0 in Python config, 1 in isolated config.
Nuevo en la versión 3.11.
wchar_t *base_exec_prefix
sys.base_exec_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.exec_prefix.
wchar_t *base_executable
Ejecutable base de Python: sys._base_executable.
Establecido por la variable de entorno __PYVENV_LAUNCHER__.
Establecido desde PyConfig.executable si NULL.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.executable.
wchar_t *base_prefix
sys.base_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.prefix.
int buffered_stdio
If equals to 0 and configure_c_stdio is non-zero, disable buffering on the C streams stdout and stderr.
Set to 0 by the -u command line option and the PYTHONUNBUFFERED environment variable.
stdin siempre se abre en modo de búfer.
Predeterminado: 1.

10.6. PyConfig 245


The Python/C API, Versión 3.13.0a5

int bytes_warning
If equals to 1, issue a warning when comparing bytes or bytearray with str, or comparing bytes
with int.
If equal or greater to 2, raise a BytesWarning exception in these cases.
Incrementado por la opción de línea de comando -b.
Predeterminado: 0.
int warn_default_encoding
Si no es cero, emite una advertencia EncodingWarning cuando io.TextIOWrapper usa su codifica-
ción predeterminada. Consulte io-encoding-warning para obtener más detalles.
Predeterminado: 0.
Nuevo en la versión 3.10.
int code_debug_ranges
If equals to 0, disables the inclusion of the end line and column mappings in code objects. Also disables
traceback printing carets to specific error locations.
Set to 0 by the PYTHONNODEBUGRANGES environment variable and by the -X no_debug_ranges
command line option.
Predeterminado: 1.
Nuevo en la versión 3.11.
wchar_t *check_hash_pycs_mode
Controla el comportamiento de validación de archivos .pyc basados en hash: valor de la opción de línea de
comando --check-hash-based-pycs.
Valores válidos:
• L"always": Calcula el hash el archivo fuente para invalidación independientemente del valor de la
marca “check_source”.
• L"never": suponga que los pycs basados en hash siempre son válidos.
• L"default": El indicador “check_source” en pycs basados en hash determina la invalidación.
Predeterminado: L"default".
Consulte también PEP 552 «Pycs deterministas».
int configure_c_stdio
Si es distinto de cero, configure los flujos estándar de C:
• En Windows, configure el modo binario (O_BINARY) en stdin, stdout y stderr.
• Si buffered_stdio es igual a cero, deshabilite el almacenamiento en búfer de los flujos stdin, stdout
y stderr.
• Si interactive no es cero, habilite el almacenamiento en búfer de flujo en stdin y stdout (solo stdout
en Windows).
Predeterminado: 1 en la configuración de Python, 0 en la configuración aislada.
int dev_mode
Si es distinto de cero, habilita Modo de desarrollo de Python.
Set to 1 by the -X dev option and the PYTHONDEVMODE environment variable.
Por defecto: -1 en modo Python, 0 en modo aislado.

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


The Python/C API, Versión 3.13.0a5

int dump_refs
Dump Python references?
Si no es cero, volcar todos los objetos que aún están vivos en la salida.
Establecido en 1 por la variable de entorno PYTHONDUMPREFS.
Needs a special build of Python with the Py_TRACE_REFS macro defined: see the configure
--with-trace-refs option.
Predeterminado: 0.
wchar_t *exec_prefix
El prefijo de directorio específico del sitio donde se instalan los archivos Python dependientes de la plataforma:
sys.exec_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.base_exec_prefix.
wchar_t *executable
La ruta absoluta del binario ejecutable para el intérprete de Python: sys.executable.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.base_executable.
int faulthandler
¿Habilitar administrador de fallas?
Si no es cero, llama a faulthandler.enable() al inicio.
Establecido en 1 por -X faulthandler y la variable de entorno PYTHONFAULTHANDLER.
Por defecto: -1 en modo Python, 0 en modo aislado.
wchar_t *filesystem_encoding
Codificación del sistema de archvios: sys.getfilesystemencoding().
En macOS, Android y VxWorks: use "utf-8" de forma predeterminada.
En Windows: utilice "utf-8" de forma predeterminada o "mbcs" si
legacy_windows_fs_encoding de PyPreConfig no es cero.
Codificación predeterminada en otras plataformas:
• "utf-8" si PyPreConfig.utf8_mode es distinto de cero.
• "ascii" if Python detects that nl_langinfo(CODESET) announces the ASCII encoding, whereas
the mbstowcs() function decodes from a different encoding (usually Latin1).
• "utf-8" si nl_langinfo(CODESET) retorna una cadena vacía.
• De lo contrario, utilice el resultado locale encoding: nl_langinfo(CODESET).
Al inicio de Python, el nombre de codificación se normaliza al nombre del códec de Python. Por ejemplo,
"ANSI_X3.4-1968" se reemplaza por "ascii".
Consulte también el miembro filesystem_errors.

10.6. PyConfig 247


The Python/C API, Versión 3.13.0a5

wchar_t *filesystem_errors
Manejador de errores del sistema de archivos: sys.getfilesystemencodeerrors().
En Windows: utilice "surrogatepass" de forma predeterminada o "replace" si
legacy_windows_fs_encoding de PyPreConfig no es cero.
En otras plataformas: utilice "surrogateescape" de forma predeterminada.
Controladores de errores admitidos:
• "strict"
• "surrogateescape"
• "surrogatepass" (solo compatible con la codificación UTF-8)
Consulte también el miembro filesystem_encoding.
unsigned long hash_seed

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

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


The Python/C API, Versión 3.13.0a5

int interactive
If greater than 0, enable the interactive mode (REPL).
Incrementado por la opción de línea de comando -i.
Predeterminado: 0.
int int_max_str_digits
Configures the integer string conversion length limitation. An initial value of -1 means the value will
be taken from the command line or environment or otherwise default to 4300 (sys.int_info.
default_max_str_digits). A value of 0 disables the limitation. Values greater than zero but less
than 640 (sys.int_info.str_digits_check_threshold) are unsupported and will produce an
error.
Configured by the -X int_max_str_digits command line flag or the PYTHONINTMAXSTRDIGITS
environment variable.
Default: -1 in Python mode. 4300 (sys.int_info.default_max_str_digits) in isolated mode.
Nuevo en la versión 3.12.
int cpu_count
If the value of cpu_count is not -1 then it will override the return values of os.cpu_count(), os.
process_cpu_count(), and multiprocessing.cpu_count().
Configured by the -X cpu_count=n|default command line flag or the PYTHON_CPU_COUNT en-
vironment variable.
Default: -1.
Nuevo en la versión 3.13.
int isolated
If greater than 0, enable isolated mode:
• Set safe_path to 1: don’t prepend a potentially unsafe path to sys.path at Python startup, such as
the current directory, the script’s directory or an empty string.
• Set use_environment to 0: ignore PYTHON environment variables.
• Set user_site_directory to 0: don’t add the user site directory to sys.path.
• Python REPL no importa readline ni habilita la configuración predeterminada de readline en men-
sajes interactivos.
Set to 1 by the -I command line option.
Por defecto: 0 en modo Python, 1 en modo aislado.
See also the Isolated Configuration and PyPreConfig.isolated.
int legacy_windows_stdio
If non-zero, use io.FileIO instead of io._WindowsConsoleIO for sys.stdin, sys.stdout
and sys.stderr.
Establecido en 1 si la variable de entorno PYTHONLEGACYWINDOWSSTDIO está establecida en una cadena
no vacía.
Solo disponible en Windows. La macro #ifdef MS_WINDOWS se puede usar para el código específico de
Windows.
Predeterminado: 0.
Consulte también PEP 528 (Cambiar la codificación de la consola de Windows a UTF-8).

10.6. PyConfig 249


The Python/C API, Versión 3.13.0a5

int malloc_stats
Si no es cero, volcar las estadísticas en Asignador de memoria Python pymalloc en la salida.
Establecido en 1 por la variable de entorno PYTHONMALLOCSTATS.
La opción se ignora si Python es configurado usando la opción --without-pymalloc.
Predeterminado: 0.
wchar_t *platlibdir
Nombre del directorio de la biblioteca de la plataforma: sys.platlibdir.
Establecido por la variable de entorno PYTHONPLATLIBDIR.
Default: value of the PLATLIBDIR macro which is set by the configure --with-platlibdir
option (default: "lib", or "DLLs" on Windows).
Parte de la entrada Python Path Configuration.
Nuevo en la versión 3.9.
Distinto en la versión 3.11: Esta macro se utiliza ahora en Windows para localizar los módulos de extensión
de la biblioteca estándar, normalmente en DLLs. Sin embargo, por compatibilidad, tenga en cuenta que este
valor se ignora para cualquier disposición no estándar, incluyendo las construcciones dentro del árbol y los
entornos virtuales.
wchar_t *pythonpath_env
Module search paths (sys.path) as a string separated by DELIM (os.pathsep).
Establecido por la variable de entorno PYTHONPATH.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
PyWideStringList module_search_paths

int module_search_paths_set
Rutas de búsqueda del módulo: sys.path.
If module_search_paths_set is equal to 0, Py_InitializeFromConfig() will replace
module_search_paths and sets module_search_paths_set to 1.
Por defecto: lista vacía (module_search_paths) y 0 (module_search_paths_set).
Parte de la salida Python Path Configuration.
int optimization_level
Nivel de optimización de compilación:
• 0: Optimizador de mirilla, configure __debug__ en True.
• 1: Nivel 0, elimina las aserciones, establece __debug__ en False.
• 2: Nivel 1, elimina docstrings.
Incrementado por la opción de línea de comando -O. Establecido en el valor de la variable de entorno
PYTHONOPTIMIZE.
Predeterminado: 0.

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


The Python/C API, Versión 3.13.0a5

PyWideStringList orig_argv
La lista de los argumentos originales de la línea de comandos pasados al ejecutable de Python: sys.
orig_argv.
Si la lista orig_argv está vacía y argv no es una lista que solo contiene una cadena vacía,
PyConfig_Read() copia argv en orig_argv antes de modificar argv (si parse_argv no es
cero).
Consulte también el miembro argv y la función Py_GetArgcArgv().
Predeterminado: lista vacía.
Nuevo en la versión 3.10.
int parse_argv
¿Analizar los argumentos de la línea de comando?
Si es igual a 1, analiza argv de la misma forma que Python normal analiza argumentos de línea de comando
y elimina los argumentos de Python de argv.
La función PyConfig_Read() solo analiza los argumentos PyConfig.argv una vez: PyConfig.
parse_argv se establece en 2 después de analizar los argumentos. Dado que los argumentos de Python se
eliminan de PyConfig.argv, analizar los argumentos dos veces analizaría las opciones de la aplicación
como opciones de Python.
Por defecto: 1 en modo Python, 0 en modo aislado.
Distinto en la versión 3.10: Los argumentos PyConfig.argv ahora solo se analizan si PyConfig.
parse_argv es igual a 1.
int parser_debug
Parser debug mode. If greater than 0, turn on parser debugging output (for expert only, depending on com-
pilation options).
Incrementado por la opción de línea de comando -d. Establecido en el valor de la variable de entorno
PYTHONDEBUG.
Needs a debug build of Python (the Py_DEBUG macro must be defined).
Predeterminado: 0.
int pathconfig_warnings
If non-zero, calculation of path configuration is allowed to log warnings into stderr. If equals to 0, suppress
these warnings.
Por defecto: 1 en modo Python, 0 en modo aislado.
Parte de la entrada Python Path Configuration.
Distinto en la versión 3.11: Ahora también se aplica en Windows.
wchar_t *prefix
El prefijo de directorio específico del sitio donde se instalan los archivos Python independientes de la plata-
forma: sys.prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
See also PyConfig.base_prefix.

10.6. PyConfig 251


The Python/C API, Versión 3.13.0a5

wchar_t *program_name
Nombre del programa utilizado para inicializar executable y en los primeros mensajes de error durante
la inicialización de Python.
• En macOS, usa la variable de entorno PYTHONEXECUTABLE si está configurada.
• Si se define la macro WITH_NEXT_FRAMEWORK, utiliza la variable de entorno
__PYVENV_LAUNCHER__ si está configurada.
• Utiliza argv[0] de argv si está disponible y no está vacío.
• De lo contrario, utiliza L"python" en Windows o L"python3" en otras plataformas.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
wchar_t *pycache_prefix
Directorio donde se escriben los archivos .pyc almacenados en caché: sys.pycache_prefix.
Set by the -X pycache_prefix=PATH command line option and the PYTHONPYCACHEPREFIX en-
vironment variable. The command-line option takes precedence.
Si NULL, sys.pycache_prefix es establecido a None.
Valor predeterminado: NULL.
int quiet
Quiet mode. If greater than 0, don’t display the copyright and version at Python startup in interactive mode.
Incrementado por la opción de línea de comando -q.
Predeterminado: 0.
wchar_t *run_command
Valor de la opción de línea de comando -c.
Usado por Py_RunMain().
Valor predeterminado: NULL.
wchar_t *run_filename
Filename passed on the command line: trailing command line argument without -c or -m. It is used by the
Py_RunMain() function.
For example, it is set to script.py by the python3 script.py arg command line.
See also the PyConfig.skip_source_first_line option.
Valor predeterminado: NULL.
wchar_t *run_module
Valor de la opción de línea de comando -m.
Usado por Py_RunMain().
Valor predeterminado: NULL.
wchar_t *run_presite
package.module path to module that should be imported before site.py is run.
Set by the -X presite=package.module command-line option and the PYTHON_PRESITE envi-
ronment variable. The command-line option takes precedence.
Needs a debug build of Python (the Py_DEBUG macro must be defined).

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


The Python/C API, Versión 3.13.0a5

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.
Needs a debug build of Python (the Py_REF_DEBUG macro must be defined).
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.
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").
Utilice la variable de entorno PYTHONIOENCODING si no está vacía.
Codificación predeterminada:
• "UTF-8" si PyPreConfig.utf8_mode es distinto de cero.
• De lo contrario, usa el locale encoding.
Manejador de errores predeterminado:
• En Windows: use "surrogateescape".
• "surrogateescape" si PyPreConfig.utf8_mode no es cero o si la configuración regional
LC_CTYPE es «C» o «POSIX».
• "strict" de lo contrario.
See also PyConfig.legacy_windows_stdio.
int tracemalloc
¿Habilitar tracemalloc?
Si no es cero, llama a tracemalloc.start() al inicio.

10.6. PyConfig 253


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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.
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 advertencia.
Se pueden especificar varias opciones, separadas por comas (,).
Predeterminado: lista vacía.

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


The Python/C API, Versión 3.13.0a5

int write_bytecode
If equal to 0, Python won’t try to write .pyc files on the import of source modules.
Establecido en 0 por la opción de línea de comando -B y la variable de entorno
PYTHONDONTWRITEBYTECODE.
sys.dont_write_bytecode se inicializa al valor invertido de write_bytecode.
Predeterminado: 1.
PyWideStringList xoptions
Valores de las opciones de la línea de comando -X: sys._xoptions.
Predeterminado: lista vacía.
Si parse_argv no es cero, los argumentos de argv se analizan de la misma forma que Python normal analiza argu-
mentos de línea de comando, y los argumentos de Python se eliminan de argv.
Las opciones de xoptions se analizan para establecer otras opciones: consulte la opción de línea de comando -X.
Distinto en la versión 3.9: El campo show_alloc_count fue removido.

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:
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;
}
(continúe en la próxima página)

10.7. Inicialización con PyConfig 255


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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 parameters.
Note that since 3.11, many parameters are not calculated until initialization, and so values cannot be read from the
configuration structure. Any values set before initialize is called will be left unchanged by initialization:

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;
}
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;
}
(continúe en la próxima página)

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


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)

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 especifican.
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 confi-


guració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
– 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).

10.8. Configuración aislada 257


The Python/C API, Versión 3.13.0a5

• 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 explicitly 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, Windows
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.
• Set use_environment to 0.
• Set site_import to 0.
• Set safe_path to 1.
The __PYVENV_LAUNCHER__ environment variable is used to set PyConfig.base_executable.

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


The Python/C API, Versión 3.13.0a5

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» initialization
phase.

10.11. Py_RunMain() 259


The Python/C API, Versión 3.13.0a5

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

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

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

if (buf == NULL)
(continúe en la próxima página)

261
The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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

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
encontrar una tabla simplificada en here. No existe un requisito estricto para usar la memoria retornada por las funciones
de asignación que pertenecen a un dominio dado solo para los propósitos sugeridos por ese dominio (aunque esta es la
práctica recomendada). Por ejemplo, se podría usar la memoria retornada por PyMem_RawMalloc() para asignar
objetos Python o la memoria retornada por PyObject_Malloc() para asignar memoria para búferes.
Los tres dominios de asignación son:
• Dominio sin formato: destinado a asignar memoria para búferes de memoria de uso general donde la asignación
debe ir al asignador del sistema o donde el asignador puede operar sin el GIL. La memoria se solicita directamente
al sistema.
• Dominio «Mem»: destinado a asignar memoria para búferes de Python y búferes de memoria de propósito general
donde la asignación debe realizarse con el GIL retenido. La memoria se toma del montículo privado de Python.
• Dominio de objeto: destinado a asignar memoria perteneciente a objetos de Python. La memoria se toma del
montículo privado de Python.
Cuando se libera memoria previamente asignada por las funciones de asignación que pertenecen a un dominio dado, se
deben utilizar las funciones de desasignación específicas coincidentes. Por ejemplo, PyMem_Free() debe usarse para
liberar memoria asignada usando PyMem_Malloc().

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


The Python/C API, Versión 3.13.0a5

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

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.

11.3. Interfaz de memoria sin procesar 263


The Python/C API, Versión 3.13.0a5

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

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


The Python/C API, Versión 3.13.0a5

• PyMem_RESIZE(ptr, type, size)


• PyMem_FREE(ptr)
• PyMem_DEL(ptr)

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 objeto
Python al interceptar las funciones de asignación en este dominio mediante los métodos descritos en la sección Personalizar
Asignadores de Memoria.

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).
Nuevo en la versión 3.5.
void *PyObject_Realloc(void *p, size_t n)
Part of the Stable ABI. Cambia el tamaño del bloque de memoria señalado por p a n bytes. Los contenidos no se
modificarán al mínimo de los tamaños antiguo y nuevo.
Si p es NULL, la llamada es equivalente a PyObject_Malloc(n); de lo contrario, si n es igual a cero, el bloque
de memoria cambia de tamaño pero no se libera, y el puntero retornado no es NULL.
A menos que p sea NULL, debe haber sido retornado por una llamada previa a PyObject_Malloc(),
PyObject_Realloc() o PyObject_Calloc().
Si la solicitud falla, PyObject_Realloc() retorna NULL y p sigue siendo un puntero válido al área de memoria
anterior.
void PyObject_Free(void *p)
Part of the Stable ABI. Libera el bloque de memoria al que apunta p, que debe haber sido retornado por una llamada
anterior a PyObject_Malloc(), PyObject_Realloc() o PyObject_Calloc(). De lo contrario, o
si se ha llamado antes a PyObject_Free(p), se produce un comportamiento indefinido.
Si p es NULL, no se realiza ninguna operación.

11.5. Asignadores de objetos 265


The Python/C API, Versión 3.13.0a5

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 + debug pymalloc + pymalloc +
debug debug
Lanzamiento de compilación, sin "malloc" malloc malloc malloc
pymalloc
Compilación de depuración, sin "malloc_debug" malloc + debug malloc + de- malloc + de-
pymalloc 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.
• mimalloc: mimalloc memory allocator. The pymalloc allocator will be used if mimalloc support isn’t available.
• «+ debug»: con enlaces de depuración en los asignadores de memoria de Python.
• «Debug build»: Compilación de Python en modo de depuración.

11.7 Personalizar asignadores de memoria

Nuevo en la versión 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 ar-
gumento
void* malloc(void *ctx, size_t size) asignar un bloque de memoria
void* calloc(void *ctx, size_t nelem, asignar un bloque de memoria inicializado
size_t elsize) con ceros
void* realloc(void *ctx, void *ptr, asignar o cambiar el tamaño de un bloque de
size_t new_size) memoria
void free(void *ctx, void *ptr) liberar un bloque de memoria

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

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


The Python/C API, Versión 3.13.0a5

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

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.

11.7. Personalizar asignadores de memoria 267


The Python/C API, Versión 3.13.0a5

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

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


The Python/C API, Versión 3.13.0a5

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

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. El asignador pymalloc 269


The Python/C API, Versión 3.13.0a5

11.9.1 Personalizar asignador de arena de pymalloc

Nuevo en la versión 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 argu-
mento
void* alloc(void *ctx, size_t size) asignar una arena de bytes de tamaño
void free(void *ctx, void *ptr, size_t liberar la arena
size)

void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)


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

11.10 The mimalloc allocator

Nuevo en la versión 3.13.


Python supports the mimalloc allocator when the underlying platform support is available. mimalloc «is a general purpose
allocator with excellent performance characteristics. Initially developed by Daan Leijen for the runtime systems of the
Koka and Lean languages.»

11.11 tracemalloc C API

Nuevo en la versión 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.

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


The Python/C API, Versión 3.13.0a5

11.12 Ejemplos

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

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

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

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

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.12. Ejemplos 271


The Python/C API, Versión 3.13.0a5

272 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 memory
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.

273
The Python/C API, Versión 3.13.0a5

void PyObject_Del(void *op)


Releases memory allocated to an object using PyObject_New or PyObject_NewVar. This is normally 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.

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


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 3.10.
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.
Nuevo en la versión 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.
Nuevo en la versión 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.
Nuevo en la versión 3.10.
PyTypeObject *Py_TYPE(PyObject *o)
Return value: Borrowed reference. 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.
Nuevo en la versión 3.9.
void Py_SET_TYPE(PyObject *o, PyTypeObject *type)
Establece el tipo del objeto o a type.
Nuevo en la versión 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.
Nuevo en la versión 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:

12.2. Estructuras de objetos comunes 275


The Python/C API, Versión 3.13.0a5

_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.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
Part of the Stable ABI since version 3.13. Type of the functions used to implement Python callables in C with
signature METH_FASTCALL. The function signature is:

PyObject *PyCFunctionFast(PyObject *self,


PyObject *const *args,
Py_ssize_t nargs);

type PyCFunctionFastWithKeywords
Part of the Stable ABI since version 3.13. Type of the functions used to implement Python callables in C with
signature METH_FASTCALL | METH_KEYWORDS. The function signature is:

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:

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


The Python/C API, Versión 3.13.0a5

PyObject *PyCMethod(PyObject *self,


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

Nuevo en la versión 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.
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 pa-
rámetros: self, args, kwargs donde kwargs es un diccionario de todos los argumentos de palabras clave o, po-
siblemente, 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).
Nuevo en la versión 3.7.
Distinto en la versión 3.10: METH_FASTCALL is now part of the stable ABI.

12.2. Estructuras de objetos comunes 277


The Python/C API, Versión 3.13.0a5

METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL supporting also keyword arguments, with methods of type
PyCFunctionFastWithKeywords. Keyword arguments are passed the same way as in the vectorcall
protocol: there is an additional fourth PyObject* parameter which is a tuple representing the names of the
keyword arguments (which are guaranteed to be strings) or possibly NULL if there are no keywords. The values
of the keyword arguments are stored in the args array, after the positional arguments.
Nuevo en la versión 3.7.
METH_METHOD
Can only be used in the combination with other flags: METH_METHOD | METH_FASTCALL | METH_KEYWORDS.
METH_METHOD | METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL | METH_KEYWORDS supporting the defining class, that is, the class that contains
the method in question. The defining class might be a superclass of Py_TYPE(self).
El método debe ser de tipo PyCMethod, lo mismo que para METH_FASTCALL | METH_KEYWORDS con el
argumento defining_clase añadido después de self.
Nuevo en la versión 3.9.
METH_NOARGS
Methods without parameters don’t need to check whether arguments are given if they are listed with the
METH_NOARGS flag. They need to be of type PyCFunction. The first parameter is typically named self and
will hold a reference to the module or object instance. In all cases the second parameter will be NULL.
La función debe tener 2 parámetros. Dado que el segundo parámetro no se usa, Py_UNUSED se puede usar para
evitar una advertencia del compilador.
METH_O
Methods with a single object argument can be listed with the METH_O flag, instead of invoking
PyArg_ParseTuple() with a "O" argument. They have the type PyCFunction, with the self parameter,
and a PyObject* parameter representing the single argument.
Estas dos constantes no se utilizan para indicar la convención de llamada si no la vinculación cuando su usan con méto-
dos de las clases. Estos no se pueden usar para funciones definidas para módulos. A lo sumo uno de estos flags puede
establecerse en un método dado.
METH_CLASS
Al método se le pasará el objeto tipo como primer parámetro, en lugar de una instancia del tipo. Esto se utiliza para
crear métodos de clase (class methods), similar a lo que se crea cuando se utiliza la función classmethod()
incorporada.
METH_STATIC
El método pasará NULL como el primer parámetro en lugar de una instancia del tipo. Esto se utiliza para crear
métodos estáticos (static methods), similar a lo que se crea cuando se utiliza la función staticmethod() in-
corporada.
En otros controles constantes dependiendo si se carga un método en su lugar (in place) de otra definición con el mismo
nombre del método.
METH_COEXIST
The method will be loaded in place of existing definitions. Without METH_COEXIST, the default is to skip re-
peated definitions. Since slot wrappers are loaded before the method table, the existence of a sq_contains slot, for
example, would generate a wrapped method named __contains__() and preclude the loading of a corres-
ponding PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in place of the
wrapper object and will co-exist with the slot. This is helpful because calls to PyCFunctions are optimized more
than wrapper object calls.

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


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 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).

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 corresponds
to a C struct member. When defining a class, put a NULL-terminated array of these structures in the tp_members
slot.
Its fields are, in order:
const char *name
Name of the member. A NULL value marks the end of a PyMemberDef[] array.
The string should be static, no copy is made of it.
int type
The type of the member in the C struct. See Member types for the possible values.
Py_ssize_t offset
The offset in bytes that the member is located on the type’s object struct.
int flags
Zero or more of the Member flags, combined using bitwise OR.
const char *doc
The docstring, or NULL. The string should be static, no copy is made of it. Typically, it is defined using
PyDoc_STR.
By default (when flags is 0), members allow both read and write access. Use the Py_READONLY flag for read-
only access. Certain types, like Py_T_STRING, imply Py_READONLY. Only Py_T_OBJECT_EX (and legacy
T_OBJECT) members can be deleted.

12.2. Estructuras de objetos comunes 279


The Python/C API, Versión 3.13.0a5

For heap-allocated types (created using PyType_FromSpec() or similar), PyMemberDef may contain a defi-
nition for the special member "__vectorcalloffset__", corresponding to tp_vectorcall_offset
in type objects. These must be defined with Py_T_PYSSIZET and Py_READONLY, for example:
static PyMemberDef spam_type_members[] = {
{"__vectorcalloffset__", Py_T_PYSSIZET,
offsetof(Spam_object, vectorcall), Py_READONLY},
{NULL} /* Sentinel */
};

(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".

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 available
with #include "structmember.h" are deprecated. READ_RESTRICTED and RESTRICTED are equivalent 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.

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


The Python/C API, Versión 3.13.0a5

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

12.2. Estructuras de objetos comunes 281


The Python/C API, Versión 3.13.0a5

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

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


The Python/C API, Versión 3.13.0a5

(*): Zero-terminated, UTF8-encoded C string. With Py_T_STRING the C representation is a pointer; with
Py_T_STRING_INPLACE the string is stored directly in the structure.
(**): String of length 1. Only ASCII is accepted.
(RO): Implies Py_READONLY.
(D): Can be deleted, in which case the pointer is set to NULL. Reading a NULL pointer raises
AttributeError.
Nuevo en la versión 3.12: In previous versions, the macros were only available with #include "structmember.h"
and were named without the Py_ prefix (e.g. as T_INT). The header is still available and contains the old names, along
with the following deprecated types:
T_OBJECT
Like Py_T_OBJECT_EX, but NULL is converted to None. This results in surprising behavior in Python: deleting
the attribute effectively sets it to None.
T_NONE
Always None. Must be used with Py_READONLY.

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.

12.2. Estructuras de objetos comunes 283


The Python/C API, Versión 3.13.0a5

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 285, 1 for-
ma-
ciónPágina 285, 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
continúe en la próxima página

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


The Python/C API, Versión 3.13.0a5

Tabla 1 – proviene de la página anterior


Ranura Type métodos/atributos especiales In-
PyTypeObjectPágina 285, 1 for-
ma-
ción2
O T D I
tp_methods PyMethodDef [] X X
tp_members PyMemberDef [] X
tp_getset PyGetSetDef [] X X
tp_base PyTypeObject * __base__ X
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

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.

12.3. Objetos tipo 285


The Python/C API, Versión 3.13.0a5

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__


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__
continúe en la próxima página

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


The Python/C API, Versión 3.13.0a5

Tabla 2 – proviene de la página anterior


Ranuras (Slot) Type métodos especiales

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

12.3. Objetos tipo 287


The Python/C API, Versión 3.13.0a5

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 *
288 Capítulo 12. Soporte de implementación de objetos
descrsetfunc int
PyObject *
The Python/C API, Versión 3.13.0a5

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;
(continúe en la próxima página)

12.3. Objetos tipo 289


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)

/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;

/* 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 argumen-
to de la macro PyObject_HEAD_INIT, y su valor normalmente debería ser &PyType_Type. Sin embargo,

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


The Python/C API, Versión 3.13.0a5

para los módulos de extensión cargables dinámicamente que deben ser utilizables en Windows (al menos), el com-
pilador se queja de que este no es un inicializador válido. Por lo tanto, la convención es pasar NULL al macro
PyObject_HEAD_INIT e inicializar este campo explícitamente al comienzo de la función de inicialización del
módulo, antes de hacer cualquier otra cosa. Esto normalmente se hace así:

Foo_Type.ob_type = &PyType_Type;

This should be done before any instances of the type are created. PyType_Ready() checks if ob_type is
NULL, and if so, initializes it to the ob_type field of the base class. PyType_Ready() will not change this
field if it is non-zero.
Herencia:
Este campo es heredado por subtipos.

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 expli-
có anteriormente). Esto significa que su tipo será imposible de guardar como pickle. Además, no figurará en la
documentación del módulo creado con pydoc.
Este campo no debe ser NULL. Es el único campo obligatorio en PyTypeObject() (que no sea potencialmente
tp_itemsize).
Herencia:
Este campo no es heredado por los subtipos.
Py_ssize_t PyTypeObject.tp_basicsize

12.3. Objetos tipo 291


The Python/C API, Versión 3.13.0a5

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

void tp_dealloc(PyObject *self);

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

static void foo_dealloc(foo_object *self) {


PyObject_GC_UnTrack(self);
Py_CLEAR(self->ref);
Py_TYPE(self)->tp_free((PyObject *)self);
}

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


The Python/C API, Versión 3.13.0a5

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

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 ase-
gurarse de que su comportamiento sea coherente con la función vectorcallfunc. Esto se puede hacer configurando
tp_call en PyVectorcall_Call().
Distinto en la versión 3.8: Antes de la versión 3.8, este slot se llamaba tp_print. En Python 2.x, se usó para
imprimir en un archivo. En Python 3.0 a 3.7, no se usó.
Distinto en la versión 3.12: Before version 3.12, it was not recommended for mutable heap types to implement
the vectorcall protocol. When a user sets __call__ in Python code, only tp_call is updated, likely making it
inconsistent with the vectorcall function. Since 3.12, setting __call__ will disable vectorcall optimization by
clearing the Py_TPFLAGS_HAVE_VECTORCALL flag.
Herencia:
This field is always inherited. However, the Py_TPFLAGS_HAVE_VECTORCALL flag is not always inherited. If
it’s not set, then the subclass won’t use vectorcall, except when PyVectorcall_Call() is explicitly called.
getattrfunc PyTypeObject.tp_getattr
Un puntero opcional a la función «obtener atributo cadena de caracteres» (get-attribute-string).
Este campo está en desuso. Cuando se define, debe apuntar a una función que actúe igual que la función
tp_getattro, pero tomando una cadena de caracteres C en lugar de un objeto de cadena Python para dar
el nombre del atributo.
Herencia:
Group: tp_getattr, tp_getattro
Este campo es heredado por los subtipos junto con tp_getattro: un subtipo hereda ambos tp_getattr y
tp_getattro de su base escriba cuando los subtipos tp_getattr y tp_getattro son ambos NULL.
setattrfunc PyTypeObject.tp_setattr
Un puntero opcional a la función para configurar y eliminar atributos.
Este campo está en desuso. Cuando se define, debe apuntar a una función que actúe igual que la función
tp_setattro, pero tomando una cadena de caracteres C en lugar de un objeto de cadena Python para dar
el nombre del atributo.

12.3. Objetos tipo 293


The Python/C API, Versión 3.13.0a5

Herencia:
Group: tp_setattr, tp_setattro
Este campo es heredado por los subtipos junto con tp_setattro: un subtipo hereda ambos tp_setattr y
tp_setattro de su base escriba cuando los subtipos tp_setattr y tp_setattro son ambos NULL.
PyAsyncMethods *PyTypeObject.tp_as_async
Puntero a una estructura adicional que contiene campos relevantes solo para los objetos que implementan los pro-
tocolos «esperable» (awaitable) y «iterador asíncrono» (asynchronous iterator) en el nivel C. Ver Estructuras de
objetos asíncronos para más detalles.
Nuevo en la versión 3.5: Anteriormente conocidos como tp_compare y tp_reserved.
Herencia:
El campo tp_as_async no se hereda, pero los campos contenidos se heredan individualmente.
reprfunc PyTypeObject.tp_repr
Un puntero opcional a una función que implementa la función incorporada repr().
La firma es la misma que para PyObject_Repr():

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 protocolo
numérico. Estos campos están documentados en Estructuras de objetos de números.
Herencia:
El campo tp_as_number no se hereda, pero los campos contenidos se heredan individualmente.
PySequenceMethods *PyTypeObject.tp_as_sequence
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el protocolo
de secuencia. Estos campos están documentados en estructuras de secuencia.
Herencia:
El campo tp_as_sequence no se hereda, pero los campos contenidos se heredan individualmente.
PyMappingMethods *PyTypeObject.tp_as_mapping
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el protocolo
de mapeo. Estos campos están documentados en Estructuras de objetos mapeo.
Herencia:
El campo tp_as_mapping no se hereda, pero los campos contenidos se heredan individualmente.

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


The Python/C API, Versión 3.13.0a5

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 cade-
na «amigable» del objeto, ya que esta es la representación que será utilizada, entre otras cosas, por la función
print().
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Cuando este campo no está configurado, se llama a PyObject_Repr() para retornar una representación de
cadena de caracteres.

12.3. Objetos tipo 295


The Python/C API, Versión 3.13.0a5

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

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

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


The Python/C API, Versión 3.13.0a5

with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the
tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and
the tp_traverse and tp_clear fields in the subtype exist and have NULL values. .. XXX are most flag bits
really inherited individually?
Por defecto:
PyBaseObject_Type uses Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE.
Máscaras de bits:
Las siguientes máscaras de bits están definidas actualmente; estos se pueden unidos por OR usando el operador |
para formar el valor del campo tp_flags. El macro PyType_HasFeature() toma un tipo y un valor de
banderas, tp y f, y comprueba si tp->tp_flags & f no es cero.
Py_TPFLAGS_HEAPTYPE
This bit is set when the type object itself is allocated on the heap, for example, types created dynamically
using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference
to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when an
instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the instance’s
ob_type gets INCREF’ed or DECREF’ed).
Herencia:
???
Py_TPFLAGS_BASETYPE
Este bit se establece cuando el tipo se puede usar como el tipo base de otro tipo. Si este bit es claro, el tipo
no puede subtiparse (similar a una clase «final» en Java).
Herencia:
???
Py_TPFLAGS_READY
Este bit se establece cuando el objeto tipo ha sido completamente inicializado por PyType_Ready().
Herencia:
???
Py_TPFLAGS_READYING
Este bit se establece mientras PyType_Ready() está en el proceso de inicialización del objeto tipo.
Herencia:
???
Py_TPFLAGS_HAVE_GC
This bit is set when the object supports garbage collection. If this bit is set, instances must be created using
PyObject_GC_New and destroyed using PyObject_GC_Del(). More information in section Apo-
yo a la recolección de basura cíclica. This bit also implies that the GC-related fields tp_traverse and
tp_clear are present in the type object.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear fields,
i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and tp_clear
fields in the subtype exist and have NULL values.

12.3. Objetos tipo 297


The Python/C API, Versión 3.13.0a5

Py_TPFLAGS_DEFAULT
This is a bitmask of all the bits that pertain to the existence of certain fields in the type object and its extension
structures. Currently, it includes the following bits: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION.
Herencia:
???
Py_TPFLAGS_METHOD_DESCRIPTOR
Este bit indica que los objetos se comportan como métodos independientes.
Si este indicador está configurado para type(meth), entonces:
• meth.__get__(obj, cls)(*args, **kwds) (con obj no None) debe ser equivalente a
meth(obj, *args, **kwds).
• meth.__get__(None, cls)(*args, **kwds) debe ser equivalente a meth(*args,
**kwds).
Este indicador (flag) permite una optimización para llamadas a métodos típicos como obj.meth(): evita
crear un objeto temporal de «método vinculado» para obj.meth.
Nuevo en la versión 3.8.
Herencia:
This flag is never inherited by types without the Py_TPFLAGS_IMMUTABLETYPE flag set. For extension
types, it is inherited whenever tp_descr_get is inherited.
Py_TPFLAGS_MANAGED_DICT
This bit indicates that instances of the class have a __dict__ attribute, and that the space for the dictionary
is managed by the VM.
If this flag is set, Py_TPFLAGS_HAVE_GC should also be set.
The type traverse function must call PyObject_VisitManagedDict() and its clear function must call
PyObject_ClearManagedDict().
Nuevo en la versión 3.12.
Herencia:
This flag is inherited unless the tp_dictoffset field is set in a superclass.
Py_TPFLAGS_MANAGED_WEAKREF
This bit indicates that instances of the class should be weakly referenceable.
Nuevo en la versión 3.12.
Herencia:
This flag is inherited unless the tp_weaklistoffset field is set in a superclass.
Py_TPFLAGS_ITEMS_AT_END
Only usable with variable-size types, i.e. ones with non-zero tp_itemsize.
Indicates that the variable-sized portion of an instance of this type is at the end of the instance’s memory area,
at an offset of Py_TYPE(obj)->tp_basicsize (which may be different in each subclass).
When setting this flag, be sure that all superclasses either use this memory layout, or are not variable-sized.
Python does not check this.
Nuevo en la versión 3.12.
Herencia:

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


The Python/C API, Versión 3.13.0a5

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 in-
tegrados deben tener su tp_flags configurado correctamente, o el código que interactúa con dichos tipos
se comportará de manera diferente dependiendo del tipo de verificación que se use.
Py_TPFLAGS_HAVE_FINALIZE
Este bit se establece cuando la ranura tp_finalize está presente en la estructura de tipo.
Nuevo en la versión 3.4.
Obsoleto desde la versión 3.8: Este indicador ya no es necesario, ya que el intérprete asume que: el espacio
tp_finalize siempre está presente en la estructura de tipos.
Py_TPFLAGS_HAVE_VECTORCALL
Este bit se establece cuando la clase implementa protocolo vectorcall. Consulte tp_vectorcall_offset
para obtener más detalles.
Herencia:
This bit is inherited if tp_call is also inherited.
Nuevo en la versión 3.9.
Distinto en la versión 3.12: This flag is now removed from a class when the class’s __call__() method is
reassigned.
This flag can now be inherited by mutable classes.
Py_TPFLAGS_IMMUTABLETYPE
Este bit se establece para objetos de tipo que son inmutables: los atributos de tipo no se pueden establecer ni
eliminar.
PyType_Ready() aplica automáticamente este indicador a static types.
Herencia:
Este flag no se hereda.
Nuevo en la versión 3.10.
Py_TPFLAGS_DISALLOW_INSTANTIATION
No permita la creación de instancias del tipo: establezca tp_new en NULL y no cree la clave __new__ en
el diccionario de tipos.

12.3. Objetos tipo 299


The Python/C API, Versión 3.13.0a5

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.

Nuevo en la versión 3.10.


Py_TPFLAGS_MAPPING
Este bit indica que las instancias de la clase pueden coincidir con los patrones de correspondencia cuan-
do 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:
This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.
Ver también:
PEP 634 - Coincidencia de patrones estructurales: especificación
Nuevo en la versión 3.10.
Py_TPFLAGS_SEQUENCE
Este bit indica que las instancias de la clase pueden coincidir con los patrones de secuencia cuando se utilizan
como sujeto de un bloque match. Se configura automáticamente al registrar o subclasificar collections.
abc.Sequence, y se desarma al registrar collections.abc.Mapping.

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
Nuevo en la versión 3.10.
Py_TPFLAGS_VALID_VERSION_TAG
Internal. Do not set or unset this flag. To indicate that a class has changed call PyType_Modified()

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


The Python/C API, Versión 3.13.0a5

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 implementation of
a tp_traverse function simply calls Py_VISIT() on each of the instance’s members that are Python objects
that the instance owns. For example, this is function local_traverse() from the _thread extension module:

static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
Py_VISIT(self->args);
Py_VISIT(self->kw);
Py_VISIT(self->dict);
return 0;
}

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

Py_VISIT(Py_TYPE(self));

It is only needed since Python 3.9. To support Python 3.8 and older, this line must be conditionnal:

#if PY_VERSION_HEX >= 0x03090000


Py_VISIT(Py_TYPE(self));
#endif

If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, the traverse function must call
PyObject_VisitManagedDict() like this:

PyObject_VisitManagedDict((PyObject*)self, visit, arg);

12.3. Objetos tipo 301


The Python/C API, Versión 3.13.0a5

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

Note that Py_VISIT() requires the visit and arg parameters to local_traverse() to have these specific
names; don’t name them just anything.
Las instancias de heap-allocated types contienen una referencia a su tipo. Por lo tanto, su función transversal debe
visitar Py_TYPE(self) o delegar esta responsabilidad llamando a tp_traverse de otro tipo asignado al heap
(como una superclase asignada al heap). Si no es así, es posible que el objeto de tipo no se recolecte como basura.
Distinto en la versión 3.9: Se espera que los tipos asignados al heap visiten Py_TYPE(self) en tp_traverse.
En versiones anteriores de Python, debido al bug 40217, hacer esto puede provocar fallas en las subclases.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the flag
bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.
inquiry PyTypeObject.tp_clear
An optional pointer to a clear function for the garbage collector. This is only used if the Py_TPFLAGS_HAVE_GC
flag bit is set. The signature is:

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

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


The Python/C API, Versión 3.13.0a5

object be NULL at that time, so that self knows the contained object can no longer be used. The Py_CLEAR()
macro performs the operations in a safe order.
If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, the traverse function must call
PyObject_ClearManagedDict() like this:

PyObject_ClearManagedDict((PyObject*)self);

Tenga en cuenta que tp_clear no se llama siempre antes de que se desasigne una instancia. Por ejemplo, cuando
el recuento de referencias es suficiente para determinar que un objeto ya no se utiliza, el recolector de basura cíclico
no está involucrado y se llama directamente a tp_dealloc.
Debido a que el objetivo de tp_clear es romper los ciclos de referencia, no es necesario borrar objetos contenidos
como cadenas de caracteres de Python o enteros de Python, que no pueden participar en los ciclos de referencia. Por
otro lado, puede ser conveniente borrar todos los objetos Python contenidos y escribir la función tp_dealloc
para invocar tp_clear.
Se puede encontrar más información sobre el esquema de recolección de basura de Python en la sección Apoyo a
la recolección de basura cíclica.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit: the
flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.
richcmpfunc PyTypeObject.tp_richcompare
Un puntero opcional a la función de comparación enriquecida, cuya firma es:

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 com-
paración no está definida, debe retornar Py_NotImplemented, si se produce otro error, debe retornar NULL
y establecer una condición de excepción.
Las siguientes constantes se definen para ser utilizadas como el tercer argumento para tp_richcompare y para
PyObject_RichCompare():

12.3. Objetos tipo 303


The Python/C API, Versión 3.13.0a5

Constante Comparación
<
Py_LT

<=
Py_LE

==
Py_EQ

!=
Py_NE

>
Py_GT

>=
Py_GE

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

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


The Python/C API, Versión 3.13.0a5

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

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

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

12.3. Objetos tipo 305


The Python/C API, Versión 3.13.0a5

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.
Herencia:
Este campo no es heredado por los subtipos (los atributos computados se heredan a través de un mecanismo dife-
rente).
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 requiere que los
inicializadores sean «constantes de dirección». Los designadores de funciones como PyType_GenericNew(),
con conversión implícita a un puntero, son constantes de dirección C99 válidas.
However, the unary “&” operator applied to a non-static variable like PyBaseObject_Type is not required to
produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers are strictly
standard conforming in this particular behavior.
En consecuencia, tp_base debe establecerse en la función init del módulo de extensión.

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

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


The Python/C API, Versión 3.13.0a5

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

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 desplazamiento
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, llame
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_flags field, then tp_dictoffset will be set to
-1, to indicate that it is unsafe to use this field.

12.3. Objetos tipo 307


The Python/C API, Versión 3.13.0a5

initproc PyTypeObject.tp_init
Un puntero opcional a una función de inicialización de instancia.
This function corresponds to the __init__() method of classes. Like __init__(), it is possible to create an
instance without calling __init__(), and it is possible to reinitialize an instance by calling its __init__()
method again.
La firma de la función es:
int tp_init(PyObject *self, PyObject *args, PyObject *kwds);

The self argument is the instance to be initialized; the args and kwds arguments represent positional and keyword
arguments of the call to __init__().
La función tp_init, si no es NULL, se llama cuando una instancia se crea normalmente llamando a su tipo,
después de la función tp_new del tipo ha retornado una instancia del tipo. Si la función tp_new retorna una
instancia de otro tipo que no es un subtipo del tipo original, no se llama la función tp_init; if tp_new retorna
una instancia de un subtipo del tipo original, se llama al subtipo tp_init.
Retorna 0 en caso de éxito, -1 y establece una excepción en caso de error.
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Para tipos estáticos, este campo no tiene un valor predeterminado.
allocfunc PyTypeObject.tp_alloc
Un puntero opcional a una función de asignación de instancia.
La firma de la función es:
PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);

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

El argumento subtype es el tipo de objeto que se está creando; los argumentos args y kwds representan argumentos
posicionales y de palabras clave de la llamada al tipo. Tenga en cuenta que subtype no tiene que ser igual al tipo
cuya función tp_new es llamada; puede ser un subtipo de ese tipo (pero no un tipo no relacionado).
La función tp_new debería llamar a subtype->tp_alloc(subtype, nitems) para asignar espacio
para el objeto, y luego hacer solo la inicialización adicional que sea absolutamente necesaria. La inicialización que
se puede ignorar o repetir de forma segura debe colocarse en el controlador tp_init. Una buena regla general

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


The Python/C API, Versión 3.13.0a5

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:
Este campo es heredado por subtipos estáticos, pero no por subtipos dinámicos (subtipos creados por una declara-
ción de clase)
Por defecto:
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.

12.3. Objetos tipo 309


The Python/C API, Versión 3.13.0a5

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

Herencia:
Este campo no se hereda.
PyObject *PyTypeObject.tp_mro
Tupla que contiene el conjunto expandido de tipos base, comenzando con el tipo en sí y terminando con object,
en orden de resolución de método.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
Herencia:
Este campo no se hereda; se calcula fresco por PyType_Ready().
PyObject *PyTypeObject.tp_cache
No usado. Solo para uso interno.
Herencia:
Este campo no se hereda.
void *PyTypeObject.tp_subclasses
A collection of subclasses. Internal use only. May be an invalid pointer.
To get a list of subclasses, call the Python method __subclasses__().
Distinto en la versión 3.12: For some types, this field does not hold a valid PyObject*. The type was changed to
void* to indicate this.
Herencia:
Este campo no se hereda.
PyObject *PyTypeObject.tp_weaklist
Cabecera de lista de referencia débil, para referencias débiles a este tipo de objeto. No heredado Solo para uso
interno.
Distinto en la versión 3.12: Internals detail: For the static builtin types this is always NULL, even if weakrefs are
added. Instead, the weakrefs for each are stored on PyInterpreterState. Use the public C-API or the internal
_PyObject_GET_WEAKREFS_LISTPTR() macro to avoid the distinction.
Herencia:
Este campo no se hereda.
destructor PyTypeObject.tp_del
Este campo está en desuso. Use tp_finalize en su lugar.
unsigned int PyTypeObject.tp_version_tag
Se usa para indexar en el caché de métodos. Solo para uso interno.
Herencia:
Este campo no se hereda.
destructor PyTypeObject.tp_finalize
Un puntero opcional a una función de finalización de instancia. Su firma es:

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


The Python/C API, Versión 3.13.0a5

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

12.3. Objetos tipo 311


The Python/C API, Versión 3.13.0a5

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 mo-
dificar los atributos del objeto tipo desde Python.
• Los objetos de tipo estático se comparten en sub intérpretes, por lo que no deben incluir ningún estado específico
del sub interpretador.
Also, since PyTypeObject is only part of the Limited API as an opaque struct, any extension modules using static types
must be compiled for a specific Python minor version.

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

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

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


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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.

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

12.4. Estructuras de objetos de números 313


The Python/C API, Versión 3.13.0a5

binaryfunc PyNumberMethods.nb_rshift

binaryfunc PyNumberMethods.nb_and

binaryfunc PyNumberMethods.nb_xor

binaryfunc PyNumberMethods.nb_or

unaryfunc PyNumberMethods.nb_int

void *PyNumberMethods.nb_reserved

unaryfunc PyNumberMethods.nb_float

binaryfunc PyNumberMethods.nb_inplace_add

binaryfunc PyNumberMethods.nb_inplace_subtract

binaryfunc PyNumberMethods.nb_inplace_multiply

binaryfunc PyNumberMethods.nb_inplace_remainder

ternaryfunc PyNumberMethods.nb_inplace_power

binaryfunc PyNumberMethods.nb_inplace_lshift

binaryfunc PyNumberMethods.nb_inplace_rshift

binaryfunc PyNumberMethods.nb_inplace_and

binaryfunc PyNumberMethods.nb_inplace_xor

binaryfunc PyNumberMethods.nb_inplace_or

binaryfunc PyNumberMethods.nb_floor_divide

binaryfunc PyNumberMethods.nb_true_divide

binaryfunc PyNumberMethods.nb_inplace_floor_divide

binaryfunc PyNumberMethods.nb_inplace_true_divide

unaryfunc PyNumberMethods.nb_index

binaryfunc PyNumberMethods.nb_matrix_multiply

binaryfunc PyNumberMethods.nb_inplace_matrix_multiply

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.

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


The Python/C API, Versión 3.13.0a5

binaryfunc PyMappingMethods.mp_subscript
Esta función es utilizada por PyObject_GetItem() y PySequence_GetSlice(), y tiene la misma firma
que PyObject_GetItem(). Este espacio debe llenarse para que la función PyMapping_Check() retorna
1, de lo contrario puede ser NULL.
objobjargproc PyMappingMethods.mp_ass_subscript
This function is used by PyObject_SetItem(), PyObject_DelItem(), PySequence_SetSlice()
and PySequence_DelSlice(). It has the same signature as PyObject_SetItem(), but v can also be set
to NULL to delete an item. If this slot is NULL, the object does not support item assignment and deletion.

12.6 Estructuras de objetos secuencia

type PySequenceMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo de secuencia.
lenfunc PySequenceMethods.sq_length
Esta función es utilizada por PySequence_Size() y PyObject_Size(), y tiene la misma firma. También
se usa para manejar índices negativos a través de los espacios sq_item y sq_ass_item.
binaryfunc PySequenceMethods.sq_concat
Esta función es utilizada por PySequence_Concat() y tiene la misma firma. También es utilizado por el
operador +, después de intentar la suma numérica a través de la ranura nb_add.
ssizeargfunc PySequenceMethods.sq_repeat
Esta función es utilizada por PySequence_Repeat() y tiene la misma firma. También es utilizado por el
operador *, después de intentar la multiplicación numérica a través de la ranura nb_multiply.
ssizeargfunc PySequenceMethods.sq_item
Esta función es utilizada por PySequence_GetItem() y tiene la misma firma. También es utilizado por
PyObject_GetItem(), después de intentar la suscripción a través de la ranura mp_subscript. Este es-
pacio debe llenarse para que la función PySequence_Check() retorna 1, de lo contrario puede ser NULL.
Negative indexes are handled as follows: if the sq_length slot is filled, it is called and the sequence length is
used to compute a positive index which is passed to sq_item. If sq_length is NULL, the index is passed as is
to the function.
ssizeobjargproc PySequenceMethods.sq_ass_item
Esta función es utilizada por PySequence_SetItem() y tiene la misma firma. También lo usan
PyObject_SetItem() y PyObject_DelItem(), después de intentar la asignación y eliminación del ele-
mento a través de la ranura mp_ass_subscript. Este espacio puede dejarse en NULL si el objeto no admite
la asignación y eliminación de elementos.
objobjproc PySequenceMethods.sq_contains
Esta función puede ser utilizada por PySequence_Contains() y tiene la misma firma. Este espacio pue-
de dejarse en NULL, en este caso PySequence_Contains() simplemente atraviesa la secuencia hasta que
encuentra una coincidencia.
binaryfunc PySequenceMethods.sq_inplace_concat
Esta función es utilizada por PySequence_InPlaceConcat() y tiene la misma firma. Debe-
ría modificar su primer operando y retornarlo. Este espacio puede dejarse en NULL, en este caso
PySequence_InPlaceConcat() volverá a PySequence_Concat(). También es utilizado por la asig-
nación aumentada +=, después de intentar la suma numérica en el lugar a través de la ranura nb_inplace_add.

12.6. Estructuras de objetos secuencia 315


The Python/C API, Versión 3.13.0a5

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

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ándar de esta función tomará
estos pasos opcionales:

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


The Python/C API, Versión 3.13.0a5

(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

Nuevo en la versión 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);

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:

12.8. Estructuras de objetos asíncronos 317


The Python/C API, Versión 3.13.0a5

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

Consulte PyIter_Send() para obtener más detalles. Esta ranura se puede establecer en NULL.
Nuevo en la versión 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 initialization. It
should return a pointer to a block of memory of adequate length for the instance, suitably aligned, 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.
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.

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


The Python/C API, Versión 3.13.0a5

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.

12.9. Tipo Ranura typedefs 319


The Python/C API, Versión 3.13.0a5

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 */
(continúe en la próxima página)

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


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
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
(continúe en la próxima página)

12.10. Ejemplos 321


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


} 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:

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 imple-
mentation must also be provided.
Py_TPFLAGS_HAVE_GC
Los objetos con un tipo con este indicador establecido deben cumplir con las reglas documentadas aquí. Por con-
veniencia, estos objetos se denominarán objetos contenedor.
Los constructores para tipos de contenedores deben cumplir con dos reglas:
1. The memory for the object must be allocated using PyObject_GC_New or PyObject_GC_NewVar.
2. Una vez que se inicializan todos los campos que pueden contener referencias a otros contenedores, debe llamar a
PyObject_GC_Track().
Del mismo modo, el desasignador (deallocator) para el objeto debe cumplir con un par similar de reglas:
1. Antes de invalidar los campos que se refieren a otros contenedores, debe llamarse PyObject_GC_UnTrack().
2. La memoria del objeto debe ser desasignada (deallocated) usando PyObject_GC_Del().

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


jado 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

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


The Python/C API, Versión 3.13.0a5

implements the garbage collector protocol and the child class does not include the Py_TPFLAGS_HAVE_GC
flag.

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

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.

Nuevo en la versión 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 se-
guimiento. 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().
Nuevo en la versión 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.

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


The Python/C API, Versión 3.13.0a5

Esto es análogo a la función de Python gc.is_finalized().


Nuevo en la versión 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 basu-
ra. 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.
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 inmutables
no tienen que definir este método ya que nunca pueden crear directamente ciclos de referencia. Tenga en cuenta que
el objeto aún debe ser válido después de llamar a este método (no solo llame a Py_DECREF() en una referencia).
El recolector de basura llamará a este método si detecta que este objeto está involucrado en un ciclo de referencia.

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


The Python/C API, Versión 3.13.0a5

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.
Nuevo en la versión 3.10.
int PyGC_Disable(void)
Part of the Stable ABI since version 3.10. Deshabilita el recolector de basura: similar a gc.disable(). Retorna
el estado anterior, 0 para deshabilitado y 1 para habilitado.
Nuevo en la versión 3.10.
int PyGC_IsEnabled(void)
Part of the Stable ABI since version 3.10. Consulta el estado del recolector de basura: similar a gc.isenabled().
Retorna el estado actual, 0 para deshabilitado y 1 para habilitado.
Nuevo en la versión 3.10.

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.

Nuevo en la versión 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.
Nuevo en la versión 3.12.

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


The Python/C API, Versión 3.13.0a5

326 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 siguiente
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

327
The Python/C API, Versión 3.13.0a5

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 >= ....
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.
Nuevo en la versión 3.11.
Todas las macros dadas se definen en Include/patchlevel.h.

328 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.
clase base abstracta
Las clases base abstractas (ABC, por sus siglas en inglés Abstract Base Class) complementan al duck-typing brindan-
do un forma de definir interfaces con técnicas como hasattr() que serían confusas o sutilmente erróneas (por
ejemplo con magic methods). Las ABC introduce subclases virtuales, las cuales son clases que no heredan desde una
clase pero aún así son reconocidas por isinstance() y issubclass(); vea la documentación del módulo
abc. Python viene con muchas ABC incorporadas para las estructuras de datos( en el módulo collections.
abc), números (en el módulo numbers ) , flujos de datos (en el módulo io ) , buscadores y cargadores de
importaciones (en el módulo importlib.abc ) . Puede crear sus propios ABCs con el módulo abc.
anotación
Una etiqueta asociada a una variable, atributo de clase, parámetro de función o valor de retorno, usado por con-
vención como un type hint.
Las anotaciones de variables no pueden ser accedidas en tiempo de ejecución, pero las anotaciones de variables
globales, atributos de clase, y funciones son almacenadas en el atributo especial __annotations__ de módulos,
clases y funciones, respectivamente.
Consulte variable annotation, function annotation, PEP 484 y PEP 526, que describen esta funcionalidad. Consulte
también annotations-howto para conocer las mejores prácticas sobre cómo trabajar con anotaciones.
argumento
Un valor pasado a una function (o method) cuando se llama a la función. Hay dos clases de argumentos:

329
The Python/C API, Versión 3.13.0a5

• argumento nombrado: es un argumento precedido por un identificador (por ejemplo, nombre=) en una llama-
da a una función o pasado como valor en un diccionario precedido por **. Por ejemplo 3 y 5 son argumentos
nombrados en las llamadas a complex():

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

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

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

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

330 Apéndice A. Glosario


The Python/C API, Versión 3.13.0a5

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

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.

331
The Python/C API, Versión 3.13.0a5

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

332 Apéndice A. Glosario


The Python/C API, Versión 3.13.0a5

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

@staticmethod
def f(arg):
...

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

333
The Python/C API, Versión 3.13.0a5

acumulación de elementos de expresión tales como literales, nombres, accesos a atributos, operadores o llamadas
a funciones, todos ellos retornando valor. A diferencia de otros lenguajes, no toda la sintaxis del lenguaje son
expresiones. También hay statements que no pueden ser usadas como expresiones, como la while. Las asignaciones
también son sentencias, no expresiones.
módulo de extensión
Un módulo escrito en C o C++, usando la API para C de Python para interactuar con el núcleo y el código del
usuario.
f-string
Son llamadas f-strings las cadenas literales que usan el prefijo 'f' o 'F', que es una abreviatura para formatted
string literals. Vea también PEP 498.
objeto archivo
An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.
Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of
storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.). File
objects are also called file-like objects or streams.
Existen tres categorías de objetos archivo: crudos raw archivos binarios, con búfer archivos binarios y archivos de
texto. Sus interfaces son definidas en el módulo io. La forma canónica de crear objetos archivo es usando la función
open().
objetos tipo archivo
Un sinónimo de file object.
codificación del sistema de archivos y manejador de errores
Controlador de errores y codificación utilizado por Python para decodificar bytes del sistema operativo y codificar
Unicode en el sistema operativo.
La codificación del sistema de archivos debe garantizar la decodificación exitosa de todos los bytes por debajo de
128. Si la codificación del sistema de archivos no proporciona esta garantía, las funciones de API pueden lanzar
UnicodeError.
Las funciones sys.getfilesystemencoding() y sys.getfilesystemencodeerrors() se pue-
den utilizar para obtener la codificación del sistema de archivos y el controlador de errores.
La codificación del sistema de archivos y el manejador de errores se configuran al inicio de Python mediante la
función PyConfig_Read(): consulte los miembros filesystem_encoding y filesystem_errors
de PyConfig.
Vea también locale encoding.
buscador
Un objeto que trata de encontrar el loader para el módulo que está siendo importado.
Desde la versión 3.3 de Python, existen dos tipos de buscadores: meta buscadores de ruta para usar con sys.
meta_path, y buscadores de entradas de rutas para usar con sys.path_hooks.
Vea PEP 302, PEP 420 y PEP 451 para mayores detalles.
división entera a la baja
Una división matemática que se redondea hacia el entero menor más cercano. El operador de la división entera
a la baja es //. Por ejemplo, la expresión 11 // 4 evalúa 2 a diferencia del 2.75 retornado por la verdadera
división de números flotantes. Note que (-11) // 4 es -3 porque es -2.75 redondeado para abajo. Ver PEP
238.
función
Una serie de sentencias que retornan un valor al que las llama. También se le puede pasar cero o más argumentos
los cuales pueden ser usados en la ejecución de la misma. Vea también parameter, method, y la sección function.

334 Apéndice A. Glosario


The Python/C API, Versión 3.13.0a5

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 Python. 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:

>>> 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 co-
llection) llevando la cuenta de las referencias, y el recogedor de basura cíclico es capaz de detectar y romper las
referencias cíclicas. El recogedor de basura puede ser controlado mediante el módulo gc .
generador
Una función que retorna un generator iterator. Luce como una función normal excepto que contiene la expresión
yield para producir series de valores utilizables en un bucle for o que pueden ser obtenidas una por una con la
función next().
Usualmente se refiere a una función generadora, pero puede referirse a un iterador generador en ciertos contextos.
En aquellos casos en los que el significado no está claro, usar los términos completos evita la ambigüedad.
iterador generador
Un objeto creado por una función generator.
Cada yield suspende temporalmente el procesamiento, recordando el estado de ejecución local (incluyendo las
variables locales y las sentencias try pendientes). Cuando el «iterador generado» vuelve, retoma donde ha dejado,
a diferencia de lo que ocurre con las funciones que comienzan nuevamente con cada invocación.
expresión generadora
An expression that returns an iterator. It looks like a normal expression followed by a for clause defining a loop
variable, range, and an optional if clause. The combined expression generates values for an enclosing function:

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

335
The Python/C API, Versión 3.13.0a5

tipos genéricos
Un type que se puede parametrizar; normalmente un container class como list o dict. Usado para type hints y
annotations.
Para más detalles, véase generic alias types, PEP 483, PEP 484, PEP 585, y el módulo typing.
GIL
Vea global interpreter lock.
bloqueo global del intérprete
Mecanismo empleado por el intérprete CPython para asegurar que sólo un hilo ejecute el bytecode Python por
vez. Esto simplifica la implementación de CPython haciendo que el modelo de objetos (incluyendo algunos críticos
como dict) están implícitamente a salvo de acceso concurrente. Bloqueando el intérprete completo se simplifica
hacerlo multi-hilos, a costa de mucho del paralelismo ofrecido por las máquinas con múltiples procesadores.
Sin embargo, algunos módulos de extensión, tanto estándar como de terceros, están diseñados para liberar el GIL
cuando se realizan tareas computacionalmente intensivas como la compresión o el hashing. Además, el GIL siempre
es liberado cuando se hace entrada/salida.
Esfuerzos previos hechos para crear un intérprete «sin hilos» (uno que bloquee los datos compartidos con una
granularidad mucho más fina) no han sido exitosos debido a que el rendimiento sufrió para el caso más común
de un solo procesador. Se cree que superar este problema de rendimiento haría la implementación mucho más
compleja y por tanto, más costosa de mantener.
hash-based pyc
Un archivo cache de bytecode que usa el hash en vez de usar el tiempo de la última modificación del archivo fuente
correspondiente para determinar su validez. Vea pyc-invalidation.
hashable
An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__()
method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare
equal must have the same hash value.
Ser hashable hace a un objeto utilizable como clave de un diccionario y miembro de un set, porque éstas estructuras
de datos usan los valores de hash internamente.
La mayoría de los objetos inmutables incorporados en Python son hashables; los contenedores mutables (como las
listas o los diccionarios) no lo son; los contenedores inmutables (como tuplas y conjuntos frozensets) son hashables
si sus elementos son hashables . Los objetos que son instancias de clases definidas por el usuario son hashables
por defecto. Todos se comparan como desiguales (excepto consigo mismos), y su valor de hash está derivado de su
función id().
IDLE
Un Entorno Integrado de Desarrollo y Aprendizaje para Python. idle es un editor básico y un entorno de intérprete
que se incluye con la distribución estándar de Python.
immortal
If an object is immortal, its reference count is never modified, and therefore it is never deallocated.
Built-in strings and singletons are immortal objects. For example, True and None singletons are immmortal.
See PEP 683 – Immortal Objects, Using a Fixed Refcount for more information.
inmutable
Un objeto con un valor fijo. Los objetos inmutables son números, cadenas y tuplas. Éstos objetos no pueden ser
alterados. Un nuevo objeto debe ser creado si un valor diferente ha de ser guardado. Juegan un rol importante en
lugares donde es necesario un valor de hash constante, por ejemplo como claves de un diccionario.
ruta de importación
Una lista de las ubicaciones (o entradas de ruta) que son revisadas por path based finder al importar módulos.

336 Apéndice A. Glosario


The Python/C API, Versión 3.13.0a5

Durante la importación, ésta lista de localizaciones usualmente viene de sys.path, pero para los subpaquetes
también puede incluir al atributo __path__ del paquete padre.
importar
El proceso mediante el cual el código Python dentro de un módulo se hace alcanzable desde otro código Python en
otro módulo.
importador
Un objeto que buscan y lee un módulo; un objeto que es tanto finder como loader.
interactivo
Python tiene un intérprete interactivo, lo que significa que puede ingresar sentencias y expresiones en el prompt del
intérprete, ejecutarlos de inmediato y ver sus resultados. Sólo ejecute python sin argumentos (podría seleccionarlo
desde el menú principal de su computadora). Es una forma muy potente de probar nuevas ideas o inspeccionar
módulos y paquetes (recuerde help(x)).
interpretado
Python es un lenguaje interpretado, a diferencia de uno compilado, a pesar de que la distinción puede ser difusa
debido al compilador a bytecode. Esto significa que los archivos fuente pueden ser corridos directamente, sin crear
explícitamente un ejecutable que es corrido luego. Los lenguajes interpretados típicamente tienen ciclos de desa-
rrollo y depuración más cortos que los compilados, sin embargo sus programas suelen correr más lentamente. Vea
también interactive.
apagado del intérprete
Cuando se le solicita apagarse, el intérprete Python ingresa a un fase especial en la cual gradualmente libera todos los
recursos reservados, como módulos y varias estructuras internas críticas. También hace varias llamadas al recolector
de basura. Esto puede disparar la ejecución de código de destructores definidos por el usuario o weakref callbacks.
El código ejecutado durante la fase de apagado puede encontrar varias excepciones debido a que los recursos que
necesita pueden no funcionar más (ejemplos comunes son los módulos de bibliotecas o los artefactos de advertencias
warnings machinery)
La principal razón para el apagado del intérpreter es que el módulo __main__ o el script que estaba corriendo
termine su ejecución.
iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such
as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you
define with an __iter__() method or with a __getitem__() method that implements sequence semantics.
Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), …).
When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the
object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to
call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating
a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and
generator.
iterador
An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it
to the built-in function next()) return successive items in the stream. When no more data are available a
StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls
to its __next__() method just raise StopIteration again. Iterators are required to have an __iter__()
method that returns the iterator object itself so every iterator is also iterable and may be used in most places where
other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container
object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a
for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous
iteration pass, making it appear like an empty container.
Puede encontrar más información en typeiter.

337
The Python/C API, Versión 3.13.0a5

Detalles de implementación de CPython: CPython does not consistently apply the requirement that an iterator
define __iter__().
función clave
Una función clave o una función de colación es un invocable que retorna un valor usado para el ordenamiento o
clasificación. Por ejemplo, locale.strxfrm() es usada para producir claves de ordenamiento que se adaptan
a las convenciones específicas de ordenamiento de un locale.
Cierta cantidad de herramientas de Python aceptan funciones clave para controlar como los elementos son orde-
nados o agrupados. Incluyendo a min(), max(), sorted(), list.sort(), heapq.merge(), heapq.
nsmallest(), heapq.nlargest(), y itertools.groupby().
Hay varias formas de crear una función clave. Por ejemplo, el método str.lower() puede servir como fun-
ción clave para ordenamientos que no distingan mayúsculas de minúsculas. Como alternativa, una función clave
puede ser realizada con una expresión lambda como lambda r: (r[0], r[2]). Además, operator.
attrgetter(), operator.itemgetter() y operator.methodcaller() son tres constructores de
funciones clave. Consulte Sorting HOW TO para ver ejemplos de cómo crear y utilizar funciones clave.
argumento nombrado
Vea argument.
lambda
Una función anónima de una línea consistente en un sola expression que es evaluada cuando la función es llamada.
La sintaxis para crear una función lambda es lambda [parameters]: expression
LBYL
Del inglés Look before you leap, «mira antes de saltar». Es un estilo de codificación que prueba explícitamente
las condiciones previas antes de hacer llamadas o búsquedas. Este estilo contrasta con la manera EAFP y está
caracterizado por la presencia de muchas sentencias if.
En entornos multi-hilos, el método LBYL tiene el riesgo de introducir condiciones de carrera entre los hilos
que están «mirando» y los que están «saltando». Por ejemplo, el código, if key in mapping: return
mapping[key] puede fallar si otro hilo remueve key de mapping después del test, pero antes de retornar el
valor. Este problema puede ser resuelto usando bloqueos o empleando el método EAFP.
codificación de la configuración regional
En Unix, es la codificación de la configuración regional LC_CTYPE. Se puede configurar con locale.
setlocale(locale.LC_CTYPE, new_locale).
En Windows, es la página de códigos ANSI (por ejemplo, "cp1252").
En Android y VxWorks, Python utiliza "utf-8" como codificación regional.
locale.getencoding() se puede utilizar para obtener la codificación de la configuración regional.
Vea también filesystem encoding and error handler.
lista
A built-in Python sequence. Despite its name it is more akin to an array in other languages than to a linked list since
access to elements is O(1).
comprensión de listas
Una forma compacta de procesar todos o parte de los elementos en una secuencia y retornar una lista como re-
sultado. result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] genera
una lista de cadenas conteniendo números hexadecimales (0x..) entre 0 y 255. La cláusula if es opcional. Si es
omitida, todos los elementos en range(256) son procesados.
cargador
Un objeto que carga un módulo. Debe definir el método llamado load_module(). Un cargador es normalmente
retornados por un finder. Vea PEP 302 para detalles y importlib.abc.Loader para una abstract base class.

338 Apéndice A. Glosario


The Python/C API, Versión 3.13.0a5

método mágico
Una manera informal de llamar a un special method.
mapeado
Un objeto contenedor que permite recupero de claves arbitrarias y que implementa los métodos especificados
en la collections.abc.Mapping o collections.abc.MutableMapping abstract base classes.
Por ejemplo, dict, collections.defaultdict, collections.OrderedDict y collections.
Counter.
meta buscadores de ruta
Un finder retornado por una búsqueda de sys.meta_path. Los meta buscadores de ruta están relacionados a
buscadores de entradas de rutas, pero son algo diferente.
Vea en importlib.abc.MetaPathFinder los métodos que los meta buscadores de ruta implementan.
metaclase
La clase de una clase. Las definiciones de clases crean nombres de clase, un diccionario de clase, y una lista de
clases base. Las metaclases son responsables de tomar estos tres argumentos y crear la clase. La mayoría de los
objetos de un lenguaje de programación orientado a objetos provienen de una implementación por defecto. Lo que
hace a Python especial que es posible crear metaclases a medida. La mayoría de los usuario nunca necesitarán esta
herramienta, pero cuando la necesidad surge, las metaclases pueden brindar soluciones poderosas y elegantes. Han
sido usadas para loggear acceso de atributos, agregar seguridad a hilos, rastrear la creación de objetos, implementar
singletons, y muchas otras tareas.
Más información hallará en metaclasses.
método
Una función que es definida dentro del cuerpo de una clase. Si es llamada como un atributo de una instancia de otra
clase, el método tomará el objeto instanciado como su primer argument (el cual es usualmente denominado self).
Vea function y nested scope.
orden de resolución de métodos
Orden de resolución de métodos es el orden en el cual una clase base es buscada por un miembro durante la
búsqueda. Mire en The Python 2.3 Method Resolution Order los detalles del algoritmo usado por el intérprete
Python desde la versión 2.3.
módulo
Un objeto que sirve como unidad de organización del código Python. Los módulos tienen espacios de nombres
conteniendo objetos Python arbitrarios. Los módulos son cargados en Python por el proceso de importing.
Vea también package.
especificador de módulo
Un espacio de nombres que contiene la información relacionada a la importación usada al leer un módulo. Una
instancia de importlib.machinery.ModuleSpec.
MRO
Vea method resolution order.
mutable
Los objetos mutables pueden cambiar su valor pero mantener su id(). Vea también immutable.
tupla nombrada
La denominación «tupla nombrada» se aplica a cualquier tipo o clase que hereda de una tupla y cuyos elemen-
tos indexables son también accesibles usando atributos nombrados. Este tipo o clase puede tener además otras
capacidades.
Varios tipos incorporados son tuplas nombradas, incluyendo los valores retornados por time.localtime() y
os.stat(). Otro ejemplo es sys.float_info:

339
The Python/C API, Versión 3.13.0a5

>>> 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étodos).
Los espacios de nombres soportan modularidad previniendo conflictos de nombramiento. Por ejemplo, las funciones
builtins.open y os.open() se distinguen por su espacio de nombres. Los espacios de nombres también
ayuda a la legibilidad y mantenibilidad dejando claro qué módulo implementa una función. Por ejemplo, escribiendo
random.seed() o itertools.islice() queda claro que éstas funciones están implementadas en los
módulos random y itertools, respectivamente.
paquete de espacios de nombres
Un PEP 420 package que sirve sólo para contener subpaquetes. Los paquetes de espacios de nombres pueden no
tener representación física, y específicamente se diferencian de los regular package porque no tienen un archivo
__init__.py.
Vea también module.
alcances anidados
La habilidad de referirse a una variable dentro de una definición encerrada. Por ejemplo, una función definida
dentro de otra función puede referir a variables en la función externa. Note que los alcances anidados por defecto
sólo funcionan para referencia y no para asignación. Las variables locales leen y escriben sólo en el alcance más
interno. De manera semejante, las variables globales pueden leer y escribir en el espacio de nombres global. Con
nonlocal se puede escribir en alcances exteriores.
clase de nuevo estilo
Old name for the flavor of classes now used for all class objects. In earlier Python versions, only new-style classes
could use Python’s newer, versatile features like __slots__, descriptors, properties, __getattribute__(),
class methods, and static methods.
objeto
Cualquier dato con estado (atributo o valor) y comportamiento definido (métodos). También es la más básica clase
base para cualquier new-style class.
paquete
Un module Python que puede contener submódulos o recursivamente, subpaquetes. Técnicamente, un paquete es
un módulo Python con un atributo __path__.
Vea también regular package y namespace package.
parámetro
Una entidad nombrada en una definición de una function (o método) que especifica un argument (o en algunos
casos, varios argumentos) que la función puede aceptar. Existen cinco tipos de argumentos:
• posicional o nombrado: especifica un argumento que puede ser pasado tanto como posicional o como nom-
brado. Este es el tipo por defecto de parámetro, como foo y bar en el siguiente ejemplo:

340 Apéndice A. Glosario


The Python/C API, Versión 3.13.0a5

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 po-
sicionales pueden ser definidos incluyendo un carácter / en la lista de parámetros de la función después de
ellos, como posonly1 y posonly2 en el ejemplo que sigue:

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 brindados
(además de cualquier argumento posicional aceptado por otros parámetros). Este parámetro puede ser definido
anteponiendo al nombre del parámetro *, como a args en el siguiente ejemplo:

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 pue-
de ser definido anteponiendo al nombre del parámetro con **, como kwargs en el ejemplo precedente.
Los parámetros puede especificar tanto argumentos opcionales como requeridos, así como valores por defecto para
algunos argumentos opcionales.
Vea también el glosario de argument, la pregunta respondida en la diferencia entre argumentos y parámetros, la
clase inspect.Parameter, la sección function , y PEP 362.
entrada de ruta
Una ubicación única en el import path que el path based finder consulta para encontrar los módulos a importar.
buscador de entradas de ruta
Un finder retornado por un invocable en sys.path_hooks (esto es, un path entry hook) que sabe cómo localizar
módulos dada una path entry.
Vea en importlib.abc.PathEntryFinder los métodos que los buscadores de entradas de ruta implemen-
tan.
gancho a entrada de ruta
A callable on the sys.path_hooks list which returns a path entry finder if it knows how to find modules on a
specific path entry.
buscador basado en ruta
Uno de los meta buscadores de ruta por defecto que busca un import path para los módulos.
objeto tipo ruta
Un objeto que representa una ruta del sistema de archivos. Un objeto tipo ruta puede ser tanto una str como un
bytes representando una ruta, o un objeto que implementa el protocolo os.PathLike. Un objeto que soporta
el protocolo os.PathLike puede ser convertido a ruta del sistema de archivo de clase str o bytes usando la
función os.fspath(); os.fsdecode() os.fsencode() pueden emplearse para garantizar que retorne
respectivamente str o bytes. Introducido por PEP 519.
PEP
Propuesta de mejora de Python, del inglés Python Enhancement Proposal. Un PEP es un documento de diseño que
brinda información a la comunidad Python, o describe una nueva capacidad para Python, sus procesos o entorno.
Los PEPs deberían dar una especificación técnica concisa y una fundamentación para las capacidades propuestas.

341
The Python/C API, Versión 3.13.0a5

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

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

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:

>>> class C:
... class D:
... def meth(self):
... pass
...
(continúe en la próxima página)

342 Apéndice A. Glosario


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


>>> 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
The number of references to an object. When the reference count of an object drops to zero, it is deallocated.
Some objects are immortal and have reference counts that are never modified, and therefore the objects are never
deallocated. Reference counting is generally not visible to Python code, but it is a key element of the CPython
implementation. Programmers can call the sys.getrefcount() function to return the reference count for a
particular object.
paquete regular
Un package tradicional, como aquellos con un directorio conteniendo el archivo __init__.py.
Vea también namespace package.
__slots__
Es una declaración dentro de una clase que ahorra memoria predeclarando espacio para las atributos de la instancia
y eliminando diccionarios de la instancia. Aunque es popular, esta técnica es algo dificultosa de lograr correctamente
y es mejor reservarla para los casos raros en los que existen grandes cantidades de instancias en aplicaciones con
uso crítico de memoria.
secuencia
An iterable which supports efficient element access using integer indices via the __getitem__() special method
and defines a __len__() method that returns the length of the sequence. Some built-in sequence types are list,
str, tuple, and bytes. Note that dict also supports __getitem__() and __len__(), but is considered
a mapping rather than a sequence because the lookups use arbitrary immutable keys rather than integers.
The collections.abc.Sequence abstract base class defines a much richer interface that goes be-
yond just __getitem__() and __len__(), adding count(), index(), __contains__(), and
__reversed__(). Types that implement this expanded interface can be registered explicitly using
register(). For more documentation on sequence methods generally, see Common Sequence Operations.
comprensión de conjuntos
Una forma compacta de procesar todos o parte de los elementos en un iterable y retornar un conjunto con los
resultados. results = {c for c in 'abracadabra' if c not in 'abc'} genera el conjunto
de cadenas {'r', 'd'}. Ver comprehensions.
despacho único
Una forma de despacho de una generic function donde la implementación es elegida a partir del tipo de un sólo
argumento.
rebanada
Un objeto que contiene una porción de una sequence. Una rebanada es creada usando la notación de suscripto, []
con dos puntos entre los números cuando se ponen varios, como en nombre_variable[1:3:5]. La notación
con corchete (suscrito) usa internamente objetos slice.

343
The Python/C API, Versión 3.13.0a5

soft deprecated
A soft deprecation can be used when using an API which should no longer be used to write new code, but it remains
safe to continue using it in existing code. The API remains documented and tested, but will not be developed further
(no enhancement).
The main difference between a «soft» and a (regular) «hard» deprecation is that the soft deprecation does not imply
scheduling the removal of the deprecated API.
Another difference is that a soft deprecation does not issue a warning.
See PEP 387: Soft Deprecation.
método especial
Un método que es llamado implícitamente por Python cuando ejecuta ciertas operaciones en un tipo, como la
adición. Estos métodos tienen nombres que comienzan y terminan con doble barra baja. Los métodos especiales
están documentados en specialnames.
sentencia
Una sentencia es parte de un conjunto (un «bloque» de código). Una sentencia tanto es una expression como alguna
de las varias sintaxis usando una palabra clave, como if, while o for.
static type checker
An external tool that reads Python code and analyzes it, looking for issues such as incorrect types. See also type
hints and the typing module.
referencia fuerte
En la API de C de Python, una referencia fuerte es una referencia a un objeto que es propiedad del código que
mantiene la referencia. La referencia fuerte se toma llamando a Py_INCREF() cuando se crea la referencia y se
libera con Py_DECREF() cuando se elimina la referencia.
La función Py_NewRef() se puede utilizar para crear una referencia fuerte a un objeto. Por lo general, se debe
llamar a la función Py_DECREF() en la referencia fuerte antes de salir del alcance de la referencia fuerte, para
evitar filtrar una referencia.
Consulte también borrowed reference.
codificación de texto
Una cadena de caracteres en Python es una secuencia de puntos de código Unicode (en el rango U+0000–
U+10FFFF). Para almacenar o transferir una cadena de caracteres, es necesario serializarla como una secuencia
de bytes.
La serialización de una cadena de caracteres en una secuencia de bytes se conoce como «codificación», y la re-
creación de la cadena de caracteres a partir de la secuencia de bytes se conoce como «decodificación».
Existe una gran variedad de serializaciones de texto codecs, que se denominan colectivamente «codificaciones de
texto».
archivo de texto
Un file object capaz de leer y escribir objetos str. Frecuentemente, un archivo de texto también accede a un flujo
de datos binario y maneja automáticamente el text encoding. Ejemplos de archivos de texto que son abiertos en
modo texto ('r' o 'w'), sys.stdin, sys.stdout, y las instancias de io.StringIO.
Vea también binary file por objeto de archivos capaces de leer y escribir objeto tipo binario.
cadena con triple comilla
Una cadena que está enmarcada por tres instancias de comillas (») o apostrofes (“). Aunque no brindan ninguna
funcionalidad que no está disponible usando cadenas con comillas simple, son útiles por varias razones. Permiten
incluir comillas simples o dobles sin escapar dentro de las cadenas y pueden abarcar múltiples líneas sin el uso de
caracteres de continuación, haciéndolas particularmente útiles para escribir docstrings.

344 Apéndice A. Glosario


The Python/C API, Versión 3.13.0a5

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]

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 convenció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 instalar
y actualizar paquetes de distribución de Python sin interferir con el comportamiento de otras aplicaciones de Python
en el mismo sistema.

345
The Python/C API, Versión 3.13.0a5

Vea también venv.


máquina virtual
Una computadora definida enteramente por software. La máquina virtual de Python ejecuta el bytecode generado
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.

346 Apéndice A. Glosario


APÉNDICE B

Acerca de estos documentos

Estos documentos son generados por reStructuredText desarrollado por Sphinx, un procesador de documentos específi-
camente escrito para la documentación de Python.
El desarrollo de la documentación y su cadena de herramientas es un esfuerzo enteramente voluntario, al igual que Python.
Si tu quieres contribuir, por favor revisa la página reporting-bugs para más información de cómo hacerlo. Los nuevos
voluntarios son siempre bienvenidos!
Agradecemos a:
• Fred L. Drake, Jr., el creador original de la documentación del conjunto de herramientas de Python y escritor de
gran parte del contenido;
• el proyecto Docutils para creación de reStructuredText y la suite Docutils;
• Fredrik Lundh por su proyecto Referencia Alternativa de Python del que Sphinx obtuvo muchas buenas ideas.

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 documentación
– Muchas gracias!

347
The Python/C API, Versión 3.13.0a5

348 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í

349
The Python/C API, Versión 3.13.0a5

Nota: Compatible con GPL no significa que estemos distribuyendo Python bajo la GPL. Todas las licencias de Python,
a diferencia de la GPL, le permiten distribuir una versión modificada sin que los cambios sean de código abierto. Las
licencias compatibles con GPL permiten combinar Python con otro software que se publica bajo la GPL; los otros no lo
hacen.

Gracias a los muchos voluntarios externos que han trabajado bajo la dirección de Guido para hacer posibles estos lanza-
mientos.

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 corres-
pondiente 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.13.0a5 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.13.0a5 alone or in any derivative
version, provided, however, that PSF's License Agreement and PSF's notice␣
,→of

copyright, i.e., "Copyright © 2001-2024 Python Software Foundation; All␣


,→Rights

Reserved" are retained in Python 3.13.0a5 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.13.0a5 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.13.0a5.

4. PSF is making Python 3.13.0a5 available to Licensee on an "AS IS" basis.


PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF

350 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.13.0a5

EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION␣
,→OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT␣
,→THE

USE OF PYTHON 3.13.0a5 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.13.0a5
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT␣
,→OF

MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.13.0a5, 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.13.0a5, 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,
(continúe en la próxima página)

C.2. Términos y condiciones para acceder o usar Python 351


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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
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
(continúe en la próxima página)

352 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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
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. Términos y condiciones para acceder o usar Python 353


The Python/C API, Versión 3.13.0a5

C.2.5 LICENCIA BSD DE CLÁUSULA CERO PARA CÓDIGO EN EL PYTHON | lanza-


miento | 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.3 Licencias y reconocimientos para software incorporado

Esta sección es una lista incompleta, pero creciente, de licencias y reconocimientos para software de terceros incorporado
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
(continúe en la próxima página)

354 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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)

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. Licencias y reconocimientos para software incorporado 355


The Python/C API, Versión 3.13.0a5

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

356 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.13.0a5

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.

C.3.6 funciones UUencode y UUdecode

The uu codec contains the following notice:

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
(continúe en la próxima página)

C.3. Licencias y reconocimientos para software incorporado 357


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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.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
(continúe en la próxima página)

358 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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.

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>

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

C.3. Licencias y reconocimientos para software incorporado 359


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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.12 OpenSSL

The modules hashlib, posix and ssl use the OpenSSL library for added performance if made available by the
operating system. Additionally, the Windows and macOS installers for Python may include a copy of the OpenSSL
libraries, so we include a copy of the OpenSSL license here. For the OpenSSL 3.0 release, and later releases derived
from that, the Apache License v2 applies:
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/

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


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

360 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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
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,
(continúe en la próxima página)

C.3. Licencias y reconocimientos para software incorporado 361


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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
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,
(continúe en la próxima página)

362 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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

C.3. Licencias y reconocimientos para software incorporado 363


The Python/C API, Versión 3.13.0a5

C.3.13 expat

La extensión pyexpat se construye usando una copia incluida de las fuentes de expatriados a menos que la construcción
esté configurada --with-system-expat:

Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper

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.

364 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.13.0a5

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
(continúe en la próxima página)

C.3. Licencias y reconocimientos para software incorporado 365


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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


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

366 Apéndice C. Historia y Licencia


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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.

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 mimalloc

MIT License
Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PAR-
TICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWA-
RE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

C.3.20 asyncio

Parts of the asyncio module are incorporated from uvloop 0.16, which is distributed under the MIT license:

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:

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

C.3. Licencias y reconocimientos para software incorporado 367


The Python/C API, Versión 3.13.0a5

(proviene de la página anterior)


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.21 Global Unbounded Sequences (GUS)

The file Python/qsbr.c is adapted from FreeBSD’s «Global Unbounded Sequences» safe memory reclamation sche-
me in subr_smr.c. The file is distributed under the 2-Clause BSD License:

Copyright (c) 2019,2020 Jeffrey Roberson <[email protected]>

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 unmodified, 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 ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

368 Apéndice C. Historia y Licencia


APÉNDICE D

Derechos de autor

Python y esta documentación es:


Copyright © 2001-2024 Python Software Foundation. All rights reserved.
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.

369
The Python/C API, Versión 3.13.0a5

370 Apéndice D. Derechos de autor


Índice

No alfabético function), 225


..., 329 _PyObject_GetDictPtr (C function), 101
>>>, 329 _PyObject_New (C function), 273
__all__ (package variable), 76 _PyObject_NewVar (C function), 273
__dict__ (module attribute), 186 _PyTuple_Resize (C function), 166
__doc__ (module attribute), 186
__file__ (module attribute), 186, 187
A
__future__, 335 a la espera, 331
__import__ abort (C function), 76
built-in function, 76 abs
__loader__ (module attribute), 186 built-in function, 111
__main__ administrador asincrónico de contexto,
module, 13, 215, 227, 228 330
__name__ (module attribute), 186, 187 administrador de contextos, 332
__package__ (module attribute), 186 alcances anidados, 340
__PYVENV_LAUNCHER__, 245, 252 alias de tipos, 345
__slots__, 343 allocfunc (C type), 318
_frozen (C struct), 79 anotación, 329
_inittab (C struct), 80 anotación de función, 335
_inittab.initfunc (C member), 80 anotación de variable, 345
_inittab.name (C member), 80 apagado del intérprete, 337
_Py_c_diff (C function), 142 API provisional, 342
_Py_c_neg (C function), 142 archivo binario, 331
_Py_c_pow (C function), 142 archivo de texto, 344
_Py_c_prod (C function), 142 argumento, 329
_Py_c_quot (C function), 142 argumento nombrado, 338
_Py_c_sum (C function), 142 argumento posicional, 342
_Py_InitializeMain (C function), 259 argv (in module sys), 244
_Py_NoneStruct (C var), 274 ascii
_PyBytes_Resize (C function), 146 built-in function, 102
_PyCode_GetExtra (C function), 184 atributo, 330
_PyCode_SetExtra (C function), 184
_PyEval_RequestCodeExtraIndex (C function),
B
184 BDFL, 331
_PyFrameEvalFunction (C type), 225 binaryfunc (C type), 319
_PyInterpreterFrame (C struct), 202 bloqueo global del intérprete, 336
_PyInterpreterState_GetEvalFrameFunc (C buffer interface
function), 225 (see buffer protocol), 118
_PyInterpreterState_SetEvalFrameFunc (C buffer object
(see buffer protocol), 118

371
The Python/C API, Versión 3.13.0a5

buffer protocol, 118 complex number


built-in function object, 142
__import__, 76 comprensión de conjuntos, 343
abs, 111 comprensión de diccionarios, 333
ascii, 102 comprensión de listas, 338
bytes, 102 contador de referencias, 343
classmethod, 278 contiguo, 332
compile, 78 contiguous, 121
divmod, 111 copyright (in module sys), 218
float, 113 corrutina, 332
hash, 103, 295 CPython, 332
int, 113
len, 103, 113, 115, 168, 173, 176 D
pow, 111, 112 decorador, 332
repr, 102, 294 descrgetfunc (C type), 318
staticmethod, 278 descriptor, 333
tuple, 115, 170 descrsetfunc (C type), 318
type, 103 despacho único, 343
builtins destructor (C type), 318
module, 13, 215, 227, 228 diccionario, 333
buscador, 334 dictionary
buscador basado en ruta, 341 object, 170
buscador de entradas de ruta, 341 división entera a la baja, 334
bytearray divmod
object, 146 built-in function, 111
bytecode, 331 docstring, 333
bytes
built-in function, 102 E
object, 144 EAFP, 333
entorno virtual, 345
C entrada de ruta, 341
cadena con triple comilla, 344 EOFError (built-in exception), 185
callable, 331 espacio de nombres, 340
calloc (C function), 261 especificador de módulo, 339
Capsule exc_info (in module sys), 11
object, 199 executable (in module sys), 217
cargador, 338 exit (C function), 76
C-contiguous, 121, 332 expresión, 333
clase, 332 expresión generadora, 335
clase base abstracta, 329
clase de nuevo estilo, 340 F
classmethod f-string, 334
built-in function, 278 file
cleanup functions, 76 object, 185
close (in module os), 228 float
CO_FUTURE_DIVISION (C var), 49 built-in function, 113
code object, 181 floating point
codificación de la configuración object, 140
regional, 338 Fortran contiguous, 121, 332
codificación de texto, 344 free (C function), 261
codificación del sistema de archivos y freefunc (C type), 318
manejador de errores, 334 freeze utility, 79
compile frozenset
built-in function, 78 object, 175

372 Índice
The Python/C API, Versión 3.13.0a5

función, 334 K
función clave, 338 KeyboardInterrupt (built-in exception), 63, 64
función corrutina, 332
función genérica, 335 L
function
lambda, 338
object, 177
LBYL, 338
len
G built-in function, 103, 113, 115, 168, 173,
gancho a entrada de ruta, 341 176
gcvisitobjects_t (C type), 325 lenfunc (C type), 319
generador, 335 list
generador asincrónico, 330 object, 168
getattrfunc (C type), 318 lista, 338
getattrofunc (C type), 318 lock, interpreter, 219
getbufferproc (C type), 319 long integer
getiterfunc (C type), 319 object, 134
getter (C type), 283 LONG_MAX (C macro), 135
GIL, 336
global interpreter lock, 219 M
magic
H método, 339
hash main(), 244
built-in function, 103, 295 malloc (C function), 261
hash-based pyc, 336 mapeado, 339
hashable, 336 mapping
hashfunc (C type), 319 object, 170
máquina virtual, 346
I memoryview
IDLE, 336 object, 197
immortal, 336 meta buscadores de ruta, 339
importador, 337 metaclase, 339
importar, 337 METH_CLASS (C macro), 278
incr_item(), 12, 13 METH_COEXIST (C macro), 278
indicador de tipo, 345 METH_FASTCALL (C macro), 277
initproc (C type), 318 METH_KEYWORDS (C macro), 277
inmutable, 336 METH_METHOD (C macro), 278
inquiry (C type), 324 METH_NOARGS (C macro), 278
instancemethod METH_O (C macro), 278
object, 179 METH_STATIC (C macro), 278
int METH_VARARGS (C macro), 277
built-in function, 113 method
integer object, 180
object, 134 MethodType (in module types), 177, 180
interactivo, 337 método, 339
interpretado, 337 magic, 339
interpreter lock, 219 special, 344
iterable, 337 método especial, 344
iterable asincrónico, 330 método mágico, 339
iterador, 337 module
iterador asincrónico, 330 __main__, 13, 215, 227, 228
iterador generador, 335 builtins, 13, 215, 227, 228
iterador generador asincrónico, 330 object, 186
iternextfunc (C type), 319 search path, 13, 215, 218

Índice 373
The Python/C API, Versión 3.13.0a5

signal, 63, 64 P
sys, 13, 215, 227, 228 package variable
modules (in module sys), 76, 215 __all__, 76
ModuleType (in module types), 186 paquete, 340
módulo, 339 paquete de espacios de nombres, 340
módulo de extensión, 334 paquete provisorio, 342
MRO, 339 paquete regular, 343
mutable, 339 parámetro, 340
path
N module search, 13, 215, 218
newfunc (C type), 318 PATH, 13
nombre calificado, 342 path (in module sys), 13, 215, 218
None PEP, 341
object, 133 platform (in module sys), 218
numeric porción, 342
object, 134 pow
número complejo, 332 built-in function, 111, 112
Py_ABS (C macro), 5
O Py_AddPendingCall (C function), 230
object Py_ALWAYS_INLINE (C macro), 5
bytearray, 146 Py_AtExit (C function), 76
bytes, 144 Py_AUDIT_READ (C macro), 280
Capsule, 199 Py_AuditHookFunction (C type), 75
code, 181 Py_BEGIN_ALLOW_THREADS (C macro), 219, 223
complex number, 142 Py_BLOCK_THREADS (C macro), 223
dictionary, 170 Py_buffer (C type), 119
file, 185 Py_buffer.buf (C member), 119
floating point, 140 Py_buffer.format (C member), 120
frozenset, 175 Py_buffer.internal (C member), 120
function, 177 Py_buffer.itemsize (C member), 119
instancemethod, 179 Py_buffer.len (C member), 119
integer, 134 Py_buffer.ndim (C member), 120
list, 168 Py_buffer.obj (C member), 119
long integer, 134 Py_buffer.readonly (C member), 119
mapping, 170 Py_buffer.shape (C member), 120
memoryview, 197 Py_buffer.strides (C member), 120
method, 180 Py_buffer.suboffsets (C member), 120
module, 186 Py_BuildValue (C function), 88
None, 133 Py_BytesMain (C function), 45
numeric, 134 Py_BytesWarningFlag (C var), 212
sequence, 144 Py_CHARMASK (C macro), 5
set, 175 Py_CLEAR (C function), 53
tuple, 165 Py_CompileString (C function), 48, 49
type, 7, 127 Py_CompileStringExFlags (C function), 48
objeto, 340 Py_CompileStringFlags (C function), 48
objeto archivo, 334 Py_CompileStringObject (C function), 48
objeto tipo ruta, 341 Py_complex (C type), 142
objetos tipo archivo, 334 PY_CXX_CONST (C macro), 88
objetos tipo binarios, 331 Py_DEBUG (C macro), 14
objobjargproc (C type), 319 Py_DebugFlag (C var), 212
objobjproc (C type), 319 Py_DecodeLocale (C function), 72
orden de resolución de métodos, 339 Py_DecRef (C function), 53
OverflowError (built-in exception), 135137 Py_DECREF (C function), 8, 52
Py_DEPRECATED (C macro), 5

374 Índice
The Python/C API, Versión 3.13.0a5

Py_DontWriteBytecodeFlag (C var), 212 Py_LeaveRecursiveCall (C function), 67


Py_Ellipsis (C var), 197 Py_LegacyWindowsFSEncodingFlag (C var), 213
Py_EncodeLocale (C function), 73 Py_LegacyWindowsStdioFlag (C var), 214
Py_END_ALLOW_THREADS (C macro), 219, 223 Py_LIMITED_API (C macro), 16
Py_EndInterpreter (C function), 228 Py_LT (C macro), 304
Py_EnterRecursiveCall (C function), 67 Py_Main (C function), 45
Py_EQ (C macro), 304 PY_MAJOR_VERSION (C macro), 327
Py_eval_input (C var), 49 Py_MAX (C macro), 6
Py_Exit (C function), 76 Py_MEMBER_SIZE (C macro), 6
Py_ExitStatusException (C function), 239 PY_MICRO_VERSION (C macro), 327
Py_False (C var), 139 Py_MIN (C macro), 6
Py_FatalError (C function), 76 PY_MINOR_VERSION (C macro), 327
Py_FdIsInteractive (C function), 71 Py_mod_create (C macro), 190
Py_file_input (C var), 49 Py_mod_exec (C macro), 190
Py_Finalize (C function), 216 Py_mod_multiple_interpreters (C macro), 190
Py_FinalizeEx (C function), 76, 215, 216, 228 Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
Py_FrozenFlag (C var), 213 (C macro), 190
Py_GE (C macro), 304 Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
Py_GenericAlias (C function), 209 (C macro), 190
Py_GenericAliasType (C var), 210 Py_MOD_PER_INTERPRETER_GIL_SUPPORTED (C
Py_GetArgcArgv (C function), 259 macro), 190
Py_GetBuildInfo (C function), 218 Py_NE (C macro), 304
Py_GetCompiler (C function), 218 Py_NewInterpreter (C function), 228
Py_GetCopyright (C function), 218 Py_NewInterpreterFromConfig (C function), 227
Py_GETENV (C macro), 6 Py_NewRef (C function), 52
Py_GetExecPrefix (C function), 13, 217 Py_NO_INLINE (C macro), 6
Py_GetPath (C function), 13, 218 Py_None (C var), 133
Py_GetPlatform (C function), 218 Py_NoSiteFlag (C var), 214
Py_GetPrefix (C function), 13, 216 Py_NotImplemented (C var), 99
Py_GetProgramFullPath (C function), 13, 217 Py_NoUserSiteDirectory (C var), 214
Py_GetProgramName (C function), 216 Py_OpenCodeHookFunction (C type), 185
Py_GetPythonHome (C function), 219 Py_OptimizeFlag (C var), 214
Py_GetVersion (C function), 218 Py_PreInitialize (C function), 242
Py_GT (C macro), 304 Py_PreInitializeFromArgs (C function), 242
Py_hash_t (C type), 92 Py_PreInitializeFromBytesArgs (C function),
Py_HashPointer (C function), 93 242
Py_HashRandomizationFlag (C var), 213 Py_PRINT_RAW (C macro), 99, 186
Py_IgnoreEnvironmentFlag (C var), 213 Py_QuietFlag (C var), 214
Py_IncRef (C function), 53 Py_READONLY (C macro), 280
Py_INCREF (C function), 8, 51 Py_REFCNT (C function), 51
Py_Initialize (C function), 13, 215, 228 Py_RELATIVE_OFFSET (C macro), 280
Py_InitializeEx (C function), 215 PY_RELEASE_LEVEL (C macro), 327
Py_InitializeFromConfig (C function), 255 PY_RELEASE_SERIAL (C macro), 327
Py_InspectFlag (C var), 213 Py_ReprEnter (C function), 67
Py_InteractiveFlag (C var), 213 Py_ReprLeave (C function), 67
Py_Is (C function), 274 Py_RETURN_FALSE (C macro), 139
Py_IS_TYPE (C function), 275 Py_RETURN_NONE (C macro), 133
Py_IsFalse (C function), 275 Py_RETURN_NOTIMPLEMENTED (C macro), 99
Py_IsFinalizing (C function), 216 Py_RETURN_RICHCOMPARE (C macro), 304
Py_IsInitialized (C function), 13, 215 Py_RETURN_TRUE (C macro), 139
Py_IsNone (C function), 275 Py_RunMain (C function), 259
Py_IsolatedFlag (C var), 213 Py_SET_REFCNT (C function), 51
Py_IsTrue (C function), 275 Py_SET_SIZE (C function), 275
Py_LE (C macro), 304 Py_SET_TYPE (C function), 275

Índice 375
The Python/C API, Versión 3.13.0a5

Py_SETREF (C macro), 53 Py_TYPE (C function), 275


Py_single_input (C var), 49 Py_UCS1 (C type), 148
Py_SIZE (C function), 275 Py_UCS2 (C type), 148
Py_ssize_t (C type), 11 Py_UCS4 (C type), 148
PY_SSIZE_T_MAX (C macro), 136 Py_uhash_t (C type), 92
Py_STRINGIFY (C macro), 6 Py_UNBLOCK_THREADS (C macro), 223
Py_T_BOOL (C macro), 282 Py_UnbufferedStdioFlag (C var), 215
Py_T_BYTE (C macro), 282 Py_UNICODE (C type), 148
Py_T_CHAR (C macro), 282 Py_UNICODE_IS_HIGH_SURROGATE (C function),
Py_T_DOUBLE (C macro), 282 151
Py_T_FLOAT (C macro), 282 Py_UNICODE_IS_LOW_SURROGATE (C function), 151
Py_T_INT (C macro), 282 Py_UNICODE_IS_SURROGATE (C function), 151
Py_T_LONG (C macro), 282 Py_UNICODE_ISALNUM (C function), 150
Py_T_LONGLONG (C macro), 282 Py_UNICODE_ISALPHA (C function), 150
Py_T_OBJECT_EX (C macro), 282 Py_UNICODE_ISDECIMAL (C function), 150
Py_T_PYSSIZET (C macro), 282 Py_UNICODE_ISDIGIT (C function), 150
Py_T_SHORT (C macro), 282 Py_UNICODE_ISLINEBREAK (C function), 150
Py_T_STRING (C macro), 282 Py_UNICODE_ISLOWER (C function), 150
Py_T_STRING_INPLACE (C macro), 282 Py_UNICODE_ISNUMERIC (C function), 150
Py_T_UBYTE (C macro), 282 Py_UNICODE_ISPRINTABLE (C function), 150
Py_T_UINT (C macro), 282 Py_UNICODE_ISSPACE (C function), 150
Py_T_ULONG (C macro), 282 Py_UNICODE_ISTITLE (C function), 150
Py_T_ULONGLONG (C macro), 282 Py_UNICODE_ISUPPER (C function), 150
Py_T_USHORT (C macro), 282 Py_UNICODE_JOIN_SURROGATES (C function), 151
Py_TPFLAGS_BASE_EXC_SUBCLASS (C macro), 299 Py_UNICODE_TODECIMAL (C function), 150
Py_TPFLAGS_BASETYPE (C macro), 297 Py_UNICODE_TODIGIT (C function), 150
Py_TPFLAGS_BYTES_SUBCLASS (C macro), 299 Py_UNICODE_TOLOWER (C function), 150
Py_TPFLAGS_DEFAULT (C macro), 297 Py_UNICODE_TONUMERIC (C function), 151
Py_TPFLAGS_DICT_SUBCLASS (C macro), 299 Py_UNICODE_TOTITLE (C function), 150
Py_TPFLAGS_DISALLOW_INSTANTIATION (C ma- Py_UNICODE_TOUPPER (C function), 150
cro), 299 Py_UNREACHABLE (C macro), 6
Py_TPFLAGS_HAVE_FINALIZE (C macro), 299 Py_UNUSED (C macro), 6
Py_TPFLAGS_HAVE_GC (C macro), 297 Py_VaBuildValue (C function), 90
Py_TPFLAGS_HAVE_VECTORCALL (C macro), 299 PY_VECTORCALL_ARGUMENTS_OFFSET (C macro),
Py_TPFLAGS_HEAPTYPE (C macro), 297 106
Py_TPFLAGS_IMMUTABLETYPE (C macro), 299 Py_VerboseFlag (C var), 215
Py_TPFLAGS_ITEMS_AT_END (C macro), 298 Py_Version (C var), 328
Py_TPFLAGS_LIST_SUBCLASS (C macro), 299 PY_VERSION_HEX (C macro), 327
Py_TPFLAGS_LONG_SUBCLASS (C macro), 299 Py_VISIT (C function), 324
Py_TPFLAGS_MANAGED_DICT (C macro), 298 Py_XDECREF (C function), 13, 52
Py_TPFLAGS_MANAGED_WEAKREF (C macro), 298 Py_XINCREF (C function), 52
Py_TPFLAGS_MAPPING (C macro), 300 Py_XNewRef (C function), 52
Py_TPFLAGS_METHOD_DESCRIPTOR (C macro), 298 Py_XSETREF (C macro), 53
Py_TPFLAGS_READY (C macro), 297 PyAIter_Check (C function), 117
Py_TPFLAGS_READYING (C macro), 297 PyAnySet_Check (C function), 175
Py_TPFLAGS_SEQUENCE (C macro), 300 PyAnySet_CheckExact (C function), 176
Py_TPFLAGS_TUPLE_SUBCLASS (C macro), 299 PyArg_Parse (C function), 87
Py_TPFLAGS_TYPE_SUBCLASS (C macro), 299 PyArg_ParseTuple (C function), 86
Py_TPFLAGS_UNICODE_SUBCLASS (C macro), 299 PyArg_ParseTupleAndKeywords (C function), 86
Py_TPFLAGS_VALID_VERSION_TAG (C macro), 300 PyArg_UnpackTuple (C function), 87
Py_tracefunc (C type), 230 PyArg_ValidateKeywordArguments (C fun-
Py_True (C var), 139 ction), 87
Py_tss_NEEDS_INIT (C macro), 233 PyArg_VaParse (C function), 86
Py_tss_t (C type), 233

376 Índice
The Python/C API, Versión 3.13.0a5

PyArg_VaParseTupleAndKeywords (C function), PyByteArray_Size (C function), 147


87 PyByteArray_Type (C var), 146
PyASCIIObject (C type), 148 PyByteArrayObject (C type), 146
PyAsyncMethods (C type), 317 PyBytes_AS_STRING (C function), 145
PyAsyncMethods.am_aiter (C member), 317 PyBytes_AsString (C function), 145
PyAsyncMethods.am_anext (C member), 317 PyBytes_AsStringAndSize (C function), 145
PyAsyncMethods.am_await (C member), 317 PyBytes_Check (C function), 144
PyAsyncMethods.am_send (C member), 317 PyBytes_CheckExact (C function), 144
PyBool_Check (C function), 139 PyBytes_Concat (C function), 146
PyBool_FromLong (C function), 139 PyBytes_ConcatAndDel (C function), 146
PyBool_Type (C var), 139 PyBytes_FromFormat (C function), 144
PyBUF_ANY_CONTIGUOUS (C macro), 122 PyBytes_FromFormatV (C function), 145
PyBUF_C_CONTIGUOUS (C macro), 122 PyBytes_FromObject (C function), 145
PyBUF_CONTIG (C macro), 122 PyBytes_FromString (C function), 144
PyBUF_CONTIG_RO (C macro), 122 PyBytes_FromStringAndSize (C function), 144
PyBUF_F_CONTIGUOUS (C macro), 122 PyBytes_GET_SIZE (C function), 145
PyBUF_FORMAT (C macro), 121 PyBytes_Size (C function), 145
PyBUF_FULL (C macro), 122 PyBytes_Type (C var), 144
PyBUF_FULL_RO (C macro), 122 PyBytesObject (C type), 144
PyBUF_INDIRECT (C macro), 121 PyCallable_Check (C function), 110
PyBUF_MAX_NDIM (C macro), 120 PyCallIter_Check (C function), 195
PyBUF_ND (C macro), 121 PyCallIter_New (C function), 195
PyBUF_READ (C macro), 197 PyCallIter_Type (C var), 194
PyBUF_RECORDS (C macro), 122 PyCapsule (C type), 199
PyBUF_RECORDS_RO (C macro), 122 PyCapsule_CheckExact (C function), 199
PyBUF_SIMPLE (C macro), 121 PyCapsule_Destructor (C type), 199
PyBUF_STRIDED (C macro), 122 PyCapsule_GetContext (C function), 200
PyBUF_STRIDED_RO (C macro), 122 PyCapsule_GetDestructor (C function), 199
PyBUF_STRIDES (C macro), 121 PyCapsule_GetName (C function), 200
PyBUF_WRITABLE (C macro), 121 PyCapsule_GetPointer (C function), 199
PyBUF_WRITE (C macro), 197 PyCapsule_Import (C function), 200
PyBuffer_FillContiguousStrides (C fun- PyCapsule_IsValid (C function), 200
ction), 125 PyCapsule_New (C function), 199
PyBuffer_FillInfo (C function), 125 PyCapsule_SetContext (C function), 200
PyBuffer_FromContiguous (C function), 124 PyCapsule_SetDestructor (C function), 200
PyBuffer_GetPointer (C function), 124 PyCapsule_SetName (C function), 200
PyBuffer_IsContiguous (C function), 124 PyCapsule_SetPointer (C function), 200
PyBuffer_Release (C function), 124 PyCell_Check (C function), 180
PyBuffer_SizeFromFormat (C function), 124 PyCell_Get (C function), 180
PyBuffer_ToContiguous (C function), 125 PyCell_GET (C function), 180
PyBufferProcs (C type), 118, 316 PyCell_New (C function), 180
PyBufferProcs.bf_getbuffer (C member), 316 PyCell_Set (C function), 181
PyBufferProcs.bf_releasebuffer (C member), PyCell_SET (C function), 181
316 PyCell_Type (C var), 180
PyByteArray_AS_STRING (C function), 147 PyCellObject (C type), 180
PyByteArray_AsString (C function), 147 PyCFunction (C type), 276
PyByteArray_Check (C function), 146 PyCFunction_New (C function), 279
PyByteArray_CheckExact (C function), 146 PyCFunction_NewEx (C function), 279
PyByteArray_Concat (C function), 147 PyCFunctionFast (C type), 276
PyByteArray_FromObject (C function), 147 PyCFunctionFastWithKeywords (C type), 276
PyByteArray_FromStringAndSize (C function), PyCFunctionWithKeywords (C type), 276
147 PyCMethod (C type), 276
PyByteArray_GET_SIZE (C function), 147 PyCMethod_New (C function), 278
PyByteArray_Resize (C function), 147 PyCode_Addr2Line (C function), 182

Índice 377
The Python/C API, Versión 3.13.0a5

PyCode_Addr2Location (C function), 182 PyConfig_InitIsolatedConfig (C function), 243


PyCode_AddWatcher (C function), 183 PyConfig_InitPythonConfig (C function), 243
PyCode_Check (C function), 181 PyConfig_Read (C function), 244
PyCode_ClearWatcher (C function), 183 PyConfig_SetArgv (C function), 243
PyCode_GetCellvars (C function), 182 PyConfig_SetBytesArgv (C function), 243
PyCode_GetCode (C function), 182 PyConfig_SetBytesString (C function), 243
PyCode_GetFirstFree (C function), 181 PyConfig_SetString (C function), 243
PyCode_GetFreevars (C function), 183 PyConfig_SetWideStringList (C function), 243
PyCode_GetNumFree (C function), 181 PyConfig.argv (C member), 244
PyCode_GetVarnames (C function), 182 PyConfig.base_exec_prefix (C member), 245
PyCode_New (C function), 181 PyConfig.base_executable (C member), 245
PyCode_NewEmpty (C function), 182 PyConfig.base_prefix (C member), 245
PyCode_NewWithPosOnlyArgs (C function), 182 PyConfig.buffered_stdio (C member), 245
PyCode_Type (C var), 181 PyConfig.bytes_warning (C member), 245
PyCode_WatchCallback (C type), 183 PyConfig.check_hash_pycs_mode (C member),
PyCodec_BackslashReplaceErrors (C fun- 246
ction), 96 PyConfig.code_debug_ranges (C member), 246
PyCodec_Decode (C function), 94 PyConfig.configure_c_stdio (C member), 246
PyCodec_Decoder (C function), 95 PyConfig.cpu_count (C member), 249
PyCodec_Encode (C function), 94 PyConfig.dev_mode (C member), 246
PyCodec_Encoder (C function), 95 PyConfig.dump_refs (C member), 246
PyCodec_IgnoreErrors (C function), 95 PyConfig.exec_prefix (C member), 247
PyCodec_IncrementalDecoder (C function), 95 PyConfig.executable (C member), 247
PyCodec_IncrementalEncoder (C function), 95 PyConfig.faulthandler (C member), 247
PyCodec_KnownEncoding (C function), 94 PyConfig.filesystem_encoding (C member),
PyCodec_LookupError (C function), 95 247
PyCodec_NameReplaceErrors (C function), 96 PyConfig.filesystem_errors (C member), 247
PyCodec_Register (C function), 94 PyConfig.hash_seed (C member), 248
PyCodec_RegisterError (C function), 95 PyConfig.home (C member), 248
PyCodec_ReplaceErrors (C function), 95 PyConfig.import_time (C member), 248
PyCodec_StreamReader (C function), 95 PyConfig.inspect (C member), 248
PyCodec_StreamWriter (C function), 95 PyConfig.install_signal_handlers (C mem-
PyCodec_StrictErrors (C function), 95 ber), 248
PyCodec_Unregister (C function), 94 PyConfig.int_max_str_digits (C member), 249
PyCodec_XMLCharRefReplaceErrors (C fun- PyConfig.interactive (C member), 248
ction), 96 PyConfig.isolated (C member), 249
PyCodeEvent (C type), 183 PyConfig.legacy_windows_stdio (C member),
PyCodeObject (C type), 181 249
PyCompactUnicodeObject (C type), 148 PyConfig.malloc_stats (C member), 249
PyCompilerFlags (C struct), 49 PyConfig.module_search_paths (C member),
PyCompilerFlags.cf_feature_version (C 250
member), 49 PyConfig.module_search_paths_set (C mem-
PyCompilerFlags.cf_flags (C member), 49 ber), 250
PyComplex_AsCComplex (C function), 143 PyConfig.optimization_level (C member), 250
PyComplex_Check (C function), 143 PyConfig.orig_argv (C member), 250
PyComplex_CheckExact (C function), 143 PyConfig.parse_argv (C member), 251
PyComplex_FromCComplex (C function), 143 PyConfig.parser_debug (C member), 251
PyComplex_FromDoubles (C function), 143 PyConfig.pathconfig_warnings (C member),
PyComplex_ImagAsDouble (C function), 143 251
PyComplex_RealAsDouble (C function), 143 PyConfig.perf_profiling (C member), 254
PyComplex_Type (C var), 143 PyConfig.platlibdir (C member), 250
PyComplexObject (C type), 143 PyConfig.prefix (C member), 251
PyConfig (C type), 243 PyConfig.program_name (C member), 251
PyConfig_Clear (C function), 244 PyConfig.pycache_prefix (C member), 252

378 Índice
The Python/C API, Versión 3.13.0a5

PyConfig.pythonpath_env (C member), 250 PyDateTime_DATE_GET_HOUR (C function), 208


PyConfig.quiet (C member), 252 PyDateTime_DATE_GET_MICROSECOND (C fun-
PyConfig.run_command (C member), 252 ction), 208
PyConfig.run_filename (C member), 252 PyDateTime_DATE_GET_MINUTE (C function), 208
PyConfig.run_module (C member), 252 PyDateTime_DATE_GET_SECOND (C function), 208
PyConfig.run_presite (C member), 252 PyDateTime_DATE_GET_TZINFO (C function), 208
PyConfig.safe_path (C member), 245 PyDateTime_DateTime (C type), 206
PyConfig.show_ref_count (C member), 253 PyDateTime_DateTimeType (C var), 206
PyConfig.site_import (C member), 253 PyDateTime_DateType (C var), 206
PyConfig.skip_source_first_line (C mem- PyDateTime_Delta (C type), 206
ber), 253 PyDateTime_DELTA_GET_DAYS (C function), 209
PyConfig.stdio_encoding (C member), 253 PyDateTime_DELTA_GET_MICROSECONDS (C fun-
PyConfig.stdio_errors (C member), 253 ction), 209
PyConfig.tracemalloc (C member), 253 PyDateTime_DELTA_GET_SECONDS (C function),
PyConfig.use_environment (C member), 254 209
PyConfig.use_hash_seed (C member), 248 PyDateTime_DeltaType (C var), 206
PyConfig.user_site_directory (C member), PyDateTime_FromDateAndTime (C function), 207
254 PyDateTime_FromDateAndTimeAndFold (C fun-
PyConfig.verbose (C member), 254 ction), 207
PyConfig.warn_default_encoding (C member), PyDateTime_FromTimestamp (C function), 209
246 PyDateTime_GET_DAY (C function), 208
PyConfig.warnoptions (C member), 254 PyDateTime_GET_MONTH (C function), 208
PyConfig.write_bytecode (C member), 254 PyDateTime_GET_YEAR (C function), 208
PyConfig.xoptions (C member), 255 PyDateTime_Time (C type), 206
PyContext (C type), 204 PyDateTime_TIME_GET_FOLD (C function), 209
PyContext_CheckExact (C function), 204 PyDateTime_TIME_GET_HOUR (C function), 208
PyContext_Copy (C function), 205 PyDateTime_TIME_GET_MICROSECOND (C fun-
PyContext_CopyCurrent (C function), 205 ction), 208
PyContext_Enter (C function), 205 PyDateTime_TIME_GET_MINUTE (C function), 208
PyContext_Exit (C function), 205 PyDateTime_TIME_GET_SECOND (C function), 208
PyContext_New (C function), 205 PyDateTime_TIME_GET_TZINFO (C function), 209
PyContext_Type (C var), 204 PyDateTime_TimeType (C var), 206
PyContextToken (C type), 204 PyDateTime_TimeZone_UTC (C var), 206
PyContextToken_CheckExact (C function), 205 PyDateTime_TZInfoType (C var), 206
PyContextToken_Type (C var), 204 PyDelta_Check (C function), 207
PyContextVar (C type), 204 PyDelta_CheckExact (C function), 207
PyContextVar_CheckExact (C function), 204 PyDelta_FromDSU (C function), 207
PyContextVar_Get (C function), 205 PyDescr_IsData (C function), 195
PyContextVar_New (C function), 205 PyDescr_NewClassMethod (C function), 195
PyContextVar_Reset (C function), 205 PyDescr_NewGetSet (C function), 195
PyContextVar_Set (C function), 205 PyDescr_NewMember (C function), 195
PyContextVar_Type (C var), 204 PyDescr_NewMethod (C function), 195
PyCoro_CheckExact (C function), 204 PyDescr_NewWrapper (C function), 195
PyCoro_New (C function), 204 PyDict_AddWatcher (C function), 174
PyCoro_Type (C var), 203 PyDict_Check (C function), 170
PyCoroObject (C type), 203 PyDict_CheckExact (C function), 170
PyDate_Check (C function), 206 PyDict_Clear (C function), 170
PyDate_CheckExact (C function), 206 PyDict_ClearWatcher (C function), 174
PyDate_FromDate (C function), 207 PyDict_Contains (C function), 171
PyDate_FromTimestamp (C function), 209 PyDict_ContainsString (C function), 171
PyDateTime_Check (C function), 206 PyDict_Copy (C function), 171
PyDateTime_CheckExact (C function), 206 PyDict_DelItem (C function), 171
PyDateTime_Date (C type), 206 PyDict_DelItemString (C function), 171
PyDateTime_DATE_GET_FOLD (C function), 208 PyDict_GetItem (C function), 171

Índice 379
The Python/C API, Versión 3.13.0a5

PyDict_GetItemRef (C function), 171 PyErr_SetExcFromWindowsErrWithFilenameObject


PyDict_GetItemString (C function), 172 (C function), 58
PyDict_GetItemStringRef (C function), 172 PyErr_SetExcFromWindowsErrWithFilenameObjects
PyDict_GetItemWithError (C function), 171 (C function), 58
PyDict_Items (C function), 172 PyErr_SetExcInfo (C function), 63
PyDict_Keys (C function), 173 PyErr_SetFromErrno (C function), 57
PyDict_Merge (C function), 173 PyErr_SetFromErrnoWithFilename (C fun-
PyDict_MergeFromSeq2 (C function), 174 ction), 58
PyDict_New (C function), 170 PyErr_SetFromErrnoWithFilenameObject (C
PyDict_Next (C function), 173 function), 57
PyDict_Pop (C function), 172 PyErr_SetFromErrnoWithFilenameObjects
PyDict_PopString (C function), 172 (C function), 57
PyDict_SetDefault (C function), 172 PyErr_SetFromWindowsErr (C function), 58
PyDict_SetDefaultRef (C function), 172 PyErr_SetFromWindowsErrWithFilename (C
PyDict_SetItem (C function), 171 function), 58
PyDict_SetItemString (C function), 171 PyErr_SetHandledException (C function), 62
PyDict_Size (C function), 173 PyErr_SetImportError (C function), 59
PyDict_Type (C var), 170 PyErr_SetImportErrorSubclass (C function),
PyDict_Unwatch (C function), 174 59
PyDict_Update (C function), 174 PyErr_SetInterrupt (C function), 63
PyDict_Values (C function), 173 PyErr_SetInterruptEx (C function), 64
PyDict_Watch (C function), 174 PyErr_SetNone (C function), 57
PyDict_WatchCallback (C type), 174 PyErr_SetObject (C function), 57
PyDict_WatchEvent (C type), 174 PyErr_SetRaisedException (C function), 61
PyDictObject (C type), 170 PyErr_SetString (C function), 11, 57
PyDictProxy_New (C function), 170 PyErr_SyntaxLocation (C function), 59
PyDoc_STR (C macro), 7 PyErr_SyntaxLocationEx (C function), 59
PyDoc_STRVAR (C macro), 7 PyErr_SyntaxLocationObject (C function), 59
PyErr_BadArgument (C function), 57 PyErr_WarnEx (C function), 59
PyErr_BadInternalCall (C function), 59 PyErr_WarnExplicit (C function), 60
PyErr_CheckSignals (C function), 63 PyErr_WarnExplicitObject (C function), 60
PyErr_Clear (C function), 11, 13, 56 PyErr_WarnFormat (C function), 60
PyErr_DisplayException (C function), 56 PyErr_WriteUnraisable (C function), 56
PyErr_ExceptionMatches (C function), 13, 60 PyEval_AcquireThread (C function), 225
PyErr_Fetch (C function), 61 PyEval_EvalCode (C function), 48
PyErr_Format (C function), 57 PyEval_EvalCodeEx (C function), 48
PyErr_FormatUnraisable (C function), 56 PyEval_EvalFrame (C function), 48
PyErr_FormatV (C function), 57 PyEval_EvalFrameEx (C function), 48
PyErr_GetExcInfo (C function), 62 PyEval_GetBuiltins (C function), 93
PyErr_GetHandledException (C function), 62 PyEval_GetFrame (C function), 94
PyErr_GetRaisedException (C function), 61 PyEval_GetFuncDesc (C function), 94
PyErr_GivenExceptionMatches (C function), 60 PyEval_GetFuncName (C function), 94
PyErr_NewException (C function), 64 PyEval_GetGlobals (C function), 94
PyErr_NewExceptionWithDoc (C function), 64 PyEval_GetLocals (C function), 93
PyErr_NoMemory (C function), 57 PyEval_MergeCompilerFlags (C function), 49
PyErr_NormalizeException (C function), 62 PyEval_ReleaseThread (C function), 226
PyErr_Occurred (C function), 11, 60 PyEval_RestoreThread (C function), 220, 221
PyErr_Print (C function), 56 PyEval_SaveThread (C function), 220, 221
PyErr_PrintEx (C function), 56 PyEval_SetProfile (C function), 231
PyErr_ResourceWarning (C function), 60 PyEval_SetProfileAllThreads (C function), 231
PyErr_Restore (C function), 61 PyEval_SetTrace (C function), 232
PyErr_SetExcFromWindowsErr (C function), 58 PyEval_SetTraceAllThreads (C function), 232
PyErr_SetExcFromWindowsErrWithFilename PyExc_ArithmeticError (C var), 68
(C function), 58 PyExc_AssertionError (C var), 68

380 Índice
The Python/C API, Versión 3.13.0a5

PyExc_AttributeError (C var), 68 PyExc_UnboundLocalError (C var), 68


PyExc_BaseException (C var), 68 PyExc_UnicodeDecodeError (C var), 68
PyExc_BlockingIOError (C var), 68 PyExc_UnicodeEncodeError (C var), 68
PyExc_BrokenPipeError (C var), 68 PyExc_UnicodeError (C var), 68
PyExc_BufferError (C var), 68 PyExc_UnicodeTranslateError (C var), 68
PyExc_BytesWarning (C var), 69 PyExc_UnicodeWarning (C var), 69
PyExc_ChildProcessError (C var), 68 PyExc_UserWarning (C var), 69
PyExc_ConnectionAbortedError (C var), 68 PyExc_ValueError (C var), 68
PyExc_ConnectionError (C var), 68 PyExc_Warning (C var), 69
PyExc_ConnectionRefusedError (C var), 68 PyExc_WindowsError (C var), 69
PyExc_ConnectionResetError (C var), 68 PyExc_ZeroDivisionError (C var), 68
PyExc_DeprecationWarning (C var), 69 PyException_GetArgs (C function), 65
PyExc_EnvironmentError (C var), 69 PyException_GetCause (C function), 65
PyExc_EOFError (C var), 68 PyException_GetContext (C function), 65
PyExc_Exception (C var), 68 PyException_GetTraceback (C function), 65
PyExc_FileExistsError (C var), 68 PyException_SetArgs (C function), 65
PyExc_FileNotFoundError (C var), 68 PyException_SetCause (C function), 65
PyExc_FloatingPointError (C var), 68 PyException_SetContext (C function), 65
PyExc_FutureWarning (C var), 69 PyException_SetTraceback (C function), 65
PyExc_GeneratorExit (C var), 68 PyFile_FromFd (C function), 185
PyExc_ImportError (C var), 68 PyFile_GetLine (C function), 185
PyExc_ImportWarning (C var), 69 PyFile_SetOpenCodeHook (C function), 185
PyExc_IndentationError (C var), 68 PyFile_WriteObject (C function), 186
PyExc_IndexError (C var), 68 PyFile_WriteString (C function), 186
PyExc_InterruptedError (C var), 68 PyFloat_AS_DOUBLE (C function), 140
PyExc_IOError (C var), 69 PyFloat_AsDouble (C function), 140
PyExc_IsADirectoryError (C var), 68 PyFloat_Check (C function), 140
PyExc_KeyboardInterrupt (C var), 68 PyFloat_CheckExact (C function), 140
PyExc_KeyError (C var), 68 PyFloat_FromDouble (C function), 140
PyExc_LookupError (C var), 68 PyFloat_FromString (C function), 140
PyExc_MemoryError (C var), 68 PyFloat_GetInfo (C function), 140
PyExc_ModuleNotFoundError (C var), 68 PyFloat_GetMax (C function), 140
PyExc_NameError (C var), 68 PyFloat_GetMin (C function), 140
PyExc_NotADirectoryError (C var), 68 PyFloat_Pack2 (C function), 141
PyExc_NotImplementedError (C var), 68 PyFloat_Pack4 (C function), 141
PyExc_OSError (C var), 68 PyFloat_Pack8 (C function), 141
PyExc_OverflowError (C var), 68 PyFloat_Type (C var), 140
PyExc_PendingDeprecationWarning (C var), 69 PyFloat_Unpack2 (C function), 141
PyExc_PermissionError (C var), 68 PyFloat_Unpack4 (C function), 141
PyExc_ProcessLookupError (C var), 68 PyFloat_Unpack8 (C function), 142
PyExc_RecursionError (C var), 68 PyFloatObject (C type), 140
PyExc_ReferenceError (C var), 68 PyFrame_Check (C function), 201
PyExc_ResourceWarning (C var), 69 PyFrame_GetBack (C function), 201
PyExc_RuntimeError (C var), 68 PyFrame_GetBuiltins (C function), 201
PyExc_RuntimeWarning (C var), 69 PyFrame_GetCode (C function), 201
PyExc_StopAsyncIteration (C var), 68 PyFrame_GetGenerator (C function), 201
PyExc_StopIteration (C var), 68 PyFrame_GetGlobals (C function), 201
PyExc_SyntaxError (C var), 68 PyFrame_GetLasti (C function), 202
PyExc_SyntaxWarning (C var), 69 PyFrame_GetLineNumber (C function), 202
PyExc_SystemError (C var), 68 PyFrame_GetLocals (C function), 202
PyExc_SystemExit (C var), 68 PyFrame_GetVar (C function), 202
PyExc_TabError (C var), 68 PyFrame_GetVarString (C function), 202
PyExc_TimeoutError (C var), 68 PyFrame_Type (C var), 201
PyExc_TypeError (C var), 68 PyFrameObject (C type), 201

Índice 381
The Python/C API, Versión 3.13.0a5

PyFrozenSet_Check (C function), 175 PyImport_AddModuleObject (C function), 77


PyFrozenSet_CheckExact (C function), 176 PyImport_AddModuleRef (C function), 77
PyFrozenSet_New (C function), 176 PyImport_AppendInittab (C function), 79
PyFrozenSet_Type (C var), 175 PyImport_ExecCodeModule (C function), 77
PyFunction_AddWatcher (C function), 178 PyImport_ExecCodeModuleEx (C function), 78
PyFunction_Check (C function), 177 PyImport_ExecCodeModuleObject (C function),
PyFunction_ClearWatcher (C function), 178 78
PyFunction_GetAnnotations (C function), 178 PyImport_ExecCodeModuleWithPathnames (C
PyFunction_GetClosure (C function), 178 function), 78
PyFunction_GetCode (C function), 177 PyImport_ExtendInittab (C function), 80
PyFunction_GetDefaults (C function), 177 PyImport_FrozenModules (C var), 79
PyFunction_GetGlobals (C function), 177 PyImport_GetImporter (C function), 79
PyFunction_GetModule (C function), 177 PyImport_GetMagicNumber (C function), 78
PyFunction_New (C function), 177 PyImport_GetMagicTag (C function), 78
PyFunction_NewWithQualName (C function), 177 PyImport_GetModule (C function), 79
PyFunction_SetAnnotations (C function), 178 PyImport_GetModuleDict (C function), 79
PyFunction_SetClosure (C function), 178 PyImport_Import (C function), 77
PyFunction_SetDefaults (C function), 178 PyImport_ImportFrozenModule (C function), 79
PyFunction_SetVectorcall (C function), 178 PyImport_ImportFrozenModuleObject (C fun-
PyFunction_Type (C var), 177 ction), 79
PyFunction_WatchCallback (C type), 178 PyImport_ImportModule (C function), 76
PyFunction_WatchEvent (C type), 178 PyImport_ImportModuleEx (C function), 76
PyFunctionObject (C type), 177 PyImport_ImportModuleLevel (C function), 77
PyGC_Collect (C function), 325 PyImport_ImportModuleLevelObject (C fun-
PyGC_Disable (C function), 325 ction), 77
PyGC_Enable (C function), 325 PyImport_ImportModuleNoBlock (C function),
PyGC_IsEnabled (C function), 325 76
PyGen_Check (C function), 203 PyImport_ReloadModule (C function), 77
PyGen_CheckExact (C function), 203 PyIndex_Check (C function), 113
PyGen_New (C function), 203 PyInstanceMethod_Check (C function), 179
PyGen_NewWithQualName (C function), 203 PyInstanceMethod_Function (C function), 179
PyGen_Type (C var), 203 PyInstanceMethod_GET_FUNCTION (C function),
PyGenObject (C type), 203 179
PyGetSetDef (C type), 283 PyInstanceMethod_New (C function), 179
PyGetSetDef.closure (C member), 283 PyInstanceMethod_Type (C var), 179
PyGetSetDef.doc (C member), 283 PyInterpreterConfig (C type), 226
PyGetSetDef.get (C member), 283 PyInterpreterConfig_DEFAULT_GIL (C macro),
PyGetSetDef.name (C member), 283 227
PyGetSetDef.set (C member), 283 PyInterpreterConfig_OWN_GIL (C macro), 227
PyGILState_Check (C function), 222 PyInterpreterConfig_SHARED_GIL (C macro),
PyGILState_Ensure (C function), 222 227
PyGILState_GetThisThreadState (C function), PyInterpreterConfig.allow_daemon_threads
222 (C member), 227
PyGILState_Release (C function), 222 PyInterpreterConfig.allow_exec (C member),
PyHASH_BITS (C macro), 93 227
PyHash_FuncDef (C type), 93 PyInterpreterConfig.allow_fork (C member),
PyHash_FuncDef.hash_bits (C member), 93 226
PyHash_FuncDef.name (C member), 93 PyInterpreterConfig.allow_threads (C
PyHash_FuncDef.seed_bits (C member), 93 member), 227
PyHash_GetFuncDef (C function), 93 PyInterpreterConfig.check_multi_interp_extensions
PyHASH_IMAG (C macro), 93 (C member), 227
PyHASH_INF (C macro), 93 PyInterpreterConfig.gil (C member), 227
PyHASH_MODULUS (C macro), 92 PyInterpreterConfig.use_main_obmalloc
PyImport_AddModule (C function), 77 (C member), 226

382 Índice
The Python/C API, Versión 3.13.0a5

PyInterpreterState (C type), 221 PyLong_FromDouble (C function), 134


PyInterpreterState_Clear (C function), 223 PyLong_FromLong (C function), 134
PyInterpreterState_Delete (C function), 223 PyLong_FromLongLong (C function), 134
PyInterpreterState_Get (C function), 224 PyLong_FromNativeBytes (C function), 135
PyInterpreterState_GetDict (C function), 225 PyLong_FromSize_t (C function), 134
PyInterpreterState_GetID (C function), 225 PyLong_FromSsize_t (C function), 134
PyInterpreterState_Head (C function), 232 PyLong_FromString (C function), 134
PyInterpreterState_Main (C function), 232 PyLong_FromUnicodeObject (C function), 135
PyInterpreterState_New (C function), 223 PyLong_FromUnsignedLong (C function), 134
PyInterpreterState_Next (C function), 232 PyLong_FromUnsignedLongLong (C function), 134
PyInterpreterState_ThreadHead (C function), PyLong_FromUnsignedNativeBytes (C fun-
232 ction), 135
PyIter_Check (C function), 117 PyLong_FromVoidPtr (C function), 135
PyIter_Next (C function), 117 PyLong_Type (C var), 134
PyIter_Send (C function), 118 PyLongObject (C type), 134
PyList_Append (C function), 169 PyMapping_Check (C function), 115
PyList_AsTuple (C function), 170 PyMapping_DelItem (C function), 116
PyList_Check (C function), 168 PyMapping_DelItemString (C function), 116
PyList_CheckExact (C function), 168 PyMapping_GetItemString (C function), 115
PyList_Clear (C function), 170 PyMapping_GetOptionalItem (C function), 115
PyList_Extend (C function), 169 PyMapping_GetOptionalItemString (C fun-
PyList_GET_ITEM (C function), 169 ction), 116
PyList_GET_SIZE (C function), 168 PyMapping_HasKey (C function), 116
PyList_GetItem (C function), 10, 169 PyMapping_HasKeyString (C function), 116
PyList_GetItemRef (C function), 169 PyMapping_HasKeyStringWithError (C fun-
PyList_GetSlice (C function), 169 ction), 116
PyList_Insert (C function), 169 PyMapping_HasKeyWithError (C function), 116
PyList_New (C function), 168 PyMapping_Items (C function), 117
PyList_Reverse (C function), 170 PyMapping_Keys (C function), 116
PyList_SET_ITEM (C function), 169 PyMapping_Length (C function), 115
PyList_SetItem (C function), 8, 169 PyMapping_SetItemString (C function), 116
PyList_SetSlice (C function), 169 PyMapping_Size (C function), 115
PyList_Size (C function), 168 PyMapping_Values (C function), 117
PyList_Sort (C function), 170 PyMappingMethods (C type), 314
PyList_Type (C var), 168 PyMappingMethods.mp_ass_subscript (C
PyListObject (C type), 168 member), 315
PyLong_AsDouble (C function), 137 PyMappingMethods.mp_length (C member), 314
PyLong_AsInt (C function), 135 PyMappingMethods.mp_subscript (C member),
PyLong_AsLong (C function), 135 314
PyLong_AsLongAndOverflow (C function), 135 PyMarshal_ReadLastObjectFromFile (C fun-
PyLong_AsLongLong (C function), 136 ction), 81
PyLong_AsLongLongAndOverflow (C function), PyMarshal_ReadLongFromFile (C function), 80
136 PyMarshal_ReadObjectFromFile (C function),
PyLong_AsNativeBytes (C function), 137 81
PyLong_AsSize_t (C function), 136 PyMarshal_ReadObjectFromString (C fun-
PyLong_AsSsize_t (C function), 136 ction), 81
PyLong_AsUnsignedLong (C function), 136 PyMarshal_ReadShortFromFile (C function), 81
PyLong_AsUnsignedLongLong (C function), 136 PyMarshal_WriteLongToFile (C function), 80
PyLong_AsUnsignedLongLongMask (C function), PyMarshal_WriteObjectToFile (C function), 80
137 PyMarshal_WriteObjectToString (C function),
PyLong_AsUnsignedLongMask (C function), 137 80
PyLong_AsVoidPtr (C function), 137 PyMem_Calloc (C function), 264
PyLong_Check (C function), 134 PyMem_Del (C function), 264
PyLong_CheckExact (C function), 134 PYMEM_DOMAIN_MEM (C macro), 267

Índice 383
The Python/C API, Versión 3.13.0a5

PYMEM_DOMAIN_OBJ (C macro), 267 PyModule_CheckExact (C function), 186


PYMEM_DOMAIN_RAW (C macro), 266 PyModule_Create (C function), 189
PyMem_Free (C function), 264 PyModule_Create2 (C function), 189
PyMem_GetAllocator (C function), 267 PyModule_ExecDef (C function), 191
PyMem_Malloc (C function), 263 PyModule_FromDefAndSpec (C function), 191
PyMem_New (C macro), 264 PyModule_FromDefAndSpec2 (C function), 191
PyMem_RawCalloc (C function), 263 PyModule_GetDef (C function), 187
PyMem_RawFree (C function), 263 PyModule_GetDict (C function), 186
PyMem_RawMalloc (C function), 263 PyModule_GetFilename (C function), 187
PyMem_RawRealloc (C function), 263 PyModule_GetFilenameObject (C function), 187
PyMem_Realloc (C function), 264 PyModule_GetName (C function), 187
PyMem_Resize (C macro), 264 PyModule_GetNameObject (C function), 186
PyMem_SetAllocator (C function), 267 PyModule_GetState (C function), 187
PyMem_SetupDebugHooks (C function), 268 PyModule_New (C function), 186
PyMemAllocatorDomain (C type), 266 PyModule_NewObject (C function), 186
PyMemAllocatorEx (C type), 266 PyModule_SetDocString (C function), 191
PyMember_GetOne (C function), 280 PyModule_Type (C var), 186
PyMember_SetOne (C function), 280 PyModuleDef (C type), 187
PyMemberDef (C type), 279 PyModuleDef_Init (C function), 189
PyMemberDef.doc (C member), 279 PyModuleDef_Slot (C type), 189
PyMemberDef.flags (C member), 279 PyModuleDef_Slot.slot (C member), 189
PyMemberDef.name (C member), 279 PyModuleDef_Slot.value (C member), 190
PyMemberDef.offset (C member), 279 PyModuleDef.m_base (C member), 187
PyMemberDef.type (C member), 279 PyModuleDef.m_clear (C member), 188
PyMemoryView_Check (C function), 197 PyModuleDef.m_doc (C member), 187
PyMemoryView_FromBuffer (C function), 197 PyModuleDef.m_free (C member), 188
PyMemoryView_FromMemory (C function), 197 PyModuleDef.m_methods (C member), 188
PyMemoryView_FromObject (C function), 197 PyModuleDef.m_name (C member), 187
PyMemoryView_GET_BASE (C function), 197 PyModuleDef.m_size (C member), 187
PyMemoryView_GET_BUFFER (C function), 197 PyModuleDef.m_slots (C member), 188
PyMemoryView_GetContiguous (C function), 197 PyModuleDef.m_slots.m_reload (C member),
PyMethod_Check (C function), 180 188
PyMethod_Function (C function), 180 PyModuleDef.m_traverse (C member), 188
PyMethod_GET_FUNCTION (C function), 180 PyNumber_Absolute (C function), 111
PyMethod_GET_SELF (C function), 180 PyNumber_Add (C function), 110
PyMethod_New (C function), 180 PyNumber_And (C function), 111
PyMethod_Self (C function), 180 PyNumber_AsSsize_t (C function), 113
PyMethod_Type (C var), 180 PyNumber_Check (C function), 110
PyMethodDef (C type), 277 PyNumber_Divmod (C function), 110
PyMethodDef.ml_doc (C member), 277 PyNumber_Float (C function), 113
PyMethodDef.ml_flags (C member), 277 PyNumber_FloorDivide (C function), 110
PyMethodDef.ml_meth (C member), 277 PyNumber_Index (C function), 113
PyMethodDef.ml_name (C member), 277 PyNumber_InPlaceAdd (C function), 111
PyMODINIT_FUNC (C macro), 5 PyNumber_InPlaceAnd (C function), 112
PyModule_Add (C function), 192 PyNumber_InPlaceFloorDivide (C function), 112
PyModule_AddFunctions (C function), 191 PyNumber_InPlaceLshift (C function), 112
PyModule_AddIntConstant (C function), 193 PyNumber_InPlaceMatrixMultiply (C fun-
PyModule_AddIntMacro (C macro), 193 ction), 112
PyModule_AddObject (C function), 192 PyNumber_InPlaceMultiply (C function), 111
PyModule_AddObjectRef (C function), 192 PyNumber_InPlaceOr (C function), 112
PyModule_AddStringConstant (C function), 193 PyNumber_InPlacePower (C function), 112
PyModule_AddStringMacro (C macro), 193 PyNumber_InPlaceRemainder (C function), 112
PyModule_AddType (C function), 193 PyNumber_InPlaceRshift (C function), 112
PyModule_Check (C function), 186 PyNumber_InPlaceSubtract (C function), 111

384 Índice
The Python/C API, Versión 3.13.0a5

PyNumber_InPlaceTrueDivide (C function), 112 PyNumberMethods.nb_invert (C member), 313


PyNumber_InPlaceXor (C function), 112 PyNumberMethods.nb_lshift (C member), 313
PyNumber_Invert (C function), 111 PyNumberMethods.nb_matrix_multiply (C
PyNumber_Long (C function), 113 member), 314
PyNumber_Lshift (C function), 111 PyNumberMethods.nb_multiply (C member), 313
PyNumber_MatrixMultiply (C function), 110 PyNumberMethods.nb_negative (C member), 313
PyNumber_Multiply (C function), 110 PyNumberMethods.nb_or (C member), 314
PyNumber_Negative (C function), 111 PyNumberMethods.nb_positive (C member), 313
PyNumber_Or (C function), 111 PyNumberMethods.nb_power (C member), 313
PyNumber_Positive (C function), 111 PyNumberMethods.nb_remainder (C member),
PyNumber_Power (C function), 111 313
PyNumber_Remainder (C function), 110 PyNumberMethods.nb_reserved (C member), 314
PyNumber_Rshift (C function), 111 PyNumberMethods.nb_rshift (C member), 313
PyNumber_Subtract (C function), 110 PyNumberMethods.nb_subtract (C member), 313
PyNumber_ToBase (C function), 113 PyNumberMethods.nb_true_divide (C member),
PyNumber_TrueDivide (C function), 110 314
PyNumber_Xor (C function), 111 PyNumberMethods.nb_xor (C member), 314
PyNumberMethods (C type), 312 PyObject (C type), 274
PyNumberMethods.nb_absolute (C member), 313 PyObject_ASCII (C function), 102
PyNumberMethods.nb_add (C member), 313 PyObject_AsFileDescriptor (C function), 185
PyNumberMethods.nb_and (C member), 314 PyObject_Bytes (C function), 102
PyNumberMethods.nb_bool (C member), 313 PyObject_Call (C function), 107
PyNumberMethods.nb_divmod (C member), 313 PyObject_CallFunction (C function), 108
PyNumberMethods.nb_float (C member), 314 PyObject_CallFunctionObjArgs (C function),
PyNumberMethods.nb_floor_divide (C mem- 108
ber), 314 PyObject_CallMethod (C function), 108
PyNumberMethods.nb_index (C member), 314 PyObject_CallMethodNoArgs (C function), 109
PyNumberMethods.nb_inplace_add (C member), PyObject_CallMethodObjArgs (C function), 109
314 PyObject_CallMethodOneArg (C function), 109
PyNumberMethods.nb_inplace_and (C member), PyObject_CallNoArgs (C function), 108
314 PyObject_CallObject (C function), 108
PyNumberMethods.nb_inplace_floor_divide PyObject_Calloc (C function), 265
(C member), 314 PyObject_CallOneArg (C function), 108
PyNumberMethods.nb_inplace_lshift (C PyObject_CheckBuffer (C function), 124
member), 314 PyObject_ClearManagedDict (C function), 105
PyNumberMethods.nb_inplace_matrix_multiply PyObject_ClearWeakRefs (C function), 199
(C member), 314 PyObject_CopyData (C function), 125
PyNumberMethods.nb_inplace_multiply (C PyObject_Del (C function), 274
member), 314 PyObject_DelAttr (C function), 101
PyNumberMethods.nb_inplace_or (C member), PyObject_DelAttrString (C function), 101
314 PyObject_DelItem (C function), 104
PyNumberMethods.nb_inplace_power (C mem- PyObject_Dir (C function), 104
ber), 314 PyObject_Format (C function), 102
PyNumberMethods.nb_inplace_remainder (C PyObject_Free (C function), 265
member), 314 PyObject_GC_Del (C function), 324
PyNumberMethods.nb_inplace_rshift (C PyObject_GC_IsFinalized (C function), 323
member), 314 PyObject_GC_IsTracked (C function), 323
PyNumberMethods.nb_inplace_subtract (C PyObject_GC_New (C macro), 323
member), 314 PyObject_GC_NewVar (C macro), 323
PyNumberMethods.nb_inplace_true_divide PyObject_GC_Resize (C macro), 323
(C member), 314 PyObject_GC_Track (C function), 323
PyNumberMethods.nb_inplace_xor (C member), PyObject_GC_UnTrack (C function), 324
314 PyObject_GenericGetAttr (C function), 100
PyNumberMethods.nb_int (C member), 314 PyObject_GenericGetDict (C function), 101

Índice 385
The Python/C API, Versión 3.13.0a5

PyObject_GenericSetAttr (C function), 101 PyObject.ob_refcnt (C member), 290


PyObject_GenericSetDict (C function), 101 PyObject.ob_type (C member), 290
PyObject_GetAIter (C function), 104 PyOS_AfterFork (C function), 72
PyObject_GetArenaAllocator (C function), 270 PyOS_AfterFork_Child (C function), 72
PyObject_GetAttr (C function), 100 PyOS_AfterFork_Parent (C function), 71
PyObject_GetAttrString (C function), 100 PyOS_BeforeFork (C function), 71
PyObject_GetBuffer (C function), 124 PyOS_CheckStack (C function), 72
PyObject_GetItem (C function), 104 PyOS_double_to_string (C function), 92
PyObject_GetItemData (C function), 105 PyOS_FSPath (C function), 71
PyObject_GetIter (C function), 104 PyOS_getsig (C function), 72
PyObject_GetOptionalAttr (C function), 100 PyOS_InputHook (C var), 47
PyObject_GetOptionalAttrString (C fun- PyOS_ReadlineFunctionPointer (C var), 47
ction), 100 PyOS_setsig (C function), 72
PyObject_GetTypeData (C function), 104 PyOS_sighandler_t (C type), 72
PyObject_HasAttr (C function), 100 PyOS_snprintf (C function), 90
PyObject_HasAttrString (C function), 100 PyOS_stricmp (C function), 92
PyObject_HasAttrStringWithError (C fun- PyOS_string_to_double (C function), 91
ction), 99 PyOS_strnicmp (C function), 92
PyObject_HasAttrWithError (C function), 99 PyOS_strtol (C function), 91
PyObject_Hash (C function), 103 PyOS_strtoul (C function), 91
PyObject_HashNotImplemented (C function), 103 PyOS_vsnprintf (C function), 90
PyObject_HEAD (C macro), 274 PyPreConfig (C type), 240
PyObject_HEAD_INIT (C macro), 275 PyPreConfig_InitIsolatedConfig (C fun-
PyObject_Init (C function), 273 ction), 240
PyObject_InitVar (C function), 273 PyPreConfig_InitPythonConfig (C function),
PyObject_IS_GC (C function), 323 240
PyObject_IsInstance (C function), 103 PyPreConfig.allocator (C member), 240
PyObject_IsSubclass (C function), 102 PyPreConfig.coerce_c_locale (C member), 241
PyObject_IsTrue (C function), 103 PyPreConfig.coerce_c_locale_warn (C mem-
PyObject_Length (C function), 103 ber), 241
PyObject_LengthHint (C function), 103 PyPreConfig.configure_locale (C member),
PyObject_Malloc (C function), 265 241
PyObject_New (C macro), 273 PyPreConfig.dev_mode (C member), 241
PyObject_NewVar (C macro), 273 PyPreConfig.isolated (C member), 241
PyObject_Not (C function), 103 PyPreConfig.legacy_windows_fs_encoding
PyObject_Print (C function), 99 (C member), 241
PyObject_Realloc (C function), 265 PyPreConfig.parse_argv (C member), 241
PyObject_Repr (C function), 102 PyPreConfig.use_environment (C member), 242
PyObject_RichCompare (C function), 101 PyPreConfig.utf8_mode (C member), 242
PyObject_RichCompareBool (C function), 102 PyProperty_Type (C var), 195
PyObject_SetArenaAllocator (C function), 270 PyRun_AnyFile (C function), 45
PyObject_SetAttr (C function), 101 PyRun_AnyFileEx (C function), 46
PyObject_SetAttrString (C function), 101 PyRun_AnyFileExFlags (C function), 46
PyObject_SetItem (C function), 104 PyRun_AnyFileFlags (C function), 45
PyObject_Size (C function), 103 PyRun_File (C function), 47
PyObject_Str (C function), 102 PyRun_FileEx (C function), 47
PyObject_Type (C function), 103 PyRun_FileExFlags (C function), 48
PyObject_TypeCheck (C function), 103 PyRun_FileFlags (C function), 47
PyObject_VAR_HEAD (C macro), 274 PyRun_InteractiveLoop (C function), 46
PyObject_Vectorcall (C function), 109 PyRun_InteractiveLoopFlags (C function), 47
PyObject_VectorcallDict (C function), 109 PyRun_InteractiveOne (C function), 46
PyObject_VectorcallMethod (C function), 109 PyRun_InteractiveOneFlags (C function), 46
PyObject_VisitManagedDict (C function), 105 PyRun_SimpleFile (C function), 46
PyObjectArenaAllocator (C type), 270 PyRun_SimpleFileEx (C function), 46

386 Índice
The Python/C API, Versión 3.13.0a5

PyRun_SimpleFileExFlags (C function), 46 PySet_Size (C function), 176


PyRun_SimpleString (C function), 46 PySet_Type (C var), 175
PyRun_SimpleStringFlags (C function), 46 PySetObject (C type), 175
PyRun_String (C function), 47 PySignal_SetWakeupFd (C function), 64
PyRun_StringFlags (C function), 47 PySlice_AdjustIndices (C function), 196
PySendResult (C type), 118 PySlice_Check (C function), 195
PySeqIter_Check (C function), 194 PySlice_GetIndices (C function), 195
PySeqIter_New (C function), 194 PySlice_GetIndicesEx (C function), 196
PySeqIter_Type (C var), 194 PySlice_New (C function), 195
PySequence_Check (C function), 113 PySlice_Type (C var), 195
PySequence_Concat (C function), 113 PySlice_Unpack (C function), 196
PySequence_Contains (C function), 114 PyState_AddModule (C function), 194
PySequence_Count (C function), 114 PyState_FindModule (C function), 194
PySequence_DelItem (C function), 114 PyState_RemoveModule (C function), 194
PySequence_DelSlice (C function), 114 PyStatus (C type), 239
PySequence_Fast (C function), 115 PyStatus_Error (C function), 239
PySequence_Fast_GET_ITEM (C function), 115 PyStatus_Exception (C function), 239
PySequence_Fast_GET_SIZE (C function), 115 PyStatus_Exit (C function), 239
PySequence_Fast_ITEMS (C function), 115 PyStatus_IsError (C function), 239
PySequence_GetItem (C function), 10, 114 PyStatus_IsExit (C function), 239
PySequence_GetSlice (C function), 114 PyStatus_NoMemory (C function), 239
PySequence_Index (C function), 114 PyStatus_Ok (C function), 239
PySequence_InPlaceConcat (C function), 114 PyStatus.err_msg (C member), 239
PySequence_InPlaceRepeat (C function), 114 PyStatus.exitcode (C member), 239
PySequence_ITEM (C function), 115 PyStatus.func (C member), 239
PySequence_Length (C function), 113 PyStructSequence_Desc (C type), 167
PySequence_List (C function), 114 PyStructSequence_Desc.doc (C member), 167
PySequence_Repeat (C function), 113 PyStructSequence_Desc.fields (C member),
PySequence_SetItem (C function), 114 167
PySequence_SetSlice (C function), 114 PyStructSequence_Desc.n_in_sequence (C
PySequence_Size (C function), 113 member), 167
PySequence_Tuple (C function), 115 PyStructSequence_Desc.name (C member), 167
PySequenceMethods (C type), 315 PyStructSequence_Field (C type), 167
PySequenceMethods.sq_ass_item (C member), PyStructSequence_Field.doc (C member), 167
315 PyStructSequence_Field.name (C member), 167
PySequenceMethods.sq_concat (C member), 315 PyStructSequence_GET_ITEM (C function), 168
PySequenceMethods.sq_contains (C member), PyStructSequence_GetItem (C function), 167
315 PyStructSequence_InitType (C function), 167
PySequenceMethods.sq_inplace_concat (C PyStructSequence_InitType2 (C function), 167
member), 315 PyStructSequence_New (C function), 167
PySequenceMethods.sq_inplace_repeat (C PyStructSequence_NewType (C function), 167
member), 315 PyStructSequence_SET_ITEM (C function), 168
PySequenceMethods.sq_item (C member), 315 PyStructSequence_SetItem (C function), 168
PySequenceMethods.sq_length (C member), 315 PyStructSequence_UnnamedField (C var), 167
PySequenceMethods.sq_repeat (C member), 315 PySys_AddAuditHook (C function), 75
PySet_Add (C function), 176 PySys_Audit (C function), 74
PySet_Check (C function), 175 PySys_AuditTuple (C function), 75
PySet_CheckExact (C function), 176 PySys_FormatStderr (C function), 74
PySet_Clear (C function), 177 PySys_FormatStdout (C function), 74
PySet_Contains (C function), 176 PySys_GetObject (C function), 74
PySet_Discard (C function), 176 PySys_GetXOptions (C function), 74
PySet_GET_SIZE (C function), 176 PySys_ResetWarnOptions (C function), 74
PySet_New (C function), 176 PySys_SetObject (C function), 74
PySet_Pop (C function), 177 PySys_WriteStderr (C function), 74

Índice 387
The Python/C API, Versión 3.13.0a5

PySys_WriteStdout (C function), 74 PYTHONDONTWRITEBYTECODE, 212, 255


Python 3000, 342 PYTHONDUMPREFS, 247
Python Enhancement Proposals PYTHONEXECUTABLE, 252
PEP 1, 342 PYTHONFAULTHANDLER, 247
PEP 7, 4, 7 PYTHONHASHSEED, 213, 248
PEP 238, 49, 334 PYTHONHOME, 13, 213, 219, 248
PEP 278, 345 Pythónico, 342
PEP 302, 334, 338 PYTHONINSPECT, 213, 248
PEP 343, 332 PYTHONINTMAXSTRDIGITS, 249
PEP 353, 11 PYTHONIOENCODING, 253
PEP 362, 330, 341 PYTHONLEGACYWINDOWSFSENCODING, 214, 241
PEP 383, 155, 156 PYTHONLEGACYWINDOWSSTDIO, 214, 249
PEP 387, 15 PYTHONMALLOC, 262, 266, 268, 269
PEP 393, 147 PYTHONMALLOCSTATS, 250, 262
PEP 411, 342 PYTHONNODEBUGRANGES, 246
PEP 420, 334, 340, 342 PYTHONNOUSERSITE, 214, 254
PEP 432, 259, 260 PYTHONOPTIMIZE, 214, 250
PEP 442, 311 PYTHONPATH, 13, 213, 250
PEP 443, 335 PYTHONPERFSUPPORT, 254
PEP 451, 190, 334 PYTHONPLATLIBDIR, 250
PEP 456, 93 PYTHONPROFILEIMPORTTIME, 248
PEP 483, 336 PYTHONPYCACHEPREFIX, 252
PEP 484, 329, 335, 336, 345 PYTHONSAFEPATH, 245
PEP 489, 191, 227 PYTHONTRACEMALLOC, 254
PEP 492, 330332 PYTHONUNBUFFERED, 215, 245
PEP 498, 334 PYTHONUTF8, 242, 257
PEP 519, 341 PYTHONVERBOSE, 215, 254
PEP 523, 202, 225 PYTHONWARNINGS, 254
PEP 525, 330 PyThread_create_key (C function), 234
PEP 526, 329, 345 PyThread_delete_key (C function), 234
PEP 528, 214, 249 PyThread_delete_key_value (C function), 235
PEP 529, 156, 214 PyThread_get_key_value (C function), 235
PEP 538, 257 PyThread_ReInitTLS (C function), 235
PEP 539, 233 PyThread_set_key_value (C function), 234
PEP 540, 257 PyThread_tss_alloc (C function), 233
PEP 552, 246 PyThread_tss_create (C function), 234
PEP 554, 229 PyThread_tss_delete (C function), 234
PEP 578, 75 PyThread_tss_free (C function), 233
PEP 585, 336 PyThread_tss_get (C function), 234
PEP 587, 237 PyThread_tss_is_created (C function), 234
PEP 590, 105 PyThread_tss_set (C function), 234
PEP 623, 147 PyThreadState (C type), 219, 221
PEP 634, 300 PyThreadState_Clear (C function), 223
PEP 3116, 345 PyThreadState_Delete (C function), 224
PEP 3119, 103 PyThreadState_DeleteCurrent (C function), 224
PEP 3121, 188 PyThreadState_EnterTracing (C function), 224
PEP 3147, 79 PyThreadState_Get (C function), 222
PEP 3151, 69 PyThreadState_GetDict (C function), 225
PEP 3155, 342 PyThreadState_GetFrame (C function), 224
PYTHON_CPU_COUNT, 249 PyThreadState_GetID (C function), 224
PYTHON_PRESITE, 252 PyThreadState_GetInterpreter (C function),
PYTHONCOERCECLOCALE, 257 224
PYTHONDEBUG, 212, 251 PyThreadState_GetUnchecked (C function), 222
PYTHONDEVMODE, 246 PyThreadState_LeaveTracing (C function), 224

388 Índice
The Python/C API, Versión 3.13.0a5

PyThreadState_New (C function), 223 PyType_GetFlags (C function), 128


PyThreadState_Next (C function), 232 PyType_GetFullyQualifiedName (C function),
PyThreadState_SetAsyncExc (C function), 225 129
PyThreadState_Swap (C function), 222 PyType_GetModule (C function), 130
PyThreadState.interp (C member), 221 PyType_GetModuleByDef (C function), 130
PyTime_AsSecondsDouble (C function), 97 PyType_GetModuleName (C function), 129
PyTime_Check (C function), 207 PyType_GetModuleState (C function), 130
PyTime_CheckExact (C function), 207 PyType_GetName (C function), 129
PyTime_FromTime (C function), 207 PyType_GetQualName (C function), 129
PyTime_FromTimeAndFold (C function), 207 PyType_GetSlot (C function), 129
PyTime_MAX (C var), 96 PyType_GetTypeDataSize (C function), 104
PyTime_MIN (C var), 96 PyType_HasFeature (C function), 128
PyTime_Monotonic (C function), 96 PyType_IS_GC (C function), 129
PyTime_PerfCounter (C function), 97 PyType_IsSubtype (C function), 129
PyTime_t (C type), 96 PyType_Modified (C function), 128
PyTime_Time (C function), 97 PyType_Ready (C function), 129
PyTimeZone_FromOffset (C function), 208 PyType_Slot (C type), 132
PyTimeZone_FromOffsetAndName (C function), PyType_Slot.pfunc (C member), 133
208 PyType_Slot.slot (C member), 133
PyTrace_C_CALL (C var), 231 PyType_Spec (C type), 132
PyTrace_C_EXCEPTION (C var), 231 PyType_Spec.basicsize (C member), 132
PyTrace_C_RETURN (C var), 231 PyType_Spec.flags (C member), 132
PyTrace_CALL (C var), 231 PyType_Spec.itemsize (C member), 132
PyTrace_EXCEPTION (C var), 231 PyType_Spec.name (C member), 132
PyTrace_LINE (C var), 231 PyType_Spec.slots (C member), 132
PyTrace_OPCODE (C var), 231 PyType_Type (C var), 127
PyTrace_RETURN (C var), 231 PyType_Watch (C function), 128
PyTraceMalloc_Track (C function), 270 PyType_WatchCallback (C type), 128
PyTraceMalloc_Untrack (C function), 270 PyTypeObject (C type), 127
PyTuple_Check (C function), 165 PyTypeObject.tp_alloc (C member), 308
PyTuple_CheckExact (C function), 165 PyTypeObject.tp_as_async (C member), 294
PyTuple_GET_ITEM (C function), 166 PyTypeObject.tp_as_buffer (C member), 296
PyTuple_GET_SIZE (C function), 166 PyTypeObject.tp_as_mapping (C member), 294
PyTuple_GetItem (C function), 166 PyTypeObject.tp_as_number (C member), 294
PyTuple_GetSlice (C function), 166 PyTypeObject.tp_as_sequence (C member), 294
PyTuple_New (C function), 165 PyTypeObject.tp_base (C member), 306
PyTuple_Pack (C function), 165 PyTypeObject.tp_bases (C member), 309
PyTuple_SET_ITEM (C function), 166 PyTypeObject.tp_basicsize (C member), 291
PyTuple_SetItem (C function), 8, 166 PyTypeObject.tp_cache (C member), 310
PyTuple_Size (C function), 166 PyTypeObject.tp_call (C member), 295
PyTuple_Type (C var), 165 PyTypeObject.tp_clear (C member), 302
PyTupleObject (C type), 165 PyTypeObject.tp_dealloc (C member), 292
PyType_AddWatcher (C function), 128 PyTypeObject.tp_del (C member), 310
PyType_Check (C function), 127 PyTypeObject.tp_descr_get (C member), 307
PyType_CheckExact (C function), 127 PyTypeObject.tp_descr_set (C member), 307
PyType_ClearCache (C function), 128 PyTypeObject.tp_dict (C member), 306
PyType_ClearWatcher (C function), 128 PyTypeObject.tp_dictoffset (C member), 307
PyType_FromMetaclass (C function), 131 PyTypeObject.tp_doc (C member), 301
PyType_FromModuleAndSpec (C function), 131 PyTypeObject.tp_finalize (C member), 310
PyType_FromSpec (C function), 132 PyTypeObject.tp_flags (C member), 296
PyType_FromSpecWithBases (C function), 131 PyTypeObject.tp_free (C member), 309
PyType_GenericAlloc (C function), 129 PyTypeObject.tp_getattr (C member), 293
PyType_GenericNew (C function), 129 PyTypeObject.tp_getattro (C member), 295
PyType_GetDict (C function), 128 PyTypeObject.tp_getset (C member), 305

Índice 389
The Python/C API, Versión 3.13.0a5

PyTypeObject.tp_hash (C member), 294 PyUnicode_Compare (C function), 164


PyTypeObject.tp_init (C member), 307 PyUnicode_CompareWithASCIIString (C fun-
PyTypeObject.tp_is_gc (C member), 309 ction), 164
PyTypeObject.tp_itemsize (C member), 291 PyUnicode_Concat (C function), 163
PyTypeObject.tp_iter (C member), 305 PyUnicode_Contains (C function), 165
PyTypeObject.tp_iternext (C member), 305 PyUnicode_CopyCharacters (C function), 154
PyTypeObject.tp_members (C member), 305 PyUnicode_Count (C function), 164
PyTypeObject.tp_methods (C member), 305 PyUnicode_DATA (C function), 149
PyTypeObject.tp_mro (C member), 310 PyUnicode_Decode (C function), 158
PyTypeObject.tp_name (C member), 291 PyUnicode_DecodeASCII (C function), 162
PyTypeObject.tp_new (C member), 308 PyUnicode_DecodeCharmap (C function), 162
PyTypeObject.tp_repr (C member), 294 PyUnicode_DecodeFSDefault (C function), 156
PyTypeObject.tp_richcompare (C member), 303 PyUnicode_DecodeFSDefaultAndSize (C fun-
PyTypeObject.tp_setattr (C member), 293 ction), 156
PyTypeObject.tp_setattro (C member), 296 PyUnicode_DecodeLatin1 (C function), 161
PyTypeObject.tp_str (C member), 295 PyUnicode_DecodeLocale (C function), 155
PyTypeObject.tp_subclasses (C member), 310 PyUnicode_DecodeLocaleAndSize (C function),
PyTypeObject.tp_traverse (C member), 301 155
PyTypeObject.tp_vectorcall (C member), 311 PyUnicode_DecodeMBCS (C function), 163
PyTypeObject.tp_vectorcall_offset (C PyUnicode_DecodeMBCSStateful (C function),
member), 293 163
PyTypeObject.tp_version_tag (C member), 310 PyUnicode_DecodeRawUnicodeEscape (C fun-
PyTypeObject.tp_watched (C member), 311 ction), 161
PyTypeObject.tp_weaklist (C member), 310 PyUnicode_DecodeUnicodeEscape (C function),
PyTypeObject.tp_weaklistoffset (C member), 161
304 PyUnicode_DecodeUTF7 (C function), 160
PyTZInfo_Check (C function), 207 PyUnicode_DecodeUTF7Stateful (C function),
PyTZInfo_CheckExact (C function), 207 160
PyUnicode_1BYTE_DATA (C function), 148 PyUnicode_DecodeUTF8 (C function), 158
PyUnicode_1BYTE_KIND (C macro), 149 PyUnicode_DecodeUTF8Stateful (C function),
PyUnicode_2BYTE_DATA (C function), 148 158
PyUnicode_2BYTE_KIND (C macro), 149 PyUnicode_DecodeUTF16 (C function), 160
PyUnicode_4BYTE_DATA (C function), 148 PyUnicode_DecodeUTF16Stateful (C function),
PyUnicode_4BYTE_KIND (C macro), 149 160
PyUnicode_AsASCIIString (C function), 162 PyUnicode_DecodeUTF32 (C function), 159
PyUnicode_AsCharmapString (C function), 162 PyUnicode_DecodeUTF32Stateful (C function),
PyUnicode_AsEncodedString (C function), 158 159
PyUnicode_AsLatin1String (C function), 161 PyUnicode_EncodeCodePage (C function), 163
PyUnicode_AsMBCSString (C function), 163 PyUnicode_EncodeFSDefault (C function), 156
PyUnicode_AsRawUnicodeEscapeString (C PyUnicode_EncodeLocale (C function), 155
function), 161 PyUnicode_EqualToUTF8 (C function), 164
PyUnicode_AsUCS4 (C function), 155 PyUnicode_EqualToUTF8AndSize (C function),
PyUnicode_AsUCS4Copy (C function), 155 164
PyUnicode_AsUnicodeEscapeString (C fun- PyUnicode_Fill (C function), 154
ction), 161 PyUnicode_Find (C function), 164
PyUnicode_AsUTF8 (C function), 159 PyUnicode_FindChar (C function), 164
PyUnicode_AsUTF8AndSize (C function), 158 PyUnicode_Format (C function), 165
PyUnicode_AsUTF8String (C function), 158 PyUnicode_FromEncodedObject (C function), 154
PyUnicode_AsUTF16String (C function), 160 PyUnicode_FromFormat (C function), 152
PyUnicode_AsUTF32String (C function), 159 PyUnicode_FromFormatV (C function), 153
PyUnicode_AsWideChar (C function), 157 PyUnicode_FromKindAndData (C function), 151
PyUnicode_AsWideCharString (C function), 157 PyUnicode_FromObject (C function), 154
PyUnicode_Check (C function), 148 PyUnicode_FromString (C function), 152
PyUnicode_CheckExact (C function), 148 PyUnicode_FromStringAndSize (C function), 151

390 Índice
The Python/C API, Versión 3.13.0a5

PyUnicode_FromWideChar (C function), 157 PyUnicodeEncodeError_SetStart (C function),


PyUnicode_FSConverter (C function), 156 66
PyUnicode_FSDecoder (C function), 156 PyUnicodeObject (C type), 148
PyUnicode_GET_LENGTH (C function), 148 PyUnicodeTranslateError_GetEnd (C fun-
PyUnicode_GetLength (C function), 154 ction), 66
PyUnicode_InternFromString (C function), 165 PyUnicodeTranslateError_GetObject (C fun-
PyUnicode_InternInPlace (C function), 165 ction), 66
PyUnicode_IsIdentifier (C function), 149 PyUnicodeTranslateError_GetReason (C fun-
PyUnicode_Join (C function), 163 ction), 66
PyUnicode_KIND (C function), 149 PyUnicodeTranslateError_GetStart (C fun-
PyUnicode_MAX_CHAR_VALUE (C function), 149 ction), 66
PyUnicode_New (C function), 151 PyUnicodeTranslateError_SetEnd (C fun-
PyUnicode_READ (C function), 149 ction), 66
PyUnicode_READ_CHAR (C function), 149 PyUnicodeTranslateError_SetReason (C fun-
PyUnicode_ReadChar (C function), 154 ction), 66
PyUnicode_READY (C function), 148 PyUnicodeTranslateError_SetStart (C fun-
PyUnicode_Replace (C function), 164 ction), 66
PyUnicode_RichCompare (C function), 164 PyUnstable, 15
PyUnicode_Split (C function), 163 PyUnstable_Code_GetExtra (C function), 184
PyUnicode_Splitlines (C function), 163 PyUnstable_Code_New (C function), 181
PyUnicode_Substring (C function), 154 PyUnstable_Code_NewWithPosOnlyArgs (C
PyUnicode_Tailmatch (C function), 164 function), 181
PyUnicode_Translate (C function), 162 PyUnstable_Code_SetExtra (C function), 184
PyUnicode_Type (C var), 148 PyUnstable_Eval_RequestCodeExtraIndex
PyUnicode_WRITE (C function), 149 (C function), 184
PyUnicode_WriteChar (C function), 154 PyUnstable_Exc_PrepReraiseStar (C fun-
PyUnicodeDecodeError_Create (C function), 66 ction), 65
PyUnicodeDecodeError_GetEncoding (C fun- PyUnstable_GC_VisitObjects (C function), 325
ction), 66 PyUnstable_InterpreterFrame_GetCode (C
PyUnicodeDecodeError_GetEnd (C function), 66 function), 202
PyUnicodeDecodeError_GetObject (C fun- PyUnstable_InterpreterFrame_GetLasti (C
ction), 66 function), 202
PyUnicodeDecodeError_GetReason (C fun- PyUnstable_InterpreterFrame_GetLine (C
ction), 66 function), 203
PyUnicodeDecodeError_GetStart (C function), PyUnstable_Long_CompactValue (C function),
66 139
PyUnicodeDecodeError_SetEnd (C function), 66 PyUnstable_Long_IsCompact (C function), 139
PyUnicodeDecodeError_SetReason (C fun- PyUnstable_Object_GC_NewWithExtraData
ction), 66 (C function), 323
PyUnicodeDecodeError_SetStart (C function), PyUnstable_PerfMapState_Fini (C function),
66 97
PyUnicodeEncodeError_GetEncoding (C fun- PyUnstable_PerfMapState_Init (C function),
ction), 66 97
PyUnicodeEncodeError_GetEnd (C function), 66 PyUnstable_Type_AssignVersionTag (C fun-
PyUnicodeEncodeError_GetObject (C fun- ction), 130
ction), 66 PyUnstable_WritePerfMapEntry (C function),
PyUnicodeEncodeError_GetReason (C fun- 97
ction), 66 PyVarObject (C type), 274
PyUnicodeEncodeError_GetStart (C function), PyVarObject_HEAD_INIT (C macro), 276
66 PyVarObject.ob_size (C member), 291
PyUnicodeEncodeError_SetEnd (C function), 66 PyVectorcall_Call (C function), 107
PyUnicodeEncodeError_SetReason (C fun- PyVectorcall_Function (C function), 107
ction), 66 PyVectorcall_NARGS (C function), 107
PyWeakref_Check (C function), 198

Índice 391
The Python/C API, Versión 3.13.0a5

PyWeakref_CheckProxy (C function), 198 ssizeargfunc (C type), 319


PyWeakref_CheckRef (C function), 198 ssizeobjargproc (C type), 319
PyWeakref_GET_OBJECT (C function), 199 static type checker, 344
PyWeakref_GetObject (C function), 198 staticmethod
PyWeakref_GetRef (C function), 198 built-in function, 278
PyWeakref_NewProxy (C function), 198 stderr (in module sys), 227, 228
PyWeakref_NewRef (C function), 198 stdin (in module sys), 227, 228
PyWideStringList (C type), 238 stdout (in module sys), 227, 228
PyWideStringList_Append (C function), 238 strerror (C function), 57
PyWideStringList_Insert (C function), 238 string
PyWideStringList.items (C member), 238 PyObject_Str (C function), 102
PyWideStringList.length (C member), 238 structmember.h, 283
PyWrapper_New (C function), 195 sum_list(), 10
sum_sequence(), 11, 12
R sys
READ_RESTRICTED (C macro), 280 module, 13, 215, 227, 228
READONLY (C macro), 280 SystemError (built-in exception), 187
realloc (C function), 261
rebanada, 343 T
recolección de basura, 335 T_BOOL (C macro), 283
referencia fuerte, 344 T_BYTE (C macro), 283
referencia prestada, 331 T_CHAR (C macro), 283
releasebufferproc (C type), 319 T_DOUBLE (C macro), 283
repr T_FLOAT (C macro), 283
built-in function, 102, 294 T_INT (C macro), 283
reprfunc (C type), 318 T_LONG (C macro), 283
RESTRICTED (C macro), 280 T_LONGLONG (C macro), 283
retrollamada, 332 T_NONE (C macro), 283
richcmpfunc (C type), 319 T_OBJECT (C macro), 283
ruta de importación, 336 T_OBJECT_EX (C macro), 283
T_PYSSIZET (C macro), 283
S T_SHORT (C macro), 283
saltos de líneas universales, 345 T_STRING (C macro), 283
search T_STRING_INPLACE (C macro), 283
path, module, 13, 215, 218 T_UBYTE (C macro), 283
secuencia, 343 T_UINT (C macro), 283
sendfunc (C type), 319 T_ULONG (C macro), 283
sentencia, 344 T_ULONGULONG (C macro), 283
sequence T_USHORT (C macro), 283
object, 144 ternaryfunc (C type), 319
set tipado de pato, 333
object, 175 tipo, 345
set_all(), 10 tipos genéricos, 336
setattrfunc (C type), 318 traverseproc (C type), 324
setattrofunc (C type), 318 tupla nombrada, 339
setswitchinterval (in module sys), 219 tuple
setter (C type), 283 built-in function, 115, 170
SIGINT (C macro), 63, 64 object, 165
signal type
module, 63, 64 built-in function, 103
SIZE_MAX (C macro), 136 object, 7, 127
soft deprecated, 344
special U
método, 344 ULONG_MAX (C macro), 136

392 Índice
The Python/C API, Versión 3.13.0a5

unaryfunc (C type), 319


USE_STACKCHECK (C macro), 72

V
variable de clase, 332
variable de contexto, 332
variables de entorno
__PYVENV_LAUNCHER__, 245, 252
PATH, 13
PYTHON_CPU_COUNT, 249
PYTHON_PRESITE, 252
PYTHONCOERCECLOCALE, 257
PYTHONDEBUG, 212, 251
PYTHONDEVMODE, 246
PYTHONDONTWRITEBYTECODE, 212, 255
PYTHONDUMPREFS, 247
PYTHONEXECUTABLE, 252
PYTHONFAULTHANDLER, 247
PYTHONHASHSEED, 213, 248
PYTHONHOME, 13, 213, 219, 248
PYTHONINSPECT, 213, 248
PYTHONINTMAXSTRDIGITS, 249
PYTHONIOENCODING, 253
PYTHONLEGACYWINDOWSFSENCODING, 214,
241
PYTHONLEGACYWINDOWSSTDIO, 214, 249
PYTHONMALLOC, 262, 266, 268, 269
PYTHONMALLOCSTATS, 250, 262
PYTHONNODEBUGRANGES, 246
PYTHONNOUSERSITE, 214, 254
PYTHONOPTIMIZE, 214, 250
PYTHONPATH, 13, 213, 250
PYTHONPERFSUPPORT, 254
PYTHONPLATLIBDIR, 250
PYTHONPROFILEIMPORTTIME, 248
PYTHONPYCACHEPREFIX, 252
PYTHONSAFEPATH, 245
PYTHONTRACEMALLOC, 254
PYTHONUNBUFFERED, 215, 245
PYTHONUTF8, 242, 257
PYTHONVERBOSE, 215, 254
PYTHONWARNINGS, 254
vectorcallfunc (C type), 106
version (in module sys), 218, 219
visitproc (C type), 324
vista de diccionario, 333

W
WRITE_RESTRICTED (C macro), 280

Z
Zen de Python, 346

Índice 393

También podría gustarte