The Python/C API
Release 3.13.7
Guido van Rossum and the Python development team
setembro 02, 2025
Python Software Foundation
Email:
[email protected] Sumário
1 Introdução 3
1.1 Padrõ es de codificaçã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Arquivos de inclusã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Macros ú teis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Objetos, tipos e contagens de referê ncias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.1 Contagens de referê ncias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.2 Tipos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5 Exceçõ es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.6 Incorporando Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.7 Compilaçõ es de depuraçã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.8 Ferramentas de terceiros recomendadas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Estabilidade da API C 15
2.1 API C Instá vel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Interface Biná ria de Aplicaçã o Está vel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.1 API C Limitada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.2 ABI Está vel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.3 Escopo e Desempenho da API Limitada . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.4 Limitaçõ es da API Limitada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3 Consideraçõ es da plataforma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4 Conteú do da API Limitada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3 A camada de nível muito alto 43
4 Contagem de referências 49
5 Manipulando Exceções 53
5.1 Impressã o e limpeza . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.2 Lançando exceçõ es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.3 Emitindo advertê ncias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.4 Consultando o indicador de erro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.5 Tratamento de sinal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.6 Classes de exceçã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.7 Objeto Exceçã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.8 Objetos de exceçã o Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.9 Controle de recursã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.10 Exception and warning types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.10.1 Exception types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.10.2 OSError aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.10.3 Warning types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
i
6 Utilitários 71
6.1 Utilitá rios do sistema operacional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.2 System Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.3 Process Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.4 Importando mó dulos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.5 Suporte a marshalling de dados . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.6 Aná lise de argumentos e construçã o de valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.6.1 Aná lise de argumentos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.6.2 Construindo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.7 Conversã o e formaçã o de strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.8 API do PyHash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.9 Reflexã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.10 Registro de codec e funçõ es de suporte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
6.10.1 API de pesquisa de codec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.10.2 API de registro de tratamentos de erros de decodificaçã o Unicode . . . . . . . . . . . . . 95
6.11 API C PyTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.11.1 Tipos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.11.2 Funçõ es de reló gio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
6.11.3 Funçõ es de reló gio brutas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.11.4 Funçõ es de conversã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.12 Suporte a Mapas do Perf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
7 Camada de Objetos Abstratos 99
7.1 Protocolo de objeto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
7.2 Protocolo de chamada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
7.2.1 O protocolo tp_call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
7.2.2 O protocolo vectorcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
7.2.3 API de chamada de objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
7.2.4 API de suporte a chamadas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
7.3 Protocolo de nú mero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
7.4 Protocolo de sequê ncia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
7.5 Protocolo de mapeamento . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
7.6 Protocolo Iterador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
7.7 Protocolo de Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
7.7.1 Estrutura de Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
7.7.2 Tipos de solicitaçã o do buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
7.7.3 Vetores Complexos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
7.7.4 Funçõ es relacionadas ao Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
8 Camada de Objetos Concretos 127
8.1 Objetos Fundamentais . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.1.1 Objetos tipo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.1.2 O Objeto None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.2 Objetos Numé ricos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.2.1 Objetos Inteiros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.2.2 Objetos Booleanos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
8.2.3 Objetos de ponto flutuante . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
8.2.4 Objetos nú meros complexos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
8.3 Objetos Sequê ncia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
8.3.1 Objetos bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
8.3.2 Objetos byte array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
8.3.3 Objetos Unicode e Codecs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
8.3.4 Objeto tupla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
8.3.5 Objetos sequê ncia de estrutura . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
8.3.6 Objeto List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
8.4 Coleçõ es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
8.4.1 Objetos dicioná rios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
8.4.2 Objeto Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
ii
8.5 Objetos Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.5.1 Objetos Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.5.2 Objetos de Mé todo de Instâ ncia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.5.3 Objetos mé todo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.5.4 Objeto cé lula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.5.5 Objetos có digo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
8.5.6 Sinalizadores de objetos có digo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
8.5.7 Informaçã o adicional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6 Outros Objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
8.6.1 Objetos arquivos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
8.6.2 Objetos do Mó dulo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
8.6.3 Objetos Iteradores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
8.6.4 Objetos Descritores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
8.6.5 Objetos Slice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
8.6.6 Objetos MemoryView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
8.6.7 Objetos referê ncia fraca . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
8.6.8 Capsules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
8.6.9 Objetos Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
8.6.10 Objetos Geradores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
8.6.11 Objetos corrotina . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
8.6.12 Objetos de variá veis de contexto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
8.6.13 Objetos DateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
8.6.14 Objetos de indicaçã o de tipos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
9 Inicialização, finalização e threads 213
9.1 Antes da inicializaçã o do Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
9.2 Variá veis de configuraçã o global . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
9.3 Inicializando e encerrando o interpretador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
9.4 Process-wide parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
9.5 Estado de thread e a trava global do interpretador . . . . . . . . . . . . . . . . . . . . . . . . . . 223
9.5.1 Releasing the GIL from extension code . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
9.5.2 Non-Python created threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
9.5.3 Cuidados com o uso de fork() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
9.5.4 Cautions regarding runtime finalization . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
9.5.5 High-level API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
9.5.6 Low-level API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
9.6 Sub-interpreter support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
9.6.1 A Per-Interpreter GIL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
9.6.2 Bugs and caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
9.7 Notificaçõ es assíncronas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
9.8 Profiling and Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
9.9 Reference tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
9.10 Advanced Debugger Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
9.11 Thread Local Storage Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
9.11.1 Thread Specific Storage (TSS) API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
9.11.2 Thread Local Storage (TLS) API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
9.12 Synchronization Primitives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
9.12.1 Python Critical Section API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
10 Configuração de Inicialização do Python 243
10.1 Exemplo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
10.2 PyWideStringList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
10.3 PyStatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
10.4 PyPreConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
10.5 Pré -inicializar Python com PyPreConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
10.6 PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
10.7 Initialization with PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
10.8 Isolated Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
iii
10.9 Configuraçã o do Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
10.10 Python Path Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
10.11 Py_GetArgcArgv() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
10.12 Multi-Phase Initialization Private Provisional API . . . . . . . . . . . . . . . . . . . . . . . . . . 263
11 Gerenciamento de Memória 265
11.1 Visã o Geral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
11.2 Allocator Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
11.3 Інтерфейс необробленої пам’яті . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
11.4 Interface da Memó ria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
11.5 Alocadores de objeto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
11.6 Alocadores de memó ria padrã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
11.7 Alocadores de memó ria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
11.8 Debug hooks on the Python memory allocators . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
11.9 Розподільник pymalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
11.9.1 Налаштувати pymalloc Arena Allocator . . . . . . . . . . . . . . . . . . . . . . . . . . 273
11.10 The mimalloc allocator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
11.11 tracemalloc C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
11.12 Exemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
12 Suporte a implementação de Objetos 277
12.1 Alocando objetos na heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
12.2 Estruturas comuns de objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
12.2.1 Base object types and macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
12.2.2 Implementing functions and methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
12.2.3 Accessing attributes of extension types . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
12.3 Type Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
12.3.1 Referê ncias rá pidas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
12.3.2 PyTypeObject Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
12.3.3 PyObject Slots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
12.3.4 PyVarObject Slots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
12.3.5 PyTypeObject Slots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
12.3.6 Static Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
12.3.7 Tipos no heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
12.3.8 Number Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
12.3.9 Mapping Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
12.3.10 Sequence Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
12.3.11 Buffer Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
12.3.12 Async Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
12.3.13 Slot Type typedefs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
12.3.14 Exemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
12.4 Suporte a Coleta Cíclica de Lixo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
12.4.1 Controlando o estado do coletor de lixo . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
12.4.2 Querying Garbage Collector State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
13 API e Versionamento de ABI 327
14 API C de monitoramento 329
15 Gerando eventos de execução 331
15.1 Gerenciando o Estado de um Monitoramento . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
A Glossário 337
B Sobre esta documentação 355
B.1 Contribuidores da documentaçã o do Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
C História e Licença 357
C.1 Histó ria do software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
iv
C.2 Termos e condiçõ es para acessar ou usar Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
C.2.1 PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 . . . . . . . . . . . . . 358
C.2.2 ACORDO DE LICENCIAMENTO DA BEOPEN.COM PARA PYTHON 2.0 . . . . . . 359
C.2.3 CONTRATO DE LICENÇA DA CNRI PARA O PYTHON 1.6.1 . . . . . . . . . . . . 360
C.2.4 ACORDO DE LICENÇA DA CWI PARA PYTHON 0.9.0 A 1.2 . . . . . . . . . . . . . 361
C.2.5 ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION . 361
C.3 Licenças e Reconhecimentos para Software Incorporado . . . . . . . . . . . . . . . . . . . . . . 361
C.3.1 Mersenne Twister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
C.3.2 Soquetes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
C.3.3 Serviços de soquete assíncrono . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
C.3.4 Gerenciamento de cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
C.3.5 Rastreamento de execuçã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
C.3.6 Funçõ es UUencode e UUdecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
C.3.7 Chamadas de procedimento remoto XML . . . . . . . . . . . . . . . . . . . . . . . . . 365
C.3.8 test_epoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
C.3.9 kqueue de seleçã o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
C.3.10 SipHash24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
C.3.11 strtod e dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
C.3.18 Conjunto de testes C14N do W3C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
C.3.19 mimalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
C.3.20 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
C.3.21 Global Unbounded Sequences (GUS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
D Direitos autorais 377
Referências Bibliográficas 379
Índice 381
v
vi
The Python/C API, Release 3.13.7
Este manual documenta a API usada por programadores C e C++ que desejam escrever mó dulos de extensõ es ou
embutir Python. É um complemento para extending-index, que descreve os princípios gerais da escrita de extensõ es
mas nã o documenta as funçõ es da API em detalhes.
Sumário 1
The Python/C API, Release 3.13.7
2 Sumário
CAPÍTULO 1
Introdução
A Interface de Programaçã o de Aplicaçõ es (API) para Python fornece aos programadores C e C++ acesso ao inter-
pretador Python em uma variedade de níveis. A API pode ser usada igualmente em C++, mas, para abreviar, geral-
mente é chamada de API Python/C. Existem dois motivos fundamentalmente diferentes para usar a API Python/C. A
primeira razã o é escrever módulos de extensão para propó sitos específicos; esses sã o mó dulos C que estendem o inter-
pretador Python. Este é provavelmente o uso mais comum. O segundo motivo é usar Python como um componente
em uma aplicaçã o maior; esta té cnica é geralmente referida como incorporação Python em uma aplicaçã o.
Escrever um mó dulo de extensã o é um processo relativamente bem compreendido, no qual uma abordagem de “livro
de receitas” funciona bem. Existem vá rias ferramentas que automatizam o processo até certo ponto. Embora as
pessoas tenham incorporado o Python em outras aplicaçõ es desde sua existê ncia inicial, o processo de incorporaçã o
do Python é menos direto do que escrever uma extensã o.
Muitas funçõ es da API sã o ú teis independentemente de você estar incorporando ou estendendo o Python; alé m disso,
a maioria das aplicaçõ es que incorporam Python també m precisará fornecer uma extensã o customizada, portanto, é
provavelmente uma boa ideia se familiarizar com a escrita de uma extensã o antes de tentar incorporar Python em
uma aplicaçã o real.
1.1 Padrões de codificação
Se você estiver escrevendo có digo C para inclusã o no CPython, deve seguir as diretrizes e padrõ es definidos na PEP 7.
Essas diretrizes se aplicam independentemente da versã o do Python com a qual você está contribuindo. Seguir essas
convençõ es nã o é necessá rio para seus pró prios mó dulos de extensã o de terceiros, a menos que você eventualmente
espere contribuí-los para o Python.
1.2 Arquivos de inclusão
Todas as definiçõ es de funçã o, tipo e macro necessá rias para usar a API Python/C estã o incluídas em seu có digo pela
seguinte linha:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
Isso implica a inclusã o dos seguintes cabeçalhos padrã o: <stdio.h>, <string.h>, <errno.h>, <limits.h>,
<assert.h> e <stdlib.h> (se disponível).
3
The Python/C API, Release 3.13.7
® Nota
Uma vez que Python pode definir algumas definiçõ es de pré -processador que afetam os cabeçalhos padrã o em
alguns sistemas, você deve incluir Python.h antes de quaisquer cabeçalhos padrã o serem incluídos.
É recomendá vel sempre definir PY_SSIZE_T_CLEAN antes de incluir Python.h. Veja Análise de argumentos e
construção de valores para uma descriçã o desta macro.
Todos os nomes visíveis ao usuá rio definidos por Python.h (exceto aqueles definidos pelos cabeçalhos padrã o in-
cluídos) tê m um dos prefixos Py ou _Py. Nomes começando com _Py sã o para uso interno pela implementaçã o
Python e nã o devem ser usados por escritores de extensã o. Os nomes dos membros da estrutura nã o tê m um prefixo
reservado.
® Nota
O có digo do usuá rio nunca deve definir nomes que começam com Py ou _Py. Isso confunde o leitor e coloca em
risco a portabilidade do có digo do usuá rio para versõ es futuras do Python, que podem definir nomes adicionais
começando com um desses prefixos.
Os arquivos de cabeçalho sã o normalmente instalados com Python. No Unix, eles estã o localizados nos di-
retó rios prefix/include/pythonversion/ e exec_prefix/include/pythonversion/, onde prefix e
exec_prefix sã o definidos pelos parâ metros correspondentes ao script configure e version do Python é '%d.%d'
% sys.version_info[:2]. No Windows, os cabeçalhos sã o instalados em prefix/include, onde prefix é
o diretó rio de instalaçã o especificado para o instalador.
Para incluir os cabeçalhos, coloque os dois diretó rios (se diferentes) no caminho de pesquisa do compilador para
as inclusõ es. Não coloque os diretó rios pais no caminho de busca e entã o use #include <pythonX.Y/Python.
h>; isto irá quebrar em compilaçõ es multiplataforma, uma vez que os cabeçalhos independentes da plataforma em
prefix incluem os cabeçalhos específicos da plataforma de exec_prefix.
Os usuá rios de C++ devem notar que embora a API seja definida inteiramente usando C, os arquivos de cabeçalho
declaram apropriadamente os pontos de entrada como extern "C". Como resultado, nã o há necessidade de fazer
nada especial para usar a API do C++.
1.3 Macros úteis
Diversas macros ú teis sã o definidas nos arquivos de cabeçalho do Python. Muitas sã o definidas mais pró ximas de
onde sã o ú teis (por exemplo, Py_RETURN_NONE). Outras de utilidade mais geral sã o definidas aqui. Esta nã o é
necessariamente uma lista completa.
PyMODINIT_FUNC
Declara uma funçã o de inicializaçã o do mó dulo de extensã o PyInit. O tipo de retorno da funçã o é
PyObject*. A macro declara quaisquer declaraçõ es de ligaçã o especial necessá rias pela plataforma e, para
C++, declara a funçã o como extern "C".
A funçã o de inicializaçã o deve ser nomeada PyInit_name, onde name é o nome do mó dulo, e deve ser o
ú nico item nã o-static definido no arquivo do mó dulo. Exemplo:
static struct PyModuleDef spam_module = {
.m_base = PyModuleDef_HEAD_INIT,
.m_name = "spam",
...
};
PyMODINIT_FUNC
PyInit_spam(void)
{
(continua na pró xima pá gina)
4 Capítulo 1. Introdução
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
return PyModuleDef_Init(&spam_module);
}
Py_ABS(x)
Retorna o valor absoluto de x.
Adicionado na versã o 3.3.
Py_ALWAYS_INLINE
Pede ao compilador para sempre embutir uma funçã o em linha está tica. O compilador pode ignorá -lo e decide
nã o inserir a funçã o.
Ele pode ser usado para inserir funçõ es em linha está ticas críticas de desempenho ao compilar Python no modo
de depuraçã o com funçã o de inserir em linha desabilitada. Por exemplo, o MSC desabilita a funçã o de inserir
em linha ao compilar no modo de depuraçã o.
Marcar cegamente uma funçã o em linha está tica com Py_ALWAYS_INLINE pode resultar em desempenhos
piores (devido ao aumento do tamanho do có digo, por exemplo). O compilador geralmente é mais inteligente
que o desenvolvedor para a aná lise de custo/benefício.
Se o Python tiver sido compilado em modo de depuraçã o (se a macro Py_DEBUG estiver definida), a macro
Py_ALWAYS_INLINE nã o fará nada.
Deve ser especificado antes do tipo de retorno da funçã o. Uso:
static inline Py_ALWAYS_INLINE int random(void) { return 4; }
Adicionado na versã o 3.11.
Py_CHARMASK(c)
O argumento deve ser um caractere ou um nú mero inteiro no intervalo [-128, 127] ou [0, 255]. Esta macro
retorna c convertido em um unsigned char.
Py_DEPRECATED(version)
Use isso para declaraçõ es descontinuadas. A macro deve ser colocada antes do nome do símbolo.
Exemplo:
Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
Alterado na versã o 3.8: Suporte a MSVC foi adicionado.
Py_GETENV(s)
Como getenv(s), mas retorna NULL se a opçã o -E foi passada na linha de comando (veja PyConfig.
use_environment).
Py_MAX(x, y)
Retorna o valor má ximo entre x e y.
Adicionado na versã o 3.3.
Py_MEMBER_SIZE(type, member)
Retorna o tamanho do member de uma estrutura (type) em bytes.
Adicionado na versã o 3.6.
Py_MIN(x, y)
Retorna o valor mínimo entre x e y.
Adicionado na versã o 3.3.
1.3. Macros úteis 5
The Python/C API, Release 3.13.7
Py_NO_INLINE
Desabilita a inserçã o em linha em uma funçã o. Por exemplo, isso reduz o consumo da pilha C: ú til em com-
pilaçõ es LTO+PGO que faz uso intenso de inserçã o em linha de có digo (veja bpo-33720).
Uso:
Py_NO_INLINE static int random(void) { return 4; }
Adicionado na versã o 3.11.
Py_STRINGIFY(x)
Converte x para uma string C. Por exemplo, Py_STRINGIFY(123) retorna "123".
Adicionado na versã o 3.4.
Py_UNREACHABLE()
Use isso quando você tiver um caminho de có digo que nã o pode ser alcançado por design. Por exemplo,
na clá usula default: em uma instruçã o switch para a qual todos os valores possíveis sã o incluídos nas
instruçõ es case. Use isto em lugares onde você pode ficar tentado a colocar uma chamada assert(0) ou
abort().
No modo de lançamento, a macro ajuda o compilador a otimizar o có digo e evita um aviso sobre có digo
inacessível. Por exemplo, a macro é implementada com __builtin_unreachable() no GCC em modo de
lançamento.
Um uso para Py_UNREACHABLE() é seguir uma chamada de uma funçã o que nunca retorna, mas que nã o é
declarada com _Py_NO_RETURN.
Se um caminho de có digo for um có digo muito imprová vel, mas puder ser alcançado em casos excepcionais,
esta macro nã o deve ser usada. Por exemplo, sob condiçã o de pouca memó ria ou se uma chamada de sistema
retornar um valor fora do intervalo esperado. Nesse caso, é melhor relatar o erro ao chamador. Se o erro nã o
puder ser reportado ao chamador, Py_FatalError() pode ser usada.
Adicionado na versã o 3.7.
Py_UNUSED(arg)
Use isso para argumentos nã o usados em uma definiçã o de funçã o para silenciar avisos do compilador. Exem-
plo: int func(int a, int Py_UNUSED(b)) { return a; }.
Adicionado na versã o 3.4.
PyDoc_STRVAR(name, str)
Cria uma variá vel com o nome name que pode ser usada em docstrings. Se o Python for compilado sem
docstrings, o valor estará vazio.
Use PyDoc_STRVAR para docstrings para ter suporte à compilaçã o do Python sem docstrings, conforme es-
pecificado em PEP 7.
Exemplo:
PyDoc_STRVAR(pop_doc, "Remove e retorna o elemento mais à direita.");
static PyMethodDef deque_methods[] = {
// ...
{"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
// ...
}
PyDoc_STR(str)
Cria uma docstring para a string de entrada fornecida ou uma string vazia se docstrings estiverem desabilitadas.
Use PyDoc_STR ao especificar docstrings para ter suporte à compilaçã o do Python sem docstrings, conforme
especificado em PEP 7.
Exemplo:
6 Capítulo 1. Introdução
The Python/C API, Release 3.13.7
static PyMethodDef pysqlite_row_methods[] = {
{"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
PyDoc_STR("Retorna as chaves da linha.")},
{NULL, NULL}
};
1.4 Objetos, tipos e contagens de referências
A maioria das funçõ es da API Python/C tem um ou mais argumentos, bem como um valor de retorno do tipo
PyObject*. Este tipo é um ponteiro para um tipo de dados opaco que representa um objeto Python arbitrá rio. Como
todos os tipos de objeto Python sã o tratados da mesma maneira pela linguagem Python na maioria das situaçõ es
(por exemplo, atribuiçõ es, regras de escopo e passagem de argumento), é adequado que eles sejam representados
por um ú nico tipo C. Quase todos os objetos Python vivem na pilha: você nunca declara uma variá vel automá tica
ou está tica do tipo PyObject, variá veis de apenas ponteiro do tipo PyObject* podem ser declaradas. A ú nica
exceçã o sã o os objetos de tipo; uma vez que estes nunca devem ser desalocados, eles sã o normalmente objetos
está ticos PyTypeObject.
Todos os objetos Python (mesmo inteiros Python) tê m um tipo e uma contagem de referências. O tipo de um objeto
determina que tipo de objeto ele é (por exemplo, um nú mero inteiro, uma lista ou uma funçã o definida pelo usuá rio;
existem muitos mais, conforme explicado em types). Para cada um dos tipos conhecidos, há uma macro para verificar
se um objeto é desse tipo; por exemplo, PyList_Check(a) é verdadeiro se (e somente se) o objeto apontado por a
for uma lista Python.
1.4.1 Contagens de referências
A contagem de referê ncias é importante porque os computadores atuais tê m um tamanho de memó ria finito (e fre-
quentemente severamente limitado); ela conta quantos lugares diferentes existem que possuem uma referência forte a
um objeto. Tal lugar pode ser outro objeto, ou uma variá vel C global (ou está tica), ou uma variá vel local em alguma
funçã o C. Quando a ú ltima referência forte a um objeto é liberada (ou seja, sua contagem de referê ncias se torna
zero), o objeto é desalocado. Se ele contiver referê ncias a outros objetos, essas referê ncias sã o liberadas. Esses
outros objetos podem ser desalocados por sua vez, se nã o houver mais referê ncias a eles, e assim por diante. (Há um
problema ó bvio com objetos que referenciam uns aos outros aqui; por enquanto, a soluçã o é “nã o faça isso”.)
Contagens de referê ncias sã o sempre manipuladas explicitamente. A maneira normal é usar a macro Py_INCREF()
para obter uma nova referê ncia a um objeto (ou seja, incrementar sua contagem de referê ncias em um), e
Py_DECREF() para liberar essa referê ncia (ou seja, decrementar a contagem de referê ncias em um). A macro
Py_DECREF() é consideravelmente mais complexa do que a incref, pois deve verificar se a contagem de referê ncias
se torna zero e, em seguida, fazer com que o desalocador do objeto seja chamado. O desalocador é um ponteiro para
funçã o contido na estrutura de tipo do objeto. O desalocador específico do tipo cuida da liberaçã o de referê ncias
para outros objetos contidos no objeto se este for um tipo de objeto composto, como uma lista, bem como de execu-
tar qualquer finalizaçã o adicional necessá ria. Nã o há chance de a contagem de referê ncias transbordar; pelo menos
tantos bits sã o usados para armazenar a contagem de referê ncia quantos forem os locais de memó ria distintos na me-
mó ria virtual (presumindo sizeof(Py_ssize_t) >= sizeof(void*)). Portanto, o incremento da contagem
de referê ncias é uma operaçã o simples.
Nã o é necessá rio manter uma referência forte (ou seja, incrementar a contagem de referê ncias) para cada variá vel
local que conté m um ponteiro para um objeto. Em teoria, a contagem de referê ncias do objeto aumenta em um
quando a variá vel é feita para apontar para ele e diminui em um quando a variá vel sai do escopo. No entanto, esses
dois se cancelam, portanto, no final, a contagem de referê ncias nã o mudou. A ú nica razã o real para usar a contagem
de referê ncias é evitar que o objeto seja desalocado enquanto nossa variá vel estiver apontando para ele. Se sabemos
que existe pelo menos uma outra referê ncia ao objeto que vive pelo menos tanto quanto nossa variá vel, nã o há
necessidade de tomar uma nova referência forte (ou seja, incrementar a contagem de referê ncias) temporariamente.
Uma situaçã o importante em que isso ocorre é em objetos que sã o passados como argumentos para funçõ es C em
um mó dulo de extensã o que sã o chamados de Python; o mecanismo de chamada garante manter uma referê ncia a
todos os argumentos durante a chamada.
No entanto, uma armadilha comum é extrair um objeto de uma lista e mantê -lo por um tempo, sem tomar uma
nova referê ncia. Alguma outra operaçã o poderia remover o objeto da lista, liberando essa referê ncia e possivelmente
1.4. Objetos, tipos e contagens de referências 7
The Python/C API, Release 3.13.7
desalocando-o. O perigo real é que operaçõ es aparentemente inocentes podem invocar có digo Python arbitrá rio que
poderia fazer isso; existe um caminho de có digo que permite que o controle flua de volta para o usuá rio a partir de
um Py_DECREF(), entã o quase qualquer operaçã o é potencialmente perigosa.
Uma abordagem segura é sempre usar as operaçõ es gené ricas (funçõ es cujo nome começa com PyObject_,
PyNumber_, PySequence_ ou PyMapping_). Essas operaçõ es sempre criam uma nova referência forte (ou seja,
incrementam a contagem de referê ncias) do objeto que retornam. Isso deixa o chamador com a responsabilidade de
chamar Py_DECREF() quando terminar com o resultado; isso logo se torna uma segunda natureza.
Detalhes da contagem de referências
O comportamento da contagem de referê ncias de funçõ es na API C/Python é melhor explicado em termos de pro-
priedade de referências. A propriedade pertence à s referê ncias, nunca aos objetos (os objetos nã o sã o possuídos:
eles sã o sempre compartilhados). “Possuir uma referê ncia” significa ser responsá vel por chamar Py_DECREF nela
quando a referê ncia nã o for mais necessá ria. A propriedade també m pode ser transferida, o que significa que o có digo
que recebe a propriedade da referê ncia torna-se responsá vel por eventualmente efetuar um liberando ela chamando
Py_DECREF() ou Py_XDECREF() quando nã o é mais necessá rio – ou passando essa responsabilidade (geralmente
para o responsá vel pela chamada). Quando uma funçã o passa a propriedade de uma referê ncia para seu chama-
dor, diz-se que o chamador recebe uma nova referê ncia. Quando nenhuma propriedade é transferida, diz-se que o
chamador toma emprestado a referê ncia. Nada precisa ser feito para uma referência emprestada.
Por outro lado, quando uma funçã o de chamada passa uma referê ncia a um objeto, há duas possibilidades: a funçã o
rouba uma referê ncia ao objeto, ou nã o. Roubar uma referência significa que quando você passa uma referê ncia para
uma funçã o, essa funçã o presume que agora ela possui essa referê ncia e você nã o é mais responsá vel por ela.
Poucas funçõ es roubam referê ncias; as duas exceçõ es notá veis sã o PyList_SetItem() e PyTuple_SetItem(),
que roubam uma referê ncia para o item (mas nã o para a tupla ou lista na qual o item é colocado!). Essas funçõ es
foram projetadas para roubar uma referê ncia devido a um idioma comum para preencher uma tupla ou lista com
objetos recé m-criados; por exemplo, o có digo para criar a tupla (1, 2, "three") pode ser parecido com isto
(esquecendo o tratamento de erros por enquanto; uma maneira melhor de codificar isso é mostrada abaixo):
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("três"));
Aqui, PyLong_FromLong() retorna uma nova referê ncia que é imediatamente roubada por PyTuple_SetItem().
Quando você quiser continuar usando um objeto, embora a referê ncia a ele seja roubada, use Py_INCREF() para
obter outra referê ncia antes de chamar a funçã o de roubo de referê ncia.
A propó sito, PyTuple_SetItem() é a única maneira de definir itens de tupla; PySequence_SetItem() e
PyObject_SetItem() se recusam a fazer isso, pois tuplas sã o um tipo de dados imutá vel. Você só deve usar
PyTuple_SetItem() para tuplas que você mesmo está criando.
O có digo equivalente para preencher uma lista pode ser escrita usando PyList_New() e PyList_SetItem().
No entanto, na prá tica, você raramente usará essas maneiras de criar e preencher uma tupla ou lista. Existe uma
funçã o gené rica, Py_BuildValue(), que pode criar objetos mais comuns a partir de valores C, dirigidos por uma
string de formato. Por exemplo, os dois blocos de có digo acima podem ser substituídos pelos seguintes (que també m
cuidam da verificaçã o de erros):
PyObject *tuple, *list;
tuple = Py_BuildValue("(iis)", 1, 2, "três");
list = Py_BuildValue("[iis]", 1, 2, "três");
É muito mais comum usar PyObject_SetItem() e amigos com itens cujas referê ncias você está apenas pegando
emprestado, como argumentos que foram passados para a funçã o que você está escrevendo. Nesse caso, o compor-
tamento deles em relaçã o à s referê ncias é muito mais sã o, já que você nã o precisa tomar uma nova referê ncia só
8 Capítulo 1. Introdução
The Python/C API, Release 3.13.7
para poder doá -la (“mande-a ser roubada”). Por exemplo, esta funçã o define todos os itens de uma lista (na verdade,
qualquer sequê ncia mutá vel) para um determinado 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;
}
A situaçã o é ligeiramente diferente para os valores de retorno da funçã o. Embora passar uma referê ncia para a
maioria das funçõ es nã o altere suas responsabilidades de propriedade para aquela referê ncia, muitas funçõ es que
retornam uma referê ncia a um objeto fornecem a propriedade da referê ncia. O motivo é simples: em muitos casos, o
objeto retornado é criado instantaneamente e a referê ncia que você obté m é a ú nica referê ncia ao objeto. Portanto, as
funçõ es gené ricas que retornam referê ncias a objetos, como PyObject_GetItem() e PySequence_GetItem(),
sempre retornam uma nova referê ncia (o chamador torna-se o dono da referê ncia).
É importante perceber que se você possui uma referê ncia retornada por uma funçã o depende de qual funçã o você
chama apenas — a plumagem (o tipo do objeto passado como um argumento para a funçã o) não entra nela! Assim,
se você extrair um item de uma lista usando PyList_GetItem(), você nã o possui a referê ncia — mas se obtiver o
mesmo item da mesma lista usando PySequence_GetItem() (que leva exatamente os mesmos argumentos), você
possui uma referê ncia ao objeto retornado.
Aqui está um exemplo de como você poderia escrever uma funçã o que calcula a soma dos itens em uma lista de
inteiros; uma vez usando PyList_GetItem(), e uma 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; /* Não é uma lista */
for (i = 0; i < n; i++) {
item = PyList_GetItem(list, i); /* Não pode falhar */
if (!PyLong_Check(item)) continue; /* Ignora não-inteiros */
value = PyLong_AsLong(item);
if (value == -1 && PyErr_Occurred())
/* Inteiro muito grande para caber em um C longo, sai */
return -1;
total += value;
}
(continua na pró xima pá gina)
1.4. Objetos, tipos e contagens de referências 9
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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; /* Não tem comprimento */
for (i = 0; i < n; i++) {
item = PySequence_GetItem(sequence, i);
if (item == NULL)
return -1; /* Não é uma sequência ou outra falha */
if (PyLong_Check(item)) {
value = PyLong_AsLong(item);
Py_DECREF(item);
if (value == -1 && PyErr_Occurred())
/* Inteiro muito grande para caber em um C longo, sai */
return -1;
total += value;
}
else {
Py_DECREF(item); /* Descartar propriedade de referência */
}
}
return total;
}
1.4.2 Tipos
Existem alguns outros tipos de dados que desempenham um papel significativo na API Python/C; a maioria sã o tipos
C simples, como int, long, double e char*. Alguns tipos de estrutura sã o usados para descrever tabelas está ticas
usadas para listar as funçõ es exportadas por um mó dulo ou os atributos de dados de um novo tipo de objeto, e outro
é usado para descrever o valor de um nú mero complexo. Eles serã o discutidos junto com as funçõ es que os utilizam.
type Py_ssize_t
Parte da ABI Está vel. Um tipo integral assinado tal que sizeof(Py_ssize_t) == sizeof(size_t).
C99 nã o define tal coisa diretamente (size_t é um tipo integral nã o assinado). Veja PEP 353 para mais detalhes.
PY_SSIZE_T_MAX é o maior valor positivo do tipo Py_ssize_t.
1.5 Exceções
O programador Python só precisa lidar com exceçõ es se o tratamento de erros específico for necessá rio; as exceçõ es
nã o tratadas sã o propagadas automaticamente para o chamador, depois para o chamador e assim por diante, até
chegarem ao interpretador de nível superior, onde sã o relatadas ao usuá rio acompanhadas por um traceback (situaçã o
da pilha de execuçã o).
Para programadores C, entretanto, a verificaçã o de erros sempre deve ser explícita. Todas as funçõ es na API
Python/C podem levantar exceçõ es, a menos que uma declaraçã o explícita seja feita de outra forma na documen-
taçã o de uma funçã o. Em geral, quando uma funçã o encontra um erro, ela define uma exceçã o, descarta todas as
referê ncias de objeto de sua propriedade e retorna um indicador de erro. Se nã o for documentado de outra forma,
este indicador é NULL ou -1, dependendo do tipo de retorno da funçã o. Algumas funçõ es retornam um resultado
10 Capítulo 1. Introdução
The Python/C API, Release 3.13.7
booleano verdadeiro/falso, com falso indicando um erro. Muito poucas funçõ es nã o retornam nenhum indicador de
erro explícito ou tê m um valor de retorno ambíguo e requerem teste explícito para erros com PyErr_Occurred().
Essas exceçõ es sã o sempre documentadas explicitamente.
O estado de exceçã o é mantido no armazenamento por thread (isso é equivalente a usar o armazenamento global em
uma aplicaçã o sem thread). Uma thread pode estar em um de dois estados: ocorreu uma exceçã o ou nã o. A funçã o
PyErr_Occurred() pode ser usada para verificar isso: ela retorna uma referê ncia emprestada ao objeto do tipo
de exceçã o quando uma exceçã o ocorreu, e NULL caso contrá rio. Existem vá rias funçõ es para definir o estado de
exceçã o: PyErr_SetString() é a funçã o mais comum (embora nã o a mais geral) para definir o estado de exceçã o,
e PyErr_Clear() limpa o estado da exceçã o.
O estado de exceçã o completo consiste em trê s objetos (todos os quais podem ser NULL): o tipo de exceçã o, o valor
de exceçã o correspondente e o traceback. Eles tê m os mesmos significados que o resultado no Python de sys.
exc_info(); no entanto, eles nã o sã o os mesmos: os objetos Python representam a ú ltima exceçã o sendo tratada
por uma instruçã o Python try … except, enquanto o estado de exceçã o de nível C só existe enquanto uma exceçã o
está sendo transmitido entre funçõ es C até atingir o laço de repetiçã o principal do interpretador de bytecode Python,
que se encarrega de transferi-lo para sys.exc_info() e amigos.
Observe que a partir do Python 1.5, a maneira preferida e segura para thread para acessar o estado de exceçã o do
có digo Python é chamar a funçã o sys.exc_info(), que retorna o estado de exceçã o por thread para o có digo
Python. Alé m disso, a semâ ntica de ambas as maneiras de acessar o estado de exceçã o mudou, de modo que uma
funçã o que captura uma exceçã o salvará e restaurará o estado de exceçã o de seu segmento de modo a preservar
o estado de exceçã o de seu chamador. Isso evita bugs comuns no có digo de tratamento de exceçõ es causados por
uma funçã o aparentemente inocente sobrescrevendo a exceçã o sendo tratada; també m reduz a extensã o da vida ú til
frequentemente indesejada para objetos que sã o referenciados pelos quadros de pilha no traceback.
Como princípio geral, uma funçã o que chama outra funçã o para realizar alguma tarefa deve verificar se a funçã o
chamada levantou uma exceçã o e, em caso afirmativo, passar o estado da exceçã o para seu chamador. Ele deve
descartar todas as referê ncias de objeto que possui e retornar um indicador de erro, mas não deve definir outra
exceçã o — que sobrescreveria a exceçã o que acabou de ser gerada e perderia informaçõ es importantes sobre a causa
exata do erro.
Um exemplo simples de detecçã o de exceçõ es e transmiti-las é mostrado no exemplo sum_sequence() acima.
Acontece que este exemplo nã o precisa limpar nenhuma referê ncia de propriedade quando detecta um erro. A
funçã o de exemplo a seguir mostra alguma limpeza de erro. Primeiro, para lembrar por que você gosta de Python,
mostramos o có digo Python equivalente:
def incr_item(dict, key):
try:
item = dict[key]
except KeyError:
item = 0
dict[key] = item + 1
Aqui está o có digo C correspondente, em toda sua gló ria:
int
incr_item(PyObject *dict, PyObject *key)
{
/* Objetos todos inicializados para NULL para Py_XDECREF */
PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
int rv = -1; /* Retorna valor inicializado para -1 (falha) */
item = PyObject_GetItem(dict, key);
if (item == NULL) {
/* Trata de KeyError apenas: */
if (!PyErr_ExceptionMatches(PyExc_KeyError))
goto error;
/* Limpa o erro e usa zero: */
(continua na pró xima pá gina)
1.5. Exceções 11
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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 */
/* Continua com o código de limpeza */
error:
/* Código de limpeza, compartilhado pelo caminho sucesso e falha */
/* Usa Py_XDECREF() para ignorar referências NULL */
Py_XDECREF(item);
Py_XDECREF(const_one);
Py_XDECREF(incremented_item);
return rv; /* -1 para erro, 0 para sucesso */
}
Este exemplo representa um uso endossado da instruçã o goto em C! Ele ilustra o uso de
PyErr_ExceptionMatches() e PyErr_Clear() para lidar com exceçõ es específicas, e o uso de
Py_XDECREF() para descartar referê ncias de propriedade que podem ser NULL (observe o 'X' no nome;
Py_DECREF() travaria quando confrontado com uma referê ncia NULL). É importante que as variá veis usadas para
manter as referê ncias de propriedade sejam inicializadas com NULL para que isso funcione; da mesma forma, o
valor de retorno proposto é inicializado para -1 (falha) e apenas definido para sucesso apó s a chamada final feita ser
bem sucedida.
1.6 Incorporando Python
A ú nica tarefa importante com a qual apenas os incorporadores (em oposiçã o aos escritores de extensã o) do inter-
pretador Python precisam se preocupar é a inicializaçã o e, possivelmente, a finalizaçã o do interpretador Python. A
maior parte da funcionalidade do interpretador só pode ser usada apó s a inicializaçã o do interpretador.
A funçã o de inicializaçã o bá sica é Py_Initialize(). Isso inicializa a tabela de mó dulos carregados e cria os
mó dulos fundamentais builtins, __main__ e sys. Ela també m inicializa o caminho de pesquisa de mó dulos
(sys.path).
Py_Initialize() nã o define a “lista de argumentos de script” (sys.argv). Se esta variá vel for necessá ria para
o có digo Python que será executado posteriormente, PyConfig.argv e PyConfig.parse_argv devem estar
definidas; veja Configuração de inicialização do Python.
Na maioria dos sistemas (em particular, no Unix e no Windows, embora os detalhes sejam ligeiramente diferentes),
Py_Initialize() calcula o caminho de pesquisa de mó dulos com base em sua melhor estimativa para a localizaçã o
do executá vel do interpretador Python padrã o, presumindo que a biblioteca Python é encontrada em um local fixo em
relaçã o ao executá vel do interpretador Python. Em particular, ele procura por um diretó rio chamado lib/pythonX.
Y relativo ao diretó rio pai onde o executá vel chamado python é encontrado no caminho de pesquisa de comandos
do shell (a variá vel de ambiente PATH).
12 Capítulo 1. Introdução
The Python/C API, Release 3.13.7
Por exemplo, se o executá vel Python for encontrado em /usr/local/bin/python, ele presumirá que as bibliotecas
estã o em /usr/local/lib/pythonX.Y . (Na verdade, este caminho particular també m é o local reserva, usado
quando nenhum arquivo executá vel chamado python é encontrado ao longo de PATH.) O usuá rio pode substituir este
comportamento definindo a variá vel de ambiente PYTHONHOME, ou insira diretó rios adicionais na frente do caminho
padrã o definindo PYTHONPATH.
A aplicaçã o de incorporaçã o pode orientar a pesquisa definindo PyConfig.program_name antes de chamar
Py_InitializeFromConfig(). Observe que PYTHONHOME ainda substitui isso e PYTHONPATH ainda é inserido
na frente do caminho padrã o. Uma aplicaçã o que requer controle total deve fornecer sua pró pria implementaçã o de
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix() e Py_GetProgramFullPath() (todas definidas
em Modules/getpath.c).
Às vezes, é desejá vel “desinicializar” o Python. Por exemplo, a aplicaçã o pode querer iniciar novamente (fazer outra
chamada para Py_Initialize()) ou a aplicaçã o simplesmente termina com o uso de Python e deseja liberar me-
mó ria alocada pelo Python. Isso pode ser feito chamando Py_FinalizeEx(). A funçã o Py_IsInitialized()
retorna verdadeiro se o Python está atualmente no estado inicializado. Mais informaçõ es sobre essas funçõ es sã o
fornecidas em um capítulo posterior. Observe que Py_FinalizeEx() não libera toda a memó ria alocada pelo
interpretador Python, por exemplo, a memó ria alocada por mó dulos de extensã o atualmente nã o pode ser liberada.
1.7 Compilações de depuração
Python pode ser compilado com vá rias macros para permitir verificaçõ es extras do interpretador e mó dulos de exten-
sã o. Essas verificaçõ es tendem a adicionar uma grande quantidade de sobrecarga ao tempo de execuçã o, portanto,
nã o sã o habilitadas por padrã o.
Uma lista completa dos vá rios tipos de compilaçõ es de depuraçã o está no arquivo Misc/SpecialBuilds.txt
na distribuiçã o do có digo-fonte do Python. Estã o disponíveis compilaçõ es que oferecem suporte ao rastreamento
de contagens de referê ncias, depuraçã o do alocador de memó ria ou criaçã o de perfil de baixo nível do laço do in-
terpretador principal. Apenas as compilaçõ es usadas com mais frequê ncia serã o descritas no restante desta seçã o.
Py_DEBUG
Compilar o interpretador com a macro Py_DEBUG definida produz o que geralmente se entende por uma construçã o
de depuraçã o do Python. Py_DEBUG é habilitada na construçã o Unix adicionando --with-pydebug ao comando
./configure. També m está implícito na presença da macro nã o específica do Python _DEBUG. Quando Py_DEBUG
está habilitado na construçã o do Unix, a otimizaçã o do compilador é desabilitada.
Alé m da depuraçã o de contagem de referê ncias descrita abaixo, verificaçõ es extras sã o realizadas, consulte Compi-
laçã o de Depuraçã o do Python.
Definir Py_TRACE_REFS habilita o rastreamento de referê ncia (veja a opçã o opção --with-trace-refs de
configure). Quando definida, uma lista circular duplamente vinculada de objetos ativos é mantida adicionando
dois campos extras a cada PyObject. As alocaçõ es totais també m sã o rastreadas. Ao sair, todas as referê ncias
existentes sã o impressas. (No modo interativo, isso acontece apó s cada instruçã o executada pelo interpretador.)
Consulte Misc/SpecialBuilds.txt na distribuiçã o do có digo-fonte Python para informaçõ es mais detalhadas.
1.8 Ferramentas de terceiros recomendadas
As seguintes ferramentas de terceiros oferecem abordagens mais simples e mais sofisticadas para criar extensõ es C,
C++ e Rust para Python:
• Cython
• cffi
• HPy
• nanobind (C++)
• Numba
1.7. Compilações de depuração 13
The Python/C API, Release 3.13.7
• pybind11 (C++)
• PyO3 (Rust)
• SWIG
O uso de ferramentas como essas pode ajudar a evitar a criaçã o de có digo estritamente vinculado a uma versã o espe-
cífica do CPython, evitar erros de contagem de referê ncias e focar mais no seu pró prio có digo do que em usar a API
do CPython. Em geral, novas versõ es do Python podem ser suportadas atualizando a ferramenta, e seu có digo fre-
quentemente usará APIs mais novas e eficientes automaticamente. Algumas ferramentas també m oferecem suporte
à compilaçã o para outras implementaçõ es do Python a partir de um ú nico conjunto de fontes.
Esses projetos nã o sã o suportados pelas mesmas pessoas que mantê m o Python, e quaisquer problemas precisam ser
relatados diretamente aos projetos. Lembre-se de verificar se o projeto ainda é mantido e tem suporte, pois a lista
acima pode ficar desatualizada.
µ Ver também
Guia do Usuário de Empacotamento do Python: Extensões Binárias
O Guia do Usuá rio de Empacotamento do Python nã o abrange apenas vá rias ferramentas disponíveis que
simplificam a criaçã o de extensõ es biná rias, mas també m discute os vá rios motivos pelos quais a criaçã o
de um mó dulo de extensã o pode ser desejá vel em primeiro lugar.
14 Capítulo 1. Introdução
CAPÍTULO 2
Estabilidade da API C
A menos que documentado de outra forma, a API C do Python é coberta pela Política de Compatibilidade com
versõ es anteriores, PEP 387. A maioria das alteraçõ es sã o compatíveis com a fonte (normalmente adicionando
apenas uma nova API). A alteraçã o ou remoçã o da API existente só é feita apó s um período de descontinuaçã o ou
para corrigir problemas sé rios.
A Interface Biná ria de Aplicaçã o (ABI) do CPython é compatível para frente e para trá s atravé s de uma versã o
menor (se elas forem compiladas da mesma maneira; veja Considerações da plataforma abaixo). Portanto, o có digo
compilado para Python 3.10.0 funcionará em 3.10.8 e vice-versa, mas precisará ser compilado separadamente para
3.9.x e 3.11.x.
Existem dois níveis de API C com diferentes expectativas de estabilidade:
• API Instável (“Unstable API”), pode mudar em versõ es menores sem período de depreciaçã o. É marcado pelo
prefixo PyUnstable nos nomes.
• API Limitada (“Limited API”), é compatível em vá rias versõ es menores. Quando Py_LIMITED_API é defi-
nido, apenas este subconjunto é exposto de Python.h.
Elas sã o discutidas em mais detalhes abaixo.
Nomes prefixados por um sublinhado, como _Py_InternalState, sã o APIs privadas que podem ser alteradas sem
aviso pré vio, mesmo em lançamentos de correçã o. Se você precisa usar essa API, considere entrar em contato com
os desenvolvedores do CPython para discutir a adiçã o de uma API pú blica para o seu caso de uso.
2.1 API C Instável
Qualquer API nomeada com o prefixo “PyUnstable” expõ e detalhes de implementaçã o do CPython e pode mudar
em cada versã o menor (por exemplo, de 3.9 para 3.10) sem nenhum aviso de depreciaçã o. No entanto, nã o mudará
em uma versã o de correçã o de bugs (por exemplo, de 3.10.0 para 3.10.1).
É geralmente destinado a ferramentas especializadas de baixo nível, como depuradores.
Projetos que utilizam esta API sã o esperados para seguir o desenvolvimento do CPython e dedicar esforço extra para
se ajustar à s mudanças.
15
The Python/C API, Release 3.13.7
2.2 Interface Binária de Aplicação Estável
Para simplificar, este documento fala sobre extensões, mas a API Limitada e a ABI Está vel funcionam da mesma
maneira para todos os usos da API – por exemplo, embutir o Python.
2.2.1 API C Limitada
Python 3.2 introduziu a API Limitada, um subconjunto da API C do Python. Extensõ es que apenas usam o Limited
API podem ser compiladas uma vez e ser carregadas em vá rias versõ es do Python. Os conteú dos da API Limitada
estã o listados abaixo.
Py_LIMITED_API
Defina essa macro antes de incluir Python.h para optar por usar apenas a API Limitada e selecionar a versã o
da API Limitada.
Defina Py_LIMITED_API com o valor de PY_VERSION_HEX correspondente à versã o mais baixa do Python
que sua extensã o suporta. A extensã o terá compatibilidade com a ABI de todas as versõ es do Python 3 a partir
daquela especificada, e poderá usar a API Limitada introduzida até aquela versã o.
Em vez de usar diretamente a macro PY_VERSION_HEX, codifique uma versã o menor mínima (por exemplo,
0x030A0000 para o Python 3.10) para garantir estabilidade ao compilar com versõ es futuras do Python.
Você també m pode definir Py_LIMITED_API como 3. Isso funciona da mesma forma que 0x03020000
(Python 3.2, a versã o que introduziu a API Limitada).
2.2.2 ABI Estável
Para habilitar isso, o Python fornece uma ABI Estável: um conjunto de símbolos que permanecerã o compatíveis com
ABI em todas as versõ es do Python 3.x.
® Nota
O ABI Está vel previne problemas de ABI, como erros de ligador devido a símbolos ausentes ou corrupçã o de
dados devido a alteraçõ es em layouts de estrutura ou assinaturas de funçã o. No entanto, outras alteraçõ es no
Python podem alterar o comportamento das extensõ es. Veja a Política de Retrocompatibilidade do Python (PEP
387) para detalhes.
A ABI Está vel conté m símbolos expostos na API Limitada, mas també m outros – por exemplo, funçõ es necessá rias
para suportar versõ es mais antigas da API Limitada.
No Windows, as extensõ es que usam a ABI Está vel devem ser vinculadas a python3.dll em vez de uma biblioteca
específica de versã o, como python39.dll.
Em algumas plataformas, o Python procurará e carregará arquivos de biblioteca compartilhada com o nome marcado
como abi3 (por exemplo, meumódulo.abi3.so). Ele nã o verifica se essas extensõ es estã o em conformidade com
uma ABI Está vel. O usuá rio (ou suas ferramentas de empacotamento) precisa garantir que, por exemplo, as extensõ es
construídas com a API Limitada 3.10+ nã o sejam instaladas em versõ es mais baixas do Python.
Todas as funçõ es na ABI está vel estã o presentes como funçõ es na biblioteca compartilhada do Python, nã o apenas
como macros. Isso as torna utilizá veis em linguagens que nã o utilizam o pré -processador C.
2.2.3 Escopo e Desempenho da API Limitada
O objetivo da API Limitada é permitir tudo o que é possível com a API C completa, mas possivelmente com uma
penalidade de desempenho.
Por exemplo, enquanto PyList_GetItem() está disponível, sua variante de macro “insegura”
PyList_GET_ITEM() nã o está . A macro pode ser mais rá pida porque pode depender de detalhes de imple-
mentaçã o específicos da versã o do objeto da lista.
16 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
Sem a definiçã o de Py_LIMITED_API, algumas funçõ es da API C sã o colocadas “inline” ou substituídas por macros.
Definir Py_LIMITED_API desativa esse inline, permitindo estabilidade à medida que as estruturas de dados do
Python sã o aprimoradas, mas possivelmente reduzindo o desempenho.
Ao deixar de fora a definiçã o Py_LIMITED_API, é possível compilar uma extensã o da API Limitada com uma ABI
específica da versã o. Isso pode melhorar o desempenho para essa versã o do Python, mas limitará a compatibilidade.
Compilar com Py_LIMITED_API vai produzir uma extensã o que pode ser distribuída quando uma específica da
versã o nã o estiver disponível – por exemplo, para pré -lançamentos de uma pró xima versã o do Python.
2.2.4 Limitações da API Limitada
Observe que compilar com Py_LIMITED_API não é uma garantia completa de que o có digo esteja em conformidade
com a API Limitada ou com a ABI Estável. Py_LIMITED_API abrange apenas definiçõ es, mas uma API també m
inclui outras questõ es, como semâ ntica esperada.
Uma questã o que Py_LIMITED_API nã o protege é a chamada de uma funçã o com argumentos invá lidos em uma
versã o inferior do Python. Por exemplo, considere uma funçã o que começa a aceitar NULL como argumento. No
Python 3.9, NULL agora seleciona um comportamento padrã o, mas no Python 3.8, o argumento será usado direta-
mente, causando uma referê ncia NULL e uma falha. Um argumento similar funciona para campos de estruturas.
Outra questã o é que alguns campos de estrutura nã o estã o atualmente ocultos quando Py_LIMITED_API é definido,
mesmo que eles façam parte da API Limitada.
Por esses motivos, recomendamos testar uma extensã o com todas as versõ es menores do Python que ela oferece
suporte e, preferencialmente, construir com a versã o mais baixa dessas.
També m recomendamos revisar a documentaçã o de todas as APIs utilizadas para verificar se ela faz parte explicita-
mente da API Limitada. Mesmo com a definiçã o de Py_LIMITED_API, algumas declaraçõ es privadas sã o expostas
por razõ es té cnicas (ou até mesmo acidentalmente, como bugs).
També m observe que a API Limitada nã o é necessariamente está vel: compilar com Py_LIMITED_API com Python
3.8 significa que a extensã o será executada com Python 3.12, mas nã o necessariamente será compilada com Python
3.12. Em particular, partes da API Limitada podem ser descontinuadas e removidas, desde que a ABI Está vel
permaneça está vel.
2.3 Considerações da plataforma
A estabilidade da ABI depende nã o apenas do Python, mas també m do compilador utilizado, das bibliotecas de
nível inferior e das opçõ es do compilador. Para os fins da ABI Estável, esses detalhes definem uma “plataforma”.
Geralmente, eles dependem do tipo de sistema operacional e da arquitetura do processador.
É responsabilidade de cada distribuidor particular do Python garantir que todas as versõ es do Python em uma plata-
forma específica sejam construídas de forma a nã o quebrar a ABI está vel. Isso é vá lido para as versõ es do Windows
e macOS disponibilizadas pela python.org e por muitos distribuidores terceiros.
2.4 Conteúdo da API Limitada
Atualmente, a API Limitada inclui os seguintes itens:
• PY_VECTORCALL_ARGUMENTS_OFFSET
• PyAIter_Check()
• PyArg_Parse()
• PyArg_ParseTuple()
• PyArg_ParseTupleAndKeywords()
• PyArg_UnpackTuple()
• PyArg_VaParse()
2.3. Considerações da plataforma 17
The Python/C API, Release 3.13.7
• PyArg_VaParseTupleAndKeywords()
• PyArg_ValidateKeywordArguments()
• PyBaseObject_Type
• PyBool_FromLong()
• PyBool_Type
• PyBuffer_FillContiguousStrides()
• PyBuffer_FillInfo()
• PyBuffer_FromContiguous()
• PyBuffer_GetPointer()
• PyBuffer_IsContiguous()
• PyBuffer_Release()
• PyBuffer_SizeFromFormat()
• PyBuffer_ToContiguous()
• PyByteArrayIter_Type
• PyByteArray_AsString()
• PyByteArray_Concat()
• PyByteArray_FromObject()
• PyByteArray_FromStringAndSize()
• PyByteArray_Resize()
• PyByteArray_Size()
• PyByteArray_Type
• PyBytesIter_Type
• PyBytes_AsString()
• PyBytes_AsStringAndSize()
• PyBytes_Concat()
• PyBytes_ConcatAndDel()
• PyBytes_DecodeEscape()
• PyBytes_FromFormat()
• PyBytes_FromFormatV()
• PyBytes_FromObject()
• PyBytes_FromString()
• PyBytes_FromStringAndSize()
• PyBytes_Repr()
• PyBytes_Size()
• PyBytes_Type
• PyCFunction
• PyCFunctionFast
• PyCFunctionFastWithKeywords
• PyCFunctionWithKeywords
18 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• PyCFunction_GetFlags()
• PyCFunction_GetFunction()
• PyCFunction_GetSelf()
• PyCFunction_New()
• PyCFunction_NewEx()
• PyCFunction_Type
• PyCMethod_New()
• PyCallIter_New()
• PyCallIter_Type
• PyCallable_Check()
• PyCapsule_Destructor
• PyCapsule_GetContext()
• PyCapsule_GetDestructor()
• PyCapsule_GetName()
• PyCapsule_GetPointer()
• PyCapsule_Import()
• PyCapsule_IsValid()
• PyCapsule_New()
• PyCapsule_SetContext()
• PyCapsule_SetDestructor()
• PyCapsule_SetName()
• PyCapsule_SetPointer()
• PyCapsule_Type
• PyClassMethodDescr_Type
• PyCodec_BackslashReplaceErrors()
• PyCodec_Decode()
• PyCodec_Decoder()
• PyCodec_Encode()
• PyCodec_Encoder()
• PyCodec_IgnoreErrors()
• PyCodec_IncrementalDecoder()
• PyCodec_IncrementalEncoder()
• PyCodec_KnownEncoding()
• PyCodec_LookupError()
• PyCodec_NameReplaceErrors()
• PyCodec_Register()
• PyCodec_RegisterError()
• PyCodec_ReplaceErrors()
• PyCodec_StreamReader()
2.4. Conteúdo da API Limitada 19
The Python/C API, Release 3.13.7
• PyCodec_StreamWriter()
• PyCodec_StrictErrors()
• PyCodec_Unregister()
• PyCodec_XMLCharRefReplaceErrors()
• PyComplex_FromDoubles()
• PyComplex_ImagAsDouble()
• PyComplex_RealAsDouble()
• PyComplex_Type
• PyDescr_NewClassMethod()
• PyDescr_NewGetSet()
• PyDescr_NewMember()
• PyDescr_NewMethod()
• PyDictItems_Type
• PyDictIterItem_Type
• PyDictIterKey_Type
• PyDictIterValue_Type
• PyDictKeys_Type
• PyDictProxy_New()
• PyDictProxy_Type
• PyDictRevIterItem_Type
• PyDictRevIterKey_Type
• PyDictRevIterValue_Type
• PyDictValues_Type
• PyDict_Clear()
• PyDict_Contains()
• PyDict_Copy()
• PyDict_DelItem()
• PyDict_DelItemString()
• PyDict_GetItem()
• PyDict_GetItemRef()
• PyDict_GetItemString()
• PyDict_GetItemStringRef()
• PyDict_GetItemWithError()
• PyDict_Items()
• PyDict_Keys()
• PyDict_Merge()
• PyDict_MergeFromSeq2()
• PyDict_New()
• PyDict_Next()
20 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• PyDict_SetItem()
• PyDict_SetItemString()
• PyDict_Size()
• PyDict_Type
• PyDict_Update()
• PyDict_Values()
• PyEllipsis_Type
• PyEnum_Type
• PyErr_BadArgument()
• PyErr_BadInternalCall()
• PyErr_CheckSignals()
• PyErr_Clear()
• PyErr_Display()
• PyErr_DisplayException()
• PyErr_ExceptionMatches()
• PyErr_Fetch()
• PyErr_Format()
• PyErr_FormatV()
• PyErr_GetExcInfo()
• PyErr_GetHandledException()
• PyErr_GetRaisedException()
• PyErr_GivenExceptionMatches()
• PyErr_NewException()
• PyErr_NewExceptionWithDoc()
• PyErr_NoMemory()
• PyErr_NormalizeException()
• PyErr_Occurred()
• PyErr_Print()
• PyErr_PrintEx()
• PyErr_ProgramText()
• PyErr_ResourceWarning()
• PyErr_Restore()
• PyErr_SetExcFromWindowsErr()
• PyErr_SetExcFromWindowsErrWithFilename()
• PyErr_SetExcFromWindowsErrWithFilenameObject()
• PyErr_SetExcFromWindowsErrWithFilenameObjects()
• PyErr_SetExcInfo()
• PyErr_SetFromErrno()
• PyErr_SetFromErrnoWithFilename()
2.4. Conteúdo da API Limitada 21
The Python/C API, Release 3.13.7
• PyErr_SetFromErrnoWithFilenameObject()
• PyErr_SetFromErrnoWithFilenameObjects()
• PyErr_SetFromWindowsErr()
• PyErr_SetFromWindowsErrWithFilename()
• PyErr_SetHandledException()
• PyErr_SetImportError()
• PyErr_SetImportErrorSubclass()
• PyErr_SetInterrupt()
• PyErr_SetInterruptEx()
• PyErr_SetNone()
• PyErr_SetObject()
• PyErr_SetRaisedException()
• PyErr_SetString()
• PyErr_SyntaxLocation()
• PyErr_SyntaxLocationEx()
• PyErr_WarnEx()
• PyErr_WarnExplicit()
• PyErr_WarnFormat()
• PyErr_WriteUnraisable()
• PyEval_AcquireThread()
• PyEval_EvalCode()
• PyEval_EvalCodeEx()
• PyEval_EvalFrame()
• PyEval_EvalFrameEx()
• PyEval_GetBuiltins()
• PyEval_GetFrame()
• PyEval_GetFrameBuiltins()
• PyEval_GetFrameGlobals()
• PyEval_GetFrameLocals()
• PyEval_GetFuncDesc()
• PyEval_GetFuncName()
• PyEval_GetGlobals()
• PyEval_GetLocals()
• PyEval_InitThreads()
• PyEval_ReleaseThread()
• PyEval_RestoreThread()
• PyEval_SaveThread()
• PyExc_ArithmeticError
• PyExc_AssertionError
22 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• PyExc_AttributeError
• PyExc_BaseException
• PyExc_BaseExceptionGroup
• PyExc_BlockingIOError
• PyExc_BrokenPipeError
• PyExc_BufferError
• PyExc_BytesWarning
• PyExc_ChildProcessError
• PyExc_ConnectionAbortedError
• PyExc_ConnectionError
• PyExc_ConnectionRefusedError
• PyExc_ConnectionResetError
• PyExc_DeprecationWarning
• PyExc_EOFError
• PyExc_EncodingWarning
• PyExc_EnvironmentError
• PyExc_Exception
• PyExc_FileExistsError
• PyExc_FileNotFoundError
• PyExc_FloatingPointError
• PyExc_FutureWarning
• PyExc_GeneratorExit
• PyExc_IOError
• PyExc_ImportError
• PyExc_ImportWarning
• PyExc_IndentationError
• PyExc_IndexError
• PyExc_InterruptedError
• PyExc_IsADirectoryError
• PyExc_KeyError
• PyExc_KeyboardInterrupt
• PyExc_LookupError
• PyExc_MemoryError
• PyExc_ModuleNotFoundError
• PyExc_NameError
• PyExc_NotADirectoryError
• PyExc_NotImplementedError
• PyExc_OSError
• PyExc_OverflowError
2.4. Conteúdo da API Limitada 23
The Python/C API, Release 3.13.7
• PyExc_PendingDeprecationWarning
• PyExc_PermissionError
• PyExc_ProcessLookupError
• PyExc_RecursionError
• PyExc_ReferenceError
• PyExc_ResourceWarning
• PyExc_RuntimeError
• PyExc_RuntimeWarning
• PyExc_StopAsyncIteration
• PyExc_StopIteration
• PyExc_SyntaxError
• PyExc_SyntaxWarning
• PyExc_SystemError
• PyExc_SystemExit
• PyExc_TabError
• PyExc_TimeoutError
• PyExc_TypeError
• PyExc_UnboundLocalError
• PyExc_UnicodeDecodeError
• PyExc_UnicodeEncodeError
• PyExc_UnicodeError
• PyExc_UnicodeTranslateError
• PyExc_UnicodeWarning
• PyExc_UserWarning
• PyExc_ValueError
• PyExc_Warning
• PyExc_WindowsError
• PyExc_ZeroDivisionError
• PyExceptionClass_Name()
• PyException_GetArgs()
• PyException_GetCause()
• PyException_GetContext()
• PyException_GetTraceback()
• PyException_SetArgs()
• PyException_SetCause()
• PyException_SetContext()
• PyException_SetTraceback()
• PyFile_FromFd()
• PyFile_GetLine()
24 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• PyFile_WriteObject()
• PyFile_WriteString()
• PyFilter_Type
• PyFloat_AsDouble()
• PyFloat_FromDouble()
• PyFloat_FromString()
• PyFloat_GetInfo()
• PyFloat_GetMax()
• PyFloat_GetMin()
• PyFloat_Type
• PyFrameObject
• PyFrame_GetCode()
• PyFrame_GetLineNumber()
• PyFrozenSet_New()
• PyFrozenSet_Type
• PyGC_Collect()
• PyGC_Disable()
• PyGC_Enable()
• PyGC_IsEnabled()
• PyGILState_Ensure()
• PyGILState_GetThisThreadState()
• PyGILState_Release()
• PyGILState_STATE
• PyGetSetDef
• PyGetSetDescr_Type
• PyImport_AddModule()
• PyImport_AddModuleObject()
• PyImport_AddModuleRef()
• PyImport_AppendInittab()
• PyImport_ExecCodeModule()
• PyImport_ExecCodeModuleEx()
• PyImport_ExecCodeModuleObject()
• PyImport_ExecCodeModuleWithPathnames()
• PyImport_GetImporter()
• PyImport_GetMagicNumber()
• PyImport_GetMagicTag()
• PyImport_GetModule()
• PyImport_GetModuleDict()
• PyImport_Import()
2.4. Conteúdo da API Limitada 25
The Python/C API, Release 3.13.7
• PyImport_ImportFrozenModule()
• PyImport_ImportFrozenModuleObject()
• PyImport_ImportModule()
• PyImport_ImportModuleLevel()
• PyImport_ImportModuleLevelObject()
• PyImport_ImportModuleNoBlock()
• PyImport_ReloadModule()
• PyIndex_Check()
• PyInterpreterState
• PyInterpreterState_Clear()
• PyInterpreterState_Delete()
• PyInterpreterState_Get()
• PyInterpreterState_GetDict()
• PyInterpreterState_GetID()
• PyInterpreterState_New()
• PyIter_Check()
• PyIter_Next()
• PyIter_Send()
• PyListIter_Type
• PyListRevIter_Type
• PyList_Append()
• PyList_AsTuple()
• PyList_GetItem()
• PyList_GetItemRef()
• PyList_GetSlice()
• PyList_Insert()
• PyList_New()
• PyList_Reverse()
• PyList_SetItem()
• PyList_SetSlice()
• PyList_Size()
• PyList_Sort()
• PyList_Type
• PyLongObject
• PyLongRangeIter_Type
• PyLong_AsDouble()
• PyLong_AsInt()
• PyLong_AsLong()
• PyLong_AsLongAndOverflow()
26 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• PyLong_AsLongLong()
• PyLong_AsLongLongAndOverflow()
• PyLong_AsSize_t()
• PyLong_AsSsize_t()
• PyLong_AsUnsignedLong()
• PyLong_AsUnsignedLongLong()
• PyLong_AsUnsignedLongLongMask()
• PyLong_AsUnsignedLongMask()
• PyLong_AsVoidPtr()
• PyLong_FromDouble()
• PyLong_FromLong()
• PyLong_FromLongLong()
• PyLong_FromSize_t()
• PyLong_FromSsize_t()
• PyLong_FromString()
• PyLong_FromUnsignedLong()
• PyLong_FromUnsignedLongLong()
• PyLong_FromVoidPtr()
• PyLong_GetInfo()
• PyLong_Type
• PyMap_Type
• PyMapping_Check()
• PyMapping_GetItemString()
• PyMapping_GetOptionalItem()
• PyMapping_GetOptionalItemString()
• PyMapping_HasKey()
• PyMapping_HasKeyString()
• PyMapping_HasKeyStringWithError()
• PyMapping_HasKeyWithError()
• PyMapping_Items()
• PyMapping_Keys()
• PyMapping_Length()
• PyMapping_SetItemString()
• PyMapping_Size()
• PyMapping_Values()
• PyMem_Calloc()
• PyMem_Free()
• PyMem_Malloc()
• PyMem_RawCalloc()
2.4. Conteúdo da API Limitada 27
The Python/C API, Release 3.13.7
• PyMem_RawFree()
• PyMem_RawMalloc()
• PyMem_RawRealloc()
• PyMem_Realloc()
• PyMemberDef
• PyMemberDescr_Type
• PyMember_GetOne()
• PyMember_SetOne()
• PyMemoryView_FromBuffer()
• PyMemoryView_FromMemory()
• PyMemoryView_FromObject()
• PyMemoryView_GetContiguous()
• PyMemoryView_Type
• PyMethodDef
• PyMethodDescr_Type
• PyModuleDef
• PyModuleDef_Base
• PyModuleDef_Init()
• PyModuleDef_Type
• PyModule_Add()
• PyModule_AddFunctions()
• PyModule_AddIntConstant()
• PyModule_AddObject()
• PyModule_AddObjectRef()
• PyModule_AddStringConstant()
• PyModule_AddType()
• PyModule_Create2()
• PyModule_ExecDef()
• PyModule_FromDefAndSpec2()
• PyModule_GetDef()
• PyModule_GetDict()
• PyModule_GetFilename()
• PyModule_GetFilenameObject()
• PyModule_GetName()
• PyModule_GetNameObject()
• PyModule_GetState()
• PyModule_New()
• PyModule_NewObject()
• PyModule_SetDocString()
28 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• PyModule_Type
• PyNumber_Absolute()
• PyNumber_Add()
• PyNumber_And()
• PyNumber_AsSsize_t()
• PyNumber_Check()
• PyNumber_Divmod()
• PyNumber_Float()
• PyNumber_FloorDivide()
• PyNumber_InPlaceAdd()
• PyNumber_InPlaceAnd()
• PyNumber_InPlaceFloorDivide()
• PyNumber_InPlaceLshift()
• PyNumber_InPlaceMatrixMultiply()
• PyNumber_InPlaceMultiply()
• PyNumber_InPlaceOr()
• PyNumber_InPlacePower()
• PyNumber_InPlaceRemainder()
• PyNumber_InPlaceRshift()
• PyNumber_InPlaceSubtract()
• PyNumber_InPlaceTrueDivide()
• PyNumber_InPlaceXor()
• PyNumber_Index()
• PyNumber_Invert()
• PyNumber_Long()
• PyNumber_Lshift()
• PyNumber_MatrixMultiply()
• PyNumber_Multiply()
• PyNumber_Negative()
• PyNumber_Or()
• PyNumber_Positive()
• PyNumber_Power()
• PyNumber_Remainder()
• PyNumber_Rshift()
• PyNumber_Subtract()
• PyNumber_ToBase()
• PyNumber_TrueDivide()
• PyNumber_Xor()
• PyOS_AfterFork()
2.4. Conteúdo da API Limitada 29
The Python/C API, Release 3.13.7
• PyOS_AfterFork_Child()
• PyOS_AfterFork_Parent()
• PyOS_BeforeFork()
• PyOS_CheckStack()
• PyOS_FSPath()
• PyOS_InputHook
• PyOS_InterruptOccurred()
• PyOS_double_to_string()
• PyOS_getsig()
• PyOS_mystricmp()
• PyOS_mystrnicmp()
• PyOS_setsig()
• PyOS_sighandler_t
• PyOS_snprintf()
• PyOS_string_to_double()
• PyOS_strtol()
• PyOS_strtoul()
• PyOS_vsnprintf()
• PyObject
• PyObject.ob_refcnt
• PyObject.ob_type
• PyObject_ASCII()
• PyObject_AsFileDescriptor()
• PyObject_Bytes()
• PyObject_Call()
• PyObject_CallFunction()
• PyObject_CallFunctionObjArgs()
• PyObject_CallMethod()
• PyObject_CallMethodObjArgs()
• PyObject_CallNoArgs()
• PyObject_CallObject()
• PyObject_Calloc()
• PyObject_CheckBuffer()
• PyObject_ClearWeakRefs()
• PyObject_CopyData()
• PyObject_DelAttr()
• PyObject_DelAttrString()
• PyObject_DelItem()
• PyObject_DelItemString()
30 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• PyObject_Dir()
• PyObject_Format()
• PyObject_Free()
• PyObject_GC_Del()
• PyObject_GC_IsFinalized()
• PyObject_GC_IsTracked()
• PyObject_GC_Track()
• PyObject_GC_UnTrack()
• PyObject_GenericGetAttr()
• PyObject_GenericGetDict()
• PyObject_GenericSetAttr()
• PyObject_GenericSetDict()
• PyObject_GetAIter()
• PyObject_GetAttr()
• PyObject_GetAttrString()
• PyObject_GetBuffer()
• PyObject_GetItem()
• PyObject_GetIter()
• PyObject_GetOptionalAttr()
• PyObject_GetOptionalAttrString()
• PyObject_GetTypeData()
• PyObject_HasAttr()
• PyObject_HasAttrString()
• PyObject_HasAttrStringWithError()
• PyObject_HasAttrWithError()
• PyObject_Hash()
• PyObject_HashNotImplemented()
• PyObject_Init()
• PyObject_InitVar()
• PyObject_IsInstance()
• PyObject_IsSubclass()
• PyObject_IsTrue()
• PyObject_Length()
• PyObject_Malloc()
• PyObject_Not()
• PyObject_Realloc()
• PyObject_Repr()
• PyObject_RichCompare()
• PyObject_RichCompareBool()
2.4. Conteúdo da API Limitada 31
The Python/C API, Release 3.13.7
• PyObject_SelfIter()
• PyObject_SetAttr()
• PyObject_SetAttrString()
• PyObject_SetItem()
• PyObject_Size()
• PyObject_Str()
• PyObject_Type()
• PyObject_Vectorcall()
• PyObject_VectorcallMethod()
• PyProperty_Type
• PyRangeIter_Type
• PyRange_Type
• PyReversed_Type
• PySeqIter_New()
• PySeqIter_Type
• PySequence_Check()
• PySequence_Concat()
• PySequence_Contains()
• PySequence_Count()
• PySequence_DelItem()
• PySequence_DelSlice()
• PySequence_Fast()
• PySequence_GetItem()
• PySequence_GetSlice()
• PySequence_In()
• PySequence_InPlaceConcat()
• PySequence_InPlaceRepeat()
• PySequence_Index()
• PySequence_Length()
• PySequence_List()
• PySequence_Repeat()
• PySequence_SetItem()
• PySequence_SetSlice()
• PySequence_Size()
• PySequence_Tuple()
• PySetIter_Type
• PySet_Add()
• PySet_Clear()
• PySet_Contains()
32 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• PySet_Discard()
• PySet_New()
• PySet_Pop()
• PySet_Size()
• PySet_Type
• PySlice_AdjustIndices()
• PySlice_GetIndices()
• PySlice_GetIndicesEx()
• PySlice_New()
• PySlice_Type
• PySlice_Unpack()
• PyState_AddModule()
• PyState_FindModule()
• PyState_RemoveModule()
• PyStructSequence_Desc
• PyStructSequence_Field
• PyStructSequence_GetItem()
• PyStructSequence_New()
• PyStructSequence_NewType()
• PyStructSequence_SetItem()
• PyStructSequence_UnnamedField
• PySuper_Type
• PySys_Audit()
• PySys_AuditTuple()
• PySys_FormatStderr()
• PySys_FormatStdout()
• PySys_GetObject()
• PySys_GetXOptions()
• PySys_ResetWarnOptions()
• PySys_SetArgv()
• PySys_SetArgvEx()
• PySys_SetObject()
• PySys_WriteStderr()
• PySys_WriteStdout()
• PyThreadState
• PyThreadState_Clear()
• PyThreadState_Delete()
• PyThreadState_Get()
• PyThreadState_GetDict()
2.4. Conteúdo da API Limitada 33
The Python/C API, Release 3.13.7
• PyThreadState_GetFrame()
• PyThreadState_GetID()
• PyThreadState_GetInterpreter()
• PyThreadState_New()
• PyThreadState_SetAsyncExc()
• PyThreadState_Swap()
• PyThread_GetInfo()
• PyThread_ReInitTLS()
• PyThread_acquire_lock()
• PyThread_acquire_lock_timed()
• PyThread_allocate_lock()
• PyThread_create_key()
• PyThread_delete_key()
• PyThread_delete_key_value()
• PyThread_exit_thread()
• PyThread_free_lock()
• PyThread_get_key_value()
• PyThread_get_stacksize()
• PyThread_get_thread_ident()
• PyThread_get_thread_native_id()
• PyThread_init_thread()
• PyThread_release_lock()
• PyThread_set_key_value()
• PyThread_set_stacksize()
• PyThread_start_new_thread()
• PyThread_tss_alloc()
• PyThread_tss_create()
• PyThread_tss_delete()
• PyThread_tss_free()
• PyThread_tss_get()
• PyThread_tss_is_created()
• PyThread_tss_set()
• PyTraceBack_Here()
• PyTraceBack_Print()
• PyTraceBack_Type
• PyTupleIter_Type
• PyTuple_GetItem()
• PyTuple_GetSlice()
• PyTuple_New()
34 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• 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_GetModuleByDef()
• PyType_GetModuleName()
• PyType_GetModuleState()
• PyType_GetName()
• PyType_GetQualName()
• PyType_GetSlot()
• PyType_GetTypeDataSize()
• PyType_IsSubtype()
• PyType_Modified()
• PyType_Ready()
• PyType_Slot
• PyType_Spec
• PyType_Type
• PyUnicodeDecodeError_Create()
• PyUnicodeDecodeError_GetEncoding()
• PyUnicodeDecodeError_GetEnd()
• PyUnicodeDecodeError_GetObject()
• PyUnicodeDecodeError_GetReason()
• PyUnicodeDecodeError_GetStart()
• PyUnicodeDecodeError_SetEnd()
• PyUnicodeDecodeError_SetReason()
• PyUnicodeDecodeError_SetStart()
• PyUnicodeEncodeError_GetEncoding()
• PyUnicodeEncodeError_GetEnd()
2.4. Conteúdo da API Limitada 35
The Python/C API, Release 3.13.7
• PyUnicodeEncodeError_GetObject()
• PyUnicodeEncodeError_GetReason()
• PyUnicodeEncodeError_GetStart()
• PyUnicodeEncodeError_SetEnd()
• PyUnicodeEncodeError_SetReason()
• PyUnicodeEncodeError_SetStart()
• PyUnicodeIter_Type
• PyUnicodeTranslateError_GetEnd()
• PyUnicodeTranslateError_GetObject()
• PyUnicodeTranslateError_GetReason()
• PyUnicodeTranslateError_GetStart()
• PyUnicodeTranslateError_SetEnd()
• PyUnicodeTranslateError_SetReason()
• PyUnicodeTranslateError_SetStart()
• PyUnicode_Append()
• PyUnicode_AppendAndDel()
• PyUnicode_AsASCIIString()
• PyUnicode_AsCharmapString()
• PyUnicode_AsDecodedObject()
• PyUnicode_AsDecodedUnicode()
• PyUnicode_AsEncodedObject()
• PyUnicode_AsEncodedString()
• PyUnicode_AsEncodedUnicode()
• PyUnicode_AsLatin1String()
• PyUnicode_AsMBCSString()
• PyUnicode_AsRawUnicodeEscapeString()
• PyUnicode_AsUCS4()
• PyUnicode_AsUCS4Copy()
• PyUnicode_AsUTF16String()
• PyUnicode_AsUTF32String()
• PyUnicode_AsUTF8AndSize()
• PyUnicode_AsUTF8String()
• PyUnicode_AsUnicodeEscapeString()
• PyUnicode_AsWideChar()
• PyUnicode_AsWideCharString()
• PyUnicode_BuildEncodingMap()
• PyUnicode_Compare()
• PyUnicode_CompareWithASCIIString()
• PyUnicode_Concat()
36 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• PyUnicode_Contains()
• PyUnicode_Count()
• PyUnicode_Decode()
• PyUnicode_DecodeASCII()
• PyUnicode_DecodeCharmap()
• PyUnicode_DecodeCodePageStateful()
• PyUnicode_DecodeFSDefault()
• PyUnicode_DecodeFSDefaultAndSize()
• PyUnicode_DecodeLatin1()
• PyUnicode_DecodeLocale()
• PyUnicode_DecodeLocaleAndSize()
• PyUnicode_DecodeMBCS()
• PyUnicode_DecodeMBCSStateful()
• PyUnicode_DecodeRawUnicodeEscape()
• PyUnicode_DecodeUTF16()
• PyUnicode_DecodeUTF16Stateful()
• PyUnicode_DecodeUTF32()
• PyUnicode_DecodeUTF32Stateful()
• PyUnicode_DecodeUTF7()
• PyUnicode_DecodeUTF7Stateful()
• PyUnicode_DecodeUTF8()
• PyUnicode_DecodeUTF8Stateful()
• PyUnicode_DecodeUnicodeEscape()
• PyUnicode_EncodeCodePage()
• PyUnicode_EncodeFSDefault()
• PyUnicode_EncodeLocale()
• PyUnicode_EqualToUTF8()
• PyUnicode_EqualToUTF8AndSize()
• PyUnicode_FSConverter()
• PyUnicode_FSDecoder()
• PyUnicode_Find()
• PyUnicode_FindChar()
• PyUnicode_Format()
• PyUnicode_FromEncodedObject()
• PyUnicode_FromFormat()
• PyUnicode_FromFormatV()
• PyUnicode_FromObject()
• PyUnicode_FromOrdinal()
• PyUnicode_FromString()
2.4. Conteúdo da API Limitada 37
The Python/C API, Release 3.13.7
• PyUnicode_FromStringAndSize()
• PyUnicode_FromWideChar()
• PyUnicode_GetDefaultEncoding()
• PyUnicode_GetLength()
• PyUnicode_InternFromString()
• PyUnicode_InternInPlace()
• PyUnicode_IsIdentifier()
• PyUnicode_Join()
• PyUnicode_Partition()
• PyUnicode_RPartition()
• PyUnicode_RSplit()
• PyUnicode_ReadChar()
• PyUnicode_Replace()
• PyUnicode_Resize()
• PyUnicode_RichCompare()
• PyUnicode_Split()
• PyUnicode_Splitlines()
• PyUnicode_Substring()
• PyUnicode_Tailmatch()
• PyUnicode_Translate()
• PyUnicode_Type
• PyUnicode_WriteChar()
• PyVarObject
• PyVarObject.ob_base
• PyVarObject.ob_size
• PyVectorcall_Call()
• PyVectorcall_NARGS()
• PyWeakReference
• PyWeakref_GetObject()
• PyWeakref_GetRef()
• PyWeakref_NewProxy()
• PyWeakref_NewRef()
• PyWrapperDescr_Type
• PyWrapper_New()
• PyZip_Type
• Py_AddPendingCall()
• Py_AtExit()
• Py_BEGIN_ALLOW_THREADS
• Py_BLOCK_THREADS
38 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• Py_BuildValue()
• Py_BytesMain()
• Py_CompileString()
• Py_DecRef()
• Py_DecodeLocale()
• Py_END_ALLOW_THREADS
• Py_EncodeLocale()
• Py_EndInterpreter()
• Py_EnterRecursiveCall()
• Py_Exit()
• Py_FatalError()
• Py_FileSystemDefaultEncodeErrors
• Py_FileSystemDefaultEncoding
• Py_Finalize()
• Py_FinalizeEx()
• Py_GenericAlias()
• Py_GenericAliasType
• Py_GetBuildInfo()
• Py_GetCompiler()
• Py_GetConstant()
• Py_GetConstantBorrowed()
• 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()
2.4. Conteúdo da API Limitada 39
The Python/C API, Release 3.13.7
• Py_IsNone()
• Py_IsTrue()
• Py_LeaveRecursiveCall()
• Py_Main()
• Py_MakePendingCalls()
• Py_NewInterpreter()
• Py_NewRef()
• Py_ReprEnter()
• Py_ReprLeave()
• Py_SetProgramName()
• Py_SetPythonHome()
• Py_SetRecursionLimit()
• Py_UCS4
• Py_UNBLOCK_THREADS
• Py_UTF8Mode
• Py_VaBuildValue()
• Py_Version
• Py_XNewRef()
• Py_buffer
• Py_intptr_t
• Py_ssize_t
• Py_uintptr_t
• allocfunc
• binaryfunc
• descrgetfunc
• descrsetfunc
• destructor
• getattrfunc
• getattrofunc
• getbufferproc
• getiterfunc
• getter
• hashfunc
• initproc
• inquiry
• iternextfunc
• lenfunc
• newfunc
• objobjargproc
40 Capítulo 2. Estabilidade da API C
The Python/C API, Release 3.13.7
• objobjproc
• releasebufferproc
• reprfunc
• richcmpfunc
• setattrfunc
• setattrofunc
• setter
• ssizeargfunc
• ssizeobjargproc
• ssizessizeargfunc
• ssizessizeobjargproc
• symtable
• ternaryfunc
• traverseproc
• unaryfunc
• vectorcallfunc
• visitproc
2.4. Conteúdo da API Limitada 41
The Python/C API, Release 3.13.7
42 Capítulo 2. Estabilidade da API C
CAPÍTULO 3
A camada de nível muito alto
As funçõ es neste capítulo permitirã o que você execute um có digo-fonte Python fornecido em um arquivo ou buffer,
mas nã o permitirã o que você interaja de forma mais detalhada com o interpretador.
Vá rias dessas funçõ es aceitam um símbolo de início da gramá tica como parâ metro. Os símbolos de início disponí-
veis sã o Py_eval_input, Py_file_input e Py_single_input. Eles sã o descritos seguindo as funçõ es que os
aceitam como parâ metros.
Note també m que vá rias dessas funçõ es aceitam parâ metros FILE*. Um problema específico que precisa ser tratado
com cuidado é que a estrutura FILE para diferentes bibliotecas C pode ser diferente e incompatível. No Windows
(pelo menos), é possível que extensõ es vinculadas dinamicamente usem bibliotecas diferentes, entã o deve-se tomar
cuidado para que os parâ metros FILE* sejam passados para essas funçõ es somente se for certo que elas foram criadas
pela mesma biblioteca que o tempo de execuçã o do Python está usando.
int PyRun_AnyFile(FILE *fp, const char *filename)
Esta é uma interface simplificada para PyRun_AnyFileExFlags() abaixo, deixando closeit definido como
0 e flags definido como NULL.
int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Esta é uma interface simplificada para PyRun_AnyFileExFlags() abaixo, deixando o argumento closeit
definido como 0.
int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
Esta é uma interface simplificada para PyRun_AnyFileExFlags() abaixo, deixando o argumento flags de-
finido como NULL.
int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)
Se fp se referir a um arquivo associado a um dispositivo interativo (entrada de console ou terminal ou
pseudo-terminal Unix), retorna o valor de PyRun_InteractiveLoop(), caso contrá rio, retorna o resul-
tado de PyRun_SimpleFile(). filename é decodificado da codificaçã o do sistema de arquivos (sys.
getfilesystemencoding()). Se filename for NULL, esta funçã o usa "???" como o nome do arquivo.
Se closeit for verdadeiro, o arquivo será fechado antes de PyRun_SimpleFileExFlags() retornar.
int PyRun_SimpleString(const char *command)
Esta é uma interface simplificada para PyRun_SimpleStringFlags() abaixo, deixando o argumento
PyCompilerFlags* definido como NULL.
int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Executa o có digo-fonte Python de command no mó dulo __main__ de acordo com o argumento flags. Se
43
The Python/C API, Release 3.13.7
__main__ ainda nã o existir, ele será criado. Retorna 0 em caso de sucesso ou -1 se uma exceçã o foi gerada.
Se houve um erro, nã o há como obter as informaçõ es da exceçã o. Para o significado de flags, veja abaixo.
Observe que se uma exceçã o SystemExit nã o tratada for levantada, esta funçã o nã o retornará -1, mas sairá
do processo, desde que PyConfig.inspect seja zero.
int PyRun_SimpleFile(FILE *fp, const char *filename)
Esta é uma interface simplificada para PyRun_SimpleFileExFlags() abaixo, deixando closeit definido
como 0 e flags definido como NULL.
int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
Esta é uma interface simplificada para PyRun_SimpleFileExFlags() abaixo, deixando o flags definido
como NULL.
int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)
Semelhante a PyRun_SimpleStringFlags(), mas o có digo-fonte Python é lido de fp em vez de uma string
na memó ria. filename deve ser o nome do arquivo, ele é decodificado a partir do tratador de erros e codificação
do sistema de arquivos. Se closeit for true, o arquivo será fechado antes que PyRun_SimpleFileExFlags()
retorne.
® Nota
No Windows, fp deve ser aberto como modo biná rio (por exemplo, fopen(filename, "rb")). Caso
contrá rio, o Python pode nã o manipular corretamente o arquivo de script com final de linha LF.
int PyRun_InteractiveOne(FILE *fp, const char *filename)
Esta é uma interface simplificada para PyRun_InteractiveOneFlags() abaixo, deixando flags definido
como NULL.
int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Lê e executa uma ú nica instruçã o de um arquivo associado a um dispositivo interativo de acordo com o ar-
gumento flags. O usuá rio será solicitado usando sys.ps1 e sys.ps2. filename é decodificado a partir do
tratador de erros e codificação do sistema de arquivos.
Retorna 0 quando a entrada foi executada com sucesso, -1 se houve uma exceçã o ou um có digo de erro do
arquivo de inclusã o errcode.h distribuído como parte do Python se houve um erro de aná lise. (Observe que
errcode.h nã o é incluído por Python.h, entã o deve ser incluído especificamente se necessá rio.)
int PyRun_InteractiveLoop(FILE *fp, const char *filename)
Esta é uma interface simplificada para PyRun_InteractiveLoopFlags() abaixo, deixando flags definido
como NULL.
int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Lê e executa instruçõ es de um arquivo associado a um dispositivo interativo até que o EOF seja atingido. O
usuá rio será consultado usando sys.ps1 e sys.ps2. filename é decodificado a partir do tratador de erros e
codificação do sistema de arquivos. Retorna 0 no EOF ou um nú mero negativo em caso de falha.
int (*PyOS_InputHook)(void)
Parte da ABI Está vel. Pode ser definido para apontar para uma funçã o com o protó tipo int func(void).
A funçã o será chamada quando o prompt do interpretador do Python estiver prestes a ficar ocioso e aguardar
a entrada do usuá rio no terminal. O valor de retorno é ignorado. A substituiçã o deste hook pode ser usada
para integrar o prompt do interpretador com outros laços de eventos, como feito em Modules/_tkinter.c
no có digo-fonte do Python.
Alterado na versã o 3.12: Esta funçã o só é chamada pelo interpretador principal.
char *(*PyOS_ReadlineFunctionPointer)(FILE*, FILE*, const char*)
Pode ser definido para apontar para uma funçã o com o protó tipo char *func(FILE *stdin, FILE
*stdout, char *prompt), substituindo a funçã o padrã o usada para ler uma ú nica linha de entrada no
prompt do interpretador. Espera-se que a funçã o produza a string prompt se nã o for NULL e, em seguida, leia
44 Capítulo 3. A camada de nível muito alto
The Python/C API, Release 3.13.7
uma linha de entrada do arquivo de entrada padrã o fornecido, retornando a string resultante. Por exemplo, o
mó dulo readline define este gancho para fornecer recursos de ediçã o de linha e preenchimento de tabulaçã o.
O resultado deve ser uma string alocada por PyMem_RawMalloc() ou PyMem_RawRealloc(), ou NULL se
ocorrer um erro.
Alterado na versã o 3.4: O resultado deve ser alocado por PyMem_RawMalloc() ou PyMem_RawRealloc(),
em vez de ser alocado por PyMem_Malloc() ou PyMem_Realloc().
Alterado na versã o 3.12: Esta funçã o só é chamada pelo interpretador principal.
PyObject *PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Retorna valor: Nova referência. Esta é uma interface simplificada para PyRun_StringFlags() abaixo,
deixando flags definido como NULL.
PyObject *PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags
*flags)
Retorna valor: Nova referência. Execut o có digo-fonte Python de str no contexto especificado pelos objetos
globals e locals com os sinalizadores do compilador especificados por flags. globals deve ser um dicioná rio;
locals pode ser qualquer objeto que implemente o protocolo de mapeamento. O parâ metro start especifica o
token de início que deve ser usado para analisar o có digo-fonte.
Retorna o resultado da execuçã o do có digo como um objeto Python, ou NULL se uma exceçã o foi levantada.
PyObject *PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)
Retorna valor: Nova referência. Esta é uma interface simplificada para PyRun_FileExFlags() abaixo,
deixando closeit definido como 0 e flags definido como NULL.
PyObject *PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int
closeit)
Retorna valor: Nova referência. Esta é uma interface simplificada para PyRun_FileExFlags() abaixo,
deixando flags definido como NULL.
PyObject *PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
Retorna valor: Nova referência. Esta é uma interface simplificada para PyRun_FileExFlags() abaixo,
deixando closeit definido como 0.
PyObject *PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
int closeit, PyCompilerFlags *flags)
Retorna valor: Nova referência. Semelhante a PyRun_StringFlags(), mas o có digo-fonte Python é lido
de fp em vez de uma string na memó ria. filename deve ser o nome do arquivo, ele é decodificado a partir do
tratador de erros e codificação do sistema de arquivos. Se closeit for true, o arquivo será fechado antes que
PyRun_FileExFlags() retorne.
PyObject *Py_CompileString(const char *str, const char *filename, int start)
Retorna valor: Nova referência. Parte da ABI Está vel. Esta é uma interface simplificada para
Py_CompileStringFlags() abaixo, deixando flags definido como NULL.
PyObject *Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)
Retorna valor: Nova referência. Esta é uma interface simplificada para Py_CompileStringExFlags()
abaixo, com optimize definido como -1.
PyObject *Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int
optimize)
Retorna valor: Nova referência. Analisa e compil o có digo-fonte Python em str, retornando o objeto de có digo
resultante. O token inicial é fornecido por start; isso pode ser usado para restringir o có digo que pode ser
compilado e deve ser Py_eval_input, Py_file_input ou Py_single_input. O nome do arquivo espe-
cificado por filename é usado para construir o objeto de có digo e pode aparecer em tracebacks ou mensagens
de exceçã o SyntaxError. Isso retorna NULL se o có digo nã o puder ser analisado ou compilado.
O inteiro optimize especifica o nível de otimizaçã o do compilador; um valor de -1 seleciona o nível de oti-
mizaçã o do interpretador dado pela opçã o -O. Níveis explícitos sã o 0 (nenhuma otimizaçã o; __debug__ é
45
The Python/C API, Release 3.13.7
verdadeiro), 1 (instruçõ es assert sã o removidas, __debug__ é falso) ou 2 (strings de documentaçã o també m
sã o removidas).
Adicionado na versã o 3.4.
PyObject *Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags,
int optimize)
Retorna valor: Nova referência. Como Py_CompileStringObject(), mas filename é uma string de bytes
decodificada a partir do tratador de erros e codificação do sistema de arquivos.
Adicionado na versã o 3.2.
PyObject *PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Retorna valor: Nova referência. Parte da ABI Está vel. Esta é uma interface simplificada para
PyEval_EvalCodeEx(), com apenas o objeto có digo e variá veis locais e globais. Os outros argumentos
sã o definidos como 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Avalia um objeto có digo pré -compilado, dado um
ambiente particular para sua avaliaçã o. Este ambiente consiste em um dicioná rio de variá veis globais, um
objeto mapeamento de variá veis locais, vetores de argumentos, nomeados e padrõ es, um dicioná rio de valores
padrõ es para argumentos somente-nomeados e uma tupla de clausura de cé lulas.
PyObject *PyEval_EvalFrame(PyFrameObject *f)
Retorna valor: Nova referência. Parte da ABI Está vel. Avalia um quadro de execuçã o. Esta é uma interface
simplificada para PyEval_EvalFrameEx(), para retrocompatibilidade.
PyObject *PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Retorna valor: Nova referência. Parte da ABI Está vel. Esta é a funçã o principal e sem retoques da interpretaçã o
Python. O objeto có digo associado ao quadro de execuçã o f é executado, interpretando bytecode e executando
chamadas conforme necessá rio. O parâ metro adicional throwflag pode ser ignorado na maioria das vezes - se
verdadeiro, ele faz com que uma exceçã o seja levantada imediatamente; isso é usado para os mé todos throw()
de objetos geradores.
Alterado na versã o 3.4: Essa funçã o agora inclui uma asserçã o de depuraçã o para ajudar a garantir que ela nã o
descarte silenciosamente uma exceçã o ativa.
int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Esta funçã o altera os sinalizadores do quadro de avaliaçã o atual e retorna verdadeiro em caso de sucesso e falso
em caso de falha.
int Py_eval_input
O símbolo inicial da gramá tica Python para expressõ es isoladas; para uso com Py_CompileString().
int Py_file_input
O símbolo de início da gramá tica Python para sequê ncias de instruçõ es conforme lidas de um arquivo ou outra
fonte; para uso com Py_CompileString(). Este é o símbolo a ser usado ao compilar có digo-fonte Python
arbitrariamente longo.
int Py_single_input
O símbolo de início da gramá tica Python para uma ú nica declaraçã o; para uso com Py_CompileString().
Este é o símbolo usado para o laço do interpretador interativo.
struct PyCompilerFlags
Esta é a estrutura usada para manter os sinalizadores do compilador. Em casos onde o có digo está apenas sendo
compilado, ele é passado como int flags, e em casos onde o có digo está sendo executado, ele é passado
como PyCompilerFlags *flags. Neste caso, from __future__ import pode modificar flags.
Sempre que PyCompilerFlags *flags for NULL, cf_flags é tratado como igual a 0, e qualquer modifi-
caçã o devido a from __future__ import é descartada.
46 Capítulo 3. A camada de nível muito alto
The Python/C API, Release 3.13.7
int cf_flags
Sinalizadores do compilador.
int cf_feature_version
cf_feature_version é a versã o secundá ria do Python. Deve ser inicializada como PY_MINOR_VERSION.
O campo é ignorado por padrã o, ele é usado se e somente se o sinalizador PyCF_ONLY_AST estiver
definido em cf_flags.
Alterado na versã o 3.8: Adicionado campo cf_feature_version.
Os sinalizadores do compilador disponíveis sã o acessíveis como macros:
PyCF_ALLOW_TOP_LEVEL_AWAIT
PyCF_ONLY_AST
PyCF_OPTIMIZED_AST
PyCF_TYPE_COMMENTS
Veja sinalizadores do compilador na documentaçã o do mó dulo Python ast, que exporta essas constantes
com os mesmos nomes.
Os sinalizadores “PyCF” acima podem ser combinados com sinalizadores “CO_FUTURE”, como
CO_FUTURE_ANNOTATIONS, para habilitar recursos normalmente selecioná veis usando instruçõ es future.
Consulte Sinalizadores de objetos código para obter uma lista completa.
47
The Python/C API, Release 3.13.7
48 Capítulo 3. A camada de nível muito alto
CAPÍTULO 4
Contagem de referências
As funçõ es e macros nesta sessã o sã o usadas para o gerenciamento de contagem de referê ncias de objetos Python.
Py_ssize_t Py_REFCNT(PyObject *o)
Obtê m a contagem de referê ncias do objeto Python o.
Observe que o valor retornado pode nã o refletir realmente quantas referê ncias ao objeto sã o realmente manti-
das. Por exemplo, alguns objetos sã o imortais e tê m uma contagem de referê ncias muito alta, que nã o reflete
o nú mero real de referê ncias. Consequentemente, nã o confie no valor retornado para ser preciso, exceto um
valor de 0 ou 1.
Use a funçã o Py_SET_REFCNT() para definir uma contagem de referê ncias de um objeto.
Alterado na versã o 3.10: Py_REFCNT() is changed to the inline static function.
Alterado na versã o 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.
Em uma construçã o do Python com threads threads livres, se refcnt for maior que UINT32_MAX, o objeto será
transformado em imortal.
Esta funçã o nã o tem efeito sobre objetos imortais.
Adicionado na versã o 3.9.
Alterado na versã o 3.12: Os objetos imortais nã o sã o modificados.
void Py_INCREF(PyObject *o)
Indicate taking a new strong reference to object o, indicating it is in use and should not be destroyed.
Esta funçã o nã o tem efeito sobre objetos imortais.
Esta funçã o é geralmente usada para transformar uma referência emprestada em uma referência forte local. A
funçã o Py_NewRef() pode ser usada para criar uma nova referência forte.
When done using the object, release is by calling Py_DECREF().
The object must not be NULL; if you aren’t sure that it isn’t 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.
Alterado na versã o 3.12: Os objetos imortais nã o sã o modificados.
49
The Python/C API, Release 3.13.7
void Py_XINCREF(PyObject *o)
Semelhante a Py_INCREF(), mas o objeto o pode ser NULL, caso em que isso nã o tem efeito.
Veja també m Py_XNewRef().
PyObject *Py_NewRef(PyObject *o)
Parte da ABI Está vel desde a versão 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.
The object o must not be NULL; use Py_XNewRef() if o can be NULL.
Por exemplo:
Py_INCREF(obj);
self->attr = obj;
can be written as:
self->attr = Py_NewRef(obj);
See also Py_INCREF().
Adicionado na versã o 3.10.
PyObject *Py_XNewRef(PyObject *o)
Parte da ABI Está vel desde a versão 3.10. Semelhante a Py_NewRef(), mas o objeto o pode ser NULL.
Se o objeto o é NULL, a funçã o apenas retorna NULL.
Adicionado na versã o 3.10.
void Py_DECREF(PyObject *o)
Release a strong reference to object o, indicating the reference is no longer used.
Esta funçã o nã o tem efeito sobre objetos imortais.
Once the last strong reference is released (i.e. the object’s reference count reaches 0), the object’s type’s deal-
location function (which must not be NULL) is invoked.
This function is usually used to delete a strong reference before exiting its scope.
The object must not be NULL; if you aren’t sure that it isn’t NULL, use Py_XDECREF().
Do not expect this function to actually modify o in any way. For at least some objects, this function has no
effect.
Á Aviso
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.
Alterado na versã o 3.12: Os objetos imortais nã o sã o modificados.
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.
50 Capítulo 4. Contagem de referências
The Python/C API, Release 3.13.7
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.
Alterado na versã o 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)
Parte da ABI Está vel. 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)
Parte da ABI Está vel. 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.
Adicionado na versã o 3.6.
Alterado na versã o 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().
Adicionado na versã o 3.6.
Alterado na versã o 3.12: The macro arguments are now only evaluated once. If an argument has side effects,
these are no longer duplicated.
51
The Python/C API, Release 3.13.7
52 Capítulo 4. Contagem de referências
CAPÍTULO 5
Manipulando Exceções
As funçõ es descritas nesse capítulo permitem você tratar e gerar exceçõ es em Python. É importante entender alguns
princípios bá sicos no tratamento de exceçã o no Python. Funciona de forma parecida com a variá vel POSIX errno:
existe um indicador global (por thread) do ú ltimo erro ocorrido. A maioria das funçõ es da API C nã o limpa isso com
ê xito, mas indica a causa do erro na falha. A maioria das funçõ es da API retorna um indicador de erro, geralmente,
NULL se eles devem retornar um ponteiro, ou -1 se retornarem um inteiro (exceçã o: as funçõ es PyArg_* retornam
1 para sucesso e 0 para falha).
Concretamente, o indicador de erro consiste em trê s ponteiros de objeto: o tipo da exceçã o, o valor da exceçã o e o
objeto de traceback. Qualquer um desses ponteiros pode ser NULL se nã o definido (embora algumas combinaçõ es
sejam proibidas, por exemplo, você nã o pode ter um retorno nã o NULL se o tipo de exceçã o for NULL).
Quando uma funçã o deve falhar porque devido à falha de alguma funçã o que ela chamou, ela geralmente nã o define
o indicador de erro; a funçã o que ela chamou já o definiu. Ela é responsá vel por manipular o erro e limpar a exceçã o
ou retornar apó s limpar todos os recursos que possui (como referê ncias a objetos ou alocaçõ es de memó ria); ela
não deve continuar normalmente se nã o estiver preparada para lidar com o erro. Se estiver retornando devido a um
erro, é importante indicar ao chamador que um erro foi definido. Se o erro nã o for manipulado ou propagado com
cuidado, chamadas adicionais para a API Python/C podem nã o se comportar conforme o esperado e podem falhar
de maneiras misteriosas.
® Nota
O indicador de erro não é resultado de sys.exc_info(). O primeiro corresponde a uma exceçã o que ainda
nã o foi capturada (e, portanto, ainda está se propagando), enquanto o segundo retorna uma exceçã o apó s ser
capturada (e, portanto, parou de se propagar).
5.1 Impressão e limpeza
void PyErr_Clear()
Parte da ABI Está vel. Limpe o indicador de erro. Se o indicador de erro nã o estiver definido, nã o haverá
efeito.
void PyErr_PrintEx(int set_sys_last_vars)
Parte da ABI Está vel. Exibe um traceback padrã o para sys.stderr e limpe o indicador de erro. A menos
que o erro seja um SystemExit, nesse caso, nenhum traceback será impresso e o processo Python será
encerrado com o có digo de erro especificado pela instâ ncia SystemExit.
53
The Python/C API, Release 3.13.7
Chame esta funçã o apenas quando o indicador de erro estiver definido. Caso contrá rio, causará um erro fatal!
If set_sys_last_vars is nonzero, the variable sys.last_exc is set to the printed exception. For backwards
compatibility, the deprecated variables sys.last_type, sys.last_value and sys.last_traceback
are also set to the type, value and traceback of this exception, respectively.
Alterado na versã o 3.12: The setting of sys.last_exc was added.
void PyErr_Print()
Parte da ABI Está vel. Apelido para PyErr_PrintEx(1).
void PyErr_WriteUnraisable(PyObject *obj)
Parte da ABI Está vel. Chama sys.unraisablehook() usando a exceçã o atual e o argumento obj.
This utility function prints a warning message to sys.stderr when an exception has been set but it is im-
possible 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.
Uma exceçã o deve ser definida ao chamar essa funçã o.
Alterado na versã o 3.4: Exibe o traceback (situaçã o da pilha de execuçã o). Exibe apenas o traceback se obj
for NULL.
Alterado na versã o 3.8: Utiliza sys.unraisablehook().
void PyErr_FormatUnraisable(const char *format, ...)
Similar to PyErr_WriteUnraisable(), but the format and subsequent parameters help format
the warning message; they have the same meaning and values as in PyUnicode_FromFormat().
PyErr_WriteUnraisable(obj) is roughly equivalent to PyErr_FormatUnraisable("Exception
ignored in: %R", obj). If format is NULL, only the traceback is printed.
Adicionado na versã o 3.13.
void PyErr_DisplayException(PyObject *exc)
Parte da ABI Está vel desde a versão 3.12. Print the standard traceback display of exc to sys.stderr,
including chained exceptions and notes.
Adicionado na versã o 3.12.
5.2 Lançando exceções
Essas funçõ es ajudam a definir o indicador de erro do thread. Por conveniê ncia, algumas dessas funçõ es sempre
retornam um ponteiro NULL ao usar instruçã o com return.
void PyErr_SetString(PyObject *type, const char *message)
Parte da ABI Está vel. 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)
Parte da ABI Está vel. Essa funçã o é semelhante à PyErr_SetString() mas permite especificar um objeto
Python arbitrá rio para o valor da exceçã o.
PyObject *PyErr_Format(PyObject *exception, const char *format, ...)
Retorna valor: Sempre NULL. Parte da ABI Está vel. This function sets the error indicator and returns NULL.
exception should be a Python exception class. The format and subsequent parameters help format the error
message; they have the same meaning and values as in PyUnicode_FromFormat(). format is an ASCII-
-encoded string.
54 Capítulo 5. Manipulando Exceções
The Python/C API, Release 3.13.7
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Retorna valor: Sempre NULL. Parte da ABI Está vel desde a versão 3.5. Igual a PyErr_Format(), mas usando
o argumento va_list em vez de um nú mero variá vel de argumentos.
Adicionado na versã o 3.5.
void PyErr_SetNone(PyObject *type)
Parte da ABI Está vel. Isso é uma abreviaçã o para PyErr_SetObject(type, Py_None).
int PyErr_BadArgument()
Parte da ABI Está vel. This is a shorthand for PyErr_SetString(PyExc_TypeError, message), where
message indicates that a built-in operation was invoked with an illegal argument. It is mostly for internal use.
PyObject *PyErr_NoMemory()
Retorna valor: Sempre NULL. Parte da ABI Está vel. Essa é uma abreviaçã o para
PyErr_SetNone(PyExc_MemoryError); que retorna NULL para que uma funçã o de alocaçã o de
objeto possa escrever return PyErr_NoMemory(); quando ficar sem memó ria.
PyObject *PyErr_SetFromErrno(PyObject *type)
Retorna valor: Sempre NULL. Parte da ABI Está vel. 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)
Retorna valor: Sempre NULL. Parte da ABI Está vel. 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)
Retorna valor: Sempre NULL. Parte da ABI Está vel desde a versão 3.7. Similar to
PyErr_SetFromErrnoWithFilenameObject(), but takes a second filename object, for raising
errors when a function that takes two filenames fails.
Adicionado na versã o 3.4.
PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
Retorna valor: Sempre NULL. Parte da ABI Está vel. Similar to
PyErr_SetFromErrnoWithFilenameObject(), but the filename is given as a C string. filename
is decoded from the filesystem encoding and error handler.
PyObject *PyErr_SetFromWindowsErr(int ierr)
Retorna valor: Sempre NULL. Parte da ABI Está vel on Windows desde a versão 3.7. This is a convenience
function to raise OSError. If called with ierr of 0, the error code returned by a call to GetLastError() is
used instead. It calls the Win32 function FormatMessage() to retrieve the Windows description of error code
given by ierr or GetLastError(), then it constructs a OSError object with the winerror attribute set to the
error code, the strerror attribute set to the corresponding error message (gotten from FormatMessage()),
and then calls PyErr_SetObject(PyExc_OSError, object). This function always returns NULL.
Disponibilidade: Windows.
PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
Retorna valor: Sempre NULL. Parte da ABI Está vel on Windows desde a versão 3.7. Similar to
PyErr_SetFromWindowsErr(), with an additional parameter specifying the exception type to be raised.
Disponibilidade: Windows.
5.2. Lançando exceções 55
The Python/C API, Release 3.13.7
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Retorna valor: Sempre NULL. Parte da ABI Está vel on Windows desde a versão 3.7. Similar to
PyErr_SetFromWindowsErr(), with the additional behavior that if filename is not NULL, it is decoded
from the filesystem encoding (os.fsdecode()) and passed to the constructor of OSError as a third para-
meter to be used to define the filename attribute of the exception instance.
Disponibilidade: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject
*filename)
Retorna valor: Sempre NULL. Parte da ABI Está vel on Windows desde a versão 3.7. Similar to
PyErr_SetExcFromWindowsErr(), with the additional behavior that if filename is not NULL, it is pas-
sed to the constructor of OSError as a third parameter to be used to define the filename attribute of the
exception instance.
Disponibilidade: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject
*filename, PyObject *filename2)
Retorna valor: Sempre NULL. Parte da ABI Está vel on Windows desde a versão 3.7. Similar à
PyErr_SetExcFromWindowsErrWithFilenameObject(), mas aceita um segundo caminho do objeto.
Disponibilidade: Windows.
Adicionado na versã o 3.4.
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)
Retorna valor: Sempre NULL. Parte da ABI Está vel on Windows desde a versão 3.7. Similar à
PyErr_SetFromWindowsErrWithFilename(), com um parâ metro adicional especificando o tipo de ex-
ceçã o a ser gerado.
Disponibilidade: Windows.
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Retorna valor: Sempre NULL. Parte da ABI Está vel desde a versão 3.7. This is a convenience function to raise
ImportError. msg will be set as the exception’s message string. name and path, both of which can be NULL,
will be set as the ImportError’s respective name and path attributes.
Adicionado na versã o 3.3.
PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject
*path)
Retorna valor: Sempre NULL. Parte da ABI Está vel desde a versão 3.6. Muito parecido com
PyErr_SetImportError() mas a funçã o permite especificar uma subclasse de ImportError para le-
vantar uma exceçã o.
Adicionado na versã o 3.6.
void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Set file, line, and offset information for the current exception. If the current exception is not a SyntaxError,
then it sets additional attributes, which make the exception printing subsystem think the exception is a
SyntaxError.
Adicionado na versã o 3.4.
void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Parte da ABI Está vel desde a versão 3.7. Like PyErr_SyntaxLocationObject(), but filename is a byte
string decoded from the filesystem encoding and error handler.
Adicionado na versã o 3.2.
void PyErr_SyntaxLocation(const char *filename, int lineno)
Parte da ABI Está vel. Like PyErr_SyntaxLocationEx(), but the col_offset parameter is omitted.
56 Capítulo 5. Manipulando Exceções
The Python/C API, Release 3.13.7
void PyErr_BadInternalCall()
Parte da ABI Está vel. This is a shorthand for PyErr_SetString(PyExc_SystemError, message),
where message indicates that an internal operation (e.g. a Python/C API function) was invoked with an il-
legal argument. It is mostly for internal use.
5.3 Emitindo advertências
Use these functions to issue warnings from C code. They mirror similar functions exported by the Python warnings
module. They normally print a warning message to sys.stderr; however, it is also possible that the user has specified
that warnings are to be turned into errors, and in that case they will raise an exception. It is also possible that the
functions raise an exception because of a problem with the warning machinery. The return value is 0 if no exception
is raised, or -1 if an exception is raised. (It is not possible to determine whether a warning message is actually printed,
nor what the reason is for the exception; this is intentional.) If an exception is raised, the caller should do its normal
exception handling (for example, Py_DECREF() owned references and return an error value).
int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Parte da ABI Está vel. Issue a warning message. The category argument is a warning category (see below)
or NULL; the message argument is a UTF-8 encoded string. stack_level is a positive number giving a number
of stack frames; the warning will be issued from the currently executing line of code in that stack frame. A
stack_level of 1 is the function calling PyErr_WarnEx(), 2 is the function above that, and so forth.
Warning categories must be subclasses of PyExc_Warning ; PyExc_Warning is a subclass of
PyExc_Exception; the default warning category is PyExc_RuntimeWarning . The standard Python war-
ning categories are available as global variables whose names are enumerated at Warning types.
For information about warning control, see the documentation for the warnings module and the -W option in
the command line documentation. There is no C API for warning control.
int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno,
PyObject *module, PyObject *registry)
Issue a warning message with explicit control over all warning attributes. This is a straightforward wrapper
around the Python function warnings.warn_explicit(); see there for more information. The module and
registry arguments may be set to NULL to get the default effect described there.
Adicionado na versã o 3.4.
int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char
*module, PyObject *registry)
Parte da ABI Está vel. Similar to PyErr_WarnExplicitObject() except that message and module are
UTF-8 encoded strings, and filename is decoded from the filesystem encoding and error handler.
int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Parte da ABI Está vel. Function similar to PyErr_WarnEx(), but use PyUnicode_FromFormat() to format
the warning message. format is an ASCII-encoded string.
Adicionado na versã o 3.2.
int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
Parte da ABI Está vel desde a versão 3.6. Function similar to PyErr_WarnFormat(), but category is
ResourceWarning and it passes source to warnings.WarningMessage.
Adicionado na versã o 3.6.
5.4 Consultando o indicador de erro
PyObject *PyErr_Occurred()
Retorna valor: Referência emprestada. Parte da ABI Está vel. Test whether the error indicator is set. If
set, return the exception type (the first argument to the last call to one of the PyErr_Set* functions or to
PyErr_Restore()). If not set, return NULL. You do not own a reference to the return value, so you do not
need to Py_DECREF() it.
5.3. Emitindo advertências 57
The Python/C API, Release 3.13.7
The caller must hold the GIL.
® Nota
Do not compare the return value to a specific exception; use PyErr_ExceptionMatches() instead,
shown below. (The comparison could easily fail since the exception may be an instance instead of a class,
in the case of a class exception, or it may be a subclass of the expected exception.)
int PyErr_ExceptionMatches(PyObject *exc)
Parte da ABI Está vel. Equivalent to PyErr_GivenExceptionMatches(PyErr_Occurred(), exc).
This should only be called when an exception is actually set; a memory access violation will occur if no
exception has been raised.
int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)
Parte da ABI Está vel. Return true if the given exception matches the exception type in exc. If exc is a class
object, this also returns true when given is an instance of a subclass. If exc is a tuple, all exception types in the
tuple (and recursively in subtuples) are searched for a match.
PyObject *PyErr_GetRaisedException(void)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 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.
Por exemplo:
{
PyObject *exc = PyErr_GetRaisedException();
/* ... code that might produce other errors ... */
PyErr_SetRaisedException(exc);
}
µ Ver também
PyErr_GetHandledException(), to save the exception currently being handled.
Adicionado na versã o 3.12.
void PyErr_SetRaisedException(PyObject *exc)
Parte da ABI Está vel desde a versão 3.12. Set exc as the exception currently being raised, clearing the existing
exception if one is set.
Á Aviso
This call steals a reference to exc, which must be a valid exception.
Adicionado na versã o 3.12.
void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
Parte da ABI Está vel. Descontinuado desde a versã o 3.12: Use PyErr_GetRaisedException() instead.
Retrieve the error indicator into three variables whose addresses are passed. If the error indicator is not set,
set all three variables to NULL. If it is set, it will be cleared and you own a reference to each object retrieved.
The value and traceback object may be NULL even when the type object is not.
58 Capítulo 5. Manipulando Exceções
The Python/C API, Release 3.13.7
® Nota
This function is normally only used by legacy code that needs to catch exceptions or save and restore the
error indicator temporarily.
Por exemplo:
{
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
/* ... code that might produce other errors ... */
PyErr_Restore(type, value, traceback);
}
void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
Parte da ABI Está vel. Descontinuado desde a versã o 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)
Parte da ABI Está vel. Descontinuado desde a versã o 3.12: Use PyErr_GetRaisedException() instead,
to avoid any possible de-normalization.
Under certain circumstances, the values returned by PyErr_Fetch() below can be “unnormalized”, meaning
that *exc is a class object but *val is not an instance of the same class. This function can be used to instantiate
the class in that case. If the values are already normalized, nothing happens. The delayed normalization is
implemented to improve performance.
® 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)
Parte da ABI Está vel desde a versão 3.11. Retrieve the active exception instance, as would be returned by
sys.exception(). This refers to an exception that was already caught, not to an exception that was freshly
raised. Returns a new reference to the exception or NULL. Does not modify the interpreter’s exception state.
5.4. Consultando o indicador de erro 59
The Python/C API, Release 3.13.7
® Nota
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when
code needs to save and restore the exception state temporarily. Use PyErr_SetHandledException()
to restore or clear the exception state.
Adicionado na versã o 3.11.
void PyErr_SetHandledException(PyObject *exc)
Parte da ABI Está vel desde a versão 3.11. Set the active exception, as known from sys.exception().
This refers to an exception that was already caught, not to an exception that was freshly raised. To clear the
exception state, pass NULL.
® Nota
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when
code needs to save and restore the exception state temporarily. Use PyErr_GetHandledException()
to get the exception state.
Adicionado na versã o 3.11.
void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
Parte da ABI Está vel desde a versão 3.7. Retrieve the old-style representation of the exception info, as
known from sys.exc_info(). This refers to an exception that was already caught, not to an excep-
tion that was freshly raised. Returns new references for the three objects, any of which may be NULL.
Does not modify the exception info state. This function is kept for backwards compatibility. Prefer using
PyErr_GetHandledException().
® Nota
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when
code needs to save and restore the exception state temporarily. Use PyErr_SetExcInfo() to restore or
clear the exception state.
Adicionado na versã o 3.3.
void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
Parte da ABI Está vel desde a versão 3.7. Set the exception info, as known from sys.exc_info(). This
refers to an exception that was already caught, not to an exception that was freshly raised. This function steals
the references of the arguments. To clear the exception state, pass NULL for all three arguments. This function
is kept for backwards compatibility. Prefer using PyErr_SetHandledException().
® Nota
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when
code needs to save and restore the exception state temporarily. Use PyErr_GetExcInfo() to read the
exception state.
Adicionado na versã o 3.3.
Alterado na versã o 3.11: The type and traceback arguments are no longer used and can be NULL. The
interpreter now derives them from the exception instance (the value argument). The function still steals
references of all three arguments.
60 Capítulo 5. Manipulando Exceções
The Python/C API, Release 3.13.7
5.5 Tratamento de sinal
int PyErr_CheckSignals()
Parte da ABI Está vel. Essa funçã o interage com o manipulador de sinais do Python.
If the function is called from the main thread and under the main Python interpreter, it checks whether a signal
has been sent to the processes and if so, invokes the corresponding signal handler. If the signal module is
supported, this can invoke a signal handler written in Python.
The function attempts to handle all pending signals, and then returns 0. However, if a Python signal handler
raises an exception, the error indicator is set and the function returns -1 immediately (such that other pending
signals may not have been handled yet: they will be on the next PyErr_CheckSignals() invocation).
If the function is called from a non-main thread, or under a non-main Python interpreter, it does nothing and
returns 0.
This function can be called by long-running C code that wants to be interruptible by user requests (such as by
pressing Ctrl-C).
® Nota
The default Python signal handler for SIGINT raises the KeyboardInterrupt exception.
void PyErr_SetInterrupt()
Parte da ABI Está vel. Simulate the effect of a SIGINT signal arriving. This is equivalent to
PyErr_SetInterruptEx(SIGINT).
® Nota
This function is async-signal-safe. It can be called without the GIL and from a C signal handler.
int PyErr_SetInterruptEx(int signum)
Parte da ABI Está vel desde a versão 3.10. Simulate the effect of a signal arriving. The next time
PyErr_CheckSignals() is called, the Python signal handler for the given signal number will be called.
This function can be called by C code that sets up its own signal handling and wants Python signal handlers
to be invoked as expected when an interruption is requested (for example when the user presses Ctrl-C to
interrupt an operation).
If the given signal isn’t handled by Python (it was set to signal.SIG_DFL or signal.SIG_IGN), it will be
ignored.
If signum is outside of the allowed range of signal numbers, -1 is returned. Otherwise, 0 is returned. The
error indicator is never changed by this function.
® Nota
This function is async-signal-safe. It can be called without the GIL and from a C signal handler.
Adicionado na versã o 3.10.
int PySignal_SetWakeupFd(int fd)
This utility function specifies a file descriptor to which the signal number is written as a single byte whenever
a signal is received. fd must be non-blocking. It returns the previous such file descriptor.
O valor -1 desabilita o recurso; este é o estado inicial. Isso é equivalente à signal.set_wakeup_fd() em
Python, mas sem nenhuma verificaçã o de erro. fd deve ser um descritor de arquivo vá lido. A funçã o só deve
ser chamada a partir da thread principal.
5.5. Tratamento de sinal 61
The Python/C API, Release 3.13.7
Alterado na versã o 3.5: No Windows, a funçã o agora també m suporta manipuladores de socket.
5.6 Classes de exceção
PyObject *PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
Retorna valor: Nova referência. Parte da ABI Está vel. This utility function creates and returns a new exception
class. The name argument must be the name of the new exception, a C string of the form module.classname.
The base and dict arguments are normally NULL. This creates a class object derived from Exception (acces-
sible in C as 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Same as PyErr_NewException(), except that the
new exception class can easily be given a docstring: If doc is non-NULL, it will be used as the docstring for the
exception class.
Adicionado na versã o 3.2.
int PyExceptionClass_Check(PyObject *ob)
Return non-zero if ob is an exception class, zero otherwise. This function always succeeds.
const char *PyExceptionClass_Name(PyObject *ob)
Parte da ABI Está vel desde a versão 3.8. Return tp_name of the exception class ob.
5.7 Objeto Exceção
PyObject *PyException_GetTraceback(PyObject *ex)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Parte da ABI Está vel. Defina o retorno traceback (situaçã o da pilha de execuçã o) associado à exceçã o como
tb. Use Py_None para limpá -lo.
PyObject *PyException_GetContext(PyObject *ex)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Parte da ABI Está vel. Set the context associated with the exception to ctx. Use NULL to clear it. There is no
type check to make sure that ctx is an exception instance. This steals a reference to ctx.
PyObject *PyException_GetCause(PyObject *ex)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Parte da ABI Está vel. 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.
62 Capítulo 5. Manipulando Exceções
The Python/C API, Release 3.13.7
PyObject *PyException_GetArgs(PyObject *ex)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.12. Return args of exception ex.
void PyException_SetArgs(PyObject *ex, PyObject *args)
Parte da ABI Está vel desde a versão 3.12. Set args of exception ex to args.
PyObject *PyUnstable_Exc_PrepReraiseStar(PyObject *orig, PyObject *excs)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
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.
Adicionado na versã o 3.12.
5.8 Objetos de exceção Unicode
As seguintes funçõ es sã o usadas para criar e modificar exceçõ es 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Create a UnicodeDecodeError object with the
attributes encoding, object, length, start, end and reason. encoding and reason are UTF-8 encoded strings.
PyObject *PyUnicodeDecodeError_GetEncoding(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetEncoding(PyObject *exc)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o atributo * encoding* dado no objeto da
exceçã o.
PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc)
PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o atributo object dado no objeto da exceçã o.
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)
Parte da ABI Está vel. Obté m o atributo start do objeto da exceçã o coloca-o em *start. start nã o deve ser
NULL. Retorna 0 se nã o der erro, -1 caso dê erro.
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)
Parte da ABI Está vel. Define o atributo start dado no objeto de exceçã o start. Em caso de sucesso, retorna 0,
em caso de falha, retorna -1.
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)
Parte da ABI Está vel. Obtenha o atributo end dado no objeto de exceçã o e coloque *end. O end nã o deve ser
NULL. Em caso de sucesso, retorna 0, em caso de falha, retorna -1.
5.8. Objetos de exceção Unicode 63
The Python/C API, Release 3.13.7
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)
Parte da ABI Está vel. Set the end attribute of the given exception object to end. Return 0 on success, -1 on
failure.
PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc)
PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o atributo reason dado no objeto da exceçã o.
int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
Parte da ABI Está vel. Set the reason attribute of the given exception object to reason. Return 0 on success,
-1 on failure.
5.9 Controle de recursão
These two functions provide a way to perform safe recursive calls at the C level, both in the core and in extension
modules. They are needed if the recursive code does not necessarily invoke Python code (which tracks its recursion
depth automatically). They are also not needed for tp_call implementations because the call protocol takes care of
recursion handling.
int Py_EnterRecursiveCall(const char *where)
Parte da ABI Está vel desde a versão 3.9. Marca um ponto em que a chamada recursiva em nível C está prestes
a ser executada.
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.
The function then checks if the recursion limit is reached. If this is the case, a RecursionError is set and a
nonzero value is returned. Otherwise, zero is returned.
where should be a UTF-8 encoded string such as " in instance check" to be concatenated to the
RecursionError message caused by the recursion depth limit.
Alterado na versã o 3.9: This function is now also available in the limited API.
void Py_LeaveRecursiveCall(void)
Parte da ABI Está vel desde a versão 3.9. Ends a Py_EnterRecursiveCall(). Must be called once for each
successful invocation of Py_EnterRecursiveCall().
Alterado na versã o 3.9: This function is now also available in the limited API.
Properly implementing tp_repr for container types requires special recursion handling. In addition to protecting the
stack, tp_repr also needs to track objects to prevent cycles. The following two functions facilitate this functionality.
Effectively, these are the C equivalent to reprlib.recursive_repr().
int Py_ReprEnter(PyObject *object)
Parte da ABI Está vel. Chamado no início da implementaçã o tp_repr para detectar ciclos.
If the object has already been processed, the function returns a positive integer. In that case the tp_repr
implementation should return a string object indicating a cycle. As examples, dict objects return {...} and
list objects return [...].
A funçã o retornará um inteiro negativo se o limite da recursã o for atingido. Nesse caso a implementaçã o
tp_repr deverá , normalmente,. retornar NULL.
Caso contrá rio, a funçã o retorna zero e a implementaçã o tp_repr poderá continuar normalmente.
64 Capítulo 5. Manipulando Exceções
The Python/C API, Release 3.13.7
void Py_ReprLeave(PyObject *object)
Parte da ABI Está vel. Termina a Py_ReprEnter(). Deve ser chamado uma vez para cada chamada de
Py_ReprEnter() que retorna zero.
5.10 Exception and warning types
All standard Python exceptions and warning categories are available as global variables whose names are PyExc_
followed by the Python exception name. These have the type PyObject*; they are all class objects.
For completeness, here are all the variables:
5.10.1 Exception types
C name Python name
BaseException
PyObject *PyExc_BaseException
Parte da ABI Está vel.
BaseExceptionGroup
PyObject *PyExc_BaseExceptionGroup
Parte da ABI Está vel desde a versão 3.11.
Exception
PyObject *PyExc_Exception
Parte da ABI Está vel.
ArithmeticError
PyObject *PyExc_ArithmeticError
Parte da ABI Está vel.
AssertionError
PyObject *PyExc_AssertionError
Parte da ABI Está vel.
AttributeError
PyObject *PyExc_AttributeError
Parte da ABI Está vel.
BlockingIOError
PyObject *PyExc_BlockingIOError
Parte da ABI Está vel desde a versão 3.7.
BrokenPipeError
PyObject *PyExc_BrokenPipeError
Parte da ABI Está vel desde a versão 3.7.
BufferError
PyObject *PyExc_BufferError
Parte da ABI Está vel.
ChildProcessError
PyObject *PyExc_ChildProcessError
Parte da ABI Está vel desde a versão 3.7.
continua na próxima página
5.10. Exception and warning types 65
The Python/C API, Release 3.13.7
Tabela 1 – continuação da página anterior
C name Python name
ConnectionAbortedError
PyObject *PyExc_ConnectionAbortedError
Parte da ABI Está vel desde a versão 3.7.
ConnectionError
PyObject *PyExc_ConnectionError
Parte da ABI Está vel desde a versão 3.7.
ConnectionRefusedError
PyObject *PyExc_ConnectionRefusedError
Parte da ABI Está vel desde a versão 3.7.
ConnectionResetError
PyObject *PyExc_ConnectionResetError
Parte da ABI Está vel desde a versão 3.7.
EOFError
PyObject *PyExc_EOFError
Parte da ABI Está vel.
FileExistsError
PyObject *PyExc_FileExistsError
Parte da ABI Está vel desde a versão 3.7.
FileNotFoundError
PyObject *PyExc_FileNotFoundError
Parte da ABI Está vel desde a versão 3.7.
FloatingPointError
PyObject *PyExc_FloatingPointError
Parte da ABI Está vel.
GeneratorExit
PyObject *PyExc_GeneratorExit
Parte da ABI Está vel.
ImportError
PyObject *PyExc_ImportError
Parte da ABI Está vel.
IndentationError
PyObject *PyExc_IndentationError
Parte da ABI Está vel.
IndexError
PyObject *PyExc_IndexError
Parte da ABI Está vel.
InterruptedError
PyObject *PyExc_InterruptedError
Parte da ABI Está vel desde a versão 3.7.
continua na próxima página
66 Capítulo 5. Manipulando Exceções
The Python/C API, Release 3.13.7
Tabela 1 – continuação da página anterior
C name Python name
IsADirectoryError
PyObject *PyExc_IsADirectoryError
Parte da ABI Está vel desde a versão 3.7.
KeyError
PyObject *PyExc_KeyError
Parte da ABI Está vel.
KeyboardInterrupt
PyObject *PyExc_KeyboardInterrupt
Parte da ABI Está vel.
LookupError
PyObject *PyExc_LookupError
Parte da ABI Está vel.
MemoryError
PyObject *PyExc_MemoryError
Parte da ABI Está vel.
ModuleNotFoundError
PyObject *PyExc_ModuleNotFoundError
Parte da ABI Está vel desde a versão 3.6.
NameError
PyObject *PyExc_NameError
Parte da ABI Está vel.
NotADirectoryError
PyObject *PyExc_NotADirectoryError
Parte da ABI Está vel desde a versão 3.7.
NotImplementedError
PyObject *PyExc_NotImplementedError
Parte da ABI Está vel.
OSError
PyObject *PyExc_OSError
Parte da ABI Está vel.
OverflowError
PyObject *PyExc_OverflowError
Parte da ABI Está vel.
PermissionError
PyObject *PyExc_PermissionError
Parte da ABI Está vel desde a versão 3.7.
ProcessLookupError
PyObject *PyExc_ProcessLookupError
Parte da ABI Está vel desde a versão 3.7.
PythonFinalizationError
PyObject *PyExc_PythonFinalizationError
continua na próxima página
5.10. Exception and warning types 67
The Python/C API, Release 3.13.7
Tabela 1 – continuação da página anterior
C name Python name
RecursionError
PyObject *PyExc_RecursionError
Parte da ABI Está vel desde a versão 3.7.
ReferenceError
PyObject *PyExc_ReferenceError
Parte da ABI Está vel.
RuntimeError
PyObject *PyExc_RuntimeError
Parte da ABI Está vel.
StopAsyncIteration
PyObject *PyExc_StopAsyncIteration
Parte da ABI Está vel desde a versão 3.7.
StopIteration
PyObject *PyExc_StopIteration
Parte da ABI Está vel.
SyntaxError
PyObject *PyExc_SyntaxError
Parte da ABI Está vel.
SystemError
PyObject *PyExc_SystemError
Parte da ABI Está vel.
SystemExit
PyObject *PyExc_SystemExit
Parte da ABI Está vel.
TabError
PyObject *PyExc_TabError
Parte da ABI Está vel.
TimeoutError
PyObject *PyExc_TimeoutError
Parte da ABI Está vel desde a versão 3.7.
TypeError
PyObject *PyExc_TypeError
Parte da ABI Está vel.
UnboundLocalError
PyObject *PyExc_UnboundLocalError
Parte da ABI Está vel.
UnicodeDecodeError
PyObject *PyExc_UnicodeDecodeError
Parte da ABI Está vel.
continua na próxima página
68 Capítulo 5. Manipulando Exceções
The Python/C API, Release 3.13.7
Tabela 1 – continuação da página anterior
C name Python name
UnicodeEncodeError
PyObject *PyExc_UnicodeEncodeError
Parte da ABI Está vel.
UnicodeError
PyObject *PyExc_UnicodeError
Parte da ABI Está vel.
UnicodeTranslateError
PyObject *PyExc_UnicodeTranslateError
Parte da ABI Está vel.
ValueError
PyObject *PyExc_ValueError
Parte da ABI Está vel.
ZeroDivisionError
PyObject *PyExc_ZeroDivisionError
Parte da ABI Está vel.
Adicionado na versã o 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 e
PyExc_TimeoutError foram introduzidos seguindo a PEP 3151.
Adicionado na versã o 3.5: PyExc_StopAsyncIteration e PyExc_RecursionError.
Adicionado na versã o 3.6: PyExc_ModuleNotFoundError.
Adicionado na versã o 3.11: PyExc_BaseExceptionGroup.
5.10.2 OSError aliases
The following are a compatibility aliases to PyExc_OSError.
Alterado na versã o 3.3: Esses aliases costumavam ser tipos de exceçã o separados.
C name Python name Notas
OSError
PyObject
*PyExc_EnvironmentError
Parte da ABI Está vel.
OSError
PyObject *PyExc_IOError
Parte da ABI Está vel.
OSError [win]
PyObject
*PyExc_WindowsError
Parte da ABI Está vel on Win-
dows desde a versão 3.7.
5.10. Exception and warning types 69
The Python/C API, Release 3.13.7
Notas:
5.10.3 Warning types
C name Python name
Warning
PyObject *PyExc_Warning
Parte da ABI Está vel.
BytesWarning
PyObject *PyExc_BytesWarning
Parte da ABI Está vel.
DeprecationWarning
PyObject *PyExc_DeprecationWarning
Parte da ABI Está vel.
EncodingWarning
PyObject *PyExc_EncodingWarning
Parte da ABI Está vel desde a versão 3.10.
FutureWarning
PyObject *PyExc_FutureWarning
Parte da ABI Está vel.
ImportWarning
PyObject *PyExc_ImportWarning
Parte da ABI Está vel.
PendingDeprecationWarning
PyObject *PyExc_PendingDeprecationWarning
Parte da ABI Está vel.
ResourceWarning
PyObject *PyExc_ResourceWarning
Parte da ABI Está vel desde a versão 3.7.
RuntimeWarning
PyObject *PyExc_RuntimeWarning
Parte da ABI Está vel.
SyntaxWarning
PyObject *PyExc_SyntaxWarning
Parte da ABI Está vel.
UnicodeWarning
PyObject *PyExc_UnicodeWarning
Parte da ABI Está vel.
UserWarning
PyObject *PyExc_UserWarning
Parte da ABI Está vel.
Adicionado na versã o 3.2: PyExc_ResourceWarning .
Adicionado na versã o 3.10: PyExc_EncodingWarning .
70 Capítulo 5. Manipulando Exceções
CAPÍTULO 6
Utilitários
As funçõ es neste capítulo executam vá rias tarefas de utilidade pú blica, desde ajudar o có digo C a ser mais portá til
em plataformas, usando mó dulos Python de C, como també m, a analise de argumentos de funçã o e a construçã o de
valores Python a partir de valores C.
6.1 Utilitários do sistema operacional
PyObject *PyOS_FSPath(PyObject *path)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.6. Retorna a representaçã o do sistema
de arquivos para path. Se o objeto for um objeto str ou bytes, entã o uma nova referência forte é retornada.
Se o objeto implementa a interface os.PathLike, entã o __fspath__() é retornado desde que seja um
objeto str ou bytes. Caso contrá rio, TypeError é levantada e NULL é retornado.
Adicionado na versã o 3.6.
int Py_FdIsInteractive(FILE *fp, const char *filename)
Retorna verdadeiro (nã o zero) se o arquivo padrã o de E/S fp com o nome filename for considerado interativo.
Este é o caso dos arquivos para os quais isatty(fileno(fp)) é verdade. Se PyConfig.interactive
for nã o zero, esta funçã o també m retorna true se o ponteiro filename for NULL ou se o nome for igual a uma
das strings '<stdin>' ou '???'.
Esta funçã o nã o deve ser chamada antes da inicializaçã o do Python.
void PyOS_BeforeFork()
Parte da ABI Está vel on platforms with fork() desde a versão 3.7. Funçã o para preparar algum estado interno
antes de ser feito um fork do processo. Isso deve ser chamado antes de chamar fork() ou qualquer funçã o
semelhante que clone o processo atual. Disponível apenas em sistemas onde fork() é definido.
Á Aviso
A chamada C fork() só deve ser feita a partir da thread “main” (do interpretador “main”). O mesmo vale
para PyOS_BeforeFork().
Adicionado na versã o 3.7.
71
The Python/C API, Release 3.13.7
void PyOS_AfterFork_Parent()
Parte da ABI Está vel on platforms with fork() desde a versão 3.7. Funçã o para atualizar algum estado interno
depois de ser feito um fork do processo. Isso deve ser chamado a partir do processo pai depois de chamar
fork() ou qualquer funçã o semelhante que clone o processo atual, independentemente da clonagem do pro-
cesso ter sido bem-sucedida ou nã o. Disponível apenas em sistemas onde fork() é definido.
Á Aviso
A chamada C fork() só deve ser feita a partir da thread “main” (do interpretador “main”). O mesmo vale
para PyOS_AfterFork_Parent().
Adicionado na versã o 3.7.
void PyOS_AfterFork_Child()
Parte da ABI Está vel on platforms with fork() desde a versão 3.7. Funçã o para atualizar o estado interno
do interpretador depois de ser feito um fork do processo. Isso deve ser chamado a partir do processo filho
depois de chamar fork() ou qualquer funçã o semelhante que clone o processo atual, se houver alguma chance
do processo ter uma chamada de retorno para o interpretador Python. Disponível apenas em sistemas onde
fork() é definido.
Á Aviso
A chamada C fork() só deve ser feita a partir da thread “main” (do interpretador “main”). O mesmo vale
para PyOS_AfterFork_Child().
Adicionado na versã o 3.7.
µ Ver também
os.register_at_fork() permite registrar funçõ es personalizadas do Python para serem chamadas por
PyOS_BeforeFork(), PyOS_AfterFork_Parent() e PyOS_AfterFork_Child().
void PyOS_AfterFork()
Parte da ABI Está vel on platforms with fork(). Funçã o para atualizar algum estado interno apó s ser feito um
fork de processo; isso deve ser chamado no novo processo se o interpretador do Python continuar a ser usado.
Se um novo executá vel é carregado no novo processo, esta funçã o nã o precisa ser chamada.
Descontinuado desde a versã o 3.7: Esta funçã o foi sucedida por PyOS_AfterFork_Child().
int PyOS_CheckStack()
Parte da ABI Está vel on platforms with USE_STACKCHECK desde a versão 3.7. Retorna verdadeiro quando
o interpretador fica sem espaço na pilha. Esta é uma verificaçã o confiá vel, mas só está disponível quando
USE_STACKCHECK é definido (atualmente em certas versõ es do Windows usando o compilador Microsoft
Visual C++). USE_STACKCHECK será definido automaticamente; você nunca deve alterar a definiçã o em seu
pró prio có digo.
typedef void (*PyOS_sighandler_t)(int)
Parte da ABI Está vel.
PyOS_sighandler_t PyOS_getsig(int i)
Parte da ABI Está vel. Retorna o manipulador de sinal atual para o sinal i. Este é um invó lucro fino em torno
de sigaction() ou signal(). Nã o chame essas funçõ es diretamente!
PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)
Parte da ABI Está vel. Define o manipulador de sinal para o sinal i como h; retornar o manipulador de si-
nal antigo. Este é um invó lucro fino em torno de sigaction() ou signal(). Nã o chame essas funçõ es
diretamente!
72 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
wchar_t *Py_DecodeLocale(const char *arg, size_t *size)
Parte da ABI Está vel desde a versão 3.7.
Á Aviso
Esta funçã o nã o deve ser chamada diretamente: use a API PyConfig com a funçã o
PyConfig_SetBytesString() que garante que Python esteja pré-inicializado.
Esta funçã o nã o deve ser chamada antes de Python estar pré-inicializado e para que a localidade
LC_CTYPE seja configurada corretamente: consulte a funçã o Py_PreInitialize().
Decodifica uma string de bytes do tratador de erros e codificação do sistema de arquivos. Se o tratador de
erros for o tratador de errors surrogateescape, bytes nã o decodificá veis sã o decodificados como caracteres no
intervalo U+DC80..U+DCFF; e se uma string de bytes puder ser decodificada como um caractere substituto,
os bytes sã o escapados usando o tratador de erros surrogateescape em vez de decodificá -los.
Retorna um ponteiro para uma string de caracteres largos recé m-alocada, usa PyMem_RawFree() para liberar
a memó ria. Se o tamanho nã o for NULL, escreve o nú mero de caracteres largos excluindo o caractere nulo em
*size
Retorna NULL em erro de decodificaçã o ou erro de alocaçã o de memó ria. Se size nã o for NULL, *size é
definido como (size_t)-1 em erro de memó ria ou definido como (size_t)-2 em erro de decodificaçã o.
tratador de erros e codificação do sistema de arquivos sã o selecionados por PyConfig_Read(): veja os mem-
bros filesystem_encoding e filesystem_errors de PyConfig .
Erros de decodificaçã o nunca devem acontecer, a menos que haja um bug na biblioteca C.
Use a funçã o Py_EncodeLocale() para codificar a string de caracteres de volta para uma string de bytes.
µ Ver também
As funçõ es PyUnicode_DecodeFSDefaultAndSize() e PyUnicode_DecodeLocaleAndSize().
Adicionado na versã o 3.5.
Alterado na versã o 3.7: A funçã o agora usa a codificaçã o UTF-8 no Modo UTF-8 do Python.
Alterado na versã o 3.8: A funçã o agora usa a codificaçã o UTF-8 no Windows se PyPreConfig.
legacy_windows_fs_encoding for zero;
char *Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
Parte da ABI Está vel desde a versão 3.7. Encode a wide character string to the filesystem encoding and
error handler. If the error handler is surrogateescape error handler, surrogate characters in the range
U+DC80..U+DCFF are converted to bytes 0x80..0xFF.
Return a pointer to a newly allocated byte string, use PyMem_Free() to free the memory. Return NULL on
encoding error or memory allocation error.
If error_pos is not NULL, *error_pos is set to (size_t)-1 on success, or set to the index of the invalid
character on encoding error.
tratador de erros e codificação do sistema de arquivos sã o selecionados por PyConfig_Read(): veja os mem-
bros filesystem_encoding e filesystem_errors de PyConfig .
Use the Py_DecodeLocale() function to decode the bytes string back to a wide character string.
Á Aviso
Esta funçã o nã o deve ser chamada antes de Python estar pré-inicializado e para que a localidade
LC_CTYPE seja configurada corretamente: consulte a funçã o Py_PreInitialize().
6.1. Utilitários do sistema operacional 73
The Python/C API, Release 3.13.7
µ Ver também
The PyUnicode_EncodeFSDefault() and PyUnicode_EncodeLocale() functions.
Adicionado na versã o 3.5.
Alterado na versã o 3.7: A funçã o agora usa a codificaçã o UTF-8 no Modo UTF-8 do Python.
Alterado na versã o 3.8: The function now uses the UTF-8 encoding on Windows if PyPreConfig.
legacy_windows_fs_encoding is zero.
6.2 System Functions
These are utility functions that make functionality from the sys module accessible to C code. They all work with
the current interpreter thread’s sys module’s dict, which is contained in the internal thread state structure.
PyObject *PySys_GetObject(const char *name)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Return the object name from the sys module or
NULL if it does not exist, without setting an exception.
int PySys_SetObject(const char *name, PyObject *v)
Parte da ABI Está vel. Set name in the sys module to v unless v is NULL, in which case name is deleted from
the sys module. Returns 0 on success, -1 on error.
void PySys_ResetWarnOptions()
Parte da ABI Está vel. Reset sys.warnoptions to an empty list. This function may be called prior to
Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Clear sys.warnoptions and warnings.
filters instead.
void PySys_WriteStdout(const char *format, ...)
Parte da ABI Está vel. Write the output string described by format to sys.stdout. No exceptions are raised,
even if truncation occurs (see below).
format should limit the total size of the formatted output string to 1000 bytes or less – after 1000 bytes, the
output string is truncated. In particular, this means that no unrestricted “%s” formats should occur; these should
be limited using “%.<N>s” where <N> is a decimal number calculated so that <N> plus the maximum size of
other formatted text does not exceed 1000 bytes. Also watch out for “%f”, which can print hundreds of digits
for very large numbers.
If a problem occurs, or sys.stdout is unset, the formatted message is written to the real (C level) stdout.
void PySys_WriteStderr(const char *format, ...)
Parte da ABI Está vel. As PySys_WriteStdout(), but write to sys.stderr or stderr instead.
void PySys_FormatStdout(const char *format, ...)
Parte da ABI Está vel. Function similar to PySys_WriteStdout() but format the message using
PyUnicode_FromFormatV() and don’t truncate the message to an arbitrary length.
Adicionado na versã o 3.2.
void PySys_FormatStderr(const char *format, ...)
Parte da ABI Está vel. As PySys_FormatStdout(), but write to sys.stderr or stderr instead.
Adicionado na versã o 3.2.
PyObject *PySys_GetXOptions()
Retorna valor: Referência emprestada. Parte da ABI Está vel desde a versão 3.7. Return the current dictionary
of -X options, similarly to sys._xoptions. On error, NULL is returned and an exception is set.
Adicionado na versã o 3.2.
74 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
int PySys_Audit(const char *event, const char *format, ...)
Parte da ABI Está vel desde a versão 3.13. Raise an auditing event with any active hooks. Return zero for
success and non-zero with an exception set on failure.
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.
Note that # format characters should always be treated as Py_ssize_t, regardless of whether
PY_SSIZE_T_CLEAN was defined.
sys.audit() performs the same function from Python code.
See also PySys_AuditTuple().
Adicionado na versã o 3.8.
Alterado na versã o 3.8.2: Require Py_ssize_t for # format characters. Previously, an unavoidable depreca-
tion warning was raised.
int PySys_AuditTuple(const char *event, PyObject *args)
Parte da ABI Está vel desde a versão 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.
Adicionado na versã o 3.13.
int PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
Append the callable hook to the list of active auditing hooks. Return zero on success and non-zero on failure.
If the runtime has been initialized, also set an error on failure. Hooks added through this API are called for all
interpreters created by the runtime.
O ponteiro userData é passado para a funçã o de gancho. Como as funçõ es de gancho podem ser chamadas de
diferentes tempos de execuçã o, esse ponteiro nã o deve se referir diretamente ao estado do Python.
This function is safe to call before Py_Initialize(). When called after runtime initialization, existing audit
hooks are notified and may silently abort the operation by raising an error subclassed from Exception (other
errors will not be silenced).
The hook function is always called with the GIL held by the Python interpreter that raised the event.
See PEP 578 for a detailed description of auditing. Functions in the runtime and standard library that raise
events are listed in the audit events table. Details are in each function’s documentation.
If the interpreter is initialized, this function raises an auditing event sys.addaudithook with no arguments.
If any existing hooks raise an exception derived from Exception, the new hook will not be added and the
exception is cleared. As a result, callers cannot assume that their hook has been added unless they control all
existing hooks.
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().
Adicionado na versã o 3.8.
6.2. System Functions 75
The Python/C API, Release 3.13.7
6.3 Process Control
void Py_FatalError(const char *message)
Parte da ABI Está vel. 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.
The Py_FatalError() function is replaced with a macro which logs automatically the name of the current
function, unless the Py_LIMITED_API macro is defined.
Alterado na versã o 3.9: Log the function name automatically.
void Py_Exit(int status)
Parte da ABI Está vel. Exit the current process. This calls Py_FinalizeEx() and then calls the standard C
library function exit(status). If Py_FinalizeEx() indicates an error, the exit status is set to 120.
Alterado na versã o 3.6: Errors from finalization no longer ignored.
int Py_AtExit(void (*func)())
Parte da ABI Está vel. Register a cleanup function to be called by Py_FinalizeEx(). The cleanup function
will be called with no arguments and should return no value. At most 32 cleanup functions can be registered.
When the registration is successful, Py_AtExit() returns 0; on failure, it returns -1. The cleanup func-
tion registered last is called first. Each cleanup function will be called at most once. Since Python’s internal
finalization will have completed before the cleanup function, no Python APIs should be called by func.
µ Ver também
PyUnstable_AtExit() for passing a void *data argument.
6.4 Importando módulos
PyObject *PyImport_ImportModule(const char *name)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Esta funçã o é um alias descontinuado de
PyImport_ImportModule().
Alterado na versã o 3.3: Essa funçã o falhava em alguns casos, quando a trava de importaçã o era mantida por
outra thread. No Python 3.3, no entanto, o esquema de trava mudou passando a ser de travas por mó dulo na
maior parte, dessa forma, o comportamento especial dessa funçã o nã o é mais necessá rio.
Deprecated since version 3.13, will be removed in version 3.15: Use PyImport_ImportModule() instead.
PyObject *PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals, PyObject
*fromlist)
Retorna valor: Nova referência. Importa um mó dulo. Isso é melhor descrito referindo-se à funçã o embutida
do Python __import__().
O valor de retorno é uma nova referê ncia ao mó dulo importado ou pacote de nível superior, ou NULL com uma
exceçã o definida em caso de falha. Como para __import__(), o valor de retorno quando um submó dulo
de um pacote é solicitado é normalmente o pacote de nível superior, a menos que um fromlist nã o vazio seja
fornecido.
As importaçõ es com falhas removem objetos incompletos do mó dulo, como em
PyImport_ImportModule().
76 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
PyObject *PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Importa um mó dulo. Isso é melhor
descrito referindo-se à funçã o embutida do Python __import__(), já que a funçã o padrã o __import__()
chama essa funçã o diretamente.
O valor de retorno é uma nova referê ncia ao mó dulo importado ou pacote de nível superior, ou NULL com uma
exceçã o definida em caso de falha. Como para __import__(), o valor de retorno quando um submó dulo
de um pacote é solicitado é normalmente o pacote de nível superior, a menos que um fromlist nã o vazio seja
fornecido.
Adicionado na versã o 3.3.
PyObject *PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals, PyObject
*fromlist, int level)
Retorna valor: Nova referência. Parte da ABI Está vel. Semelhante para
PyImport_ImportModuleLevelObject(), mas o nome é uma string codificada em UTF-8 de um
objeto Unicode.
Alterado na versã o 3.3: Valores negativos para level nã o sã o mais aceitos.
PyObject *PyImport_Import(PyObject *name)
Retorna valor: Nova referência. Parte da ABI Está vel. Essa é uma interface de alto nível que chama a atual
“funçã o auxiliar de importaçã o” (com um level explícito de 0, significando importaçã o absoluta). Invoca a
funçã o __import__() a partir de __builtins__ da global atual. Isso significa que a importaçã o é feita
usando quaisquer extras de importaçã o instalados no ambiente atual.
Esta funçã o sempre usa importaçõ es absolutas.
PyObject *PyImport_ReloadModule(PyObject *m)
Retorna valor: Nova referência. Parte da ABI Está vel. Recarrega um mó dulo. Retorna uma nova referê ncia
para o mó dulo recarregado, ou NULL com uma exceçã o definida em caso de falha (o mó dulo ainda existe neste
caso).
PyObject *PyImport_AddModuleRef(const char *name)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.13. Return the module object corres-
ponding 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 struc-
tures implied by a dotted name for name are not created if not already present.
Adicionado na versã o 3.13.
PyObject *PyImport_AddModuleObject(PyObject *name)
Retorna valor: Referência emprestada. Parte da ABI Está vel desde a versão 3.7. Similar to
PyImport_AddModuleRef(), but return a borrowed reference and name is a Python str object.
Adicionado na versã o 3.3.
PyObject *PyImport_AddModule(const char *name)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Similar to PyImport_AddModuleRef(), but
return a borrowed reference.
PyObject *PyImport_ExecCodeModule(const char *name, PyObject *co)
Retorna valor: Nova referência. Parte da ABI Está vel. 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
6.4. Importando módulos 77
The Python/C API, Release 3.13.7
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 funçã o recarregará o mó dulo se este já tiver sido importado. Veja PyImport_ReloadModule() para
forma desejada de recarregar um mó dulo.
Se name apontar para um nome pontilhado no formato de package.module, quaisquer estruturas de pacote
ainda nã o criadas ainda nã o serã o criadas.
Veja també m PyImport_ExecCodeModuleEx() e PyImport_ExecCodeModuleWithPathnames().
Alterado na versã o 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Like PyImport_ExecCodeModule(), but the
__file__ attribute of the module object is set to pathname if it is non-NULL.
Veja també m PyImport_ExecCodeModuleWithPathnames().
PyObject *PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, PyObject
*cpathname)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Like
PyImport_ExecCodeModuleEx(), but the __cached__ attribute of the module object is set to
cpathname if it is non-NULL. Of the three functions, this is the preferred one to use.
Adicionado na versã o 3.3.
Alterado na versã o 3.12: Setting __cached__ is deprecated. See ModuleSpec for alternatives.
PyObject *PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char
*pathname, const char *cpathname)
Retorna valor: Nova referência. Parte da ABI Está vel. Como PyImport_ExecCodeModuleObject(), mas
name, pathname e cpathname sã o strings codificadas em UTF-8. També m sã o feitas tentativas para descobrir
qual valor para pathname deve ser de cpathname se o primeiro estiver definido como NULL.
Adicionado na versã o 3.2.
Alterado na versã o 3.3: Uses imp.source_from_cache() in calculating the source path if only the bytecode
path is provided.
Alterado na versã o 3.12: No longer uses the removed imp module.
long PyImport_GetMagicNumber()
Parte da ABI Está vel. Retorna o nú mero má gico para arquivos de bytecode Python (també m conhecido como
arquivo .pyc). O nú mero má gico deve estar presente nos primeiros quatro bytes do arquivo bytecode, na
ordem de bytes little-endian. Retorna -1 em caso de erro.
Alterado na versã o 3.3: Retorna o valor de -1 no caso de falha.
const char *PyImport_GetMagicTag()
Parte da ABI Está vel. Retorna a string de tag má gica para nomes de arquivo de bytecode Python no formato
de PEP 3147. Tenha em mente que o valor em sys.implementation.cache_tag é autoritativo e deve
ser usado no lugar desta funçã o.
Adicionado na versã o 3.2.
78 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
PyObject *PyImport_GetModuleDict()
Retorna valor: Referência emprestada. Parte da ABI Está vel. Retorna o dicioná rio usado para a administraçã o
do mó dulo (també m conhecido como sys.modules). Observe que esta é uma variá vel por interpretador.
PyObject *PyImport_GetModule(PyObject *name)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.8. Retorna o mó dulo já importado
com o nome fornecido. Se o mó dulo ainda nã o foi importado, retorna NULL, mas nã o define um erro. Retorna
NULL e define um erro se a pesquisa falhar.
Adicionado na versã o 3.7.
PyObject *PyImport_GetImporter(PyObject *path)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Parte da ABI Está vel desde a versão 3.7. Carrega um mó dulo congelado chamado name. Retorna 1 para
sucesso, 0 se o mó dulo nã o for encontrado e -1 com uma exceçã o definida se a inicializaçã o falhar. Para acessar
o mó dulo importado em um carregamento bem-sucedido, use PyImport_ImportModule(). (Observe o
nome incorreto — esta funçã o recarregaria o mó dulo se ele já tivesse sido importado.)
Adicionado na versã o 3.3.
Alterado na versã o 3.4: O atributo __file__ nã o está mais definido no mó dulo.
int PyImport_ImportFrozenModule(const char *name)
Parte da ABI Está vel. Semelhante a PyImport_ImportFrozenModuleObject(), mas o nome é uma string
codificada em UTF-8 em vez de um objeto Unicode.
struct _frozen
Esta é a definiçã o do tipo de estrutura para descritores de mó dulo congelados, conforme gerado pelo utilitá rio
freeze (veja Tools/freeze/ na distribuiçã o fonte do Python). Sua definiçã o, encontrada em Include/
import.h, é :
struct _frozen {
const char *name;
const unsigned char *code;
int size;
bool is_package;
};
Alterado na versã o 3.11: O novo campo is_package indica se o mó dulo é um pacote ou nã o. Isso substitui
a configuraçã o do campo size para um valor negativo.
const struct _frozen *PyImport_FrozenModules
Este ponteiro é inicializado para apontar para um vetor de registros de _frozen, terminado por um cujos
membros sã o todos NULL ou zero. Quando um mó dulo congelado é importado, ele é pesquisado nesta tabela.
O có digo de terceiros pode fazer truques com isso para fornecer uma coleçã o criada dinamicamente de mó dulos
congelados.
int PyImport_AppendInittab(const char *name, PyObject *(*initfunc)(void))
Parte da ABI Está vel. Adiciona um ú nico mó dulo à tabela existente de mó dulos embutidos. Este é um invó lucro
prá tico em torno de PyImport_ExtendInittab(), retornando -1 se a tabela nã o puder ser estendida. O
novo mó dulo pode ser importado pelo nome name e usa a funçã o initfunc como a funçã o de inicializaçã o
chamada na primeira tentativa de importaçã o. Deve ser chamado 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
6.4. Importando módulos 79
The Python/C API, Release 3.13.7
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().
Se Python é inicializado vá rias vezes, PyImport_AppendInittab() ou PyImport_ExtendInittab()
devem ser chamados antes de cada inicializaçã o do Python.
6.5 Suporte a marshalling de dados
Essas rotinas permitem que o có digo C trabalhe com objetos serializados usando o mesmo formato de dados que o
mó dulo marshal. Existem funçõ es para gravar dados no formato de serializaçã o e funçõ es adicionais que podem
ser usadas para ler os dados novamente. Os arquivos usados para armazenar dados empacotados devem ser abertos
no modo biná rio.
Os valores numé ricos sã o armazenados primeiro com o byte menos significativo.
O mó dulo oferece suporte a duas versõ es do formato de dados: a versã o 0 é a versã o histó rica, a versã o 1 compartilha
strings internas no arquivo e apó s a desserializaçã o. A versã o 2 usa um formato biná rio para nú meros de ponto
flutuante. Py_MARSHAL_VERSION indica o formato do arquivo atual (atualmente 2).
void PyMarshal_WriteLongToFile(long value, FILE *file, int version)
Aplica marshalling em um inteiro long, value, para file. Isso escreverá apenas os 32 bits menos significativos
de value; independentemente do tamanho do tipo nativo long. version indica o formato do arquivo.
Esta funçã o pode falhar, caso em que define o indicador de erro. Use PyErr_Occurred() para verificar isso.
void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)
Aplica marshalling em um objeto Python, value, para file. version indica o formato do arquivo.
Esta funçã o pode falhar, caso em que define o indicador de erro. Use PyErr_Occurred() para verificar isso.
PyObject *PyMarshal_WriteObjectToString(PyObject *value, int version)
Retorna valor: Nova referência. Retorna um objeto de bytes que conté m a representaçã o pó s-marshalling de
value. version indica o formato do arquivo.
As seguintes funçõ es permitem que os valores pó s-marshalling sejam lidos novamente.
long PyMarshal_ReadLongFromFile(FILE *file)
Retorna um long C do fluxo de dados em um FILE* aberto para leitura. Somente um valor de 32 bits pode
ser lido usando essa funçã o, independentemente do tamanho nativo de long.
Em caso de erro, define a exceçã o apropriada (EOFError) e retorna -1.
int PyMarshal_ReadShortFromFile(FILE *file)
Retorna um short C do fluxo de dados em um FILE* aberto para leitura. Somente um valor de 16 bits pode
ser lido usando essa funçã o, independentemente do tamanho nativo de short.
Em caso de erro, define a exceçã o apropriada (EOFError) e retorna -1.
PyObject *PyMarshal_ReadObjectFromFile(FILE *file)
Retorna valor: Nova referência. Retorna um objeto Python do fluxo de dados em um FILE* aberto para leitura.
Em caso de erro, define a exceçã o apropriada (EOFError, ValueError ou TypeError) e retorna NULL.
80 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
PyObject *PyMarshal_ReadLastObjectFromFile(FILE *file)
Retorna valor: Nova referência. Retorna um objeto Python do fluxo de dados em um FILE* aberto para
leitura. Diferentemente de PyMarshal_ReadObjectFromFile(), essa funçã o presume que nenhum objeto
adicional será lido do arquivo, permitindo que ela carregue agressivamente os dados do arquivo na memó ria,
para que a desserializaçã o possa operar a partir de dados na memó ria em vez de ler um byte por vez do arquivo.
Use essas variantes apenas se tiver certeza de que nã o estará lendo mais nada do arquivo.
Em caso de erro, define a exceçã o apropriada (EOFError, ValueError ou TypeError) e retorna NULL.
PyObject *PyMarshal_ReadObjectFromString(const char *data, Py_ssize_t len)
Retorna valor: Nova referência. Retorna um objeto Python do fluxo de dados em um buffer de bytes contendo
len bytes apontados por data.
Em caso de erro, define a exceçã o apropriada (EOFError, ValueError ou TypeError) e retorna NULL.
6.6 Análise de argumentos e construção de valores
Essas funçõ es sã o ú teis ao criar suas pró prias funçõ es e mé todos de extensã o. Informaçõ es adicionais e exemplos
estã o disponíveis em extending-index.
As trê s primeiras funçõ es descritas, PyArg_ParseTuple(), PyArg_ParseTupleAndKeywords(), e
PyArg_Parse(), todas usam a string de formatação que informam à funçã o sobre os argumentos esperados. As
strings de formato usam a mesma sintaxe para cada uma dessas funçõ es.
6.6.1 Análise de argumentos
Uma string de formato consiste em zero ou mais “unidades de formato”. Uma unidade de formato descreve um objeto
Python; geralmente é um ú nico caractere ou uma sequê ncia entre parê nteses de unidades de formato. Com algumas
poucas exceçõ es, uma unidade de formato que nã o é uma sequê ncia entre parê nteses normalmente corresponde a um
ú nico argumento de endereço para essas funçõ es. Na descriçã o a seguir, a forma citada é a unidade de formato; a
entrada em parê nteses ( ) é o tipo de objeto Python que corresponde à unidade de formato; e a entrada em colchetes
[ ] é o tipo da variá vel(s) C cujo endereço deve ser passado.
Strings e buffers
® Nota
No Python 3.12 e anteriores, a macro PY_SSIZE_T_CLEAN deve ser definida antes da inclusã o de Python.h
para usar todas as variantes no formato # (s#, y#, etc.) explicadas abaixo. Isso nã o é necessá rio no Python 3.13
e posteriores.
Esses formatos permitem acessar um objeto como um pedaço contíguo de memó ria. Você nã o precisa fornecer
armazenamento bruto para a á rea de unicode ou bytes retornada.
Salvo indicaçã o em contrá rio, os buffers nã o sã o terminados em NUL.
Existem trê s maneiras pelas quais strings e buffers podem ser convertidos em C:
• Formatos como y* e s* estã o dentro de uma estrutura Py_buffer. Isso bloqueia o buffer subjacente para
que o chamador possa posteriormente usar o buffer, mesmo dentro de um bloco Py_BEGIN_ALLOW_THREADS
sem que haja o risco de que dados mutá veis sejam redimensionados ou destruídos. Dessa forma, você precisa
chamar PyBuffer_Release() depois de ter concluído o processamento de dados (ou em qualquer caso de
interrupçã o precoce).
• Os formatos es, es#, et e et# alocam o buffer resultante. Você precisa chamar PyMem_Free() depois de
ter concluído o processamento de dados (ou em qualquer caso de interrupçã o precoce).
• Outros formatos usam um str ou um objeto bytes ou similar somente leitura, como bytes, e fornecem um
ponteiro const char * para seu buffer. Nesse caso, o buffer é “emprestado”: ele é gerenciado pelo ob-
6.6. Análise de argumentos e construção de valores 81
The Python/C API, Release 3.13.7
jeto Python correspondente e compartilha o tempo de vida desse objeto. Você mesmo nã o precisará liberar
nenhuma memó ria.
Para garantir que o buffer subjacente possa ser emprestado com segurança, o campo PyBufferProcs.
bf_releasebuffer do objeto deve ser NULL. Isso nã o permite objetos mutá veis comuns, como bytearray,
mas també m alguns objetos somente leitura, como memoryview ou bytes.
Alé m desse requisito bf_releasebuffer, nã o há nenhuma verificaçã o para saber se o objeto de entrada é
imutá vel (por exemplo, se ele atenderia a uma solicitaçã o de um buffer gravá vel ou se outro thread pode alterar
os dados).
s (str) [const char *]
Converte um objeto Unicode para um ponteiro em C para uma string. Um ponteiro para uma string existente
é armazenado na variá vel do ponteiro do caractere cujo o endereço que você está passando. A string em
C é terminada em NULO. A string no Python nã o deve conter pontos de có digo nulo embutidos; se isso
acontecer, uma exceçã o ValueError é levantada. Objetos Unicode sã o convertidos para strings em C usando
a codificaçã o 'utf-8'. Se essa conversã o falhar, uma exceçã o UnicodeError é levantada.
® Nota
Esse formato nã o aceita objetos bytes ou similares. Se você quer aceitar caminhos de sistema de
arquivos e convertê -los para strings de caracteres em C, é preferível que use o formato O& com
PyUnicode_FSConverter() como conversor.
Alterado na versã o 3.5: Anteriormente, a exceçã o TypeError era levantada quando pontos de có digo nulo
embutidos em string Python eram encontrados.
s* (str ou objeto bytes ou similar) [Py_buffer]
Esse formato aceita tanto objetos Unicode quanto objetos bytes ou similares. Preenche uma estrutura
Py_buffer fornecida pelo chamador. Nesse caso, a string em C resultante pode conter bytes NUL embutidos.
Objetos Unicode sã o convertidos para strings em C usando codificaçã o 'utf-8'.
s# (str, objeto bytes ou similar somente leitura) [const char *, Py_ssize_t]
Como s*, exceto que nã o fornece um buffer emprestado. O resultado é armazenado em duas variá veis em C,
a primeira é um ponteiro para uma string em C, a segunda é o tamanho. A string pode conter bytes nulos
embutidos. Objetos Unicode sã o convertidos para strings em C usando codificaçã o 'utf-8'.
z (str ou None) [const char *]
Como s, mas o objeto Python també m pode ser None, nesse caso o ponteiro C é definido como NULL.
z* (str, objeto bytes ou similar ou None) [Py_buffer]
Como s*, mas o objeto Python també m pode ser None, nesse caso o membro buf da estrutura Py_buffer
é definido como NULL.
z# (str, objeto bytes ou similar somente leitura ou None) [const char *, Py_ssize_t]
Como s#, mas o objeto Python també m pode ser None, nesse caso o ponteiro C é definido como NULL.
y (objeto bytes ou similar somente leitura) [const char *]
Este formato converte um objeto bytes ou similar para um ponteiro C para uma string de caracteres emprestada;
nã o aceita objetos Unicode. O buffer de bytes nã o pode conter bytes nulos embutidos; se isso ocorrer uma
exceçã o ValueError será levantada.
Alterado na versã o 3.5: Anteriormente, a exceçã o TypeError era levantada quando pontos de có digo nulo
embutidos em string Python eram encontrados no buffer de bytes.
y* (objeto bytes ou similar) [Py_buffer]
Esta variante em s* nã o aceita objetos unicode, apenas objetos bytes ou similares. Esta é a maneira reco-
mendada para aceitar dados binários.
y# (objeto bytes ou similar somente leitura) [const char *, Py_ssize_t]
Esta variaçã o de s# nã o aceita objetos Unicode, apenas objetos bytes ou similares.
82 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
S (bytes) [PyBytesObject *]
Exige que o objeto Python seja um objeto bytes, sem tentar nenhuma conversã o. Levanta TypeError se o
objeto nã o for um objeto byte. A variá vel C pode ser declarada como PyObject*.
Y (bytearray) [PyByteArrayObject *]
Exige que o objeto Python seja um objeto bytearray, sem aceitar qualquer conversã o. Levanta TypeError
se o objeto nã o é um objeto bytearray. A variá vel C apenas pode ser declarada como PyObject*.
U (str) [PyObject *]
Exige que o objeto python seja um objeto Unicode, sem tentar alguma conversã o. Levanta TypeError se o
objeto nã o for um objeto Unicode. A variá vel C deve ser declarada como PyObject*.
w* (objeto bytes ou similar de leitura e escrita) [Py_buffer]
Este formato aceita qualquer objeto que implemente a interface do buffer de leitura e escrita. Ele preenche uma
estrutura Py_buffer fornecida pelo chamador. O buffer pode conter bytes nulos incorporados. O chamador
deve chamar PyBuffer_Release() quando isso for feito com o buffer.
es (str) [const char *encoding, char **buffer]
Esta variante em s é utilizada para codificaçã o do Unicode em um buffer de caracteres. Ele só funciona para
dados codificados sem NUL bytes incorporados.
Este formato exige dois argumentos. O primeiro é usado apenas como entrada e deve ser a const char*
que aponta para o nome de uma codificaçã o como uma string terminada em NUL ou NULL, nesse caso a
codificaçã o 'utf-8' é usada. Uma exceçã o é levantada se a codificaçã o nomeada nã o for conhecida pelo
Python. O segundo argumento deve ser um char**; o valor do ponteiro a que ele faz referê ncia será definido
como um buffer com o conteú do do texto do argumento. O texto será codificado na codificaçã o especificada
pelo primeiro argumento.
PyArg_ParseTuple() alocará um buffer do tamanho necessá rio, copiará os dados codificados nesse buffer
e ajustará *buffer para referenciar o armazenamento recé m-alocado. O chamador é responsá vel por chamar
PyMem_Free() para liberar o buffer alocado apó s o uso.
et (str, bytes ou bytearray) [const char *encoding, char **buffer]
O mesmo que es, exceto que os objetos strings de bytes sã o passados sem os recodificar. Em vez disso, a
implementaçã o presume que o objeto string de bytes usa a codificaçã o passada como parâ metro.
es# (str) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
Essa variante em s# é usada para codificar Unicode em um buffer de caracteres. Diferente do formato es,
essa variante permite a entrada de dados que contê m caracteres NUL.
Exige trê s argumentos. O primeiro é usado apenas como entrada e deve ser a const char* que aponta
para o nome de uma codificaçã o como uma string terminada em NUL ou NULL, nesse caso a codificaçã o
'utf-8' é usada. Uma exceçã o será gerada se a codificaçã o nomeada nã o for conhecida pelo Python. O
segundo argumento deve ser um char**; o valor do ponteiro a que ele faz referê ncia será definido como
um buffer com o conteú do do texto do argumento. O texto será codificado na codificaçã o especificada pelo
primeiro argumento. O terceiro argumento deve ser um ponteiro para um nú mero inteiro; o nú mero inteiro
referenciado será definido como o nú mero de bytes no buffer de saída.
Há dois modos de operaçã o:
Se *buffer apontar um ponteiro NULL, a funçã o irá alocar um buffer do tamanho necessá rio, copiar os dados
codificados para dentro desse buffer e configurar *buffer para referenciar o novo armazenamento alocado. O
chamador é responsá vel por chamar PyMem_Free() para liberar o buffer alocado apó s o uso.
Se *buffer apontar para um ponteiro que nã o seja NULL (um buffer já alocado), PyArg_ParseTuple() irá
usar essa localizaçã o como buffer e interpretar o valor inicial de *buffer_length como sendo o tamanho do
buffer. Depois ela vai copiar os dados codificados para dentro do buffer e terminá -lo com NUL. Se o buffer
nã o for suficientemente grande, um ValueError será definido.
Em ambos os casos, o *buffer_length é definido como o comprimento dos dados codificados sem o byte NUL
à direita.
et# (str, bytes ou bytearray) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
O mesmo que es#, exceto que os objetos strings de bytes sã o passados sem que sejam recodificados. Em vez
disso, a implementaçã o presume que o objeto string de bytes usa a codificaçã o passada como parâ metro.
6.6. Análise de argumentos e construção de valores 83
The Python/C API, Release 3.13.7
Alterado na versã o 3.12: u, u#, Z e Z# foram removidos porque usavam uma representaçã o herdada de
Py_UNICODE*.
Números
Esses formatos permitem representar nú meros Python ou caracteres ú nicos como nú meros C. Formatos que exigem
int, float ou complex també m podem usar os mé todos especiais correspondentes __index__(), __float__()
ou __complex__() para converter o objeto Python para o tipo necessá rio.
Para formatos inteiros com sinal, OverflowError é levantada se o valor estiver fora do intervalo para o tipo C.
Para formatos inteiros nã o assinados, nenhuma verificaçã o de intervalo é feita — os bits mais significativos sã o
silenciosamente truncados quando o campo de recebimento é muito pequeno para receber o valor.
b (int) [unsigned char]
Converte um inteiro Python nã o negativo em um inteiro pequeno sem sinal (unsigned tiny integer), armazenado
em um unsigned char do C.
B (int) [unsigned char]
Converte um inteiro Python para um inteiro pequeno (tiny integer) sem verificaçã o de estouro, armazenado
em um unsigned char do C.
h (int) [short int]
Converte um inteiro Python para um short int do C.
H (int) [unsigned short int]
Converte um inteiro Python para um unsigned short int do C, sem verificaçã o de estouro.
i (int) [int]
Converte um inteiro Python para um int simples do C.
I (int) [unsigned int]
Converte um inteiro Python para um unsigned int do C, sem verificaçã o de estouro.
l (int) [long int]
Converte um inteiro Python para um long int do C.
k (int) [unsigned long]
Converte um inteiro Python para um unsigned long do C sem verificaçã o de estouro.
L (int) [longo longo]
Converte um inteiro Python para um long long do C.
K (int) [unsigned long long]
Converte um inteiro Python para um unsigned long long do C sem verificaçã o de estouro.
n (int) [Py_ssize_t]
Converte um inteiro Python para um Py_ssize_t do C.
c (bytes ou bytearray de comprimento 1) [char]
Converte um byte Python, representado com um objeto byte ou bytearray de comprimento 1, para um
char do C.
Alterado na versã o 3.3: Permite objetos bytearray.
C (str de comprimento 1) [int]
Converte um caractere Python, representado como uma str objeto de comprimento 1, para um int do C
f` (float) [float]
Converte um nú mero de ponto flutuante Python para um float do C.
d (float) [double]
Converte um nú mero de ponto flutuante Python para um double do C.
D (complex) [Py_complex]
Converte um nú mero complexo Python para uma estrutura C Py_complex
84 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
Outros objetos
O (objeto) [PyObject*]
Armazena um objeto Python (sem qualquer conversã o) em um ponteiro de objeto C. O programa C entã o
recebe o objeto real que foi passado. Uma nova referência forte ao objeto nã o é criado (isto é sua contagem de
referê ncias nã o é aumentada). O ponteiro armazenado nã o é NULL.
O! (objeto) [typeobject, PyObject *]
Armazena um objeto Python em um ponteiro de objeto C. Isso é similar a O, mas usa dois argumentos C: o pri-
meiro é o endereço de um objeto do tipo Python, o segundo é um endereço da variá vel C (de tipo PyObject*)
no qual o ponteiro do objeto está armazenado. Se o objeto Python nã o tiver o tipo necessá rio, TypeError é
levantada.
O& (objeto) [converter, address]
Converte um objeto Python em uma variá vel C atravé s de uma funçã o converter. Isso leva dois argumentos:
o primeiro é a funçã o, o segundo é o endereço da variá vel C (de tipo arbitrá rio), convertendo para void*. A
funçã o converter por sua vez, é chamada da seguinte maneira:
status = converter(object, address);
onde object é o objeto Python a ser convertido e address é o argumento void* que foi passado para a funçã o
PyArg_Parse*. O status retornado deve ser 1 para uma conversã o bem-sucedida e 0 se a conversã o falhar.
Quando a conversã o falha, a funçã o converter deve levantar uma exceçã o e deixar o conteú do de address
inalterado. Se o converter retornar Py_CLEANUP_SUPPORTED, ele poderá ser chamado uma segunda vez se
a aná lise do argumento eventualmente falhar, dando ao conversor a chance de liberar qualquer memó ria que
já havia alocado. Nesta segunda chamada, o parâ metro object será NULL; address terá o mesmo valor que na
chamada original.
Exemplos de conversores: PyUnicode_FSConverter() e PyUnicode_FSDecoder().
Alterado na versã o 3.1: Py_CLEANUP_SUPPORTED foi adicionado.
p (bool) [int]
Testa o valor transmitido para a verdade (um booleano predicado) e converte o resultado em seu valor inteiro
C verdadeiro/falso equivalente. Define o int como 1 se a expressã o for verdadeira e 0 se for falsa. Isso aceita
qualquer valor vá lido do Python. Veja truth para obter mais informaçõ es sobre como o Python testa valores
para a verdade.
Adicionado na versã o 3.3.
(items) (tuple) [matching-items]
O objeto deve ser uma sequê ncia Python cujo comprimento seja o nú mero de unidades de formato em items.
Os argumentos C devem corresponder à s unidades de formato individuais em items. As unidades de formato
para sequê ncias podem ser aninhadas.
Alguns outros caracteres possuem significados na string de formataçã o. Isso pode nã o ocorrer dentro de parê nteses
aninhados. Eles sã o:
|
Indica que os argumentos restantes na lista de argumentos do Python sã o opcionais. As variá veis C corres-
pondentes a argumentos opcionais devem ser inicializadas para seus valores padrã o — quando um argumento
opcional nã o é especificado, PyArg_ParseTuple() nã o toca no conteú do da(s) variá vel(eis) C correspon-
dente(s).
$
PyArg_ParseTupleAndKeywords() apenas: Indica que os argumentos restantes na lista de argumentos
do Python sã o somente-nomeados. Atualmente, todos os argumentos somente-nomeados devem ser també m
argumentos opcionais, entã o | deve sempre ser especificado antes de $ na string de formataçã o.
Adicionado na versã o 3.3.
:
A lista de unidades de formataçã o acaba aqui; a string apó s os dois pontos é usada como o nome da funçã o nas
mensagens de erro (o “valor associado” da exceçã o que PyArg_ParseTuple() levanta).
6.6. Análise de argumentos e construção de valores 85
The Python/C API, Release 3.13.7
;
A lista de unidades de formataçã o acaba aqui; a string apó s o ponto e vírgula é usada como a mensagem de
erro ao invés da mensagem de erro padrã o. : e ; se excluem mutuamente.
Note que quaisquer referê ncias a objeto Python que sã o fornecidas ao chamador sã o referê ncias emprestadas; nã o
libera-as (isto é , nã o decremente a contagem de referê ncias delas)!
Argumentos adicionais passados para essas funçõ es devem ser endereços de variá veis cujo tipo é determinado pela
string de formataçã o; estes sã o usados para armazenar valores vindos da tupla de entrada. Existem alguns casos,
como descrito na lista de unidades de formataçã o acima, onde esses parâ metros sã o usados como valores de entrada;
eles devem concordar com o que é especificado para a unidade de formataçã o correspondente nesse caso.
Para a conversã o funcionar, o objeto arg deve corresponder ao formato e o formato deve estar completo. Em caso
de sucesso, as funçõ es PyArg_Parse* retornam verdadeiro, caso contrá rio retornam falso e levantam uma exceçã o
apropriada. Quando as funçõ es PyArg_Parse* falham devido a uma falha de conversã o em uma das unidades de
formataçã o, as variá veis nos endereços correspondentes à quela unidade e à s unidades de formataçã o seguintes sã o
deixadas intocadas.
Funções da API
int PyArg_ParseTuple(PyObject *args, const char *format, ...)
Parte da ABI Está vel. Analisa os parâ metros de uma funçã o que recebe apenas parâ metros posicionais em
variá veis locais. Retorna verdadeiro em caso de sucesso; em caso de falha, retorna falso e levanta a exceçã o
apropriada.
int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
Parte da ABI Está vel. Idê ntico a PyArg_ParseTuple(), exceto que aceita uma va_list ao invé s de um
nú mero variá vel de argumentos.
int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *const
*keywords, ...)
Parte da ABI Está vel. Analisa os parâ metros de uma funçã o que aceita tanto parâ metros posicionais quando
parâ metros nomeados e os converte em variá veis locais. O argumento keywords é um array terminado em
NULL de nomes de parâ metros nomeados especificados como strings C codificadas em ASCII ou UTF-8 e
terminadas com nulo. Nomes vazios representam parâmetros somente-posicional. Retorna verdadeiro em caso
de sucesso; em caso de falha, retorna falso e levanta a exceçã o apropriada.
® Nota
A declaraçã o do parâ metro keywords é char *const* em C e const char *const* em C++. Isso
pode ser substituído com a macro PY_CXX_CONST .
Alterado na versã o 3.6: Adicionado suporte para positional-only parameters.
Alterado na versã o 3.13: O parâ metro keywords é agora do tipo char *const* em C e const char
*const* em C++, no lugar de char**. Adicionado suporte para nomes de parâ metros nomeados nã o-ASCII.
int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *const
*keywords, va_list vargs)
Parte da ABI Está vel. Idê ntico a PyArg_ParseTupleAndKeywords(), exceto que aceita uma va_list ao
invé s de um nú mero variá vel de argumentos.
int PyArg_ValidateKeywordArguments(PyObject*)
Parte da ABI Está vel. Garante que as chaves no dicioná rio de argumento de palavras reservadas sã o strings.
Isso só é necessá rio se PyArg_ParseTupleAndKeywords() nã o é usado, já que o ú ltimo já faz essa checa-
gem.
Adicionado na versã o 3.2.
86 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
int PyArg_Parse(PyObject *args, const char *format, ...)
Parte da ABI Está vel. Analisa o parâ metro de uma funçã o que recebe um ú nico parâ metro posicional e o
converte em uma variá vel local. Retorna verdadeiro em caso de sucesso; em caso de falha, retorna falso e
levanta a exceçã o apropriada.
Exemplo:
// Função usando a convenção de chamada ao método METH_O
static PyObject*
my_function(PyObject *module, PyObject *arg)
{
int value;
if (!PyArg_Parse(arg, "i:my_function", &value)) {
return NULL;
}
// ... usar valor ...
}
int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
Parte da ABI Está vel. Uma forma mais simples de recuperaçã o de parâ metro que nã o usa uma string de formato
para especificar os tipos de argumentos. Funçõ es que usam este mé todo para recuperar seus parâ metros devem
ser declaradas como METH_VARARGS em tabelas de funçã o ou mé todo. A tupla contendo os parâ metros reais
deve ser passada como args; deve realmente ser uma tupla. O comprimento da tupla deve ser de pelo menos
min e nã o mais do que max; min e max podem ser iguais. Argumentos adicionais devem ser passados para
a funçã o, cada um dos quais deve ser um ponteiro para uma variá vel PyObject*; eles serã o preenchidos
com os valores de args; eles conterã o referências emprestadas. As variá veis que correspondem a parâ metros
opcionais nã o fornecidos por args nã o serã o preenchidas; estes devem ser inicializados pelo chamador. Esta
funçã o retorna verdadeiro em caso de sucesso e falso se args nã o for uma tupla ou contiver o nú mero incorreto
de elementos; uma exceçã o será definida se houver uma falha.
Este é um exemplo do uso dessa funçã o, tirado das fontes do mó dulo auxiliar para referê ncias fracas _weakref:
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
PyObject *result = NULL;
if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
result = PyWeakref_NewRef(object, callback);
}
return result;
}
A chamada à PyArg_UnpackTuple() neste exemplo é inteiramente equivalente à chamada para
PyArg_ParseTuple():
PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
PY_CXX_CONST
O valor para ser inserido, se houver, antes de char *const* na declaraçã o do parâ metro keywords das
funçõ es PyArg_ParseTupleAndKeywords() e PyArg_VaParseTupleAndKeywords(). Por padrã o, é
vazio para C e const for C++ (const char *const*). Para substituir, defina o valor desejado antes de
incluir Python.h.
Adicionado na versã o 3.13.
6.6. Análise de argumentos e construção de valores 87
The Python/C API, Release 3.13.7
6.6.2 Construindo valores
PyObject *Py_BuildValue(const char *format, ...)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um novo valor baseado em uma string de forma-
taçã o similar à quelas aceitas pela família de funçõ es PyArg_Parse* e uma sequê ncia de valores. Retorna o
valor ou NULL em caso de erro; uma exceçã o será levantada se NULL for retornado.
Py_BuildValue() nã o constró i sempre uma tupla. Ela constró i uma tupla apenas se a sua string de forma-
taçã o conté m duas ou mais unidades de formataçã o. Se a string de formataçã o estiver vazia, ela retorna None;
se ela conté m exatamente uma unidade de formataçã o, ela retorna qualquer que seja o objeto que for descrito
pela unidade de formataçã o. Para forçar ela a retornar uma tupla de tamanho 0 ou um, use parê nteses na string
de formataçã o.
Quando buffers de memó ria sã o passados como parâ metros para fornecer dados para construir objetos, como
nos formatos s e s#, os dados necessá rios sã o copiados. Buffers fornecidos pelo chamador nunca sã o referen-
ciados pelos objetos criados por Py_BuildValue(). Em outras palavras, se o seu có digo invoca malloc() e
passa a memó ria alocada para Py_BuildValue(), seu có digo é responsá vel por chamar free() para aquela
memó ria uma vez que Py_BuildValue() tiver retornado.
Na descriçã o a seguir, a forma entre aspas é a unidade de formataçã o; a entrada em parê nteses (arredondado)
é o tipo do objeto Python que a unidade de formataçã o irá retornar; e a entrada em colchetes [quadrado] é o
tipo do(s) valor(es) C a ser(em) passado(s).
Os caracteres de espaço, tab, dois pontos e vírgula sã o ignorados em strings de formataçã o (mas nã o dentro
de unidades de formataçã o como s#). Isso pode ser usado para tornar strings de formataçã o longas um pouco
mais legíveis.
s (str ou None) [const char *]
Converte uma string C terminada em NULL em um objeto Python str usando codificaçã o 'utf-8'.
Se o ponteiro da string C é NULL, None é usado.
s# (str ou None) [const char *, Py_ssize_t]
Converte uma string C e seu comprimento em um objeto Python str usando a codificaçã o 'utf-8'.
Se o ponteiro da string C é NULL, o comprimento é ignorado e None é retornado.
y (bytes) [const char *]
Isso converte uma string C para um objeto Python bytes. Se o ponteiro da string C é NULL, None é
retornado.
y# (bytes) [const char *, Py_ssize_t]
Isso converte uma string C e seu comprimento para um objeto Python. Se o ponteiro da string C é NULL,
None é retornado.
z (str ou None) [const char *]
O mesmo de s.
z# (str ou None) [const char *, Py_ssize_t]
O mesmo de s#.
u (str) [const wchar_t *]
Converte um buffer terminado por null wchar_t de dados Unicode (UTF-16 ou UCS-4) para um objeto
Python Unicode. Se o ponteiro do buffer Unicode é NULL, None é retornado.
u# (str) [const wchar_t *, Py_ssize_t]
Converte um buffer de dados Unicode (UTF-17 ou UCS-4) e seu comprimento em um objeto Python
Unicode. Se o ponteiro do buffer Unicode é NULL, o comprimento é ignorado e None é retornado.
U (str ou None) [const char *]
O mesmo de s.
U# (str ou None) [const char *, Py_ssize_t]
O mesmo de s#.
i (int) [int]
Converte um simples int do C em um objeto inteiro do Python.
88 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
b (int) [char]
Converte um simples char do C em um objeto inteiro do Python.
h (int) [short int]
Converte um simples short int do C em um objeto inteiro do Python.
l (int) [long int]
Converte um long int do C em um objeto inteiro do Python.
B (int) [unsigned char]
Converte um unsigned char do C em um objeto inteiro do Python.
H (int) [unsigned short int]
Converte um unsigned short int do C em um objeto inteiro do Python.
I (int) [unsigned int]
Converte um unsigned int do C em um objeto inteiro do Python.
k (int) [unsigned long]
Converte um unsigned long do C em um objeto inteiro do Python.
L (int) [longo longo]
Converte um long long do C em um objeto inteiro do Python.
K (int) [unsigned long long]
Converte um unsigned long long do C em um objeto inteiro do Python.
n (int) [Py_ssize_t]
Converte um Py_ssize_t do C em um objeto inteiro do Python.
c (bytes de comprimento 1) [char]
Converte um int representando um byte do C em um objeto bytes de comprimento 1 do Python.
C (str de comprimento 1) [int]
Converte um int representando um caractere do C em um objeto str de comprimento 1 do Python.
d (float) [double]
Converte um double do C em um nú mero ponto flutuante do Python.
f` (float) [float]
Converte um float do C em um nú mero ponto flutuante do Python.
D (complex) [Py_complex *]
Converte uma estrutura Py_complex do C em um nú mero complexo do Python.
O (objeto) [PyObject*]
Passa um objeto Python intocado, mas cria uma nova referência forte a ele (isto é , sua contagem de
referê ncias é incrementada por um). Se o objeto passado é um ponteiro NULL, presume-se que isso
foi causado porque a chamada que produziu o argumento encontrou um erro e definiu uma exceçã o.
Portanto, Py_BuildValue() irá retornar NULL mas nã o irá levantar uma exceçã o. Se nenhuma exceçã o
foi levantada ainda, SystemError é definida.
S (objeto) [PyObject *]
O mesmo que O.
N (objeto) [PyObject *]
O mesmo que O, exceto que nã o cria uma nova referência forte. Útil quando o objeto é criado por uma
chamada a um construtor de objeto na lista de argumento.
O& (objeto) [converter, anything]
Converte anything para um objeto Python atravé s de uma funçã o converter. A funçã o é chamada com
anything (que deve ser compatível com o void*) como argumento e deve retornar um “novo” objeto
Python, ou NULL se um erro ocorreu.
(items) (tuple) [matching-items]
Converte uma sequê ncia de valores C para uma tupla Python com o mesmo nú mero de itens.
6.6. Análise de argumentos e construção de valores 89
The Python/C API, Release 3.13.7
[items] (list) [matching-items]
Converte uma sequê ncia de valores C para uma lista Python com o mesmo nú mero de itens.
{items} (dict) [matching-items]
Converte uma sequê ncia de valores C para um dicioná rio Python. Cada par de valores consecutivos do
C adiciona um item ao dicioná rio, servindo como chave e valor, respectivamente.
Se existir um erro na string de formataçã o, a exceçã o SystemError é definida e NULL é retornado.
PyObject *Py_VaBuildValue(const char *format, va_list vargs)
Retorna valor: Nova referência. Parte da ABI Está vel. Idê ntico a Py_BuildValue(), exceto que aceita uma
va_list ao invé s de um nú mero variá vel de argumentos.
6.7 Conversão e formação de strings
Funçõ es para conversã o de nú meros e saída formatada de strings.
int PyOS_snprintf(char *str, size_t size, const char *format, ...)
Parte da ABI Está vel. Saída nã o superior a size bytes para str de acordo com a string de formato format e os
argumentos extras. Veja a pá gina man do Unix snprintf(3).
int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
Parte da ABI Está vel. Saída nã o superior a size bytes para str de acordo com o string de formato format e a
variá vel argumento de lista va. Pá gina man do Unix vsnprintf(3).
PyOS_snprintf() e PyOS_vsnprintf() envolvem as funçõ es snprintf() e vsnprintf() da biblioteca Stan-
dard C. Seu objetivo é garantir um comportamento consistente em casos extremos, o que as funçõ es do Standard C
nã o garantem.
Os invó lucros garantem que str[size-1] seja sempre '\0' no retorno. Eles nunca escrevem mais do que size
bytes (incluindo o '\0' ao final) em str. Ambas as funçõ es exigem que str != NULL, size > 0, format !=
NULL e size < INT_MAX. Note que isso significa que nã o há equivalente ao n = snprintf(NULL, 0, ...)
do C99 que determinaria o tamanho de buffer necessá rio.
O valor de retorno (rv) para essas funçõ es deve ser interpretado da seguinte forma:
• Quando 0 <= rv < size, a conversã o de saída foi bem-sucedida e os caracteres de rv foram escritos em str
(excluindo o '\0' byte em str[rv]).
• Quando rv >= size, a conversã o de saída foi truncada e um buffer com rv + 1 bytes teria sido necessá rio
para ter sucesso. str[size-1] é '\0' neste caso.
• Quando rv < 0, “aconteceu algo de errado.” str[size-1] é '\0' neste caso també m, mas o resto de str é
indefinido. A causa exata do erro depende da plataforma subjacente.
As funçõ es a seguir fornecem strings independentes de localidade para conversõ es de nú meros.
unsigned long PyOS_strtoul(const char *str, char **ptr, int base)
Parte da ABI Está vel. Converte a parte inicial da string em str para um valor unsigned long de acordo
com a base fornecida, que deve estar entre 2 e 36 inclusive, ou ser o valor especial 0.
Espaços em branco iniciais e diferenciaçã o entre caracteres maiú sculos e minú sculos sã o ignorados. Se base
for zero, procura um 0b, 0o ou 0x inicial para informar qual base. Se estes estiverem ausentes, o padrã o é 10.
Base deve ser 0 ou entre 2 e 36 (inclusive). Se ptr nã o for NULL, conterá um ponteiro para o fim da varredura.
Se o valor convertido ficar fora do intervalo do tipo de retorno correspondente, ocorrerá um erro de intervalo
(errno é definido como ERANGE) e ULONG_MAX será retornado. Se nenhuma conversã o puder ser realizada,
0 será retornado.
Veja també m a pá gina man do Unix strtoul(3).
Adicionado na versã o 3.2.
90 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
long PyOS_strtol(const char *str, char **ptr, int base)
Parte da ABI Está vel. Converte a parte inicial da string em str para um valor long de acordo com a base
fornecida, que deve estar entre 2 e 36 inclusive, ou ser o valor especial 0.
O mesmo que PyOS_strtoul(), mas retorna um valor long e LONG_MAX em caso de estouro.
Veja també m a pá gina man do Unix strtol(3).
Adicionado na versã o 3.2.
double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)
Parte da ABI Está vel. Converte uma string s em double, levantando uma exceçã o Python em caso de falha.
O conjunto de strings aceitas corresponde ao conjunto de strings aceito pelo construtor float() do Python,
exceto que s nã o deve ter espaços em branco à esquerda ou à direita. A conversã o é independente da localidade
atual.
Se endptr for NULL, converte a string inteira. Levanta ValueError e retorna -1.0 se a string nã o for uma
representaçã o vá lida de um nú mero de ponto flutuante.
Se endptr nã o for NULL, converte o má ximo possível da string e define *endptr para apontar para o primeiro
caractere nã o convertido. Se nenhum segmento inicial da string for a representaçã o vá lida de um nú mero de
ponto flutuante, define *endptr para apontar para o início da string, levanta ValueError e retorna -1.0.
Se s representa um valor que é muito grande para armazenar em um ponto flutuante (por exemplo, "1e500" é
uma string assim em muitas plataformas), entã o se overflow_exception for NULL retorna Py_HUGE_VAL
(com um sinal apropriado) e nã o define nenhuma exceçã o. Caso contrá rio, overflow_exception deve
apontar para um objeto de exceçã o Python; levanta essa exceçã o e retorna -1.0. Em ambos os casos, define
*endptr para apontar para o primeiro caractere apó s o valor convertido.
Se qualquer outro erro ocorrer durante a conversã o (por exemplo, um erro de falta de memó ria), define a
exceçã o Python apropriada e retorna -1.0.
Adicionado na versã o 3.1.
char *PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)
Parte da ABI Está vel. Converte um val double para uma string usando format_code, precision e flags forne-
cidos.
format_code deve ser um entre 'e', 'E', 'f', 'F', 'g', 'G' ou 'r'. Para 'r', a precisã o precision fornecida
deve ser 0 e é ignorada. O có digo de formato 'r' especifica o formato padrã o de repr().
flags pode ser zero ou mais de valores Py_DTSF_SIGN, Py_DTSF_ADD_DOT_0 ou Py_DTSF_ALT, alternados
por operador ló gico OU:
• Py_DTSF_SIGN significa sempre preceder a string retornada com um caractere de sinal, mesmo se val
nã o for negativo.
• Py_DTSF_ADD_DOT_0 significa garantir que a string retornada nã o se pareça com um inteiro.
• Py_DTSF_ALT significa aplicar regras de formataçã o “alternativas”. Veja a documentaçã o para o espe-
cificador '#' de PyOS_snprintf() para detalhes.
Se type nã o for NULL, entã o o valor para o qual ele aponta será definido como um dos Py_DTST_FINITE,
Py_DTST_INFINITE ou Py_DTST_NAN, significando que val é um nú mero finito, um nú mero infinito ou nã o
um nú mero, respectivamente.
O valor de retorno é um ponteiro para buffer com a string convertida ou NULL se a conversã o falhou. O
chamador é responsá vel por liberar a string retornada chamando PyMem_Free().
Adicionado na versã o 3.1.
int PyOS_stricmp(const char *s1, const char *s2)
Comparaçã o de strings sem diferença entre maiú sculas e minú sculas. A funçã o funciona quase de forma
idê ntica a strcmp() exceto que ignora a diferença entre maiú sculas e minú sculas.
6.7. Conversão e formação de strings 91
The Python/C API, Release 3.13.7
int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size)
Comparaçã o de strings sem diferença entre maiú sculas e minú sculas. A funçã o funciona quase de forma
idê ntica a strncmp() exceto que ignora a diferença entre maiú sculas e minú sculas.
6.8 API do PyHash
Veja també m o membro PyTypeObject.tp_hash e numeric-hash.
type Py_hash_t
Tipo de valor do hash: inteiro com sinal.
Adicionado na versã o 3.2.
type Py_uhash_t
Tipo de valor do hash: inteiro sem sinal.
Adicionado na versã o 3.2.
PyHASH_MODULUS
O primo de Mersenne P = 2**n -1, usado para esquema de hash numé rico.
Adicionado na versã o 3.13.
PyHASH_BITS
O expoente n de P em PyHASH_MODULUS.
Adicionado na versã o 3.13.
PyHASH_MULTIPLIER
Multiplicador de primo usado em strings e vá rios outros hashes.
Adicionado na versã o 3.13.
PyHASH_INF
O valor de hash retornado para um infinito positivo.
Adicionado na versã o 3.13.
PyHASH_IMAG
O multiplicador usado para a parte imaginá ria de um nú mero complexo.
Adicionado na versã o 3.13.
type PyHash_FuncDef
Definiçã o de funçã o de hash usada por PyHash_GetFuncDef().
Py_hash_t (*const hash)(const void*, Py_ssize_t)
Hash function.
const char *name
Nome de funçã o hash (string codificada em UTF-8).
const int hash_bits
Tamanho interno do valor do hash em bits.
const int seed_bits
Tamanho da entrada de seed em bits.
Adicionado na versã o 3.4.
PyHash_FuncDef *PyHash_GetFuncDef(void)
Obté m a definiçã o de funçã o de hash.
92 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
µ Ver também
PEP 456 “Algoritmo de hash seguro e intercambiá vel”.
Adicionado na versã o 3.4.
Py_hash_t Py_HashPointer(const void *ptr)
Hash de um valor de ponteiro: processa o valor do ponteiro como um inteiro (converte-o para uintptr_t
internamente). O ponteiro nã o é desreferenciado.
A funçã o nã o pode falhar: ela nã o pode retornar -1.
Adicionado na versã o 3.13.
Py_hash_t PyObject_GenericHash(PyObject *obj)
Funçã o de hash gené rica que deve ser colocada no slot tp_hash de um objeto de tipo. Seu resultado depende
apenas da identidade do objeto.
No CPython, é equivalente a Py_HashPointer().
Adicionado na versã o 3.13.
6.9 Reflexão
PyObject *PyEval_GetBuiltins(void)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Descontinuado desde a versã o 3.13: Use
PyEval_GetFrameBuiltins().
Retorna um dicioná rio dos componentes embutidos no quadro de execuçã o atual ou o interpretador do estado
da thread, se nenhum quadro estiver em execuçã o no momento.
PyObject *PyEval_GetLocals(void)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Descontinuado desde a versã o 3.13: Use
PyEval_GetFrameLocals() para obter o mesmo comportamento que chamar locals() no có digo
Python, ou entã o chame PyFrame_GetLocals() no resultado de PyEval_GetFrame() para acessar o
atributo f_locals do quadro atualmente em execuçã o.
Retorna um mapeamento fornecendo acesso à s variá veis locais no quadro de execuçã o atual ou NULL se nenhum
quadro estiver sendo executado no momento.
Consulte locals() para detalhes do mapeamento retornado em diferentes escopos.
Como esta funçã o retorna uma referência emprestada, o dicioná rio retornado para escopos otimizados é ar-
mazenado em cache no objeto frame e permanecerá ativo enquanto o objeto frame o fizer. Ao contrá rio de
PyEval_GetFrameLocals() e locals(), chamadas subsequentes para esta funçã o no mesmo quadro atu-
alizarã o o conteú do do dicioná rio em cache para refletir as mudanças no estado das variá veis locais em vez de
retornar um novo snapshot.
Alterado na versã o 3.13: Como parte da PEP 667, PyFrame_GetLocals(), locals() e FrameType.
f_locals nã o fazem mais uso do dicioná rio de cache compartilhado. Consulte a entrada de O Que Há de
Novo para detalhes adicionais.
PyObject *PyEval_GetGlobals(void)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Descontinuado desde a versã o 3.13: Use
PyEval_GetFrameGlobals().
Retorna um dicioná rio das variá veis globais no quadro de execuçã o atual ou NULL se nenhum quadro estiver
sendo executado no momento.
PyFrameObject *PyEval_GetFrame(void)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Retorna o quadro do estado atual da thread, que
é NULL se nenhum quadro estiver em execuçã o no momento.
6.9. Reflexão 93
The Python/C API, Release 3.13.7
Veja també m PyThreadState_GetFrame().
PyObject *PyEval_GetFrameBuiltins(void)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.13. Retorna um dicioná rio dos com-
ponentes embutidos no quadro de execuçã o atual ou o interpretador do estado da thread, se nenhum quadro
estiver em execuçã o no momento.
Adicionado na versã o 3.13.
PyObject *PyEval_GetFrameLocals(void)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.13. Retorna um dicioná rio das va-
riá veis locais no quadro de execuçã o atual ou NULL se nenhum quadro estiver sendo executado no momento.
Equivalente a chamar locals() em có digo Python.
Para acessar f_locals no quadro atual sem fazer um snapshot independente em escopos otimizados, chame
PyFrame_GetLocals() no resultado de PyEval_GetFrame().
Adicionado na versã o 3.13.
PyObject *PyEval_GetFrameGlobals(void)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.13. Retorna um dicioná rio das variá -
veis globais no quadro de execuçã o atual ou NULL se nenhum quadro estiver sendo executado no momento.
Equivalente a chamar globals() em có digo Python.
Adicionado na versã o 3.13.
const char *PyEval_GetFuncName(PyObject *func)
Parte da ABI Está vel. Retorna o nome de func se for uma funçã o, classe ou objeto de instâ ncia, senã o o nome
do tipo da func.
const char *PyEval_GetFuncDesc(PyObject *func)
Parte da ABI Está vel. Retorna uma sequê ncia de caracteres de descriçã o, dependendo do tipo de func. Os
valores de retorno incluem “()” para funçõ es e mé todos, “ constructor”, “ instance” e “ object”.. Concatenado
com o resultado de PyEval_GetFuncName(), o resultado será uma descriçã o de func.
6.10 Registro de codec e funções de suporte
int PyCodec_Register(PyObject *search_function)
Parte da ABI Está vel. Registra uma nova funçã o de busca de codec.
Como efeito colateral, tenta carregar o pacote encodings, se isso ainda nã o tiver sido feito, com o propó sito
de garantir que ele sempre seja o primeiro na lista de funçõ es de busca.
int PyCodec_Unregister(PyObject *search_function)
Parte da ABI Está vel desde a versão 3.10. Cancela o registro de uma funçã o de busca de codec e limpa o
cache de registro. Se a funçã o de busca nã o está registrada, nã o faz nada. Retorna 0 no sucesso. Levanta uma
exceçã o e retorna -1 em caso de erro.
Adicionado na versã o 3.10.
int PyCodec_KnownEncoding(const char *encoding)
Parte da ABI Está vel. Retorna 1 ou 0 dependendo se há um codec registrado para a dada codificaçã o encoding.
Essa funçã o sempre é bem-sucedida.
PyObject *PyCodec_Encode(PyObject *object, const char *encoding, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. API de codificaçã o baseada em codec gené rico.
object é passado atravé s da funçã o de codificaçã o encontrada para a codificaçã o fornecida por meio de encoding,
usando o mé todo de tratamento de erros definido por errors. errors pode ser NULL para usar o mé todo padrã o
definido para o codec. Levanta um LookupError se nenhum codificador puder ser encontrado.
94 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
PyObject *PyCodec_Decode(PyObject *object, const char *encoding, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. API de decodificaçã o baseada em decodificador gené -
rico.
object é passado atravé s da funçã o de decodificaçã o encontrada para a codificaçã o fornecida por meio de
encoding, usando o mé todo de tratamento de erros definido por errors. errors pode ser NULL para usar o mé todo
padrã o definido para o codec. Levanta um LookupError se nenhum codificador puder ser encontrado.
6.10.1 API de pesquisa de codec
Nas funçõ es a seguir, a string encoding é pesquisada com todos os caracteres sendo convertidos para minú sculo, o
que faz com que as codificaçõ es pesquisadas por esse mecanismo nã o façam distinçã o entre maiú sculas e minú sculas.
Se nenhum codec for encontrado, um KeyError é definido e NULL é retornado.
PyObject *PyCodec_Encoder(const char *encoding)
Retorna valor: Nova referência. Parte da ABI Está vel. Obté m uma funçã o de codificaçã o para o encoding
dado.
PyObject *PyCodec_Decoder(const char *encoding)
Retorna valor: Nova referência. Parte da ABI Está vel. Obté m uma funçã o de decodificaçã o para o encoding
dado.
PyObject *PyCodec_IncrementalEncoder(const char *encoding, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. Obté m um objeto IncrementalEncoder para o
encoding dado.
PyObject *PyCodec_IncrementalDecoder(const char *encoding, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. Obté m um objeto IncrementalDecoder para o
encoding dado.
PyObject *PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. Obté m uma funçã o de fá brica StreamReader para o
encoding dado.
PyObject *PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. Obté m uma funçã o de fá brica StreamWriter para o
encoding dado.
6.10.2 API de registro de tratamentos de erros de decodificação Unicode
int PyCodec_RegisterError(const char *name, PyObject *error)
Parte da ABI Está vel. Registra a funçã o de retorno de chamada de tratamento de erro para o nome fornecido.
Esta chamada de funçã o é invocada por um codificador quando encontra caracteres/bytes indecodificá veis e
nome é especificado como o parâ metro de erro na chamada da funçã o de codificaçã o/decodificaçã o.
O retorno de chamada obté m um ú nico argumento, uma instâ ncia de UnicodeEncodeError,
UnicodeDecodeError ou UnicodeTranslateError que conté m informaçõ es sobre a sequencia proble-
má tica de caracteres ou bytes e seu deslocamento na string original (consulte Objetos de exceção Unicode para
funçõ es que extraem essa informaçã o). A funçã o de retorno de chamada deve levantar a exceçã o dada, ou re-
tornar uma tupla de dois itens contendo a substituiçã o para a sequê ncia problemá tica, e um inteiro fornecendo
o deslocamento na string original na qual a codificaçã o/decodificaçã o deve ser retomada.
Retorna 0 em caso de sucesso, -1 em caso de erro.
PyObject *PyCodec_LookupError(const char *name)
Retorna valor: Nova referência. Parte da ABI Está vel. Pesquisa a funçã o de retorno de chamada de tratamento
de erros registrada em name. Como um caso especial, NULL pode ser passado; nesse caso, o erro no tratamento
de retorno de chamada para “strict” será retornado.
PyObject *PyCodec_StrictErrors(PyObject *exc)
Retorna valor: Sempre NULL. Parte da ABI Está vel. Levanta exc como uma exceçã o.
6.10. Registro de codec e funções de suporte 95
The Python/C API, Release 3.13.7
PyObject *PyCodec_IgnoreErrors(PyObject *exc)
Retorna valor: Nova referência. Parte da ABI Está vel. Ignora o erro de unicode, ignorando a entrada que
causou o erro.
PyObject *PyCodec_ReplaceErrors(PyObject *exc)
Retorna valor: Nova referência. Parte da ABI Está vel. Substitui o erro de unicode por ? ou U+FFFD.
PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
Retorna valor: Nova referência. Parte da ABI Está vel. Substitui o erro de unicode por caracteres da referê ncia
XML.
PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc)
Retorna valor: Nova referência. Parte da ABI Está vel. Substitui o erro de unicode com escapes de barra
invertida (\x, \u e \U).
PyObject *PyCodec_NameReplaceErrors(PyObject *exc)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Substitui os erros de codificaçã o
unicode com escapes \N{...}.
Adicionado na versã o 3.5.
6.11 API C PyTime
Adicionado na versã o 3.13.
A API C de reló gios provê acesso a reló gios do sistema. Ela é similar ao mó dulo Python time.
Para uma API C relacionada ao mó dulo datetime, veja Objetos DateTime.
6.11.1 Tipos
type PyTime_t
Um registro de data e hora ou uma duraçã o em nanossegundos, representados como um inteiro de 64 bits com
sinal.
O ponto de referê ncia para registros de data e hora depende do reló gio usado. Por exemplo, PyTime_Time()
retorna registros relativos à é poca UNIX.
É suportada uma amplitude em torno de [-292.3 anos; +292.3 anos]. Usando o início da é poca UNIX (1º de
Janeiro de 1970) como referê ncia, a gama de datas suportadas é em torno de [1677-09-21; 2262-04-11]. Os
limites exatos sã o expostos como constantes:
PyTime_t PyTime_MIN
Valor mínimo de PyTime_t.
PyTime_t PyTime_MAX
Valor má ximo de PyTime_t.
6.11.2 Funções de relógio
As funçõ es a seguir aceitam um ponteiro para PyTime_t ao qual elas atribuem o valor de um determinado reló gio.
Detalhes de cada reló gio estã o disponíveis nas documentaçõ es das funçõ es Python correspondentes.
As funçõ es retornam 0 em caso de sucesso, ou -1 (com uma exceçã o definida) em caso de falha.
Em caso de estouro de inteiros, elas definem a exceçã o PyExc_OverflowError e definem *result como o valor
limitado ao intervalo [PyTime_MIN; PyTime_MAX]. (Em sistemas atuais, estouros de inteiros sã o provavelmente
causados por uma má configuraçã o do tempo do sistema).
Como qualquer outra API C (se nã o especificado o contrá rio), as funçõ es devem ser chamadas sob posse da GIL.
96 Capítulo 6. Utilitários
The Python/C API, Release 3.13.7
int PyTime_Monotonic(PyTime_t *result)
Lê o reló gio monó tono. Veja time.monotonic() para detalhes importantes sobre este reló gio.
int PyTime_PerfCounter(PyTime_t *result)
Lê o contador de desempenho. Veja time.perf_counter() para detalhes importantes sobre este reló gio.
int PyTime_Time(PyTime_t *result)
Lê o “reló gio de parede”. Veja time.time() para detalhes importantes sobre este reló gio.
6.11.3 Funções de relógio brutas
Similares à s funçõ es de reló gio, mas nã o definem uma exceçã o em condiçõ es de erro, e nã o requerem que o chamador
possua a trava GIL.
Em caso de sucesso, as funçõ es retornam 0.
Em caso de falha, elas definem *result como 0 e retornam -1, sem definir uma exceçã o. Para acessar a causa
do erro, obtenha a GIL e chame a funçã o regular (sem o sufixo Raw). Obserrve que a funçã o regular pode ser
bem-sucedida mesmo apó s a bruta falhar.
int PyTime_MonotonicRaw(PyTime_t *result)
Similar a PyTime_Monotonic(), mas nã o define uma exceçã o em caso de erro, e nã o exige a posse da GIL.
int PyTime_PerfCounterRaw(PyTime_t *result)
Similar a PyTime_PerfCounter(), mas nã o define uma exceçã o em caso de erro e nã o requer a posse da
GIL.
int PyTime_TimeRaw(PyTime_t *result)
Similar a PyTime_Time(), mas nã o define uma exceçã o em caso de erro e nã o requer a posse da GIL.
6.11.4 Funções de conversão
double PyTime_AsSecondsDouble(PyTime_t t)
Converte um registro de data e hora para uma quantidade de segundos como um double C.
Esta funçã o nunca falha, mas note que double tem acurá cia limitada para valores grandes.
6.12 Suporte a Mapas do Perf
Em plataformas suportadas (no momento em que este livro foi escrito, apenas Linux), o tempo de execuçã o pode
tirar vantagem dos arquivos de mapa perf para tornar as funçõ es Python visíveis para uma ferramenta de perfilaçã o
externa (como perf). Um processo em execuçã o pode criar um arquivo no diretó rio /tmp, que conté m entradas
que podem mapear uma seçã o de có digo executá vel para um nome. Esta interface é descrita na documentaçã o da
ferramenta Linux Perf.
Em Python, essas APIs auxiliares podem ser usadas por bibliotecas e recursos que dependem da geraçã o de có digo
de má quina dinamicamente.
Observe que manter a trava global do interpretador (GIL) nã o é necessá rio para essas APIs.
int PyUnstable_PerfMapState_Init(void)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Abre o arquivo /tmp/perf-$pid.map, a menos que já esteja aberto, e cria uma trava para
garantir escritas seguras para thread no arquivo (desde que as escritas sejam feitas atravé s de
PyUnstable_WritePerfMapEntry() ). Normalmente, nã o há necessidade de chamar isso explicitamente;
basta usar PyUnstable_WritePerfMapEntry() e ele inicializará o estado na primeira chamada.
6.12. Suporte a Mapas do Perf 97
The Python/C API, Release 3.13.7
Retorna 0 em caso de sucesso, -1 em caso de falha ao criar/abrir o arquivo de mapa de desempenho ou -2 em
caso de falha na criaçã o de uma trava. Verifique errno para mais informaçõ es sobre a causa de uma falha.
int PyUnstable_WritePerfMapEntry(const void *code_addr, unsigned int code_size, const char
*entry_name)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Escreve uma ú nica entrada no arquivo /tmp/perf-$pid.map. Esta funçã o é segura para thread. Aqui está
a aparê ncia de um exemplo de entrada:
# endereço tamanho nome
7f3529fcf759 b py::bar:/run/t.py
Chamará PyUnstable_PerfMapState_Init() antes de escrever a entrada, se o arquivo de mapa de
desempenho ainda nã o estiver aberto. Retorna 0 em caso de sucesso ou os mesmos có digos de erro que
PyUnstable_PerfMapState_Init() em caso de falha.
void PyUnstable_PerfMapState_Fini(void)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Fecha o arquivo de mapa do perf aberto por PyUnstable_PerfMapState_Init(). Isso é chamado pelo
pró prio tempo de execuçã o durante o desligamento do interpretador. Em geral, nã o deve haver motivo para
chamar isso explicitamente, exceto para lidar com cená rios específicos, como bifurcaçã o.
98 Capítulo 6. Utilitários
CAPÍTULO 7
Camada de Objetos Abstratos
As funçõ es neste capítulo interagem com objetos Python independentemente do seu tipo, ou com classes amplas de
tipos de objetos (por exemplo, todos os tipos numé ricos ou todos os tipos de sequê ncia). Quando usadas em tipos de
objetos para os quais nã o se aplicam, elas irã o levantar uma exceçã o Python.
Nã o é possível usar essas funçõ es em objetos que nã o foram inicializados corretamente, como um objeto de lista
criado por PyList_New(), mas cujos itens ainda nã o foram definidos para algum valor diferente de NULL.
7.1 Protocolo de objeto
PyObject *Py_GetConstant(unsigned int constant_id)
Parte da ABI Está vel desde a versão 3.13. Obté m uma referência forte para uma constante.
Define uma exceçã o e retorna NULL se constant_id for invá lido.
constant_id deve ser um destes identificadores constantes:
99
The Python/C API, Release 3.13.7
Identificador da constante Valor Objeto retornado
0 None
Py_CONSTANT_NONE
1 False
Py_CONSTANT_FALSE
2 True
Py_CONSTANT_TRUE
3 Ellipsis
Py_CONSTANT_ELLIPSIS
4 NotImplemented
Py_CONSTANT_NOT_IMPLEMENTED
5 0
Py_CONSTANT_ZERO
6 1
Py_CONSTANT_ONE
7 ''
Py_CONSTANT_EMPTY_STR
8 b''
Py_CONSTANT_EMPTY_BYTES
9 ()
Py_CONSTANT_EMPTY_TUPLE
Valores numé ricos sã o fornecidos apenas para projetos que nã o podem usar identificadores constantes.
Adicionado na versã o 3.13.
No CPython, todas essas constantes sã o imortais.
PyObject *Py_GetConstantBorrowed(unsigned int constant_id)
Parte da ABI Está vel desde a versão 3.13. Semelhante a Py_GetConstant(), mas retorna uma referência
emprestada.
Esta funçã o destina-se principalmente à compatibilidade com versõ es anteriores: usar Py_GetConstant()
é recomendado para novo có digo.
A referê ncia é emprestada do interpretador e é vá lida até a finalizaçã o do interpretador.
Adicionado na versã o 3.13.
PyObject *Py_NotImplemented
O singleton NotImplemented, usado para sinalizar que uma operaçã o nã o foi implementada para a combi-
naçã o de tipo fornecida.
Py_RETURN_NOTIMPLEMENTED
Manipula adequadamente o retorno de Py_NotImplemented de dentro de uma funçã o C (ou seja, cria uma
nova referência forte para NotImplemented e retorna-a).
Py_PRINT_RAW
Sinaliza a ser usado com mú ltiplas funçõ es que imprimem o objeto (como PyObject_Print() e
PyFile_WriteObject()). Se passada, esta funçã o usaria o str() do objeto em vez do repr().
100 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
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, PyObject *attr_name)
Parte da ABI Está vel desde a versão 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.
Adicionado na versã o 3.13.
int PyObject_HasAttrStringWithError(PyObject *o, const char *attr_name)
Parte da ABI Está vel desde a versão 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*.
Adicionado na versã o 3.13.
int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
Parte da ABI Está vel. 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__() methods aren’t
propagated, but instead given to sys.unraisablehook(). For proper error handling, use
PyObject_HasAttrWithError(), PyObject_GetOptionalAttr() or PyObject_GetAttr()
instead.
int PyObject_HasAttrString(PyObject *o, const char *attr_name)
Parte da ABI Está vel. 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__() methods
or while creating the temporary str object are silently ignored. For proper error han-
dling, use PyObject_HasAttrStringWithError(), PyObject_GetOptionalAttrString() or
PyObject_GetAttrString() instead.
PyObject *PyObject_GetAttr(PyObject *o, PyObject *attr_name)
Retorna valor: Nova referência. Parte da ABI Está vel. Retrieve an attribute named attr_name from object
o. Returns the attribute value on success, or NULL on failure. This is the equivalent of the Python expression
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)
Retorna valor: Nova referência. Parte da ABI Está vel. 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);
Parte da ABI Está vel desde a versão 3.13. Variant of PyObject_GetAttr() which doesn’t raise
AttributeError if the attribute is not found.
7.1. Protocolo de objeto 101
The Python/C API, Release 3.13.7
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.
Adicionado na versã o 3.13.
int PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject **result);
Parte da ABI Está vel desde a versão 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*.
Adicionado na versã o 3.13.
PyObject *PyObject_GenericGetAttr(PyObject *o, PyObject *name)
Retorna valor: Nova referência. Parte da ABI Está vel. Generic attribute getter function that is meant to be
put into a type object’s tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object’s
MRO as well as an attribute in the object’s __dict__ (if present). As outlined in descriptors, data descriptors
take preference over instance attributes, while non-data descriptors don’t. Otherwise, an AttributeError is
raised.
int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)
Parte da ABI Está vel. Set the value of the attribute named attr_name, for object o, to the value v. Raise
an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement
o.attr_name = v.
If v is NULL, the attribute is deleted. This behaviour is deprecated in favour of using PyObject_DelAttr(),
but there are currently no plans to remove it.
int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)
Parte da ABI Está vel. 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*.
If v is NULL, the attribute is deleted, but this feature is deprecated in favour of using
PyObject_DelAttrString().
The number of different attribute names passed to this function should be kept small, usually by using
a statically allocated string as attr_name. For attribute names that aren’t known at compile time, pre-
fer calling PyUnicode_FromString() and PyObject_SetAttr() directly. For more details, see
PyUnicode_InternFromString(), which may be used internally to create a key object.
int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)
Parte da ABI Está vel. Generic attribute setter and deleter function that is meant to be put into a type object’s
tp_setattro slot. It looks for a data descriptor in the dictionary of classes in the object’s MRO, and if found
it takes preference over setting or deleting the attribute in the instance dictionary. Otherwise, the attribute is set
or deleted in the object’s __dict__ (if present). On success, 0 is returned, otherwise an AttributeError
is raised and -1 is returned.
int PyObject_DelAttr(PyObject *o, PyObject *attr_name)
Parte da ABI Está vel desde a versão 3.13. Delete attribute named attr_name, for object o. Returns -1 on
failure. This is the equivalent of the Python statement del o.attr_name.
int PyObject_DelAttrString(PyObject *o, const char *attr_name)
Parte da ABI Está vel desde a versão 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*.
The number of different attribute names passed to this function should be kept small, usually by using
a statically allocated string as attr_name. For attribute names that aren’t known at compile time, pre-
fer calling PyUnicode_FromString() and PyObject_DelAttr() directly. For more details, see
PyUnicode_InternFromString(), which may be used internally to create a key object for lookup.
PyObject *PyObject_GenericGetDict(PyObject *o, void *context)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.10. A generic implementation for the
getter of a __dict__ descriptor. It creates the dictionary if necessary.
102 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
This function may also be called to get the __dict__ of the object o. Pass NULL for context when cal-
ling it. Since this function may need to allocate memory for the dictionary, it may be more efficient to call
PyObject_GetAttr() when accessing an attribute on the object.
On failure, returns NULL with an exception set.
Adicionado na versã o 3.3.
int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
Parte da ABI Está vel desde a versão 3.7. A generic implementation for the setter of a __dict__ descriptor.
This implementation does not allow the dictionary to be deleted.
Adicionado na versã o 3.3.
PyObject **_PyObject_GetDictPtr(PyObject *obj)
Return a pointer to __dict__ of the object obj. If there is no __dict__, return NULL without setting an
exception.
This function may need to allocate memory for the dictionary, so it may be more efficient to call
PyObject_GetAttr() when accessing an attribute on the object.
PyObject *PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Parte da ABI Está vel. 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)
Parte da ABI Está vel. 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Compute a string representation of object o. Returns
the string representation on success, NULL on failure. This is the equivalent of the Python expression repr(o).
Called by the repr() built-in function.
Alterado na versã o 3.4: Essa funçã o agora inclui uma asserçã o de depuraçã o para ajudar a garantir que ela nã o
descarte silenciosamente uma exceçã o ativa.
PyObject *PyObject_ASCII(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. As PyObject_Repr(), compute a string representa-
tion of object o, but escape the non-ASCII characters in the string returned by PyObject_Repr() with \x,
\u or \U escapes. This generates a string similar to that returned by PyObject_Repr() in Python 2. Called
by the ascii() built-in function.
PyObject *PyObject_Str(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Compute a string representation of object o. Returns
the string representation on success, NULL on failure. This is the equivalent of the Python expression str(o).
Called by the str() built-in function and, therefore, by the print() function.
7.1. Protocolo de objeto 103
The Python/C API, Release 3.13.7
Alterado na versã o 3.4: Essa funçã o agora inclui uma asserçã o de depuraçã o para ajudar a garantir que ela nã o
descarte silenciosamente uma exceçã o ativa.
PyObject *PyObject_Bytes(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Compute a bytes representation of object o. NULL is
returned on failure and a bytes object on success. This is equivalent to the Python expression bytes(o), when
o is not an integer. Unlike bytes(o), a TypeError is raised when o is an integer instead of a zero-initialized
bytes object.
int PyObject_IsSubclass(PyObject *derived, PyObject *cls)
Parte da ABI Está vel. Return 1 if the class derived is identical to or derived from the class cls, otherwise return
0. In case of an error, return -1.
If cls is a tuple, the check will be done against every entry in cls. The result will be 1 when at least one of the
checks returns 1, otherwise it will be 0.
If cls has a __subclasscheck__() method, it will be called to determine the subclass status as described
in PEP 3119. Otherwise, derived is a subclass of cls if it is a direct or indirect subclass, i.e. contained in
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)
Parte da ABI Está vel. Return 1 if inst is an instance of the class cls or a subclass of cls, or 0 if not. On error,
returns -1 and sets an exception.
If cls is a tuple, the check will be done against every entry in cls. The result will be 1 when at least one of the
checks returns 1, otherwise it will be 0.
If cls has a __instancecheck__() method, it will be called to determine the subclass status as described in
PEP 3119. Otherwise, inst is an instance of cls if its class is a subclass of 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)
Parte da ABI Está vel. Compute and return the hash value of an object o. On failure, return -1. This is the
equivalent of the Python expression hash(o).
Alterado na versã o 3.2: The return type is now Py_hash_t. This is a signed integer the same size as
Py_ssize_t.
Py_hash_t PyObject_HashNotImplemented(PyObject *o)
Parte da ABI Está vel. 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)
Parte da ABI Está vel. Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to
the Python expression not not o. On failure, return -1.
int PyObject_Not(PyObject *o)
Parte da ABI Está vel. Returns 0 if the object o is considered to be true, and 1 otherwise. This is equivalent to
the Python expression not o. On failure, return -1.
PyObject *PyObject_Type(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. When o is non-NULL, returns a type object corres-
ponding 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.
104 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)
Return non-zero if the object o is of type type or a subtype of type, and 0 otherwise. Both parameters must be
non-NULL.
Py_ssize_t PyObject_Size(PyObject *o)
Py_ssize_t PyObject_Length(PyObject *o)
Parte da ABI Está vel. Return the length of object o. If the object o provides either the sequence and mapping
protocols, the sequence length is returned. On error, -1 is returned. This is the equivalent to the Python
expression len(o).
Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
Return an estimated length for the object o. First try to return its actual length, then an estimate using
__length_hint__(), and finally return the default value. On error return -1. This is the equivalent to
the Python expression operator.length_hint(o, defaultvalue).
Adicionado na versã o 3.4.
PyObject *PyObject_GetItem(PyObject *o, PyObject *key)
Retorna valor: Nova referência. Parte da ABI Está vel. Return element of o corresponding to the object key or
NULL on failure. This is the equivalent of the Python expression o[key].
int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)
Parte da ABI Está vel. Map the object key to the value v. Raise an exception and return -1 on failure; return
0 on success. This is the equivalent of the Python statement o[key] = v. This function does not steal a
reference to v.
int PyObject_DelItem(PyObject *o, PyObject *key)
Parte da ABI Está vel. Remove the mapping for the object key from the object o. Return -1 on failure. This is
equivalent to the Python statement del o[key].
int PyObject_DelItemString(PyObject *o, const char *key)
Parte da ABI Está vel. É o mesmo que PyObject_DelItem(), mas key é especificada como uma string de
bytes const char* codificada em UTF-8, em vez de um PyObject*.
PyObject *PyObject_Dir(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. This is equivalent to the Python expression dir(o),
returning a (possibly empty) list of strings appropriate for the object argument, or NULL if there was an error.
If the argument is NULL, this is like the Python dir(), returning the names of the current locals; in this case,
if no execution frame is active then NULL is returned but PyErr_Occurred() will return false.
PyObject *PyObject_GetIter(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. This is equivalent to the Python expression iter(o).
It returns a new iterator for the object argument, or the object itself if the object is already an iterator. Raises
TypeError and returns NULL if the object cannot be iterated.
PyObject *PyObject_SelfIter(PyObject *obj)
Retorna valor: Nova referência. Parte da ABI Está vel. This is equivalent to the Python __iter__(self):
return self method. It is intended for iterator types, to be used in the PyTypeObject.tp_iter slot.
PyObject *PyObject_GetAIter(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.10. This is the equivalent to the Python
expression aiter(o). Takes an AsyncIterable object and returns an AsyncIterator for it. This is
typically a new iterator but if the argument is an AsyncIterator, this returns itself. Raises TypeError and
returns NULL if the object cannot be iterated.
Adicionado na versã o 3.10.
void *PyObject_GetTypeData(PyObject *o, PyTypeObject *cls)
Parte da ABI Está vel desde a versão 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.
7.1. Protocolo de objeto 105
The Python/C API, Release 3.13.7
On error, set an exception and return NULL.
Adicionado na versã o 3.12.
Py_ssize_t PyType_GetTypeDataSize(PyTypeObject *cls)
Parte da ABI Está vel desde a versão 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.
Adicionado na versã o 3.12.
void *PyObject_GetItemData(PyObject *o)
Get a pointer to per-item data for a class with Py_TPFLAGS_ITEMS_AT_END.
On error, set an exception and return NULL. TypeError is raised if o does not have
Py_TPFLAGS_ITEMS_AT_END set.
Adicionado na versã o 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.
Adicionado na versã o 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.
Adicionado na versã o 3.13.
7.2 Protocolo de chamada
O CPython permite dois protocolos de chamada: tp_call e vectorcall.
7.2.1 O protocolo tp_call
Instâ ncias de classe que definem tp_call sã o chamá veis. A assinatura do slot é :
PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);
Uma chamada é feita usando uma tupla para os argumentos posicionais e um dicioná rio para os argumentos nomeados,
similar a callable(*args, **kwargs) no Python. args nã o pode ser nulo (utilize uma tupla vazia se nã o houver
argumentos), mas kwargs pode ser NULL se nã o houver argumentos nomeados.
Esta convençã o nã o é somente usada por tp_call: tp_new e tp_init també m passam argumento dessa forma.
Para chamar um objeto, use PyObject_Call() ou outra call API.
7.2.2 O protocolo vectorcall
Adicionado na versã o 3.9.
O protocolo vectorcall foi introduzido pela PEP 590 como um protocolo adicional para tornar invocaçõ es mais
eficientes.
106 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
Como regra de bolso. CPython vai preferir o vectorcall para invocaçõ es internas se o chamá vel suportar. Entre-
tanto, isso nã o é uma regra rígida. Ademais, alguma extensõ es de terceiros usam diretamente tp_call (em vez de
utilizar PyObject_Call()). Portanto, uma classe que suporta vectorcall precisa també m implementar tp_call.
Alé m disso, o chamá vel precisa se comportar da mesma forma independe de qual protocolo é utilizado. A forma
recomendada de alcançar isso é definindo tp_call para PyVectorcall_Call(). Vale a pena repetir:
Á Aviso
Uma classe que suporte vectorcall també m precisa implementar tp_call com a mesma semâ ntica.
Alterado na versã o 3.12: O sinalizador Py_TPFLAGS_HAVE_VECTORCALL agora é removida da classe quando o
mé todo __call__() está reatribuído. (Internamente, isso apenas define tp_call, e portanto, pode fazê -lo com-
portar-se de forma diferente da funçã o vetorcall. Em versõ es anteriores do Python, vectorcall só deve ser usado com
tipos imutáveis ou está ticos.
Uma classe nã o deve implementar vectorcall se for mais lento que tp_call. Por exemplo, se o chamador precisa
converter os argumentos para uma tupla args e um dicioná rio kwargs de qualquer forma, entã o nã o é necessá rio
implementar vectorcall.
Classes podem implementar o protocolo vectorcall ativando o sinalizador Py_TPFLAGS_HAVE_VECTORCALL e con-
figurando tp_vectorcall_offset para o offset dentro da estrutura do objeto onde uma vectorcallfunc aparece.
Este é um ponteiro para uma funçã o com a seguinte assinatura:
typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Parte da ABI Está vel desde a versão 3.12.
• callable é o objeto sendo chamado.
• args é um array C formado pelos argumentos posicionais seguidos de
valores dos argumentos nomeados. Este pode ser NULL se nã o existirem argumentos.
• nargsf é o número de argumentos posicionais somado á possível
Sinalizador PY_VECTORCALL_ARGUMENTS_OFFSET . Para obter o nú mero real de argumentos posicio-
nais de nargsf, use PyVectorcall_NARGS().
• kwnames é uma tupla contendo os nomes dos argumentos nomeados;
em outras palavras, as chaves do dicioná rio kwargs. Estes nomes devem ser strings (instâ ncias de str
ou uma subclasse) e eles devem ser ú nicos. Se nã o existem argumentos nomeados, entã o kwnames deve
entã o ser NULL.
PY_VECTORCALL_ARGUMENTS_OFFSET
Parte da ABI Está vel desde a versão 3.12. Se esse sinalizador é definido em um argumento nargsf do vectorcall,
deve ser permitido ao chamado temporariamente mudar args[-1]. Em outras palavras, args aponta para o
argumento 1 (nã o 0) no vetor alocado. O chamado deve restaurar o valor de args[-1] antes de retornar.
Para PyObject_VectorcallMethod(), este sinalizador significa que args[0] pode ser alterado.
Sempre que podem realizar a um custo tã o baixo (sem alocaçõ es adicionais), invocadores sã o encorajados a
usar PY_VECTORCALL_ARGUMENTS_OFFSET . Isso permitirá invocados como mé todos vinculados a instâ ncias
fazerem suas pró prias invocaçõ es (o que inclui um argumento self) muito eficientemente.
Adicionado na versã o 3.8.
Para invocar um objeto que implementa vectorcall, utilize a funçã o call API como qualquer outra invocá vel.
PyObject_Vectorcall() será normalmente mais eficiente.
Controle de recursão
Quando utilizando tp_call, invocadores nã o precisam se preocupar sobre recursão: CPython usa
Py_EnterRecursiveCall() e Py_LeaveRecursiveCall() para chamadas utilizando tp_call.
7.2. Protocolo de chamada 107
The Python/C API, Release 3.13.7
Por questã o de eficiê ncia, este nã o é o caso de chamadas utilizando o vectorcall: o que chama deve utilizar
Py_EnterRecursiveCall e Py_LeaveRecursiveCall se necessá rio.
API de suporte à chamada de vetores
Py_ssize_t PyVectorcall_NARGS(size_t nargsf)
Parte da ABI Está vel desde a versão 3.12. Dado um argumento de chamada de vetor nargsf, retorna o nú mero
real de argumentos. Atualmente equivalente a:
(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)
Entretanto, a funçã o PyVectorcall_NARGS deve ser usada para permitir para futuras extensõ es.
Adicionado na versã o 3.8.
vectorcallfunc PyVectorcall_Function(PyObject *op)
Se op nã o suporta o protocolo de chamada de vetor (seja porque o tipo ou a instâ ncia específica nã o suportam),
retorne NULL. Se nã o, retorne o ponteiro da funçã o chamada de vetor armazenado em op. Esta funçã o nunca
levanta uma exceçã o.
É mais ú til checar se op suporta ou nã o chamada de vetor, o que pode ser feito checando
PyVectorcall_Function(op) != NULL.
Adicionado na versã o 3.9.
PyObject *PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict)
Parte da ABI Está vel desde a versão 3.12. Chama o vectorcallfunc de callable com argumentos posicionais
e nomeados dados em uma tupla e dicioná rio, respectivamente.
Esta é uma funçã o especializada, feita para ser colocada no slot tp_call ou usada em uma implementaçã o
de tp_call. Ela nã o verifica o sinalizador Py_TPFLAGS_HAVE_VECTORCALL e nã o retorna para tp_call.
Adicionado na versã o 3.8.
7.2.3 API de chamada de objetos
Vá rias funçõ es estã o disponíveis para chamar um objeto Python. Cada uma converte seus argumentos para uma
convençã o suportada pelo objeto chamado – seja tp_call ou chamada de vetor. Para fazer o mínimo possível de
conversõ es, escolha um que melhor se adapte ao formato de dados que você tem disponível.
A tabela a seguir resume as funçõ es disponíveis; por favor, veja a documentaçã o individual para detalhes.
Função chamável args kwargs
PyObject_Call() PyObject * tupla dict/NULL
PyObject_CallNoArgs() PyObject * — —
PyObject_CallOneArg() PyObject * 1 objeto —
PyObject_CallObject() PyObject * tupla/NULL —
PyObject_CallFunction() PyObject * format —
PyObject_CallMethod() obj + char* format —
PyObject_CallFunctionObjArgs() PyObject * variá dica —
PyObject_CallMethodObjArgs() obj + nome variá dica —
PyObject_CallMethodNoArgs() obj + nome — —
PyObject_CallMethodOneArg() obj + nome 1 objeto —
PyObject_Vectorcall() PyObject * vectorcall vectorcall
PyObject_VectorcallDict() PyObject * vectorcall dict/NULL
PyObject_VectorcallMethod() arg + nome vectorcall vectorcall
PyObject *PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)
Retorna valor: Nova referência. Parte da ABI Está vel. Chama um objeto Python chamá vel de callable, com
argumentos dados pela tupla args, e argumentos nomeados dados pelo dicioná rio kwargs.
108 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
args nã o deve ser NULL; use uma tupla vazia se nã o precisar de argumentos. Se nenhum argumento nomeado
é necessá rio, kwargs pode ser NULL.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Esse é o equivalente da expressã o Python: callable(*args, **kwargs).
PyObject *PyObject_CallNoArgs(PyObject *callable)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.10. Chama um objeto Python chamá -
vel de callable sem nenhum argumento. É o jeito mais eficiente de chamar um objeto Python sem nenhum
argumento.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Adicionado na versã o 3.9.
PyObject *PyObject_CallOneArg(PyObject *callable, PyObject *arg)
Retorna valor: Nova referência. Chama um objeto Python chamá vel de callable com exatamente 1 argumento
posicional arg e nenhum argumento nomeado.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Adicionado na versã o 3.9.
PyObject *PyObject_CallObject(PyObject *callable, PyObject *args)
Retorna valor: Nova referência. Parte da ABI Está vel. Chama um objeto Python chamá vel de callable com
argumentos dados pela tupla args. Se nenhum argumento é necessá rio, args pode ser NULL.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Este é o equivalente da expressã o Python: callable(*args).
PyObject *PyObject_CallFunction(PyObject *callable, const char *format, ...)
Retorna valor: Nova referência. Parte da ABI Está vel. Chama um objeto Python chamá vel de callable, com
um nú mero variá vel de argumentos C. Os argumentos C sã o descritos usando uma string de estilo no formato
Py_BuildValue(). O formato pode ser NULL, indicando que nenhum argumento foi provido.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Este é o equivalente da expressã o Python: callable(*args).
Note que se você apenas passa argumentos PyObject*, PyObject_CallFunctionObjArgs() é uma al-
ternativa mais rá pida.
Alterado na versã o 3.4: O tipo de format foi mudado de char *.
PyObject *PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
Retorna valor: Nova referência. Parte da ABI Está vel. Chama o mé todo chamado name do objeto obj
com um nú mero variá vel de argumentos C. Os argumentos C sã o descritos com uma string de formato
Py_BuildValue() que deve produzir uma tupla.
O formato pode ser NULL, indicado que nenhum argumento foi provido.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Este é o equivalente da expressã o Python: obj.name(arg1, arg2, ...).
Note que se você apenas passa argumentos PyObject*, PyObject_CallMethodObjArgs() é uma alter-
nativa mais rá pida.
Alterado na versã o 3.4: Os tipos de name e format foram mudados de char *.
PyObject *PyObject_CallFunctionObjArgs(PyObject *callable, ...)
Retorna valor: Nova referência. Parte da ABI Está vel. Chama um objeto Python chamá vel de callable, com
um nú mero variá vel de argumentos PyObject*. Os argumentos sã o providos como um nú mero variá vel de
parâ metros seguidos por um NULL.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
7.2. Protocolo de chamada 109
The Python/C API, Release 3.13.7
Este é o equivalente da expressã o Python: callable(arg1, arg2, ...).
PyObject *PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ...)
Retorna valor: Nova referência. Parte da ABI Está vel. Chama um mé todo do objeto Python obj, onde o
nome do mé todo é dado como um objeto string Python em name. É chamado com um nú mero variá vel de
argumentos PyObject*. Os argumentos sã o providos como um nú mero variá vel de parâ metros seguidos por
um NULL.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
PyObject *PyObject_CallMethodNoArgs(PyObject *obj, PyObject *name)
Chama um mé todo do objeto Python obj sem argumentos, onde o nome do mé todo é fornecido como um
objeto string do Python em name.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Adicionado na versã o 3.9.
PyObject *PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObject *arg)
Chama um mé todo do objeto Python obj com um argumento posicional arg, onde o nome do mé todo é forne-
cido como um objeto string do Python em name.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Adicionado na versã o 3.9.
PyObject *PyObject_Vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Parte da ABI Está vel desde a versão 3.12. Chama um objeto Python chamá vel callable. Os argumentos sã o
os mesmos de vectorcallfunc. Se callable tiver suporte a vectorcall, isso chamará diretamente a funçã o
vectorcall armazenada em callable.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Adicionado na versã o 3.9.
PyObject *PyObject_VectorcallDict(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwdict)
Chama callable com argumentos posicionais passados exatamente como no protocolo vectorcall, mas com
argumentos nomeados passados como um dicioná rio kwdict. O array args conté m apenas os argumentos po-
sicionais.
Independentemente de qual protocolo é usado internamente, uma conversã o de argumentos precisa ser feita.
Portanto, esta funçã o só deve ser usada se o chamador já tiver um dicioná rio pronto para usar para os argu-
mentos nomeados, mas nã o uma tupla para os argumentos posicionais.
Adicionado na versã o 3.9.
PyObject *PyObject_VectorcallMethod(PyObject *name, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Parte da ABI Está vel desde a versão 3.12. Chama um mé todo usando a convençã o de chamada vector-
call. O nome do mé todo é dado como uma string Python name. O objeto cujo mé todo é chamado é
args[0], e o array args começando em args[1] representa os argumentos da chamada. Deve haver pelo
menos um argumento posicional. nargsf é o nú mero de argumentos posicionais incluindo args[0], mais
PY_VECTORCALL_ARGUMENTS_OFFSET se o valor de args[0] puder ser alterado temporariamente. Ar-
gumentos nomeados podem ser passados como em PyObject_Vectorcall().
Se o objeto tem o recurso Py_TPFLAGS_METHOD_DESCRIPTOR, isso irá chamar o objeto de mé todo nã o
vinculado com o vetor args inteiro como argumentos.
Retorna o resultado da chamada em sucesso, ou levanta uma exceçã o e retorna NULL em caso de falha.
Adicionado na versã o 3.9.
110 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
7.2.4 API de suporte a chamadas
int PyCallable_Check(PyObject *o)
Parte da ABI Está vel. Determine se o objeto o é chamá vel. Devolva 1 se o objeto é chamá vel e 0 caso contrá rio.
Esta funçã o sempre tem ê xito.
7.3 Protocolo de número
int PyNumber_Check(PyObject *o)
Parte da ABI Está vel. Retorna 1 se o objeto o fornece protocolos numé ricos; caso contrá rio, retorna falso.
Esta funçã o sempre tem sucesso.
Alterado na versã o 3.8: Retorna 1 se o for um nú mero inteiro de índice.
PyObject *PyNumber_Add(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o resultado da adiçã o de o1 e o2, ou NULL em
caso de falha. Este é o equivalente da expressã o Python o1 + o2.
PyObject *PyNumber_Subtract(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o resultado da subtraçã o de o2 por o1, ou NULL
em caso de falha. Este é o equivalente da expressã o Python o1 - o2.
PyObject *PyNumber_Multiply(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o resultado da multiplicaçã o de o1 e o2, ou
NULL em caso de falha. Este é o equivalente da expressã o Python o1 * o2.
PyObject *PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Retorna o resultado da multiplicaçã o
da matriz em o1 e o2, ou NULL em caso de falha. Este é o equivalente da expressã o Python o1 @ o2.
Adicionado na versã o 3.5.
PyObject *PyNumber_FloorDivide(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає нижню частину o1, поділену на o2, або
NULL у разі помилки. Це еквівалент виразу Python o1 // o2.
PyObject *PyNumber_TrueDivide(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. 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. This is the equivalent of the Python expression o1 / o2.
PyObject *PyNumber_Remainder(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає залишок від ділення o1 на o2 або NULL у
разі помилки. Це еквівалент виразу Python o1 % o2.
PyObject *PyNumber_Divmod(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Перегляньте вбудовану функцію divmod().
Повертає NULL у разі помилки. Це еквівалент виразу Python divmod(o1, o2).
PyObject *PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3)
Retorna valor: Nova referência. Parte da ABI Está vel. Перегляньте вбудовану функцію pow(). Повертає
NULL у разі помилки. Це еквівалент виразу Python pow(o1, o2, o3), де o3 є необов’язковим.
Якщо o3 потрібно ігнорувати, передайте замість нього Py_None (передача NULL для o3 призведе до
незаконного доступу до пам’яті).
PyObject *PyNumber_Negative(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає заперечення o у разі успіху або NULL у
разі невдачі. Це еквівалент виразу Python -o.
7.3. Protocolo de número 111
The Python/C API, Release 3.13.7
PyObject *PyNumber_Positive(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає o у разі успіху або NULL у разі невдачі.
Це еквівалент виразу Python +o.
PyObject *PyNumber_Absolute(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає абсолютне значення o або NULL у разі
помилки. Це еквівалент виразу Python abs(o).
PyObject *PyNumber_Invert(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає порозрядне заперечення o у разі успіху
або NULL у разі невдачі. Це еквівалент виразу Python ~o.
PyObject *PyNumber_Lshift(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає результат зсуву вліво o1 на o2 у разі успіху
або NULL у разі помилки. Це еквівалент виразу Python o1 << o2.
PyObject *PyNumber_Rshift(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає результат зсуву праворуч o1 на o2 у разі
успіху або NULL у разі помилки. Це еквівалент виразу Python o1 >> o2.
PyObject *PyNumber_And(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає “порозрядне та” o1 і o2 у разі успіху та
NULL у разі помилки. Це еквівалент виразу Python o1 & o2.
PyObject *PyNumber_Xor(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає “порозрядне виняткове або” o1 на o2 у
разі успіху або NULL у разі помилки. Це еквівалент виразу Python o1 ^ o2.
PyObject *PyNumber_Or(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає “порозрядне або” o1 і o2 у разі успіху або
NULL у разі помилки. Це еквівалент виразу Python o1 | o2.
PyObject *PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає результат додавання o1 і o2 або NULL у
разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент оператора Python
o1 += o2.
PyObject *PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає результат віднімання o2 від o1 або NULL
у разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент оператора Python
o1 -= o2.
PyObject *PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає результат множення o1 і o2 або NULL у
разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент оператора Python
o1 *= o2.
PyObject *PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Повертає результат множення
матриці на o1 і o2 або NULL у разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це
еквівалент оператора Python o1 @= o2.
Adicionado na versã o 3.5.
PyObject *PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає математичний рівень ділення o1 на o2 або
NULL у разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент оператора
Python o1 //= o2.
112 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
PyObject *PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає залишок від ділення o1 на o2 або NULL у
разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент оператора Python
o1 %= o2.
PyObject *PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3)
Retorna valor: Nova referência. Parte da ABI Está vel. Перегляньте вбудовану функцію pow(). Повертає
NULL у разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент оператора
Python o1 **= o2, коли o3 дорівнює Py_None, або альтернативного варіанту pow(o1, o2, o3)
інакше. Якщо o3 потрібно ігнорувати, передайте замість нього Py_None (передача NULL для o3
призведе до незаконного доступу до пам’яті).
PyObject *PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає результат зсуву ліворуч o1 на o2 у разі
успіху або NULL у разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент
оператора Python o1 <<= o2.
PyObject *PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає результат зсуву праворуч o1 на o2 у разі
успіху або NULL у разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент
оператора Python o1 >>= o2.
PyObject *PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає “порозрядне та” o1 і o2 у разі успіху та
NULL у разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент оператора
Python o1 &= o2.
PyObject *PyNumber_InPlaceXor(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає “порозрядне виняткове або” o1 на o2 у разі
успіху або NULL у разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент
оператора Python o1 ^= o2.
PyObject *PyNumber_InPlaceOr(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає “порозрядне або” o1 і o2 у разі успіху або
NULL у разі помилки. Операція виконується на місці, якщо o1 її підтримує. Це еквівалент оператора
Python o1 |= o2.
PyObject *PyNumber_Long(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає o, перетворений на цілий об’єкт у разі
успіху, або NULL у разі помилки. Це еквівалент виразу Python int(o).
PyObject *PyNumber_Float(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає o, перетворений на об’єкт float у разі
успіху, або NULL у разі помилки. Це еквівалент виразу Python float(o).
PyObject *PyNumber_Index(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає o, перетворений на Python int у разі успіху
або NULL з виключенням TypeError, яке виникає в разі помилки.
Alterado na versã o 3.10: O resultado sempre tem o tipo exato int. Anteriormente, o resultado poderia ter
sido uma instâ ncia de uma subclasse de int.
7.3. Protocolo de número 113
The Python/C API, Release 3.13.7
PyObject *PyNumber_ToBase(PyObject *n, int base)
Retorna valor: Nova referência. Parte da ABI Está vel. Повертає ціле число n, перетворене на базу base як
рядок. Аргумент base має бути одним із 2, 8, 10 або 16. Для base 2, 8 або 16 повернутий рядок має
префікс базового маркера '0b', '0o' або '0x'' відповідно. Якщо n не є int Python, воно спочатку
перетворюється за допомогою PyNumber_Index().
Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc)
Parte da ABI Está vel. Повертає o, перетворене на значення Py_ssize_t, якщо o можна інтерпретувати
як ціле число. Якщо виклик не вдається, виникає виняток і повертається -1.
Якщо o можна перетворити на Python int, але спроба перетворити на значення Py_ssize_t призведе
до появи OverflowError, тоді аргумент exc є типом винятку, який викличе бути викликано (зазвичай
IndexError або OverflowError). Якщо exc дорівнює NULL, тоді виняток очищається, а значення
обрізається до PY_SSIZE_T_MIN для від’ємного цілого числа або PY_SSIZE_T_MAX для додатного
цілого числа.
int PyIndex_Check(PyObject *o)
Parte da ABI Está vel desde a versão 3.8. Повертає 1, якщо o є цілим індексом (має заповнений слот
nb_index структури tp_as_number), і 0 інакше. Ця функція завжди успішна.
7.4 Protocolo de sequência
int PySequence_Check(PyObject *o)
Parte da ABI Está vel. Retorna 1 se o objeto fornecer o protocolo de sequê ncia e 0 caso contrá rio. Note que
ele retorna 1 para classes Python com um mé todo __getitem__() a menos que sejam subclasses de dict
já que no caso geral é impossível determinar que tipo de chaves a classe provê . Esta funçã o sempre obté m
sucesso.
Py_ssize_t PySequence_Size(PyObject *o)
Py_ssize_t PySequence_Length(PyObject *o)
Parte da ABI Está vel. Retorna o nú mero de objetos na sequê ncia o em caso de sucesso, ou -1 em caso de
falha. Equivale à expressã o Python len(o).
PyObject *PySequence_Concat(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna a concatenaçã o de o1 e o2 em caso de sucesso,
e NULL em caso de falha. Equivale à expressã o Python o1 + o2.
PyObject *PySequence_Repeat(PyObject *o, Py_ssize_t count)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o resultado da repetiçã o do objeto sequê ncia o
count vezes ou NULL em caso de falha. Equivale à expressã o Python o * count.
PyObject *PySequence_InPlaceConcat(PyObject *o1, PyObject *o2)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna a concatenaçã o de o1 e o2 em caso de sucesso,
e NULL em caso de falha. A operaçã o é feita localmente se o1 permitir. Equivale à expressã o Python o1 +=
o2.
PyObject *PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o resultado da repetiçã o do objeto sequê ncia
o count vezes ou NULL em caso de falha. A operaçã o é feita localmente se o permitir. Equivale à expressã o
Python o *= count.
PyObject *PySequence_GetItem(PyObject *o, Py_ssize_t i)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o elemento i de o ou NULL em caso de falha.
Equivale à expressã o Python o[i].
PyObject *PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna a fatia do objeto sequê ncia o entre i1 e i2, ou
NULL em caso de falha. Equivale à expressã o Python o[i1:i2].
114 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v)
Parte da ABI Está vel. Atribui o objeto v ao elemento i de o. Levanta uma exceçã o e retorna -1 em caso de
falha; retorna 0 em caso de sucesso. Esta funçã o não rouba uma referê ncia a v. Equivale à instruçã o Python
o[i]=v.
Se v for NULL, o elemento será removido, mas este recurso foi descontinuado em favor do uso de
PySequence_DelItem().
int PySequence_DelItem(PyObject *o, Py_ssize_t i)
Parte da ABI Está vel. Exclui o elemento i do objeto o. Retorna -1 em caso de falha. Equivale à instruçã o
Python del o[i].
int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v)
Parte da ABI Está vel. Atribui o objeto sequê ncia v à fatia no objeto sequê ncia o de i1 a i2. Equivale à instruçã o
Python o[i1:i2] = v.
int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
Parte da ABI Está vel. Exclui a fatia no objeto sequê ncia o de i1 a i2. Retorna -1 em caso de falha. Equivale
à instruçã o Python del o[i1:i2].
Py_ssize_t PySequence_Count(PyObject *o, PyObject *value)
Parte da ABI Está vel. Retorna a quantidade de ocorrê ncias de value em o, isto é , retorna a quantidade de chaves
onde o[key] == value. Em caso de falha, retorna -1. Equivale à expressã o Python o.count(value).
int PySequence_Contains(PyObject *o, PyObject *value)
Parte da ABI Está vel. Determina se o conté m value. Se um item em o for igual a value, retorna 1, senã o,
retorna 0. Em caso de erro, retorna -1. Equivale à expressã o Python value in o.
Py_ssize_t PySequence_Index(PyObject *o, PyObject *value)
Parte da ABI Está vel. Retorna o primeiro índice i tal que o[i] == value. Em caso de erro, retorna -1.
Equivale à expressã o Python o.index(value).
PyObject *PySequence_List(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um objeto lista com o mesmo conteú do da
sequê ncia ou iterá vel o, ou NULL em caso de falha. Garante-se que a lista retornada será nova. Equivale à
expressã o Python list(o).
PyObject *PySequence_Tuple(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o objeto tupla com o mesmo conteú do da
sequê ncia ou iterá vel o, ou NULL em caso de falha. Se o for uma tupla, retorna uma nova referê ncia. Senã o,
uma tupla será construída com o conteú do apropriado. Equivale à expressã o Python tuple(o).
PyObject *PySequence_Fast(PyObject *o, const char *m)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna a sequê ncia ou iterá vel o como um objeto
usá vel por outras funçõ es da família PySequence_Fast*. Se o objeto nã o for uma sequê ncia ou iterá vel,
levanta TypeError com m sendo o texto da mensagem. Retorna NULL em caso de falha.
As funçõ es PySequence_Fast* tê m esse nome porque presumem que o é um PyTupleObject ou um
PyListObject e porque acessam os campos de dados de o diretamente.
Como detalhe de implementaçã o de CPython, se o já for uma sequê ncia ou lista, ele será retornado.
Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o)
Retorna o comprimento de o, presumindo que o foi retornado por PySequence_Fast() e que o
nã o seja NULL. O tamanho també m pode ser obtido ao chamar PySequence_Size() em o, mas
PySequence_Fast_GET_SIZE() é mais rá pida, ao supor que o é uma lista ou tupla.
PyObject *PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i)
Retorna valor: Referência emprestada. Retorna o elemento i de o, presumindo que o foi retornado por
PySequence_Fast(), que o seja NULL, e que i esteja nos limites.
7.4. Protocolo de sequência 115
The Python/C API, Release 3.13.7
PyObject **PySequence_Fast_ITEMS(PyObject *o)
Retorna o vetor subjacente de ponteiros PyObject. Presume que o foi retornado por PySequence_Fast() e
que o nã o seja NULL.
Note que, se uma lista for redimensionada, a realocaçã o poderá reposicionar o vetor de itens. Portanto, só use
o ponteiro de vetor subjacente em contextos onde a sequê ncia nã o mudará .
PyObject *PySequence_ITEM(PyObject *o, Py_ssize_t i)
Retorna valor: Nova referência. Retorna o elemento i de o, ou NULL em caso de falha. É uma forma mais
rá pida de PySequence_GetItem(), mas sem verificar se PySequence_Check() em o é verdadeiro e sem
ajustar índices negativos.
7.5 Protocolo de mapeamento
Veja també m PyObject_GetItem(), PyObject_SetItem() e PyObject_DelItem().
int PyMapping_Check(PyObject *o)
Parte da ABI Está vel. Retorna 1 se o objeto fornece protocolo de mapeamento ou suporta fatiamento e 0 caso
contrá rio. Note que ele retorna 1 para classes Python com um mé todo __getitem__() visto que geralmente
é impossível determinar a que tipo de chaves a classe tem suporte. Esta funçã o sempre tem sucesso.
Py_ssize_t PyMapping_Size(PyObject *o)
Py_ssize_t PyMapping_Length(PyObject *o)
Parte da ABI Está vel. Retorna o nú mero de chaves no objeto o em caso de sucesso e -1 em caso de falha. Isso
é equivalente à expressã o Python len(o).
PyObject *PyMapping_GetItemString(PyObject *o, const char *key)
Retorna valor: Nova referência. Parte da ABI Está vel. É o mesmo que PyObject_GetItem(), mas key é
especificada como uma string de bytes const char* codificada em UTF-8, em vez de um PyObject*.
int PyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result)
Parte da ABI Está vel desde a versão 3.13. Variante de PyObject_GetItem() que nã o levanta KeyError
se a chave nã o for encontrada.
Se a chave for encontrada, retorna 1 e define *result como uma nova referência forte para o valor correspon-
dente. Se a chave nã o for encontrada, retorna 0 e define *result como NULL; o KeyError é silenciado. Se um
erro diferente de KeyError for levanta, retorna -1 e define *result como NULL.
Adicionado na versã o 3.13.
int PyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result)
Parte da ABI Está vel desde a versão 3.13. É o mesmo que PyMapping_GetOptionalItem(), mas key é
especificado como uma string de bytes codificada em UTF-8 const char*, em vez de um PyObject*.
Adicionado na versã o 3.13.
int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *v)
Parte da ABI Está vel. É o mesmo que PyObject_SetItem(), mas key é especificada como uma string de
bytes const char* codificada em UTF-8, em vez de um PyObject*.
int PyMapping_DelItem(PyObject *o, PyObject *key)
Este é um apelido de PyObject_DelItem().
int PyMapping_DelItemString(PyObject *o, const char *key)
É o mesmo que PyObject_DelItem(), mas key é especificada como uma string de bytes const char*
codificada em UTF-8, em vez de um PyObject*.
int PyMapping_HasKeyWithError(PyObject *o, PyObject *key)
Parte da ABI Está vel desde a versão 3.13. Retorna 1 se o objeto de mapeamento tiver a chave key e 0 caso
contrá rio. Isso é equivalente à expressã o Python key in o. Em caso de falha, retorna -1.
Adicionado na versã o 3.13.
116 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
int PyMapping_HasKeyStringWithError(PyObject *o, const char *key)
Parte da ABI Está vel desde a versão 3.13. É o mesmo que PyMapping_HasKeyWithError(), mas key é
especificada como uma string de bytes const char* codificada em UTF-8, em vez de um PyObject*.
Adicionado na versã o 3.13.
int PyMapping_HasKey(PyObject *o, PyObject *key)
Parte da ABI Está vel. Retorna 1 se o objeto de mapeamento tiver a chave key e 0 caso contrá rio. Isso é
equivalente à expressã o Python key in o. Esta funçã o sempre tem sucesso.
® Nota
As exceçõ es que ocorrem quando esse mé todo chama __getitem__() sã o silenciosamente
ignoradas. Para o tratamento adequado de erros, use PyMapping_HasKeyWithError(),
PyMapping_GetOptionalItem() ou PyObject_GetItem() em vez disso.
int PyMapping_HasKeyString(PyObject *o, const char *key)
Parte da ABI Está vel. É o mesmo que PyMapping_HasKey(), mas key é especificada como uma string de
bytes const char* codificada em UTF-8, em vez de um PyObject*.
® Nota
As exceçõ es que ocorrem quando esse mé todo chama __getitem__() ou ao criar o ob-
jeto temporá rio str sã o silenciosamente ignoradas. Para o tratamento adequado de er-
ros, use PyMapping_HasKeyStringWithError(), PyMapping_GetOptionalItemString() ou
PyMapping_GetItemString() em vez disso.
PyObject *PyMapping_Keys(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Em caso de sucesso, retorna uma lista das chaves no
objeto o. Em caso de falha, retorna NULL.
Alterado na versã o 3.7: Anteriormente, a funçã o retornava uma lista ou tupla.
PyObject *PyMapping_Values(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Em caso de sucesso, retorna uma lista dos valores no
objeto o. Em caso de falha, retorna NULL.
Alterado na versã o 3.7: Anteriormente, a funçã o retornava uma lista ou tupla.
PyObject *PyMapping_Items(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Em caso de sucesso, retorna uma lista dos itens no
objeto o, onde cada item é uma tupla contendo um par de valores-chave. Em caso de falha, retorna NULL.
Alterado na versã o 3.7: Anteriormente, a funçã o retornava uma lista ou tupla.
7.6 Protocolo Iterador
Existem duas funçõ es especificas para trabalhar com iteradores.
int PyIter_Check(PyObject *o)
Parte da ABI Está vel desde a versão 3.8. Retorna valor diferente de zero se o objeto o puder ser passado com
segurança para PyIter_Next(), e 0 caso contrá rio. Esta funçã o sempre é bem-sucedida.
int PyAIter_Check(PyObject *o)
Parte da ABI Está vel desde a versão 3.10. Retorna valor diferente de zero se o objeto o fornecer o protocolo
AsyncIterator e 0 caso contrá rio. Esta funçã o sempre é bem-sucedida.
Adicionado na versã o 3.10.
7.6. Protocolo Iterador 117
The Python/C API, Release 3.13.7
PyObject *PyIter_Next(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o pró ximo valor do iterador o. O objeto deve
ser um iterador de acordo com PyIter_Check() (cabe ao chamador verificar isso). Se nã o houver valores
restantes, retorna NULL sem nenhuma exceçã o definida. Se ocorrer um erro ao recuperar o item, retorna NULL
e passa a exceçã o.
Para escrever um laço que itere sobre um iterador, o có digo C deve ser algo como isto:
PyObject *iterator = PyObject_GetIter(obj);
PyObject *item;
if (iterator == NULL) {
/* propaga o erro */
}
while ((item = PyIter_Next(iterator))) {
/* faz algo com o item */
...
/* liberar a referência quando concluído */
Py_DECREF(item);
}
Py_DECREF(iterator);
if (PyErr_Occurred()) {
/* propaga o erro */
}
else {
/* continua fazendo algum trabalho útil */
}
type PySendResult
O valor de enum usado para representar diferentes resultados de PyIter_Send().
Adicionado na versã o 3.10.
PySendResult PyIter_Send(PyObject *iter, PyObject *arg, PyObject **presult)
Parte da ABI Está vel desde a versão 3.10. Envia o valor arg para o iterador iter. Retorna:
• PYGEN_RETURN se o iterador retornar. O valor de retorno é retornado via presult.
• PYGEN_NEXT se o iterador render. O valor preduzido é retornado via presult.
• PYGEN_ERROR se o iterador tiver levantado uma exceçã o. presult é definido como NULL.
Adicionado na versã o 3.10.
7.7 Protocolo de Buffer
Certos objetos disponíveis no Python envolvem o acesso a um vetor ou buffer de memó ria subjacente. Esses objetos
incluem as bytes e bytearray embutidas, e alguns tipos de extensã o como array.array. As bibliotecas de
terceiros podem definir seus pró prios tipos para fins especiais, como processamento de imagem ou aná lise numé rica.
Embora cada um desses tipos tenha sua pró pria semâ ntica, eles compartilham a característica comum de serem
suportados por um buffer de memó ria possivelmente grande. É desejá vel, em algumas situaçõ es, acessar esse buffer
diretamente e sem có pia intermediá ria.
Python fornece essa facilidade no nível C e Python sob a forma de protocolo de buffer. Este protocolo tem dois lados:
• do lado do produtor, um tipo pode exportar uma “interface de buffer” que permite que objetos desse tipo
exponham informaçõ es sobre o buffer subjacente. Esta interface é descrita na seçã o Buffer Object Structures;
para Python, consulte python-buffer-protocol.
118 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
• do lado do consumidor, vá rios meios estã o disponíveis para obter o ponteiro para os dados subjacentes de um
objeto (por exemplo, um parâ metro de mé todo). Para Python, consulte python-buffer-protocol.
Objetos simples como bytes e bytearray expõ em seu buffer subjacente em uma forma orientada a byte. Outras
formas sã o possíveis; por exemplo, os elementos expostos por uma array.array podem ser valores de vá rios bytes.
Um exemplo de interface de um consumidor de buffer é o mé todo write() de objetos arquivo: qualquer objeto
que possa exportar uma sé rie de bytes por meio da interface de buffer pode ser gravado em um arquivo. Enquanto
o write() precisa apenas de acesso de somente leitura ao conteú do interno do objeto passado, outros mé todos,
como readinto(), precisam de acesso de somente escrita ao conteú do interno. A interface de buffer permite que
o objetos possam permitir ou rejeitar a exportaçã o para buffers de leitura e escrita ou somente leitura.
Existem duas maneiras para um consumidor da interface de buffer adquirir um buffer em um objeto alvo:
• chamada de PyObject_GetBuffer() com os parâ metros certos;
• chamada de PyArg_ParseTuple() (ou um dos seus irmã os) com um dos códigos de formatação y*, w* ou
s*.
Em ambos os casos, PyBuffer_Release() deve ser chamado quando o buffer nã o é mais necessá rio. A falta de
tal pode levar a vá rias questõ es, tais como vazamentos de recursos.
Adicionado na versã o 3.12: O protocolo de buffer agora está acessível em Python, veja python-buffer-protocol e
memoryview.
7.7.1 Estrutura de Buffer
As estruturas de buffer (ou simplesmente “buffers”) sã o ú teis como uma maneira de expor os dados biná rios de
outro objeto para o programador Python. Eles també m podem ser usados como um mecanismo de có pia silenciosa.
Usando sua capacidade de fazer referê ncia a um bloco de memó ria, é possível expor facilmente qualquer dado ao
programador Python. A memó ria pode ser uma matriz grande e constante em uma extensã o C, pode ser um bloco
bruto de memó ria para manipulaçã o antes de passar para uma biblioteca do sistema operacional, ou pode ser usado
para transmitir dados estruturados no formato nativo e formato de memó ria.
Ao contrá rio da maioria dos tipos de dados expostos pelo interpretador Python, os buffers nã o sã o ponteiros
PyObject mas sim estruturas C simples. Isso permite que eles sejam criados e copiados de forma muito simples.
Quando um invó lucro gené rico em torno de um buffer é necessá rio, um objeto memoryview pode ser criado.
Para obter instruçõ es curtas sobre como escrever um objeto exportador, consulte Buffer Object Structures. Para obter
um buffer, veja PyObject_GetBuffer().
type Py_buffer
Parte da ABI Está vel (incluindo todos os membros) desde a versão 3.11.
void *buf
Um ponteiro para o início da estrutura ló gica descrita pelos campos do buffer. Este pode ser qualquer
local dentro do bloco de memó ria física subjacente do exportador. Por exemplo, com negativo strides
o valor pode apontar para o final do bloco de memó ria.
Para vetores contíguos, o valor aponta para o início do bloco de memó ria.
PyObject *obj
Uma nova referê ncia ao objeto sendo exporta. A referê ncia pertence ao consumidor e é automatica-
mente liberada (por exemplo, a contagem de referê ncias é decrementada) e é atribuída para NULL por
PyBuffer_Release(). O campo é equivalmente ao valor de retorno de qualquer funçã o do padrã o
C-API.
Como um caso especial, para buffers temporários que sã o encapsulados por
PyMemoryView_FromBuffer() ou PyBuffer_FillInfo() esse campo é NULL. Em geral,
objetos exportadores NÃO DEVEM usar esse esquema.
Py_ssize_t len
product(shape) * itemsize. Para matrizes contíguas, este é o comprimento do bloco de memó ria
subjacente. Para matrizes nã o contíguas, é o comprimento que a estrutura ló gica teria se fosse copiado
para uma representaçã o contígua.
7.7. Protocolo de Buffer 119
The Python/C API, Release 3.13.7
Acessando ((char *)buf)[0] up to ((char *)buf)[len-1] só é vá lido se o buffer tiver sido
obtido por uma solicitaçã o que garanta a contiguidade. Na maioria dos casos, esse pedido será
PyBUF_SIMPLE ou PyBUF_WRITABLE.
int readonly
Um indicador de se o buffer é somente leitura. Este campo é controlado pelo sinalizador
PyBUF_WRITABLE.
Py_ssize_t itemsize
O tamanho do item em bytes de um ú nico elemento. O mesmo que o valor de struct.calcsize()
chamado em valores nã o NULL de format.
Exceçã o importante: Se um consumidor requisita um buffer sem sinalizador PyBUF_FORMAT , format
será definido como NULL, mas itemsize ainda terá seu valor para o formato original.
Se shape está presente, a igualdade product(shape) * itemsize == len ainda é vá lida e o usuá -
rio pode usar itemsize para navegar o buffer.
Se shape é NULL como resultado de uma PyBUF_SIMPLE ou uma requisiçã o PyBUF_WRITABLE, o
consumidor deve ignorar itemsize e presumir itemsize == 1.
char *format
Uma string terminada por NULL no estilo de sintaxe de mó dulo struct descrevendo os conteú dos de
um ú nico item. Se isso é NULL, "B" (unsigned bytes) é presumido.
Este campo é controlado pelo sinalizador PyBUF_FORMAT .
int ndim
O nú mero de dimensõ es de memó ria representado como um array n-dimensional. Se for 0, buf aponta
para um ú nico elemento representando um escalar. Neste caso, shape, strides e suboffsets DE-
VEM ser NULL. O nú mero má ximo de dimensõ es é dado por PyBUF_MAX_NDIM .
Py_ssize_t *shape
Uma matriz de Py_ssize_t do comprimento ndim indicando a forma da memó ria como uma matriz
n-dimensional. Observe que a forma shape[0] * ... * shape[ndim-1] * itemsize DEVE ser
igual a len.
Os valores da forma sã o restritos a shape[n] >= 0. The case shape[n] == 0 requer atençã o espe-
cial. Veja complex arrays para mais informaçõ es.
A forma de acesso a matriz é de somente leitura para o usuá rio.
Py_ssize_t *strides
Um vetor de Py_ssize_t de comprimento ndim dando o nú mero de bytes para saltar para obter um
novo elemento em cada dimensã o.
Os valores de Stride podem ser qualquer nú mero inteiro. Para arrays regulares, os passos sã o geralmente
positivos, mas um consumidor DEVE ser capaz de lidar com o caso strides[n] <= 0. Veja complex
arrays para mais informaçõ es.
A matriz de passos é somente leitura para o consumidor.
Py_ssize_t *suboffsets
Uma matriz de Py_ssize_t de comprimento ndim. Se suboffsets[n] >= 0, os valores armaze-
nados ao longo da n-é sima dimensã o sã o ponteiros e o valor suboffset determina quantos bytes para
adicionar a cada ponteiro apó s desreferenciar. Um valor de suboffset que é negativo indica que nã o deve
ocorrer desreferenciaçã o (caminhando em um bloco de memó ria contíguo).
Se todos os subconjuntos forem negativos (ou seja, nã o é necessá rio fazer referê ncia), entã o este campo
deve ser NULL (o valor padrã o).
Esse tipo de representaçã o de matriz é usado pela Python Imaging Library (PIL). Veja complex arrays
para obter mais informaçõ es sobre como acessar elementos dessa matriz.a matriz.
A matriz de subconjuntos é somente leitura para o consumidor.
120 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
void *internal
Isso é para uso interno pelo objeto exportador. Por exemplo, isso pode ser re-moldado como um nú mero
inteiro pelo exportador e usado para armazenar bandeiras sobre se os conjuntos de forma, passos e su-
boffsets devem ou nã o ser liberados quando o buffer é liberado. O consumidor NÃO DEVE alterar esse
valor.
Constantes:
PyBUF_MAX_NDIM
O nú mero má ximo de dimensõ es que a memó ria representa. Exportadores DEVEM respeitar esse limite,
consumidores de buffers multi-dimensionais DEVEM ser capazes de liader com até PyBUF_MAX_NDIM di-
mensõ es. Atualmente definido como 64.
7.7.2 Tipos de solicitação do buffer
Os buffers geralmente sã o obtidos enviando uma solicitaçã o de buffer para um objeto exportador via
PyObject_GetBuffer(). Uma vez que a complexidade da estrutura ló gica da memó ria pode variar drastica-
mente, o consumidor usa o argumento flags para especificar o tipo de buffer exato que pode manipular.
Todos os campos Py_buffer sã o definidos de forma nã o-ambígua pelo tipo de requisiçã o.
campos independentes do pedido
Os seguintes campos nã o sã o influenciados por flags e devem sempre ser preenchidos com os valores corretos: obj,
buf , len, itemsize, ndim.
apenas em formato
PyBUF_WRITABLE
Controla o campo readonly . Se configurado, o exportador DEVE fornecer um buffer gravá vel
ou entã o relatar falha. Do contrá rio, o exportador PODE fornecer um buffer somente leitura ou um
buffer gravá vel , mas a escolha DEVE ser consistente para todos os consumidores. Por exemplo,
PyBUF_SIMPLE | PyBUF_WRITABLE pode ser usado para requisitar um buffer simples gravá vel.
PyBUF_FORMAT
Controla o campo format. Se configurado, este campo DEVE ser preenchido corretamente. Caso
contrá rio, este campo DEVE ser NULL.
:PyBUF_WRITABLE pode ser |’d para qualquer um dos sinalizadores na pró xima seçã o. Uma vez que
PyBUF_WRITABLE é definido como 0, PyBUF_WRITABLE pode ser usado como uma bandeira autô noma para soli-
citar um buffer simples gravá vel.
PyBUF_FORMAT deve ser |’d para qualquer um dos sinalizadores exceto PyBUF_SIMPLE, uma vez que este já indica
que o formato B (unsigned bytes). PyBUF_FORMAT nã o pode ser utilizado sozinho.
forma, avanços, suboffsets
As bandeiras que controlam a estrutura ló gica da memó ria estã o listadas em ordem decrescente de complexidade.
Observe que cada bandeira conté m todos os bits das bandeiras abaixo.
7.7. Protocolo de Buffer 121
The Python/C API, Release 3.13.7
Solicitação Forma Avanços subconjuntos
sim sim se necessá rio
PyBUF_INDIRECT
sim sim NULL
PyBUF_STRIDES
sim NULL NULL
PyBUF_ND
NULL NULL NULL
PyBUF_SIMPLE
requisições contíguas
contiguity do C ou Fortran podem ser explicitamente solicitadas, com ou sem informaçã o de avanço. Sem informaçã o
de avanço, o buffer deve ser C-contíguo.
Solicitação Forma Avanços subconjuntos contig
sim sim NULL C
PyBUF_C_CONTIGUOUS
sim sim NULL F
PyBUF_F_CONTIGUOUS
sim sim NULL C ou F
PyBUF_ANY_CONTIGUOUS
PyBUF_ND sim NULL NULL C
requisições compostas
Todas as requisiçõ es possíveis foram completamente definidas por alguma combinaçã o dos sinalizadores na seçã o
anterior. Por conveniê ncia, o protocolo do buffer fornece combinaçõ es frequentemente utilizadas como sinalizadores
ú nicos.
Na seguinte tabela U significa contiguidade indefinida. O consumidor deve chamar PyBuffer_IsContiguous()
para determinar a contiguidade.
122 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
Solicitação Forma Avanços subconjuntos contig readonly format
sim sim se necessá rio U 0 sim
PyBUF_FULL
sim sim se necessá rio U 1 ou 0 sim
PyBUF_FULL_RO
sim sim NULL U 0 sim
PyBUF_RECORDS
sim sim NULL U 1 ou 0 sim
PyBUF_RECORDS_RO
sim sim NULL U 0 NULL
PyBUF_STRIDED
sim sim NULL U 1 ou 0 NULL
PyBUF_STRIDED_RO
sim NULL NULL C 0 NULL
PyBUF_CONTIG
sim NULL NULL C 1 ou 0 NULL
PyBUF_CONTIG_RO
7.7.3 Vetores Complexos
Estilo NumPy: forma e avanços
A estrutura ló gica de vetores do estilo NumPy é definida por itemsize, ndim, shape e strides.
Se ndim == 0, a localizaçã o da memó ria apontada para buf é interpretada como um escalar de tamanho itemsize.
Nesse caso, ambos shape e strides sã o NULL.
Se strides é NULL, o vetor é interpretado como um vetor C n-dimensional padrã o. Caso contrá rio, o consumidor
deve acessar um vetor n-dimensional como a seguir:
ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];
item = *((typeof(item) *)ptr);
Como notado acima, buf pode apontar para qualquer localizaçã o dentro do bloco de memó ria em si. Um exportador
pode verificar a validade de um buffer com essa funçã o:
def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
"""Verifica se os parâmetros representa um vetor válido dentro
dos limites da memória alocada:
char *mem: início do bloco de memória física
memlen: comprimento do bloco de memória física
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
(continua na pró xima pá gina)
7.7. Protocolo de Buffer 123
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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, avanços e suboffsets
Alé m dos itens normais, uma matriz em estilo PIL pode conter ponteiros que devem ser seguidos para se obter o
pró ximo elemento em uma dimensã o. Por exemplo, a matriz tridimensional em C char v[2][2][3] també m
pode ser vista como um vetor de 2 ponteiros para duas matrizes bidimensionais: char (*v[2])[2][3]. Na repre-
sentaçã o por suboffsets, esses dois ponteiros podem ser embutidos no início de buf , apontando para duas matrizes
char x[2][3] que podem estar localizadas em qualquer lugar na memó ria.
Esta é uma funçã o que retorna um ponteiro para o elemento em uma matriz N-D apontada por um índice N-
-dimensional onde existem ambos passos e subconjuntos nã o-NULL:
void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
Py_ssize_t *suboffsets, Py_ssize_t *indices) {
char *pointer = (char*)buf;
int i;
for (i = 0; i < ndim; i++) {
pointer += strides[i] * indices[i];
if (suboffsets[i] >=0 ) {
pointer = *((char**)pointer) + suboffsets[i];
}
}
return (void*)pointer;
}
7.7.4 Funções relacionadas ao Buffer
int PyObject_CheckBuffer(PyObject *obj)
Parte da ABI Está vel desde a versão 3.11. Retorna 1 se obj oferece suporte à interface de buffer, se nã o, 0.
Quando 1 é retornado, isso nã o garante que PyObject_GetBuffer() será bem sucedida. Esta funçã o é
sempre bem sucedida.
int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags)
Parte da ABI Está vel desde a versão 3.11. Envia uma requisiçã o ao exporter para preencher a view conforme
especificado por flags. Se o exporter nã o conseguir prover um buffer do tipo especificado, ele DEVE levantar
BufferError, definir view->obj para NULL e retornar -1.
Em caso de sucesso, preenche view, define view->obj para uma nova referê ncia para exporter e retorna 0.
No caso de provedores de buffer encadeados que redirecionam requisiçõ es para um ú nico objeto, view->obj
DEVE se referir a este objeto em vez de exporter (Veja Buffer Object Structures).
Chamadas bem sucedidas para PyObject_GetBuffer() devem ser emparelhadas a chamadas para
PyBuffer_Release(), similar para malloc() e free(). Assim, apó s o consumidor terminar com o buf-
fer, PyBuffer_Release() deve ser chamado exatamente uma vez.
void PyBuffer_Release(Py_buffer *view)
Parte da ABI Está vel desde a versão 3.11. Libera o buffer de view e libera o strong reference (por exemplo,
124 Capítulo 7. Camada de Objetos Abstratos
The Python/C API, Release 3.13.7
decrementa o contador de referê ncias) para o objeto de suporte da view, view->obj. Esta funçã o DEVE ser
chamada quando o buffer nã o estiver mais sendo usado, ou o vazamento de referê ncias pode acontecer.
É um erro chamar essa funçã o em um buffer que nã o foi obtido via PyObject_GetBuffer().
Py_ssize_t PyBuffer_SizeFromFormat(const char *format)
Parte da ABI Está vel desde a versão 3.11. Retorna o itemsize implícito de format. Em erro, levantar e
exceçã o e retornar -1.
Adicionado na versã o 3.9.
int PyBuffer_IsContiguous(const Py_buffer *view, char order)
Parte da ABI Está vel desde a versão 3.11. Retorna 1 se a memó ria definida pela view é contígua no estilo C
(order é 'C') ou no estilo Fortran (order é 'F') ou qualquer outra (order é 'A'). Retorna 0 caso contrá rio.
Essa funçã o é sempre bem sucedida.
void *PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices)
Parte da ABI Está vel desde a versão 3.11. Recebe a á rea de memó ria apontada pelos indices dentro da view
dada. indices deve apontar para um array de view->ndim índices.
int PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
Parte da ABI Está vel desde a versão 3.11. Copia len bytes contíguos de buf para view. fort pode ser 'C' ou
'F' (para ordenaçã o estilo C ou estilo Fortran). Retorna 0 em caso de sucesso e -1 em caso de erro.
int PyBuffer_ToContiguous(void *buf, const Py_buffer *src, Py_ssize_t len, char order)
Parte da ABI Está vel desde a versão 3.11. Copia len bytes de src para sua representaçã o contígua em buf.
order pode ser 'C' ou 'F' ou 'A' (para ordenaçã o estilo C, Fortran ou qualquer uma). O retorno é 0 em caso
de sucesso e -1 em caso de falha.
Esta funçã o falha se len != src->len.
int PyObject_CopyData(PyObject *dest, PyObject *src)
Parte da ABI Está vel desde a versão 3.11. Copia os dados do buffer src para o buffer dest. Pode converter
entre buffers de estilo C e/ou estilo Fortran.
0 é retornado em caso de sucesso, -1 em caso de erro.
void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char
order)
Parte da ABI Está vel desde a versão 3.11. Preenche o array strides com byte-strides de um array contíguo
(estilo C se order é 'C' ou estilo Fortran se order for 'F') da forma dada com o 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)
Parte da ABI Está vel desde a versão 3.11. Manipula requisiçõ es de buffer para um exportador que quer expor
buf de tamanho len com capacidade de escrita definida de acordo com readonly. buf é interpretada como uma
sequê ncia de bytes sem sinal.
O argumento flags indica o tipo de requisiçã o. Esta funçã o sempre preenche view como especificado por flags,
a nã o ser que buf seja designado como somente leitura e PyBUF_WRITABLE esteja definido em flags.
Em caso de sucesso, defina view->obj como um novo referê ncia para exporter e retorna 0. Caso contrá rio,
levante BufferError , defina view->obj para NULL e retorne -1 ;
Se esta funçã o é usada como parte de um getbufferproc, exporter DEVE ser definida para o objeto de exportaçã o
e flags deve ser passado sem modificaçõ es. Caso contrá rio, exporter DEVE ser NULL.
7.7. Protocolo de Buffer 125
The Python/C API, Release 3.13.7
126 Capítulo 7. Camada de Objetos Abstratos
CAPÍTULO 8
Camada de Objetos Concretos
As funçõ es neste capítulo sã o específicas para certos tipos de objetos Python. Passar para eles um objeto do tipo
errado nã o é uma boa ideia; se você receber um objeto de um programa Python e nã o tiver certeza de que ele tem o
tipo certo, primeiro execute uma verificaçã o de tipo; por exemplo, para verificar se um objeto é um dicioná rio, use
PyDict_Check(). O capítulo está estruturado como a “á rvore genealó gica” dos tipos de objetos Python.
Á Aviso
Enquanto as funçõ es descritas neste capítulo verificam cuidadosamente o tipo de objetos passados, muitos deles
nã o verificam a passagem de NULL em vez de um objeto vá lido. Permitir a passagem de NULL pode causar
violaçõ es ao acesso à memó ria e encerramento imediato do interpretador.
8.1 Objetos Fundamentais
Esta seçã o descreve os objetos de tipo Python e o objeto singleton None.
8.1.1 Objetos tipo
type PyTypeObject
Parte da API Limitada (como uma estrutura opaca). A estrutura C dos objetos usados para descrever tipos
embutidos.
PyTypeObject PyType_Type
Parte da ABI Está vel. Este é o objeto de tipo para objetos tipo; é o mesmo objeto que type na camada Python.
int PyType_Check(PyObject *o)
Retorna valor diferente de zero se o objeto o for um objeto tipo, incluindo instâ ncias de tipos derivados do
objeto tipo padrã o. Retorna 0 em todos os outros casos. Esta funçã o sempre tem sucesso.
int PyType_CheckExact(PyObject *o)
Retorna valor diferente de zero se o objeto o for um objeto tipo, mas nã o um subtipo do objeto tipo padrã o.
Retorna 0 em todos os outros casos. Esta funçã o sempre tem sucesso.
unsigned int PyType_ClearCache()
Parte da ABI Está vel. Limpa o cache de pesquisa interno. Retorna a marcaçã o de versã o atual.
127
The Python/C API, Release 3.13.7
unsigned long PyType_GetFlags(PyTypeObject *type)
Parte da ABI Está vel. 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.
Adicionado na versã o 3.2.
Alterado na versã o 3.4: O tipo de retorno é agora um unsigned long em vez de um long.
PyObject *PyType_GetDict(PyTypeObject *type)
Return the type object’s internal namespace, which is otherwise only exposed via a read-only proxy (cls.
__dict__). This is a replacement for accessing tp_dict directly. The returned dictionary must be treated
as read-only.
This function is meant for specific embedding and language-binding cases, where direct access to the dict is
necessary and indirect access (e.g. via the proxy or PyObject_GetAttr()) isn’t adequate.
Extension modules should continue to use tp_dict, directly or indirectly, when setting up their own types.
Adicionado na versã o 3.12.
void PyType_Modified(PyTypeObject *type)
Parte da ABI Está vel. Invalida o cache de pesquisa interna para o tipo e todos os seus subtipos. Esta funçã o
deve ser chamada apó s qualquer modificaçã o manual dos atributos ou classes bases do 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.
In free-threaded builds, PyType_AddWatcher() is not thread-safe, so it must be called at start up (before
spawning the first thread).
Adicionado na versã o 3.12.
int PyType_ClearWatcher(int watcher_id)
Clear watcher identified by watcher_id (previously returned from PyType_AddWatcher()). Return 0 on
success, -1 on error (e.g. if watcher_id was never registered.)
An extension should never call PyType_ClearWatcher with a watcher_id that was not returned to it by a
previous call to PyType_AddWatcher().
Adicionado na versã o 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().
Adicionado na versã o 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.
Adicionado na versã o 3.12.
int PyType_HasFeature(PyTypeObject *o, int feature)
Retorna valor diferente de zero se o objeto tipo o define o recurso feature. Os recursos de tipo sã o denotados
por sinalizadores de bit ú nico.
128 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
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)
Parte da ABI Está vel. Retorna verdadeiro se a for um subtipo de b.
This function only checks for actual subtypes, which means that __subclasscheck__() is not called on b.
Call PyObject_IsSubclass() to do the same check that issubclass() would do.
PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Retorna valor: Nova referência. Parte da ABI Está vel. Manipulador gené rico para o slot tp_alloc de um
objeto tipo. Use o mecanismo de alocaçã o de memó ria padrã o do Python para alocar uma nova instâ ncia e
inicializar todo o seu conteú do para NULL.
PyObject *PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
Retorna valor: Nova referência. Parte da ABI Está vel. Manipulador gené rico para o slot tp_new de um objeto
tipo. Cria uma nova instâ ncia usando o slot tp_alloc do tipo.
int PyType_Ready(PyTypeObject *type)
Parte da ABI Está vel. Finaliza um objeto tipo. Isso deve ser chamado em todos os objetos tipo para finalizar
sua inicializaçã o. Esta funçã o é responsá vel por adicionar slots herdados da classe base de um tipo. Retorna 0
em caso de sucesso, ou retorna -1 e define uma exceçã o em caso de erro.
® 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 implement the GC protocol itself by at least implementing the tp_traverse handle.
PyObject *PyType_GetName(PyTypeObject *type)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.11. Return the type’s name. Equivalent
to getting the type’s __name__ attribute.
Adicionado na versã o 3.11.
PyObject *PyType_GetQualName(PyTypeObject *type)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.11. Return the type’s qualified name.
Equivalent to getting the type’s __qualname__ attribute.
Adicionado na versã o 3.11.
PyObject *PyType_GetFullyQualifiedName(PyTypeObject *type)
Parte da ABI Está vel desde a versão 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".
Adicionado na versã o 3.13.
PyObject *PyType_GetModuleName(PyTypeObject *type)
Parte da ABI Está vel desde a versão 3.13. Return the type’s module name. Equivalent to getting the type.
__module__ attribute.
Adicionado na versã o 3.13.
void *PyType_GetSlot(PyTypeObject *type, int slot)
Parte da ABI Está vel desde a versão 3.4. Retorna o ponteiro de funçã o armazenado no slot fornecido. Se o
resultado for NULL, isso indica que o slot é NULL ou que a funçã o foi chamada com parâ metros invá lidos. Os
chamadores normalmente lançarã o o ponteiro do resultado no tipo de funçã o apropriado.
Veja PyType_Slot.slot por possíveis valores do argumento slot.
8.1. Objetos Fundamentais 129
The Python/C API, Release 3.13.7
Adicionado na versã o 3.4.
Alterado na versã o 3.10: PyType_GetSlot() can now accept all types. Previously, it was limited to heap
types.
PyObject *PyType_GetModule(PyTypeObject *type)
Parte da ABI Está vel desde a versão 3.10. Retorna o objeto de mó dulo associado ao tipo fornecido quando o
tipo foi criado usando PyType_FromModuleAndSpec().
Se nenhum mó dulo estiver associado com o tipo fornecido, define TypeError e 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.
Adicionado na versã o 3.9.
void *PyType_GetModuleState(PyTypeObject *type)
Parte da ABI Está vel desde a versão 3.10. Return the state of the module object associated with the given
type. This is a shortcut for calling PyModule_GetState() on the result of PyType_GetModule().
Se nenhum mó dulo estiver associado com o tipo fornecido, define TypeError e retorna NULL.
If the type has an associated module but its state is NULL, returns NULL without setting an exception.
Adicionado na versã o 3.9.
PyObject *PyType_GetModuleByDef(PyTypeObject *type, struct PyModuleDef *def)
Retorna valor: Referência emprestada. Parte da ABI Está vel desde a versão 3.13. Find the first superclass
whose module was created from the given PyModuleDef def, and return that module.
If no module is found, raises a TypeError and returns NULL.
This function is intended to be used together with PyModule_GetState() to get module state from slot
methods (such as tp_init or nb_add) and other places where a method’s defining class cannot be passed
using the PyCMethod calling convention.
The returned reference is borrowed from type, and will be valid as long as you hold a reference to type. Do not
release it with Py_DECREF() or similar.
Adicionado na versã o 3.11.
int PyUnstable_Type_AssignVersionTag(PyTypeObject *type)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
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.
Adicionado na versã o 3.12.
Creating Heap-Allocated Types
The following functions and structs are used to create heap types.
PyObject *PyType_FromMetaclass(PyTypeObject *metaclass, PyObject *module, PyType_Spec *spec, PyObject
*bases)
Parte da ABI Está vel desde a versão 3.12. Create and return a heap type from the spec (see
Py_TPFLAGS_HEAPTYPE).
130 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
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.)
The bases argument can be used to specify base classes; it can either be only one class or a tuple of classes. If
bases is NULL, the Py_tp_bases slot is used instead. If that also is NULL, the Py_tp_base slot is used instead. If
that also is NULL, the new type derives from object.
The module argument can be used to record the module in which the new class is defined. It must be a
module object or NULL. If not NULL, the module is associated with the new type and can later be retrieved
with PyType_GetModule(). The associated module is not inherited by subclasses; it must be specified for
each class individually.
This function calls PyType_Ready() on the new type.
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.
Adicionado na versã o 3.12.
PyObject *PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.10. Equivalent to
PyType_FromMetaclass(NULL, module, spec, bases).
Adicionado na versã o 3.9.
Alterado na versã o 3.10: The function now accepts a single class as the bases argument and NULL as the
tp_doc slot.
Alterado na versã o 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)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.3. Equivalent to
PyType_FromMetaclass(NULL, NULL, spec, bases).
Adicionado na versã o 3.3.
Alterado na versã o 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Equivalent to PyType_FromMetaclass(NULL,
NULL, spec, NULL).
Alterado na versã o 3.12: The function now finds and uses a metaclass corresponding to the base classes pro-
vided 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.
8.1. Objetos Fundamentais 131
The Python/C API, Release 3.13.7
type PyType_Spec
Parte da ABI Está vel (incluindo todos os membros). Structure defining a type’s behavior.
const char *name
Name of the type, used to set PyTypeObject.tp_name.
int basicsize
If positive, specifies the size of the instance in bytes. It is used to set PyTypeObject.tp_basicsize.
If zero, specifies that tp_basicsize should be inherited.
If negative, the absolute value specifies how much space instances of the class need in addition to the
superclass. Use PyObject_GetTypeData() to get a pointer to subclass-specific memory reserved
this way. For negative basicsize, Python will insert padding when needed to meet tp_basicsize’s
alignment requirements.
Alterado na versã o 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
Type flags, used to set PyTypeObject.tp_flags.
If the Py_TPFLAGS_HEAPTYPE flag is not set, PyType_FromSpecWithBases() sets it automatically.
PyType_Slot *slots
Array of PyType_Slot structures. Terminated by the special slot value {0, NULL}.
Each slot ID should be specified at most once.
type PyType_Slot
Parte da ABI Está vel (incluindo todos os membros). Structure defining optional functionality of a type, con-
taining a slot ID and a value pointer.
int slot
A slot ID.
Slot IDs are named like the field names of the structures PyTypeObject, PyNumberMethods,
PySequenceMethods, PyMappingMethods and PyAsyncMethods with an added Py_ prefix. For
example, use:
• Py_tp_dealloc to set PyTypeObject.tp_dealloc
• Py_nb_add to set PyNumberMethods.nb_add
• Py_sq_length to set PySequenceMethods.sq_length
The following “offset” fields cannot be set using PyType_Slot:
• tp_weaklistoffset (use Py_TPFLAGS_MANAGED_WEAKREF instead if possible)
• tp_dictoffset (use Py_TPFLAGS_MANAGED_DICT instead if possible)
132 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
• tp_vectorcall_offset (use "__vectorcalloffset__" in PyMemberDef)
If it is not possible to switch to a MANAGED flag (for example, for vectorcall or to support Python older
than 3.12), specify the offset in Py_tp_members. See 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.
Alterado na versã o 3.9: Slots in PyBufferProcs may be set in the unlimited API.
Alterado na versã o 3.11: bf_getbuffer and bf_releasebuffer are now available under the limited
API.
void *pfunc
The desired value of the slot. In most cases, this is a pointer to a function.
Slots other than Py_tp_doc may not be NULL.
8.1.2 O Objeto None
Observe que o PyTypeObject para None nã o está diretamente exposto pela API Python/C. Como None é um
singleton, é suficiente testar a identidade do objeto (usando == em C). Nã o há nenhuma funçã o PyNone_Check()
pela mesma razã o.
PyObject *Py_None
O objeto Python None, denotando falta de valor. Este objeto nã o tem mé todos e é imortal.
Alterado na versã o 3.12: Py_None é imortal.
Py_RETURN_NONE
Retorna Py_None de uma funçã o.
8.2 Objetos Numéricos
8.2.1 Objetos Inteiros
Todos os inteiros sã o implementados como objetos inteiros “longos” de tamanho arbitrá rio.
Em caso de erro, a maioria das APIs PyLong_As* retorna (tipo de retorno)-1 que nã o pode ser distinguido
de um nú mero. Use PyErr_Occurred() para desambiguar.
type PyLongObject
Parte da API Limitada (como uma estrutura opaca). Este subtipo de PyObject representa um objeto inteiro
Python.
PyTypeObject PyLong_Type
Parte da ABI Está vel. Esta instâ ncia de PyTypeObject representa o tipo inteiro Python. Este é o mesmo
objeto que int na camada Python.
int PyLong_Check(PyObject *p)
Retorna true se seu argumento é um PyLongObject ou um subtipo de PyLongObject. Esta funçã o sempre
tem sucesso.
int PyLong_CheckExact(PyObject *p)
Retorna true se seu argumento é um PyLongObject, mas nã o um subtipo de PyLongObject. Esta funçã o
sempre tem sucesso.
8.2. Objetos Numéricos 133
The Python/C API, Release 3.13.7
PyObject *PyLong_FromLong(long v)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto PyLongObject de v ou NULL
em caso de falha.
A implementaçã o atual manté m um vetor de objetos inteiros para todos os inteiros entre -5 e 256. Quando
você cria um int nesse intervalo, você na verdade apenas obté m uma referê ncia ao objeto existente.
PyObject *PyLong_FromUnsignedLong(unsigned long v)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto PyLongObject de um
unsigned long C ou NULL em caso de falha.
PyObject *PyLong_FromSsize_t(Py_ssize_t v)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto PyLongObject de um
Py_ssize_t C ou NULL em caso de falha.
PyObject *PyLong_FromSize_t(size_t v)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto PyLongObject de um
size_t C ou NULL em caso de falha.
PyObject *PyLong_FromLongLong(long long v)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto PyLongObject de um long
long C ou NULL em caso de falha.
PyObject *PyLong_FromUnsignedLongLong(unsigned long long v)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto PyLongObject de um
unsigned long long C ou NULL em caso de falha.
PyObject *PyLong_FromDouble(double v)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto PyLongObject da parte
inteira de v ou NULL em caso de falha.
PyObject *PyLong_FromString(const char *str, char **pend, int base)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo PyLongObject com base no valor
da string em str, que é interpretado de acordo com a raiz em base ou NULL em caso de falha. Se pend nã o for
NULL, *pend apontará para o fim do str em caso de sucesso ou para seu primeiro caractere que nã o pode ser
processado em caso de erro. Se base for 0, str é interpretado usando a definiçã o de integers; neste caso, zeros
à esquerda em um nú mero decimal diferente de zero aumenta um ValueError. Se base nã o for 0, deve estar
entre 2 e 36, inclusive. Espaços em branco no início ou no final e sublinhados simples apó s um especificador
de base e entre dígitos sã o ignorados. Se nã o houver dígitos ou str nã o for terminado em NULL apó s os dígitos
e espaços em branco à direita, ValueError será levantada.
µ Ver também
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)
Retorna valor: Nova referência. Converte uma sequê ncia de dígitos Unicode na string u para um valor inteiro
Python.
Adicionado na versã o 3.3.
PyObject *PyLong_FromVoidPtr(void *p)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um inteiro Python a partir do ponteiro p. O valor
do ponteiro pode ser recuperado do valor resultante usando PyLong_AsVoidPtr().
PyObject *PyLong_FromNativeBytes(const void *buffer, size_t n_bytes, int flags)
Create a Python integer from the value contained in the first n_bytes of buffer, interpreted as a two’s-
-complement signed number.
134 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
flags are as for PyLong_AsNativeBytes(). Passing -1 will select the native endian that
CPython was compiled with and assume that the most-significant bit is a sign bit. Pas-
sing Py_ASNATIVEBYTES_UNSIGNED_BUFFER will produce the same result as calling
PyLong_FromUnsignedNativeBytes(). Other flags are ignored.
Adicionado na versã o 3.13.
PyObject *PyLong_FromUnsignedNativeBytes(const void *buffer, size_t n_bytes, int flags)
Create a Python integer from the value contained in the first n_bytes of buffer, interpreted as an unsigned
number.
flags are as for PyLong_AsNativeBytes(). Passing -1 will select the native endian that CPython was
compiled with and assume that the most-significant bit is not a sign bit. Flags other than endian are ignored.
Adicionado na versã o 3.13.
long PyLong_AsLong(PyObject *obj)
Parte da ABI Está vel. 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 no caso de erro. Use PyErr_Occurred() para desambiguar.
Alterado na versã o 3.8: Usa __index__(), se disponível.
Alterado na versã o 3.10: This function will no longer use __int__().
long PyLong_AS_LONG(PyObject *obj)
A soft deprecated alias. Exactly equivalent to the preferred PyLong_AsLong. In particular, it can fail
with OverflowError or another exception.
Descontinuado desde a versã o 3.14: The function is soft deprecated.
int PyLong_AsInt(PyObject *obj)
Parte da ABI Está vel desde a versão 3.13. Similar to PyLong_AsLong(), but store the result in a C int
instead of a C long.
Adicionado na versã o 3.13.
long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow)
Parte da ABI Está vel. 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 no caso de erro. Use PyErr_Occurred() para desambiguar.
Alterado na versã o 3.8: Usa __index__(), se disponível.
Alterado na versã o 3.10: This function will no longer use __int__().
long long PyLong_AsLongLong(PyObject *obj)
Parte da ABI Está vel. 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 no caso de erro. Use PyErr_Occurred() para desambiguar.
Alterado na versã o 3.8: Usa __index__(), se disponível.
Alterado na versã o 3.10: This function will no longer use __int__().
8.2. Objetos Numéricos 135
The Python/C API, Release 3.13.7
long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)
Parte da ABI Está vel. 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 no caso de erro. Use PyErr_Occurred() para desambiguar.
Adicionado na versã o 3.2.
Alterado na versã o 3.8: Usa __index__(), se disponível.
Alterado na versã o 3.10: This function will no longer use __int__().
Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
Parte da ABI Está vel. Retorna uma representaçã o de Py_ssize_t C de pylong. pylong deve ser uma instâ ncia
de PyLongObject.
Levanta OverflowError se o valor de pylong estiver fora do intervalo de um Py_ssize_t.
Retorna -1 no caso de erro. Use PyErr_Occurred() para desambiguar.
unsigned long PyLong_AsUnsignedLong(PyObject *pylong)
Parte da ABI Está vel. 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 no caso de erro. Use PyErr_Occurred() para desambiguar.
size_t PyLong_AsSize_t(PyObject *pylong)
Parte da ABI Está vel. Retorna uma representaçã o de size_t C de pylong. pylong deve ser uma instâ ncia de
PyLongObject.
Levanta OverflowError se o valor de pylong estiver fora do intervalo de um size_t.
Retorna (size)-1 no caso de erro. Use PyErr_Occurred() para desambiguar.
unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)
Parte da ABI Está vel. 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 no caso de erro. Use PyErr_Occurred() para desambiguar.
Alterado na versã o 3.1: Um pylong negativo agora levanta OverflowError, nã o TypeError.
unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)
Parte da ABI Está vel. 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 no caso de erro. Use PyErr_Occurred() para desambiguar.
Alterado na versã o 3.8: Usa __index__(), se disponível.
Alterado na versã o 3.10: This function will no longer use __int__().
unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj)
Parte da ABI Está vel. 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.
136 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Retorna (unsigned long long)-1 no caso de erro. Use PyErr_Occurred() para desambiguar.
Alterado na versã o 3.8: Usa __index__(), se disponível.
Alterado na versã o 3.10: This function will no longer use __int__().
double PyLong_AsDouble(PyObject *pylong)
Parte da ABI Está vel. 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 no caso de erro. Use PyErr_Occurred() para desambiguar.
void *PyLong_AsVoidPtr(PyObject *pylong)
Parte da ABI Está vel. 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 no caso de erro. Use PyErr_Occurred() para desambiguar.
Py_ssize_t PyLong_AsNativeBytes(PyObject *pylong, void *buffer, Py_ssize_t n_bytes, int flags)
Copy the Python integer value pylong to a native buffer of size n_bytes. The flags can be set to -1 to behave
similarly to a C cast, or to values documented below to control the behavior.
Returns -1 with an exception raised on error. This may happen if pylong cannot be interpreted as an integer,
or if pylong was negative and the Py_ASNATIVEBYTES_REJECT_NEGATIVE flag was set.
Otherwise, returns the number of bytes required to store the value. If this is equal to or less than n_bytes, the
entire value was copied. All n_bytes of the buffer are written: large buffers are padded with zeroes.
If the returned value is greater than n_bytes, the value was truncated: as many of the lowest bits of the value as
could fit are written, and the higher bits are ignored. This matches the typical behavior of a C-style downcast.
® Nota
Overflow is not considered an error. If the returned value is larger than n_bytes, most significant bits were
discarded.
0 will never be returned.
Values are always copied as two’s-complement.
Usage example:
int32_t value;
Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, &value, sizeof(value), -1);
if (bytes < 0) {
// Failed. A Python exception was set with the reason.
return NULL;
}
else if (bytes <= (Py_ssize_t)sizeof(value)) {
// Success!
}
else {
// Overflow occurred, but 'value' contains the truncated
// lowest bits of pylong.
}
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. If n_bytes=0, buffer may be NULL.
8.2. Objetos Numéricos 137
The Python/C API, Release 3.13.7
® Nota
Passing n_bytes=0 to this function is not an accurate way to determine the bit length of the value.
To get at the entire Python value of an unknown size, the function can be called twice: first to determine the
buffer size, then to fill it:
// Ask how much space we need.
Py_ssize_t expected = PyLong_AsNativeBytes(pylong, NULL, 0, -1);
if (expected < 0) {
// Failed. 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_AsNativeBytes(pylong, bignum, expected, -1);
if (bytes < 0) { // Exception has been set.
free(bignum);
return NULL;
}
else if (bytes > expected) { // This 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);
flags is either -1 (Py_ASNATIVEBYTES_DEFAULTS) to select defaults that behave most like a C cast, or a
combination of the other flags in the table below. Note that -1 cannot be combined with other flags.
Currently, -1 corresponds to Py_ASNATIVEBYTES_NATIVE_ENDIAN |
Py_ASNATIVEBYTES_UNSIGNED_BUFFER.
138 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Sinalizador Valor
-1
Py_ASNATIVEBYTES_DEFAULTS
0
Py_ASNATIVEBYTES_BIG_ENDIAN
1
Py_ASNATIVEBYTES_LITTLE_ENDIAN
3
Py_ASNATIVEBYTES_NATIVE_ENDIAN
4
Py_ASNATIVEBYTES_UNSIGNED_BUFFER
8
Py_ASNATIVEBYTES_REJECT_NEGATIVE
16
Py_ASNATIVEBYTES_ALLOW_INDEX
Specifying Py_ASNATIVEBYTES_NATIVE_ENDIAN will override any other endian flags. Passing 2 is reserved.
By default, sufficient buffer will be requested to include a sign bit. For example, when converting 128 with
n_bytes=1, the function will return 2 (or more) in order to store a zero sign bit.
If Py_ASNATIVEBYTES_UNSIGNED_BUFFER is specified, a zero sign bit will be omitted from size calcula-
tions. This allows, for example, 128 to fit in a single-byte buffer. If the destination buffer is later treated as
signed, a positive input value may become negative. Note that the flag does not affect handling of negative
values: for those, space for a sign bit is always requested.
Specifying Py_ASNATIVEBYTES_REJECT_NEGATIVE causes an exception to be set if pylong is negative.
Without this flag, negative values will be copied provided there is enough space for at least one sign bit, regar-
dless of whether Py_ASNATIVEBYTES_UNSIGNED_BUFFER was specified.
If Py_ASNATIVEBYTES_ALLOW_INDEX is specified and a non-integer value is passed, its __index__()
method will be called first. This may result in Python code executing and other threads being allowed to run,
which could cause changes to other objects or values in use. When flags is -1, this option is not set, and
non-integer values will raise TypeError.
® Nota
With the default flags (-1, or UNSIGNED_BUFFER without REJECT_NEGATIVE), multiple Python inte-
gers can map to a single value without overflow. For example, both 255 and -1 fit a single-byte buffer and
set all its bits. This matches typical C cast behavior.
Adicionado na versã o 3.13.
PyObject *PyLong_GetInfo(void)
Parte da ABI Está vel. On success, return a read only named tuple, that holds information about Python’s
internal representation of integers. See sys.int_info for description of individual fields.
Em caso de falha, retorna NULL com uma exceçã o definida.
Adicionado na versã o 3.1.
8.2. Objetos Numéricos 139
The Python/C API, Release 3.13.7
int PyUnstable_Long_IsCompact(const PyLongObject *op)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
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.
Adicionado na versã o 3.12.
Py_ssize_t PyUnstable_Long_CompactValue(const PyLongObject *op)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
If op is compact, as determined by PyUnstable_Long_IsCompact(), return its value.
Otherwise, the return value is undefined.
Adicionado na versã o 3.12.
8.2.2 Objetos Booleanos
Os booleanos no Python sã o implementados como um subclasse de inteiros. Há apenas dois booleanos, Py_False
e Py_True. Assim sendo, as funçõ es de criaçã o e a exclusã o normais nã o se aplicam aos booleanos. No entanto, as
seguintes macros estã o disponíveis.
PyTypeObject PyBool_Type
Parte da ABI Está vel. Este instâ ncia de PyTypeObject representa o tipo booleano em Python; é o mesmo
objeto que bool na camada Python.
int PyBool_Check(PyObject *o)
Retorna verdadeiro se o for do tipo PyBool_Type. Esta funçã o sempre tem sucesso.
PyObject *Py_False
O objeto Python False. Este objeto nã o tem mé todos e é imortal.
Alterado na versã o 3.12: Py_False é imortal.
PyObject *Py_True
O objeto Python True. Este objeto nã o tem mé todos e é imortal.
Alterado na versã o 3.12: Py_True é imortal.
Py_RETURN_FALSE
Retorna Py_False de uma funçã o.
Py_RETURN_TRUE
Retorna Py_True de uma funçã o.
PyObject *PyBool_FromLong(long v)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna Py_True ou Py_False, dependendo do valor
verdade de v.
140 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
8.2.3 Objetos de ponto flutuante
type PyFloatObject
Este subtipo de PyObject representa um objeto de ponto flutuante do Python.
PyTypeObject PyFloat_Type
Parte da ABI Está vel. Esta instâ ncia do PyTypeObject representa o tipo de ponto flutuante do Python. Este
é o mesmo objeto float na camada do Python.
int PyFloat_Check(PyObject *p)
Retorna true se seu argumento é um PyFloatObject ou um subtipo de PyFloatObject. Esta funçã o
sempre tem sucesso.
int PyFloat_CheckExact(PyObject *p)
Retorna true se seu argumento é um PyFloatObject, mas um subtipo de PyFloatObject. Esta funçã o
sempre tem sucesso.
PyObject *PyFloat_FromString(PyObject *str)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um objeto PyFloatObject baseado em uma
string de valor “str” ou NULL em falha.
PyObject *PyFloat_FromDouble(double v)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um objeto PyFloatObject de v ou NULL em
falha.
double PyFloat_AsDouble(PyObject *pyfloat)
Parte da ABI Está vel. Retorna uma representaçã o C double do conteú do de pyfloat. Se pyfloat nã o é
um objeto de ponto flutuante do Python, mas possui o mé todo __float__(), esse mé todo será chamado
primeiro para converter pyfloat em um ponto flutuante. Se __float__() nã o estiver definido, será usado
__index__(). Este mé todo retorna -1.0 em caso de falha, portanto, deve-se chamar PyErr_Occurred()
para verificar se há erros.
Alterado na versã o 3.8: Usa __index__(), se disponível.
double PyFloat_AS_DOUBLE(PyObject *pyfloat)
Retorna uma representaçã o C double do conteú do de pyfloat, mas sem verificaçã o de erro.
PyObject *PyFloat_GetInfo(void)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna uma instâ ncia de structseq que conté m infor-
maçõ es sobre a precisã o, os valores mínimo e má ximo de um ponto flutuante. É um invó lucro fino em torno
do arquivo de cabeçalho float.h.
double PyFloat_GetMax()
Parte da ABI Está vel. Retorna o ponto flutuante finito má ximo representá vel DBL_MAX como double do C.
double PyFloat_GetMin()
Parte da ABI Está vel. Retorna o ponto flutuante positivo mínimo normalizado DBL_MIN como double do
C.
As funções Pack e Unpack
As funçõ es de empacotamento e desempacotamento, pack e unpack respectivamente, fornecem uma maneira efi-
ciente e independente de plataforma de armazenar valores de ponto flutuante como strings de bytes. As rotinas de
Pack produzem uma string de bytes a partir de um C double, e as rotinas de Unpack produzem um C double a
partir dessa string de bytes. O sufixo (2, 4 ou 8) especifica o nú mero de bytes na string de bytes.
Em plataformas que parecem usar o formato IEEE 754, essas funçõ es funcionam copiando bits. Em outras plata-
formas, o formato de 2 bytes é idê ntico ao formato de meia precisã o biná rio 16 do IEEE 754, o formato de 4 bytes
(32 bits) é idê ntico ao formato de precisã o simples biná rio 32 do IEEE 754 e o formato de 8 bytes ao formato de
precisã o dupla biná rio 64 do IEEE 754, embora o empacotamento de INFs e NaNs (se tais recursos existirem na
plataforma) nã o seja tratado corretamente, e tentar desempacotar uma string de bytes contendo um INF ou NaN do
IEEE levantará uma exceçã o.
8.2. Objetos Numéricos 141
The Python/C API, Release 3.13.7
Em plataformas que nã o aderem IEEE com maior precisã o ou maior alcance dinâ mico do que o suportado pelo IEEE
754, nem todos os valores podem ser empacotados; em plataformas que nã o aderem IEEE com menor precisã o ou
menor alcance dinâ mico, nem todos os valores podem ser desempacotados. O que acontece nesses casos é em parte
acidental (infelizmente).
Adicionado na versã o 3.11.
Funções Pack
As rotinas de empacotamento gravam 2, 4 ou 8 bytes, começando em p. le é um argumento int, diferente de zero
se você quiser a sequê ncia de bytes no formato little-endian (expoente por ú ltimo, em p+1, p+3 ou p+6 p+7), zero
se você quiser o formato big-endian (expoente primeiro, em p). A constante PY_BIG_ENDIAN pode ser usada para
usar o endian nativo: é igual a 1 em processadores big-endian ou 0 em processadores little-endian.
Valor de retorno: 0 se tudo estiver OK, -1 se houver erro (e uma exceçã o for definida, provavelmente
OverflowError).
Existem dois problemas em plataformas nã o IEEE:
• O que isso faz é indefinido se x é um NaN ou infinito.
• -0.0 e +0.0 produzem a mesma sequê ncia de bytes.
int PyFloat_Pack2(double x, char *p, int le)
Pack a C double as the IEEE 754 binary16 half-precision format.
int PyFloat_Pack4(double x, char *p, int le)
Pack a C double as the IEEE 754 binary32 single precision format.
int PyFloat_Pack8(double x, char *p, int le)
Pack a C double as the IEEE 754 binary64 double precision format.
Funções de Unpack
As rotinas de desempacotamento leem 2, 4 ou 8 bytes, começando em p. le é um argumento int, diferente de zero
se a sequê ncia de bytes estiver no formato little-endian (expoente por ú ltimo, em p+1, p+3 ou p+6 e p+7), zero se
big-endian (expoente primeiro, em p). A constante PY_BIG_ENDIAN pode ser usada para usar o endian nativo: é
igual a 1 em processadores big-endian ou 0 em processadores little-endian.
Valor de retorno: O double descompactado. Em caso de erro, é -1.0 e PyErr_Occurred() é verdadeiro (e uma
exceçã o é definida, provavelmente OverflowError).
Observe que em uma plataforma que nã o adere IEEE isso se recusará a descompactar uma sequê ncia de bytes que
representa um NaN ou infinito.
double PyFloat_Unpack2(const char *p, int le)
Unpack the IEEE 754 binary16 half-precision format as a C double.
double PyFloat_Unpack4(const char *p, int le)
Unpack the IEEE 754 binary32 single precision format as a C double.
double PyFloat_Unpack8(const char *p, int le)
Unpack the IEEE 754 binary64 double precision format as a C double.
8.2.4 Objetos números complexos
Os objetos nú meros complexos do Python sã o implementados como dois tipos distintos quando visualizados na API
C: um é o objeto Python exposto aos programas Python e o outro é uma estrutura C que representa o valor real do
nú mero complexo. A API fornece funçõ es para trabalhar com ambos.
142 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Números complexos como estruturas C.
Observe que as funçõ es que aceitam essas estruturas como parâ metros e as retornam como resultados o fazem por
valor em vez de desreferenciá -las por meio de ponteiros. Isso é consistente em toda a API.
type Py_complex
A estrutura C que corresponde à parte do valor de um objeto de nú mero complexo Python. A maioria das
funçõ es para lidar com objetos de nú meros complexos usa estruturas desse tipo como valores de entrada ou
saída, conforme apropriado.
double real
double imag
A estrutura é definida como:
typedef struct {
double real;
double imag;
} Py_complex;
Py_complex _Py_c_sum(Py_complex left, Py_complex right)
Retorna a soma de dois nú meros complexos, utilizando a representaçã o C Py_complex.
Py_complex _Py_c_diff(Py_complex left, Py_complex right)
Retorna a diferença entre dois nú meros complexos, utilizando a representaçã o C Py_complex.
Py_complex _Py_c_neg(Py_complex num)
Retorna a negaçã o do nú mero complexo num, utilizando a representaçã o C Py_complex.
Py_complex _Py_c_prod(Py_complex left, Py_complex right)
Retorna o produto de dois nú meros complexos, utilizando a representaçã o C Py_complex.
Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor)
Retorna o quociente de dois nú meros complexos, utilizando a representaçã o C Py_complex.
Se divisor é nulo, este mé todo retorna zero e define errno para EDOM.
Py_complex _Py_c_pow(Py_complex num, Py_complex exp)
Retorna a exponenciaçã o de num por exp, utilizando a representaçã o C Py_complex
Se num for nulo e exp nã o for um nú mero real positivo, este mé todo retorna zero e define errno para EDOM.
Números complexos como objetos Python
type PyComplexObject
Este subtipo de PyObject representa um objeto Python de nú mero complexo.
PyTypeObject PyComplex_Type
Parte da ABI Está vel. Esta instâ ncia de PyTypeObject representa o tipo de nú mero complexo Python. É o
mesmo objeto que complex na camada Python.
int PyComplex_Check(PyObject *p)
Retorna true se seu argumento é um PyComplexObject ou um subtipo de PyComplexObject. Esta funçã o
sempre tem sucesso.
int PyComplex_CheckExact(PyObject *p)
Retorna true se seu argumento é um PyComplexObject, mas nã o um subtipo de PyComplexObject. Esta
funçã o sempre tem sucesso.
PyObject *PyComplex_FromCComplex(Py_complex v)
Retorna valor: Nova referência. Cria um novo objeto de nú mero complexo Python a partir de um valor C
Py_complex. Retorna NULL com uma exceçã o definida ao ocorrer um erro.
8.2. Objetos Numéricos 143
The Python/C API, Release 3.13.7
PyObject *PyComplex_FromDoubles(double real, double imag)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto PyComplexObject de real e
imag. Retorna NULL com uma exceçã o definida ao ocorrer um erro.
double PyComplex_RealAsDouble(PyObject *op)
Parte da ABI Está vel. Retorna a parte real de op como um double C.
Se op nã o é um objeto de nú mero complexo Python, mas tem um mé todo __complex__(), este mé todo será
primeiro chamado para converter op em um objeto de nú mero complexo Python. Se __complex__() nã o
estiver definido, ele volta a chamar PyFloat_AsDouble() e retorna seu resultado.
Em caso de falha, este mé todo retorna -1.0 com uma exceçã o definida, entã o deve-se chamar
PyErr_Occurred() para verificar se há erros.
Alterado na versã o 3.13: Usa __complex__(), se disponível.
double PyComplex_ImagAsDouble(PyObject *op)
Parte da ABI Está vel. Retorna a parte imaginá ria de op como um double C.
Se op nã o é um objeto de nú mero complexo Python, mas tem um mé todo __complex__(), este mé todo será
primeiro chamado para converter op em um objeto de nú mero complexo Python. Se __complex__() nã o
estiver definido, ele volta a chamar PyFloat_AsDouble() e retorna 0.0 em caso de sucesso.
Em caso de falha, este mé todo retorna -1.0 com uma exceçã o definida, entã o deve-se chamar
PyErr_Occurred() para verificar se há erros.
Alterado na versã o 3.13: Usa __complex__(), se disponível.
Py_complex PyComplex_AsCComplex(PyObject *op)
Retorna o valor Py_complex do nú mero complexo op.
Se op nã o é um objeto de nú mero complexo Python, mas tem um mé todo __complex__(), este mé todo será
primeiro chamado para converter op em um objeto de nú mero complexo Python. Se __complex__() nã o
for definido, entã o ele recorre a __float__(). Se __float__() nã o estiver definido, entã o ele volta para
__index__().
Em caso de falha, este mé todo retorna Py_complex com real definido para -1.0 e com uma exceçã o
definida, entã o deve-se chamar PyErr_Occurred() para verificar se há erros.
Alterado na versã o 3.8: Usa __index__(), se disponível.
8.3 Objetos Sequência
Operaçõ es gené ricas em objetos de sequê ncia foram discutidas no capítulo anterior; Esta seçã o lida com os tipos
específicos de objetos sequê ncia que sã o intrínsecos à linguagem Python.
8.3.1 Objetos bytes
Estas funçõ es levantam TypeError quando se espera um parâ metro bytes e sã o chamados com um parâ metro que
nã o é bytes.
type PyBytesObject
Esta é uma instâ ncia de PyObject representando o objeto bytes do Python.
PyTypeObject PyBytes_Type
Parte da ABI Está vel. Esta instâ ncia de PyTypeObject representa o tipo de bytes Python; é o mesmo objeto
que bytes na camada de Python.
int PyBytes_Check(PyObject *o)
Retorna verdadeiro se o objeto o for um objeto bytes ou se for uma instâ ncia de um subtipo do tipo bytes. Esta
funçã o sempre tem sucesso.
144 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyBytes_CheckExact(PyObject *o)
Retorna verdadeiro se o objeto o for um objeto bytes, mas nã o uma instâ ncia de um subtipo do tipo bytes. Esta
funçã o sempre tem sucesso.
PyObject *PyBytes_FromString(const char *v)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto de bytes com uma có pia da
string v como valor em caso de sucesso e NULL em caso de falha. O parâ metro v nã o deve ser NULL e isso nã o
será verificado.
PyObject *PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto de bytes com uma có pia da
string v como valor e comprimento len em caso de sucesso e NULL em caso de falha. Se v for NULL, o conteú do
do objeto bytes nã o será inicializado.
PyObject *PyBytes_FromFormat(const char *format, ...)
Retorna valor: Nova referência. Parte da ABI Está vel. Leva uma string tipo printf() do C format e um
nú mero variá vel de argumentos, calcula o tamanho do objeto bytes do Python resultante e retorna um objeto
bytes com os valores formatados nela. Os argumentos da variá vel devem ser tipos C e devem corresponder
exatamente aos caracteres de formato na string format. Os seguintes formatos de caracteres sã o permitidos:
Caracteres Formatados Tipo Comentário
%% n/d O caractere literal %.
%c int Um ú nico byte, representado como um C int.
%d int Equivalente a printf("%d").1
%u unsigned int Equivalente a printf("%u").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* Uma matriz de caracteres C com terminaçã o nula.
%p const void* A representaçã o hexadecimal de um ponteiro C.
Principalmente equivalente a printf("%p") exceto que é
garantido que comece com o literal 0x independentemente
do que o printf da plataforma ceda.
Um caractere de formato nã o reconhecido faz com que todo o resto da string de formato seja copiado como é
para o objeto resultante e todos os argumentos extras sejam descartados.
PyObject *PyBytes_FromFormatV(const char *format, va_list vargs)
Retorna valor: Nova referência. Parte da ABI Está vel. Idê ntico a PyBytes_FromFormat() exceto que é
preciso exatamente dois argumentos.
PyObject *PyBytes_FromObject(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna a representaçã o de bytes do objeto o que
implementa o protocolo de buffer.
Py_ssize_t PyBytes_Size(PyObject *o)
Parte da ABI Está vel. Retorna o comprimento dos bytes em objeto bytes o.
Py_ssize_t PyBytes_GET_SIZE(PyObject *o)
Similar a PyBytes_Size(), mas sem verificaçã o de erro.
1 Para especificadores de nú mero inteiro (d, u, ld, lu, zd, zu, i, x): o sinalizador de conversã o 0 tem efeito mesmo quando uma precisã o é
fornecida.
8.3. Objetos Sequência 145
The Python/C API, Release 3.13.7
char *PyBytes_AsString(PyObject *o)
Parte da ABI Está vel. Retorna um ponteiro para o conteú do de o. O ponteiro se refere ao buffer interno de
o, que consiste em len(o) + 1 bytes. O ú ltimo byte no buffer é sempre nulo, independentemente de haver
outros bytes nulos. Os dados nã o devem ser modificados de forma alguma, a menos que o objeto tenha sido
criado usando PyBytes_FromStringAndSize(NULL, size). Nã o deve ser desalocado. Se o nã o é um
objeto de bytes, PyBytes_AsString() retorna NULL e levanta TypeError.
char *PyBytes_AS_STRING(PyObject *string)
Similar a PyBytes_AsString(), mas sem verificaçã o de erro.
int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
Parte da ABI Está vel. Retorna os conteú dos terminados nulos do objeto obj atravé s das variá veis de saída
buffer e length. Retorna 0 em caso de sucesso.
Se length for NULL, o objeto bytes nã o poderá conter bytes nulos incorporados; se isso acontecer, a funçã o
retornará -1 e a ValueError será levantado.
O buffer refere-se a um buffer interno de obj, que inclui um byte nulo adicional no final (nã o contado em
length). Os dados nã o devem ser modificados de forma alguma, a menos que o objeto tenha sido criado apenas
usando PyBytes_FromStringAndSize(NULL, size). Nã o deve ser desalinhado. Se obj nã o é um objeto
bytes, PyBytes_AsStringAndSize() retorna -1 e levanta TypeError.
Alterado na versã o 3.5: Anteriormente TypeError era levantado quando os bytes nulos incorporados eram
encontrados no objeto bytes.
void PyBytes_Concat(PyObject **bytes, PyObject *newpart)
Parte da ABI Está vel. Cria um novo objeto de bytes em *bytes contendo o conteú do de newpart anexado a
bytes; o chamador será o proprietá rio da nova referê ncia. A referê ncia ao valor antigo de bytes será roubada.
Se o novo objeto nã o puder ser criado, a antiga referê ncia a bytes ainda será descartada e o valor de *bytes será
definido como NULL; a exceçã o apropriada será definida.
void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart)
Parte da ABI Está vel. “Crie um novo objeto bytes em *bytes contendo o conteú do de newpart anexado a
bytes. Esta versã o libera a strong reference (referê ncia forte) para newpart (ou seja, decrementa a contagem de
referê ncias a ele).”
int _PyBytes_Resize(PyObject **bytes, Py_ssize_t newsize)
Redimensiona um objeto de bytes. newsize será o novo tamanho do objeto bytes. Você pode pensar nisso
como se estivesse criando um novo objeto de bytes e destruindo o antigo, só que de forma mais eficiente. Passe
o endereço de um objeto de bytes existente como um lvalue (pode ser gravado) e o novo tamanho desejado.
Em caso de sucesso, *bytes manté m o objeto de bytes redimensionados e 0 é retornado; o endereço em *bytes
pode diferir do seu valor de entrada. Se a realocaçã o falhar, o objeto de bytes originais em *bytes é desalocado,
*bytes é definido como NULL, MemoryError é definido e -1 é retornado.
8.3.2 Objetos byte array
type PyByteArrayObject
Esse subtipo de PyObject representa um objeto Python bytearray.
PyTypeObject PyByteArray_Type
Parte da ABI Está vel. Essa instâ ncia de PyTypeObject representa um tipo Python bytearray; é o mesmo
objeto que o bytearray na camada Python.
Macros para verificação de tipo
int PyByteArray_Check(PyObject *o)
Retorna verdadeiro se o objeto o for um objeto bytearray ou se for uma instâ ncia de um subtipo do tipo
bytearray. Esta funçã o sempre tem sucesso.
146 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyByteArray_CheckExact(PyObject *o)
Retorna verdadeiro se o objeto o for um objeto bytearray, mas nã o uma instâ ncia de um subtipo do tipo
bytearray. Esta funçã o sempre tem sucesso.
Funções diretas da API
PyObject *PyByteArray_FromObject(PyObject *o)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto bytearray, o, que implementa
o protocolo de buffer.
Em caso de falha, retorna NULL com uma exceçã o definida.
PyObject *PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um novo objeto bytearray a partir de string e seu
comprimento, len.
Em caso de falha, retorna NULL com uma exceçã o definida.
PyObject *PyByteArray_Concat(PyObject *a, PyObject *b)
Retorna valor: Nova referência. Parte da ABI Está vel. Concatena os bytearrays a e b e retorna um novo
bytearray com o resultado.
Em caso de falha, retorna NULL com uma exceçã o definida.
Py_ssize_t PyByteArray_Size(PyObject *bytearray)
Parte da ABI Está vel. Retorna o tamanho de bytearray apó s verificar se há um ponteiro NULL.
char *PyByteArray_AsString(PyObject *bytearray)
Parte da ABI Está vel. Retorna o conteú do de bytearray como uma matriz de caracteres apó s verificar um
ponteiro NULL. O array retornado sempre tem um byte nulo extra acrescentado.
int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len)
Parte da ABI Está vel. Redimensiona o buffer interno de bytearray para o tamanho len.
Macros
Estas macros trocam segurança por velocidade e nã o verificam os ponteiros.
char *PyByteArray_AS_STRING(PyObject *bytearray)
Similar a PyByteArray_AsString(), mas sem verificaçã o de erro.
Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray)
Similar a PyByteArray_Size(), mas sem verificaçã o de erro.
8.3.3 Objetos Unicode e Codecs
Objetos Unicode
Desde a implementaçã o da PEP 393 no Python 3.3, os objetos Unicode usam internamente uma variedade de repre-
sentaçõ es para permitir o processamento de toda a gama de caracteres Unicode, mantendo a eficiê ncia de memó ria.
Há casos especiais para strings em que todos os pontos de có digo estã o abaixo de 128, 256 ou 65536; caso contrá rio,
os pontos de có digo devem estar abaixo de 1114112 (que é a gama completa de caracteres Unicode).
A representaçã o UTF-8 é criada sob demanda e armazenada em cache no objeto Unicode.
® Nota
A representaçã o Py_UNICODE foi removida desde o Python 3.12 com APIs descontinuadas. Consulte PEP 623
para obter mais informaçõ es.
8.3. Objetos Sequência 147
The Python/C API, Release 3.13.7
Tipo Unicode
Estes sã o os tipos bá sicos de objetos Unicode usados para a implementaçã o Unicode em Python:
type Py_UCS4
type Py_UCS2
type Py_UCS1
Parte da ABI Está vel. Esses tipos sã o definiçõ es de tipo para tipos inteiros sem sinal, amplos o suficiente para
conter caracteres de 32 bits, 16 bits e 8 bits, respectivamente. Ao lidar com caracteres Unicode simples, use
Py_UCS4.
Adicionado na versã o 3.3.
type Py_UNICODE
Este é um typedef de wchar_t, que é um tipo de 16 bits ou 32 bits, dependendo da plataforma.
Alterado na versã o 3.3: Em versõ es anteriores, esse era um tipo de 16 bits ou de 32 bits, dependendo se você
selecionava uma versã o Unicode “estreita” ou “ampla” do Python no momento da construçã o.
Deprecated since version 3.13, will be removed in version 3.15.
type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject
Esses subtipos de PyObject representam um objeto Unicode do Python. Em quase todos os casos, eles
nã o devem ser usados diretamente, pois todas as funçõ es da API que lidam com objetos Unicode recebem e
retornam ponteiros PyObject.
Adicionado na versã o 3.3.
PyTypeObject PyUnicode_Type
Parte da ABI Está vel. Esta instâ ncia de PyTypeObject representa o tipo Unicode do Python. Ela é exposta
ao có digo Python como str.
PyTypeObject PyUnicodeIter_Type
Parte da ABI Está vel. Esta instâ ncia de PyTypeObject representa o tipo iterador Unicode do Python. É
usada para iterar sobre objetos string Unicode.
As seguintes APIs sã o macros C e funçõ es está ticas embutidas para verificaçõ es rá pidas e acesso a dados internos
somente leitura de objetos Unicode:
int PyUnicode_Check(PyObject *obj)
Retorna verdadeiro se o objeto obj for um objeto Unicode ou uma instâ ncia de um subtipo Unicode. Esta
funçã o sempre tem sucesso.
int PyUnicode_CheckExact(PyObject *obj)
Retorna verdadeiro se o objeto obj for um objeto Unicode, mas nã o uma instâ ncia de um subtipo. Esta funçã o
sempre tem sucesso.
int PyUnicode_READY(PyObject *unicode)
Retorna 0. Essa API é mantida apenas para retrocompatibilidade.
Adicionado na versã o 3.3.
Descontinuado desde a versã o 3.10: Esta API nã o faz nada desde o Python 3.12.
Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)
Retorna o comprimento da string Unicode, em pontos de có digo. unicode deve ser um objeto Unicode na
representaçã o “canô nica” (nã o marcado).
Adicionado na versã o 3.3.
Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *unicode)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *unicode)
148 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Py_UCS4 *PyUnicode_4BYTE_DATA(PyObject *unicode)
Retorna um ponteiro para a representaçã o canô nica convertida para tipos inteiros UCS1, UCS2 ou UCS4 para
acesso direto aos caracteres. Nenhuma verificaçã o é realizada se a representaçã o canô nica tem o tamanho de
caractere correto; use PyUnicode_KIND() para selecionar a funçã o correta.
Adicionado na versã o 3.3.
PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND
Valores de retorno da macro PyUnicode_KIND().
Adicionado na versã o 3.3.
Alterado na versã o 3.12: PyUnicode_WCHAR_KIND foi removida.
int PyUnicode_KIND(PyObject *unicode)
Retorna uma das constantes do tipo PyUnicode (veja acima) que indicam quantos bytes por caractere este
objeto Unicode usa para armazenar seus dados. unicode precisa ser um objeto Unicode na representaçã o
“canô nica” (nã o marcado).
Adicionado na versã o 3.3.
void *PyUnicode_DATA(PyObject *unicode)
Retorna um ponteiro vazio para o buffer Unicode bruto. unicode deve ser um objeto Unicode na representaçã o
“canô nica” (nã o marcado).
Adicionado na versã o 3.3.
void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, Py_UCS4 value)
Escreva em uma representaçã o canô nica data (conforme obtido com PyUnicode_DATA()). Esta funçã o nã o
realiza verificaçõ es de sanidade e destina-se ao uso em laços. O chamador deve armazenar em cache o valor
de type e o ponteiro data conforme obtidos de outras chamadas. índice é o índice na string (começa em 0) e
value é o novo valor do ponto de có digo que deve ser escrito naquele local.
Adicionado na versã o 3.3.
Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index)
Lê um ponto de có digo de uma representaçã o canô nica data (conforme obtido com PyUnicode_DATA()).
Nenhuma verificaçã o ou chamada pronta é realizada.
Adicionado na versã o 3.3.
Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)
Lê um caractere de um objeto Unicode unicode, que deve estar na representaçã o “canô nica”. Isso é menos
eficiente do que PyUnicode_READ() se você fizer vá rias leituras consecutivas.
Adicionado na versã o 3.3.
Py_UCS4 PyUnicode_MAX_CHAR_VALUE(PyObject *unicode)
Retorna o ponto de có digo má ximo adequado para criar outra string baseada em unicode, que deve estar na
representaçã o “canô nica”. Isso é sempre uma aproximaçã o, mas é mais eficiente do que iterar sobre a string.
Adicionado na versã o 3.3.
int PyUnicode_IsIdentifier(PyObject *unicode)
Parte da ABI Está vel. Retorna 1 se a string é um identificador vá lido conforme a definiçã o da linguagem, seçã o
identifiers. Do contrá rio, retorna 0.
Alterado na versã o 3.9: A funçã o nã o chama mais Py_FatalError() se a string nã o estiver pronta.
8.3. Objetos Sequência 149
The Python/C API, Release 3.13.7
Propriedade de caracteres Unicode
O Unicode fornece muitas propriedades de caracteres diferentes. As mais frequentemente necessá rias estã o dispo-
níveis por meio destas macros, que sã o mapeadas para funçõ es C, dependendo da configuraçã o do Python.
int Py_UNICODE_ISSPACE(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere de espaço em branco.
int Py_UNICODE_ISLOWER(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere minú sculo.
int Py_UNICODE_ISUPPER(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere maiú sculo.
int Py_UNICODE_ISTITLE(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere em TitleCase.
int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere de quebra de linha.
int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere decimal.
int Py_UNICODE_ISDIGIT(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere de dígito.
int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere numé rico.
int Py_UNICODE_ISALPHA(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere alfabé tico.
int Py_UNICODE_ISALNUM(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere alfanumé rico.
int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)
Retorna 1 ou 0 dependendo se ch é um caractere imprimível, no sentido de str.isprintable().
These APIs can be used for fast direct character conversions:
Py_UCS4 Py_UNICODE_TOLOWER(Py_UCS4 ch)
Return the character ch converted to lower case.
Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)
Return the character ch converted to upper case.
Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)
Return the character ch converted to title case.
int Py_UNICODE_TODECIMAL(Py_UCS4 ch)
Return the character ch converted to a decimal positive integer. Return -1 if this is not possible. This function
does not raise exceptions.
int Py_UNICODE_TODIGIT(Py_UCS4 ch)
Return the character ch converted to a single digit integer. Return -1 if this is not possible. This function does
not raise exceptions.
double Py_UNICODE_TONUMERIC(Py_UCS4 ch)
Return the character ch converted to a double. Return -1.0 if this is not possible. This function does not raise
exceptions.
These APIs can be used to work with surrogates:
150 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int Py_UNICODE_IS_SURROGATE(Py_UCS4 ch)
Check if ch is a surrogate (0xD800 <= ch <= 0xDFFF).
int Py_UNICODE_IS_HIGH_SURROGATE(Py_UCS4 ch)
Check if ch is a high surrogate (0xD800 <= ch <= 0xDBFF).
int Py_UNICODE_IS_LOW_SURROGATE(Py_UCS4 ch)
Check if ch is a low surrogate (0xDC00 <= ch <= 0xDFFF).
Py_UCS4 Py_UNICODE_JOIN_SURROGATES(Py_UCS4 high, Py_UCS4 low)
Join two surrogate code points 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].
Creating and accessing Unicode strings
To create Unicode objects and access their basic sequence properties, use these APIs:
PyObject *PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
Retorna valor: Nova referência. Create a new Unicode object. maxchar should be the true maximum code
point to be placed in the string. As an approximation, it can be rounded up to the nearest value in the sequence
127, 255, 65535, 1114111.
This is the recommended way to allocate a new Unicode object. Objects created using this function are not
resizable.
On error, set an exception and return NULL.
Adicionado na versã o 3.3.
PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
Retorna valor: Nova referência. Cria um novo objeto Unicode com o tipo type fornecido (os valores possíveis
sã o PyUnicode_1BYTE_KIND etc., conforme retornado por PyUnicode_KIND()). O buffer deve apontar
para um array de unidades com size de 1, 2 ou 4 bytes por caractere, conforme fornecido pelo tipo.
If necessary, the input buffer is copied and transformed into the canonical representation. For example, if the
buffer is a UCS4 string (PyUnicode_4BYTE_KIND) and it consists only of codepoints in the UCS1 range, it
will be transformed into UCS1 (PyUnicode_1BYTE_KIND).
Adicionado na versã o 3.3.
PyObject *PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
Retorna valor: Nova referência. Parte da ABI Está vel. 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
Alterado na versã o 3.12: str == NULL with size > 0 is not allowed anymore.
PyObject *PyUnicode_FromString(const char *str)
Retorna valor: Nova referência. Parte da ABI Está vel. Create a Unicode object from a UTF-8 encoded null-
-terminated char buffer str.
PyObject *PyUnicode_FromFormat(const char *format, ...)
Retorna valor: Nova referência. Parte da ABI Está vel. 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.
8.3. Objetos Sequência 151
The Python/C API, Release 3.13.7
Um especificador de conversã o conté m dois ou mais caracteres e tem os seguintes componentes, que devem
aparecer nesta ordem:
1. O caractere '%', que determina o início do especificador.
2. Flags de conversã o (opcional), que afetam o resultado de alguns tipos de conversã o.
3. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is given in the next
argument, which must be of type int, and the object to convert comes after the minimum field width
and optional precision.
4. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk),
the actual precision is given in the next argument, which must be of type int, and the value to convert
comes after the precision.
5. Modificador de comprimento (opcional).
6. Tipos de conversã o.
Os caracteres flags de conversã o sã o:
Sinalizador Significado
0 A conversã o será preenchida por zeros para valores numé ricos.
- 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 Tipos
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. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Con- Tipo Comentário
version
Speci-
fier
% n/d The literal % character.
d, i Specified by the The decimal representation of a signed C integer.
length modifier
u Specified by the The decimal representation of an unsigned C integer.
length modifier
o Specified by the The octal representation of an unsigned C integer.
length modifier
x Specified by the The hexadecimal representation of an unsigned C integer (lowercase).
length modifier
X Specified by the The hexadecimal representation of an unsigned C integer (uppercase).
length modifier
c int A single character.
s const char* or Uma matriz de caracteres C com terminaçã o nula.
const wchar_t*
p const void* The hex representation of a C pointer. Mostly equivalent to
printf("%p") except that it is guaranteed to start with the literal 0x
regardless of what the platform’s printf yields.
A PyObject* The result of calling ascii().
U PyObject* A Unicode object.
V PyObject*, A Unicode object (which may be NULL) and a null-terminated C cha-
const char* or racter array as a second parameter (which will be used, if the first pa-
const wchar_t* rameter is NULL).
S PyObject* The result of calling PyObject_Str().
R PyObject* The result of calling PyObject_Repr().
T PyObject* Get the fully qualified name of an object type; call
PyType_GetFullyQualifiedName().
#T PyObject* Similar to T format, but use a colon (:) as separator between the module
name and the qualified name.
N PyTypeObject* Get the fully qualified name of a type; call
PyType_GetFullyQualifiedName().
#N PyTypeObject* Similar to N format, but use a colon (:) as separator between the module
name and the qualified name.
® 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).
Alterado na versã o 3.2: Suporte adicionado para "%lld" e "%llu".
Alterado na versã o 3.3: Support for "%li", "%lli" and "%zi" added.
Alterado na versã o 3.4: Support width and precision formatter for "%s", "%A", "%U", "%V", "%S", "%R"
8.3. Objetos Sequência 153
The Python/C API, Release 3.13.7
added.
Alterado na versã o 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.
Alterado na versã o 3.13: Support for %T, %#T, %N and %#N formats added.
PyObject *PyUnicode_FromFormatV(const char *format, va_list vargs)
Retorna valor: Nova referência. Parte da ABI Está vel. Identical to PyUnicode_FromFormat() except that
it takes exactly two arguments.
PyObject *PyUnicode_FromObject(PyObject *obj)
Retorna valor: Nova referência. Parte da ABI Está vel. 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.
Objects other than Unicode or its subtypes will cause a TypeError.
PyObject *PyUnicode_FromOrdinal(int ordinal)
Retorna valor: Nova referência. Parte da ABI Está vel. Create a Unicode Object from the given Unicode code
point ordinal.
The ordinal must be in range(0x110000). A ValueError is raised in the case it is not.
PyObject *PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. Decode an encoded object obj to a Unicode object.
bytes, bytearray and other bytes-like objects are decoded according to the given encoding and using the
error handling defined by errors. Both can be NULL to have the interface use the default values (see Built-in
Codecs for details).
All other objects, including Unicode objects, cause a TypeError to be set.
The API returns NULL if there was an error. The caller is responsible for decref’ing the returned objects.
PyObject *PyUnicode_BuildEncodingMap(PyObject *string)
Retorna valor: Nova referência. Parte da ABI Está vel. Return a mapping suitable for decoding a custom single-
-byte encoding. Given a Unicode string string of up to 256 characters representing an encoding table, returns
either a compact internal mapping object or a dictionary mapping character ordinals to byte values. Raises a
TypeError and return NULL on invalid input. .. versionadded:: 3.2
const char *PyUnicode_GetDefaultEncoding(void)
Parte da ABI Está vel. Return the name of the default string encoding, "utf-8". See sys.
getdefaultencoding().
The returned string does not need to be freed, and is valid until interpreter shutdown.
Py_ssize_t PyUnicode_GetLength(PyObject *unicode)
Parte da ABI Está vel desde a versão 3.7. Return the length of the Unicode object, in code points.
On error, set an exception and return -1.
Adicionado na versã o 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.
Adicionado na versã o 3.3.
154 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)
Fill a string with a character: write fill_char into unicode[start:start+length].
Fail if fill_char is bigger than the string maximum character, or if the string has more than 1 reference.
Return the number of written character, or return -1 and raise an exception on error.
Adicionado na versã o 3.3.
int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 character)
Parte da ABI Está vel desde a versão 3.7. Write a character to a string. The string must have been created
through PyUnicode_New(). Since Unicode strings are supposed to be immutable, the string must not be
shared, or have been hashed yet.
This function checks that unicode is a Unicode object, that the index is not out of bounds, and that the object
can be modified safely (i.e. that it its reference count is one).
Return 0 on success, -1 on error with an exception set.
Adicionado na versã o 3.3.
Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
Parte da ABI Está vel desde a versão 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.
Return character on success, -1 on error with an exception set.
Adicionado na versã o 3.3.
PyObject *PyUnicode_Substring(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Return a substring of unicode, from
character index start (included) to character index end (excluded). Negative indices are not supported. On
error, set an exception and return NULL.
Adicionado na versã o 3.3.
Py_UCS4 *PyUnicode_AsUCS4(PyObject *unicode, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)
Parte da ABI Está vel desde a versão 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.
Adicionado na versã o 3.3.
Py_UCS4 *PyUnicode_AsUCS4Copy(PyObject *unicode)
Parte da ABI Está vel desde a versão 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.
Adicionado na versã o 3.3.
Locale Encoding
The current locale encoding can be used to decode text from the operating system.
PyObject *PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t length, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Decode a string from UTF-8 on
Android and VxWorks, or from the current locale encoding on other platforms. The supported error handlers
are "strict" and "surrogateescape" (PEP 383). The decoder uses "strict" error handler if errors
is NULL. str must end with a null character but cannot contain embedded null characters.
Use PyUnicode_DecodeFSDefaultAndSize() to decode a string from the filesystem encoding and error
handler.
This function ignores the Python UTF-8 Mode.
8.3. Objetos Sequência 155
The Python/C API, Release 3.13.7
µ Ver também
The Py_DecodeLocale() function.
Adicionado na versã o 3.3.
Alterado na versã o 3.7: The function now also uses the current locale encoding for the surrogateescape
error handler, except on Android. Previously, Py_DecodeLocale() was used for the surrogateescape,
and the current locale encoding was used for strict.
PyObject *PyUnicode_DecodeLocale(const char *str, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Similar to
PyUnicode_DecodeLocaleAndSize(), but compute the string length using strlen().
Adicionado na versã o 3.3.
PyObject *PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Encode a Unicode object to UTF-8
on Android and VxWorks, or to the current locale encoding on other platforms. The supported error handlers
are "strict" and "surrogateescape" (PEP 383). The encoder uses "strict" error handler if errors
is NULL. Return a bytes object. unicode cannot contain embedded null characters.
Use PyUnicode_EncodeFSDefault() to encode a string to the filesystem encoding and error handler.
This function ignores the Python UTF-8 Mode.
µ Ver também
The Py_EncodeLocale() function.
Adicionado na versã o 3.3.
Alterado na versã o 3.7: The function now also uses the current locale encoding for the surrogateescape
error handler, except on Android. Previously, Py_EncodeLocale() was used for the surrogateescape,
and the current locale encoding was used for strict.
File System Encoding
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)
Parte da ABI Está vel. PyArg_Parse* 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 an address of a C variable of type PyObject* (or PyBytesObject*). On success, set the
variable to a new strong reference to a bytes object which must be released when it is no longer used and return
a non-zero value (Py_CLEANUP_SUPPORTED). Embedded null bytes are not allowed in the result. On failure,
return 0 with an exception set.
If obj is NULL, the function releases a strong reference stored in the variable referred by result and returns 1.
Adicionado na versã o 3.1.
Alterado na versã o 3.6: Aceita um objeto caminho ou similar.
To decode file names to str during argument parsing, the "O&" converter should be used, passing
PyUnicode_FSDecoder() as the conversion function:
156 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyUnicode_FSDecoder(PyObject *obj, void *result)
Parte da ABI Está vel. PyArg_Parse* converter: decode bytes objects – obtained either directly or indirectly
through the os.PathLike interface – to str using PyUnicode_DecodeFSDefaultAndSize(); str ob-
jects are output as-is. result must be an address of a C variable of type PyObject* (or PyUnicodeObject*).
On success, set the variable to a new strong reference to a Unicode object which must be released when it is
no longer used and return a non-zero value (Py_CLEANUP_SUPPORTED). Embedded null characters are not
allowed in the result. On failure, return 0 with an exception set.
If obj is NULL, release the strong reference to the object referred to by result and return 1.
Adicionado na versã o 3.2.
Alterado na versã o 3.6: Aceita um objeto caminho ou similar.
PyObject *PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
Retorna valor: Nova referência. Parte da ABI Está vel. Decode a string from the filesystem encoding and error
handler.
If you need to decode a string from the current locale encoding, use PyUnicode_DecodeLocaleAndSize().
µ Ver também
The Py_DecodeLocale() function.
Alterado na versã o 3.6: The filesystem error handler is now used.
PyObject *PyUnicode_DecodeFSDefault(const char *str)
Retorna valor: Nova referência. Parte da ABI Está vel. Decode a null-terminated string from the filesystem
encoding and error handler.
If the string length is known, use PyUnicode_DecodeFSDefaultAndSize().
Alterado na versã o 3.6: The filesystem error handler is now used.
PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode)
Retorna valor: Nova referência. Parte da ABI Está vel. 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 também
The Py_EncodeLocale() function.
Adicionado na versã o 3.2.
Alterado na versã o 3.6: The filesystem error handler is now used.
wchar_t Support
wchar_t support for platforms which support it:
PyObject *PyUnicode_FromWideChar(const wchar_t *wstr, Py_ssize_t size)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Parte da ABI Está vel. 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.
8.3. Objetos Sequência 157
The Python/C API, Release 3.13.7
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)
Parte da ABI Está vel desde a versão 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.
Adicionado na versã o 3.2.
Alterado na versã o 3.7: Raises a ValueError if size is NULL and the wchar_t* string contains null characters.
Built-in Codecs
Python provides a set of built-in codecs which are written in C for speed. All of these codecs are directly usable via
the following functions.
Many of the following APIs take two arguments encoding and errors, and they have the same semantics as the ones
of the built-in str() string object constructor.
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.
Error handling is set by errors which may also be set to NULL meaning to use the default handling defined for the
codec. Default error handling for all built-in codecs is “strict” (ValueError is raised).
The codecs all use a similar interface. Only deviations from the following generic ones are documented for simplicity.
Generic Codecs
These are the generic codec APIs:
PyObject *PyUnicode_Decode(const char *str, Py_ssize_t size, const char *encoding, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Encode a Unicode object and return the result as Python
bytes object. encoding and errors have the same meaning as the parameters of the same name in the Unicode
encode() method. The codec to be used is looked up using the Python codec registry. Return NULL if an
exception was raised by the codec.
UTF-8 Codecs
These are the UTF-8 codec APIs:
PyObject *PyUnicode_DecodeUTF8(const char *str, Py_ssize_t size, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. 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.
158 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
PyObject *PyUnicode_DecodeUTF8Stateful(const char *str, Py_ssize_t size, const char *errors, Py_ssize_t
*consumed)
Retorna valor:Nova referência. Parte da ABI Está vel. If consumed is NULL, behave like
PyUnicode_DecodeUTF8(). If consumed is not NULL, trailing incomplete UTF-8 byte sequences will not
be treated as an error. Those bytes will not be decoded and the number of bytes that have been decoded will
be stored in consumed.
PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
Retorna valor: Nova referência. Parte da ABI Está vel. Encode a Unicode object using UTF-8 and return the
result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.
The function fails if the string contains surrogate code points (U+D800 - U+DFFF).
const char *PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)
Parte da ABI Está vel desde a versão 3.10. Return a pointer to the UTF-8 encoding of the Unicode object, and
store the size of the encoded representation (in bytes) in size. The size argument can be NULL; in this case no
size will be stored. The returned buffer always has an extra null byte appended (not included in size), regardless
of whether there are any other null code points.
On error, set an exception, set size to -1 (if it’s not NULL) and return NULL.
The function fails if the string contains surrogate code points (U+D800 - U+DFFF).
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.
Adicionado na versã o 3.3.
Alterado na versã o 3.7: The return type is now const char * rather of char *.
Alterado na versã o 3.10: This function is a part of the limited API.
const char *PyUnicode_AsUTF8(PyObject *unicode)
As PyUnicode_AsUTF8AndSize(), but does not store the size.
Á Aviso
This function does not have any special behavior for null characters embedded within unicode. As a re-
sult, strings containing null characters will remain in the returned string, which some C functions might
interpret as the end of the string, leading to truncation. If truncation is an issue, it is recommended to use
PyUnicode_AsUTF8AndSize() instead.
Adicionado na versã o 3.3.
Alterado na versã o 3.7: The return type is now const char * rather of char *.
UTF-32 Codecs
These are the UTF-32 codec APIs:
PyObject *PyUnicode_DecodeUTF32(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
Retorna valor: Nova referência. Parte da ABI Está vel. Decode size bytes from a UTF-32 encoded buffer string
and return the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to
“strict”.
If byteorder is non-NULL, the decoder starts decoding using the given byte order:
*byteorder == -1: little endian
*byteorder == 0: native order
*byteorder == 1: big endian
8.3. Objetos Sequência 159
The Python/C API, Release 3.13.7
If *byteorder is zero, and the first four bytes of the input data are a byte order mark (BOM), the decoder
switches to this byte order and the BOM is not copied into the resulting Unicode string. If *byteorder is -1
or 1, any byte order mark is copied to the output.
After completion, *byteorder is set to the current byte order at the end of input data.
If byteorder is NULL, the codec starts in native order mode.
Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Retorna valor:Nova referência. Parte da ABI Está vel. If consumed is NULL, behave like
PyUnicode_DecodeUTF32(). If consumed is not NULL, PyUnicode_DecodeUTF32Stateful() will not
treat trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible by four) as an error.
Those bytes will not be decoded and the number of bytes that have been decoded will be stored in consumed.
PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
Retorna valor: Nova referência. Parte da ABI Está vel. Return a Python byte string using the UTF-32 encoding
in native byte order. The string always starts with a BOM mark. Error handling is “strict”. Return NULL if an
exception was raised by the codec.
UTF-16 Codecs
These are the UTF-16 codec APIs:
PyObject *PyUnicode_DecodeUTF16(const char *str, Py_ssize_t size, const char *errors, int *byteorder)
Retorna valor: Nova referência. Parte da ABI Está vel. Decode size bytes from a UTF-16 encoded buffer string
and return the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to
“strict”.
If byteorder is non-NULL, the decoder starts decoding using the given byte order:
*byteorder == -1: little endian
*byteorder == 0: native order
*byteorder == 1: big endian
If *byteorder is zero, and the first two bytes of the input data are a byte order mark (BOM), the decoder
switches to this byte order and the BOM is not copied into the resulting Unicode string. If *byteorder is
-1 or 1, any byte order mark is copied to the output (where it will result in either a \ufeff or a \ufffe
character).
After completion, *byteorder is set to the current byte order at the end of input data.
If byteorder is NULL, the codec starts in native order mode.
Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Retorna valor:Nova referência. Parte da ABI Está vel. If consumed is NULL, behave like
PyUnicode_DecodeUTF16(). If consumed is not NULL, PyUnicode_DecodeUTF16Stateful() will not
treat trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a split surrogate pair) as
an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in
consumed.
PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
Retorna valor: Nova referência. Parte da ABI Está vel. Return a Python byte string using the UTF-16 encoding
in native byte order. The string always starts with a BOM mark. Error handling is “strict”. Return NULL if an
exception was raised by the codec.
160 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
UTF-7 Codecs
These are the UTF-7 codec APIs:
PyObject *PyUnicode_DecodeUTF7(const char *str, Py_ssize_t size, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Retorna valor:Nova referência. Parte da ABI Está vel. If consumed is NULL, behave like
PyUnicode_DecodeUTF7(). If consumed is not NULL, trailing incomplete UTF-7 base-64 sections will
not be treated as an error. Those bytes will not be decoded and the number of bytes that have been decoded
will be stored in consumed.
Unicode-Escape Codecs
These are the “Unicode Escape” codec APIs:
PyObject *PyUnicode_DecodeUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Encode a Unicode object using Unicode-Escape and
return the result as a bytes object. Error handling is “strict”. Return NULL if an exception was raised by the
codec.
Raw-Unicode-Escape Codecs
These are the “Raw Unicode Escape” codec APIs:
PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Encode a Unicode object using Raw-Unicode-Escape
and return the result as a bytes object. Error handling is “strict”. Return NULL if an exception was raised by
the codec.
Latin-1 Codecs
These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted
by the codecs during encoding.
PyObject *PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Encode a Unicode object using Latin-1 and return the
result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.
ASCII Codecs
These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors.
8.3. Objetos Sequência 161
The Python/C API, Release 3.13.7
PyObject *PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Encode a Unicode object using ASCII and return the
result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.
Character Map Codecs
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.
These are the mapping codec APIs:
PyObject *PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, PyObject *mapping, const char
*errors)
Retorna valor: Nova referência. Parte da ABI Está vel. 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.
If mapping is NULL, Latin-1 decoding will be applied. Else mapping must map bytes ordinals (integers in the
range from 0 to 255) to Unicode strings, integers (which are then interpreted as Unicode ordinals) or None.
Unmapped data bytes – ones which cause a LookupError, as well as ones which get mapped to None, 0xFFFE
or '\ufffe', are treated as undefined mappings and cause an error.
PyObject *PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
Retorna valor: Nova referência. Parte da ABI Está vel. Encode a Unicode object using the given mapping
object and return the result as a bytes object. Error handling is “strict”. Return NULL if an exception was
raised by the codec.
The mapping object must map Unicode ordinal integers to bytes objects, integers in the range from 0 to 255
or None. Unmapped character ordinals (ones which cause a LookupError) as well as mapped to None are
treated as “undefined mapping” and cause an error.
The following codec API is special in that maps Unicode to Unicode.
PyObject *PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel. Translate a string by applying a character mapping table
to it and return the resulting Unicode object. Return NULL if an exception was raised by the codec.
The mapping table must map Unicode ordinal integers to Unicode ordinal integers or None (causing deletion
of the character).
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 has the usual meaning for codecs. It may be NULL which indicates to use the default error handling.
MBCS codecs for Windows
These are the MBCS codec APIs. They are currently only available on Windows and use the Win32 MBCS converters
to implement the conversions. Note that MBCS (or DBCS) is a class of encodings, not just one. The target encoding
is defined by the user settings on the machine running the codec.
PyObject *PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel on Windows desde a versão 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)
162 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Retorna valor: Nova referência. Parte da ABI Está vel on Windows desde a versão 3.7. If
consumed is NULL, behave like PyUnicode_DecodeMBCS(). If consumed is not NULL,
PyUnicode_DecodeMBCSStateful() will not decode trailing lead byte and the number of bytes
that have been decoded will be stored in consumed.
PyObject *PyUnicode_DecodeCodePageStateful(int code_page, const char *str, Py_ssize_t size, const char
*errors, Py_ssize_t *consumed)
Retorna valor: Nova referência. Parte da ABI Está vel on Windows desde a versão 3.7. Similar to
PyUnicode_DecodeMBCSStateful(), except uses the code page specified by code_page.
PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
Retorna valor: Nova referência. Parte da ABI Está vel on Windows desde a versão 3.7. Encode a Unicode
object using MBCS and return the result as Python bytes object. Error handling is “strict”. Return NULL if an
exception was raised by the codec.
PyObject *PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)
Retorna valor: Nova referência. Parte da ABI Está vel on Windows desde a versão 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.
Adicionado na versã o 3.3.
Methods and Slot Functions
The following APIs are capable of handling Unicode objects and strings on input (we refer to them as strings in the
descriptions) and return Unicode objects or integers as appropriate.
They all return NULL or -1 if an exception occurs.
PyObject *PyUnicode_Concat(PyObject *left, PyObject *right)
Retorna valor: Nova referência. Parte da ABI Está vel. Concat two strings giving a new Unicode string.
PyObject *PyUnicode_Split(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
Retorna valor: Nova referência. Parte da ABI Está vel. Split a string giving a list of Unicode strings. If sep
is NULL, splitting will be done at all whitespace substrings. Otherwise, splits occur at the given separator. At
most maxsplit splits will be done. If negative, no limit is set. Separators are not included in the resulting list.
On error, return NULL with an exception set.
Equivalent to str.split().
PyObject *PyUnicode_RSplit(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
Retorna valor: Nova referência. Parte da ABI Está vel. Similar to PyUnicode_Split(), but splitting will be
done beginning at the end of the string.
On error, return NULL with an exception set.
Equivalent to str.rsplit().
PyObject *PyUnicode_Splitlines(PyObject *unicode, int keepends)
Retorna valor: Nova referência. Parte da ABI Está vel. 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_Partition(PyObject *unicode, PyObject *sep)
Retorna valor: Nova referência. Parte da ABI Está vel. Split a Unicode string at the first occurrence of sep, and
return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator.
If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
sep must not be empty.
On error, return NULL with an exception set.
Equivalent to str.partition().
8.3. Objetos Sequência 163
The Python/C API, Release 3.13.7
PyObject *PyUnicode_RPartition(PyObject *unicode, PyObject *sep)
Retorna valor: Nova referência. Parte da ABI Está vel. Similar to PyUnicode_Partition(), but split a
Unicode string at the last occurrence of sep. If the separator is not found, return a 3-tuple containing two
empty strings, followed by the string itself.
sep must not be empty.
On error, return NULL with an exception set.
Equivalent to str.rpartition().
PyObject *PyUnicode_Join(PyObject *separator, PyObject *seq)
Retorna valor: Nova referência. Parte da ABI Está vel. Join a sequence of strings using the given separator and
return the resulting Unicode string.
Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
Parte da ABI Está vel. 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)
Parte da ABI Está vel. 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)
Parte da ABI Está vel desde a versão 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.
Adicionado na versã o 3.3.
Alterado na versã o 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)
Parte da ABI Está vel. 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)
Retorna valor: Nova referência. Parte da ABI Está vel. 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)
Parte da ABI Está vel. Compare two strings and return -1, 0, 1 for less than, equal, and greater than, respec-
tively.
This function returns -1 upon failure, so one should call PyErr_Occurred() to check for errors.
int PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *string, Py_ssize_t size)
Parte da ABI Está vel desde a versão 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 code points (U+D800 - U+DFFF) or the C string is not valid UTF-8, false (0) is
returned.
This function does not raise exceptions.
Adicionado na versã o 3.13.
int PyUnicode_EqualToUTF8(PyObject *unicode, const char *string)
Parte da ABI Está vel desde a versão 3.13. Similar to PyUnicode_EqualToUTF8AndSize(), but compute
string length using strlen(). If the Unicode object contains null characters, false (0) is returned.
164 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Adicionado na versã o 3.13.
int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
Parte da ABI Está vel. 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.
This function does not raise exceptions.
PyObject *PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Retorna valor: Nova referência. Parte da ABI Está vel. Rich compare two Unicode strings and return one of
the following:
• NULL in case an exception was raised
• 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)
Retorna valor: Nova referência. Parte da ABI Está vel. Return a new string object from format and args; this
is analogous to format % args.
int PyUnicode_Contains(PyObject *unicode, PyObject *substr)
Parte da ABI Está vel. 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)
Parte da ABI Está vel. 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.
(Clarification: even though there is a lot of talk about references, think of this function as reference-neutral.
You must own the object you pass in; after the call you no longer own the passed-in reference, but you newly
own the result.)
This function never raises an exception. On error, it leaves its argument unchanged without interning it.
Instances of subclasses of str may not be interned, that is, PyUnicode_CheckExact(*p_unicode) must
be true. If it is not, then – as with any other error – the argument is left unchanged.
Note that interned strings are not “immortal”. You must keep a reference to the result to benefit from interning.
PyObject *PyUnicode_InternFromString(const char *str)
Retorna valor: Nova referência. Parte da ABI Está vel. A combination of PyUnicode_FromString() and
PyUnicode_InternInPlace(), meant for statically allocated strings.
Return a new (“owned”) reference to either a new Unicode string object that has been interned, or an earlier
interned string object with the same value.
Python may keep a reference to the result, or make it immortal, preventing it from being garbage-collected
promptly. For interning an unbounded number of different strings, such as ones coming from user input,
prefer calling PyUnicode_FromString() and PyUnicode_InternInPlace() directly.
8.3.4 Objeto tupla
type PyTupleObject
Este subtipo de PyObject representa um objeto tupla em Python.
8.3. Objetos Sequência 165
The Python/C API, Release 3.13.7
PyTypeObject PyTuple_Type
Parte da ABI Está vel. Esta instâ ncia de PyTypeObject representa o tipo tupla de Python; é o mesmo objeto
que tuple na camada Python.
int PyTuple_Check(PyObject *p)
Retorna verdadeiro se p é um objeto tupla ou uma instâ ncia de um subtipo do tipo tupla. Esta funçã o sempre
tem sucesso.
int PyTuple_CheckExact(PyObject *p)
Retorna verdadeiro se p é um objeto tupla, mas nã o uma instâ ncia de um subtipo do tipo tupla. Esta funçã o
sempre tem sucesso.
PyObject *PyTuple_New(Py_ssize_t len)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto tupla de tamanho len, ou NULL
com uma exceçã o definida em caso de falha.
PyObject *PyTuple_Pack(Py_ssize_t n, ...)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto tupla de tamanho n, ou NULL
com uma exceçã o em caso de falha. Os valores da tupla sã o inicializados para os n argumentos C subsequentes
apontando para objetos Python. `PyTuple_Pack(2, a, b) é equivalente a Py_BuildValue("(OO)",
a, b).
Py_ssize_t PyTuple_Size(PyObject *p)
Parte da ABI Está vel. Pega um ponteiro para um objeto tupla e retorna o tamanho dessa tupla. No erro, retorna
-1 e com uma exceçã o definida.
Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
Como PyTuple_Size(), mas sem verificaçã o de erro.
PyObject *PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Retorna o objeto na posiçã o pos na tupla apontada
por p. Se pos estiver fora dos limites, retorna NULL e define uma exceçã o IndexError.
A referê ncia retornada é emprestada da tupla p (ou seja: ela só é vá lida enquanto você manté m
uma referê ncia a p). Para obter uma referência forte, use Py_NewRef(PyTuple_GetItem(...)) ou
PySequence_GetItem().
PyObject *PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)
Retorna valor: Referência emprestada. Como PyTuple_GetItem(), mas faz nenhuma verificaçã o de seus
argumentos.
PyObject *PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna a fatia da tupla apontada por p entre low e high,
ou NULL com uma exceçã o definida em caso de falha.
Isso é o equivalente da expressã o Python p[low:high]. A indexaçã o do final da tupla nã o é suportada.
int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Parte da ABI Está vel. Insere uma referê ncia ao objeto o na posiçã o pos da tupla apontada por p. Retorna 0
em caso de sucesso. Se pos estiver fora dos limites, retorne -1 e define uma exceçã o IndexError.
® Nota
Esta funçã o “rouba” uma referê ncia a o e descarta uma referê ncia a um item já na tupla na posiçã o afetada.
void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)
Como PyTuple_SetItem(), mas nã o verifica erros e deve apenas ser usado para preencher novas tuplas.
A verificaçã o de limites é realizada como uma asserçã o se o Python for construído em modo de depuraçã o ou
com asserções.
166 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
® Nota
Esta funçã o “rouba” uma referê ncia para o e, ao contrá rio de PyTuple_SetItem(), não descarta uma
referê ncia para nenhum item que esteja sendo substituído; qualquer referê ncia na tupla na posiçã o pos será
perdida.
int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)
Pode ser usado para redimensionar uma tupla. newsize será o novo comprimento da tupla. Como as tuplas
sã o supostamente imutá veis, isso só deve ser usado se houver apenas uma referê ncia ao objeto. Não use isto
se a tupla já for conhecida por alguma outra parte do có digo. A tupla sempre aumentará ou diminuirá no
final. Pense nisso como destruir a tupla antiga e criar uma nova, mas com mais eficiê ncia. Retorna 0 em caso
de sucesso. O có digo do cliente nunca deve presumir que o valor resultante de *p será o mesmo de antes de
chamar esta funçã o. Se o objeto referenciado por *p for substituído, o *p original será destruído. Em caso de
falha, retorna -1 e define *p para NULL, e levanta MemoryError ou SystemError.
8.3.5 Objetos sequência de estrutura
Objetos sequê ncia de estrutura sã o o equivalente em C dos objetos namedtuple(), ou seja, uma sequê ncia cujos
itens també m podem ser acessados por meio de atributos. Para criar uma sequê ncia de estrutura, você primeiro
precisa criar um tipo de sequê ncia de estrutura específico.
PyTypeObject *PyStructSequence_NewType(PyStructSequence_Desc *desc)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um novo tipo de sequê ncia de estru-
tura a partir dos dados em desc, descrito abaixo. Instâ ncias do tipo resultante podem ser criadas com
PyStructSequence_New().
Retorna NULL com uma exceçã o definida em caso de falha.
void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)
Inicializa um tipo de sequê ncia de estrutura type de desc no lugar.
int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc)
Como PyStructSequence_InitType(), mas retorna 0 em caso de sucesso e -1 com uma exceçã o definida
em caso de falha.
Adicionado na versã o 3.4.
type PyStructSequence_Desc
Parte da ABI Está vel (incluindo todos os membros). Conté m as metainformaçõ es de um tipo de sequê ncia de
estrutura a ser criado.
const char *name
Nome totalmente qualificado do tipo; codificado em UTF-8 terminado em nulo. O nome deve conter o
nome do mó dulo.
const char *doc
Ponteiro para docstring para o tipo ou NULL para omitir
PyStructSequence_Field *fields
Ponteiro para um vetor terminado em NULL com nomes de campos do novo tipo
int n_in_sequence
Nú mero de campos visíveis para o lado Python (se usado como tupla)
type PyStructSequence_Field
Parte da ABI Está vel (incluindo todos os membros). Descreve um campo de uma sequê ncia de estrutura. Como
uma sequê ncia de estrutura é modelada como uma tupla, todos os campos sã o digitados como PyObject*.
O índice no vetor fields do PyStructSequence_Desc determina qual campo da sequê ncia de estrutura é
descrito.
8.3. Objetos Sequência 167
The Python/C API, Release 3.13.7
const char *name
Nome do campo ou NULL para terminar a lista de campos nomeados; definida para
PyStructSequence_UnnamedField para deixar sem nome.
const char *doc
Campo docstring ou NULL para omitir.
const char *const PyStructSequence_UnnamedField
Parte da ABI Está vel desde a versão 3.11. Valor especial para um nome de campo para deixá -lo sem nome.
Alterado na versã o 3.9: O tipo foi alterado de char *.
PyObject *PyStructSequence_New(PyTypeObject *type)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um instâ ncia de type, que deve ser criada com
PyStructSequence_NewType().
Retorna NULL com uma exceçã o definida em caso de falha.
PyObject *PyStructSequence_GetItem(PyObject *p, Py_ssize_t pos)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Retorna o objeto na posiçã o pos na sequê ncia de
estrutura apontada por p.
A verificaçã o de limites é realizada como uma asserçã o se o Python for construído em modo de depuraçã o ou
com asserções.
PyObject *PyStructSequence_GET_ITEM(PyObject *p, Py_ssize_t pos)
Retorna valor: Referência emprestada. Apelido para PyStructSequence_GetItem().
Alterado na versã o 3.13: Agora implementada como um apelido para PyStructSequence_GetItem().
void PyStructSequence_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Parte da ABI Está vel. Define o campo no índice pos da sequê ncia de estrutura p para o valor o. Como
PyTuple_SET_ITEM(), isto só deve ser usado para preencher novas instâ ncias.
A verificaçã o de limites é realizada como uma asserçã o se o Python for construído em modo de depuraçã o ou
com asserções.
® Nota
Esta funçã o “rouba” uma referê ncia a o.
void PyStructSequence_SET_ITEM(PyObject *p, Py_ssize_t *pos, PyObject *o)
Apelido para PyStructSequence_SetItem().
Alterado na versã o 3.13: Agora implementada como um apelido para PyStructSequence_SetItem().
8.3.6 Objeto List
type PyListObject
Este subtipo de PyObject representa um objeto de lista Python.
PyTypeObject PyList_Type
Parte da ABI Está vel. Esta instâ ncia de PyTypeObject representa o tipo de lista Python. Este é o mesmo
objeto que list na camada Python.
int PyList_Check(PyObject *p)
Retorna verdadeiro se p é um objeto lista ou uma instâ ncia de um subtipo do tipo lista. Esta funçã o sempre
tem sucesso.
int PyList_CheckExact(PyObject *p)
Retorna verdadeiro se p é um objeto lista, mas nã o uma instâ ncia de um subtipo do tipo lista. Esta funçã o
sempre tem sucesso.
168 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
PyObject *PyList_New(Py_ssize_t len)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna uma nova lista de comprimento len em caso
de sucesso, ou NULL em caso de falha.
® Nota
Se len for maior que zero, os itens do objeto da lista retornada sã o definidos como NULL. Portanto, você nã o
pode usar funçõ es API abstratas, como PySequence_SetItem() ou expor o objeto ao có digo Python
antes de definir todos os itens para um objeto real com PyList_SetItem() ou PyList_SET_ITEM().
As seguintes APIs sã o seguras desde que antes as listas tenham sido inicializadas: PyList_SetItem() e
PyList_SET_ITEM().
Py_ssize_t PyList_Size(PyObject *list)
Parte da ABI Está vel. Retorna o comprimento do objeto de lista em list; isto é equivalente a len(list) em
um objeto lista.
Py_ssize_t PyList_GET_SIZE(PyObject *list)
Similar a PyList_Size(), mas sem verificaçã o de erro.
PyObject *PyList_GetItemRef(PyObject *list, Py_ssize_t index)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.13. Retorna o objeto na posiçã o index
na lista apontada por list. A posiçã o deve ser nã o negativa; nã o há suporte à indexaçã o do final da lista. Se
index estiver fora dos limites (<0 or >=len(list)), retorna NULL e levanta uma exceçã o IndexError.
Adicionado na versã o 3.13.
PyObject *PyList_GetItem(PyObject *list, Py_ssize_t index)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Como PyList_GetItemRef(), mas retorna
uma referência emprestada em vez de uma referência forte.
PyObject *PyList_GET_ITEM(PyObject *list, Py_ssize_t i)
Retorna valor: Referência emprestada. Similar a PyList_GetItem(), mas sem verificaçã o de erro.
int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)
Parte da ABI Está vel. Define o item no índice index na lista como item. Retorna 0 em caso de sucesso. Se
index estiver fora dos limites, retorna -1 e levanta uma exceçã o IndexError.
® Nota
Esta funçã o “rouba” uma referê ncia para o item e descarta uma referê ncia para um item já presente na lista
na posiçã o afetada.
void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o)
Forma macro de PyList_SetItem() sem verificaçã o de erro. Este é normalmente usado apenas para pre-
encher novas listas onde nã o há conteú do anterior.
A verificaçã o de limites é realizada como uma asserçã o se o Python for construído em modo de depuraçã o ou
com asserções.
® Nota
Esta macro “rouba” uma referê ncia para o item e, ao contrá rio de PyList_SetItem(), não descarta uma
referê ncia para nenhum item que esteja sendo substituído; qualquer referê ncia em list será perdida.
int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item)
Parte da ABI Está vel. Insere o item item na lista list na frente do índice index. Retorna 0 se for bem-sucedido;
retorna -1 e levanta uma exceçã o se malsucedido. Aná logo a list.insert(index, item).
8.3. Objetos Sequência 169
The Python/C API, Release 3.13.7
int PyList_Append(PyObject *list, PyObject *item)
Parte da ABI Está vel. Adiciona o item item ao final da lista list. Retorna 0 se for bem-sucedido; retorna -1 e
levanta uma exceçã o se malsucedido. Aná logo a list.insert(index, item).
PyObject *PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna uma lista dos objetos em list contendo os
objetos entre low e alto. Retorne NULL e levanta uma exceçã o se malsucedido. Aná logo a list[low:high].
Nã o há suporte à indexaçã o do final da lista.
int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)
Parte da ABI Está vel. Define a fatia de list entre low e high para o conteú do de itemlist. Aná logo a
list[low:high] = itemlist. itemlist pode ser NULL, indicando a atribuiçã o de uma lista vazia (exclusã o
de fatia). Retorna 0 em caso de sucesso, -1 em caso de falha. Nã o há suporte à indexaçã o do final da lista.
int PyList_Extend(PyObject *list, PyObject *iterable)
Estende list com o conteú do de iterable. Isto é o mesmo que PyList_SetSlice(list,
PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, iterable) e aná logo a list.extend(iterable) ou
list += iterable.
Levanta uma exceçã o e retorna -1 se list nã o for um objeto list. Retorna 0 em caso de sucesso.
Adicionado na versã o 3.13.
int PyList_Clear(PyObject *list)
Remove todos os itens da lista. Isto é o mesmo que PyList_SetSlice(list, 0, PY_SSIZE_T_MAX,
NULL) e aná logo a list.clear() ou del list[:].
Levanta uma exceçã o e retorna -1 se list nã o for um objeto list. Retorna 0 em caso de sucesso.
Adicionado na versã o 3.13.
int PyList_Sort(PyObject *list)
Parte da ABI Está vel. Ordena os itens de list no mesmo lugar. Retorna 0 em caso de sucesso, e -1 em caso de
falha. Isso é o equivalente de list.sort().
int PyList_Reverse(PyObject *list)
Parte da ABI Está vel. Inverte os itens de list no mesmo lugar. Retorna 0 em caso de sucesso, e -1 em caso de
falha. Isso é o equivalente de list.reverse().
PyObject *PyList_AsTuple(PyObject *list)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto tupla contendo os conteú dos
de list; equivale a tuple(list).
8.4 Coleções
8.4.1 Objetos dicionários
type PyDictObject
Este subtipo do PyObject representa um objeto dicioná rio Python.
PyTypeObject PyDict_Type
Parte da ABI Está vel. Esta instâ ncia do PyTypeObject representa o tipo do dicioná rio Python. Este é o
mesmo objeto dict na camada do Python.
int PyDict_Check(PyObject *p)
Retorna verdadeiro se p é um objeto dicioná rio ou uma instâ ncia de um subtipo do tipo dicioná rio. Esta funçã o
sempre tem sucesso.
int PyDict_CheckExact(PyObject *p)
Retorna verdadeiro se p é um objeto dicioná rio, mas nã o uma instâ ncia de um subtipo do tipo dicioná rio. Esta
funçã o sempre tem sucesso.
170 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
PyObject *PyDict_New()
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo dicioná rio vazio ou NULL em caso de
falha.
PyObject *PyDictProxy_New(PyObject *mapping)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um objeto types.MappingProxyType para
um mapeamento que reforça o comportamento somente leitura. Isso normalmente é usado para criar uma
visã o para evitar a modificaçã o do dicioná rio para tipos de classes nã o dinâ micas.
void PyDict_Clear(PyObject *p)
Parte da ABI Está vel. Esvazia um dicioná rio existente de todos os pares chave-valor.
int PyDict_Contains(PyObject *p, PyObject *key)
Parte da ABI Está vel. Determina se o dicioná rio p conté m key. Se um item em p corresponder à key, retorna
1, caso contrá rio, retorna 0. Em caso de erro, retorna -1. Isso é equivalente à expressã o Python key in p.
int PyDict_ContainsString(PyObject *p, const char *key)
É o mesmo que PyDict_Contains(), mas key é especificada como uma string de bytes const char*
codificada em UTF-8, em vez de um PyObject*.
Adicionado na versã o 3.13.
PyObject *PyDict_Copy(PyObject *p)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo dicioná rio que conté m o mesmo
chave-valor como p.
int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
Parte da ABI Está vel. Insere val no dicioná rio p com a tecla key. key deve ser hasheável; se nã o for, TypeError
será levantada. Retorna 0 em caso de sucesso ou -1 em caso de falha. Esta funçã o não rouba uma referê ncia
a val.
int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
Parte da ABI Está vel. É o mesmo que PyDict_SetItem(), mas key é especificada como uma string de bytes
const char* codificada em UTF-8, em vez de um PyObject*.
int PyDict_DelItem(PyObject *p, PyObject *key)
Parte da ABI Está vel. Remove a entrada no dicioná rio p com a chave key. key deve ser hasheável; se nã o
for, TypeError é levantada. Se key nã o estiver no dicioná rio, KeyError é levantada. Retorna 0 em caso de
sucesso ou -1 em caso de falha.
int PyDict_DelItemString(PyObject *p, const char *key)
Parte da ABI Está vel. É o mesmo que PyDict_DelItem(), mas key é especificada como uma string de bytes
const char* codificada em UTF-8, em vez de um PyObject*.
int PyDict_GetItemRef(PyObject *p, PyObject *key, PyObject **result)
Parte da ABI Está vel desde a versão 3.13. Retorna uma nova referência forte para o objeto dicioná rio p que
possui uma chave key:
• Se a chave estiver presente, define *result como uma nova referência forte para o valor e retorna 1.
• Se a chave estiver ausente, define *result como NULL e retorna 0.
• Em caso de erro, levanta uma exceçã o e retorna -1.
Adicionado na versã o 3.13.
Veja també m a funçã o PyObject_GetItem().
PyObject *PyDict_GetItem(PyObject *p, PyObject *key)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Retorna um referência emprestada para o objeto
do dicioná rio p que possui uma chave key. Retorna NULL se a chave key nã o estiver presente, mas sem definir
uma exceçã o.
8.4. Coleções 171
The Python/C API, Release 3.13.7
® Nota
Exceçõ es que ocorrem ao chamar os mé todos __hash__() e __eq__() sã o ignoradas silenciosamente.
Ao invé s disso, use a funçã o PyDict_GetItemWithError().
Alterado na versã o 3.10: Chamar esta API sem GIL retida era permitido por motivos histó ricos. Nã o é mais
permitido.
PyObject *PyDict_GetItemWithError(PyObject *p, PyObject *key)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Variante de PyDict_GetItem() que nã o
suprime exceçõ es. Retorna NULL com uma exceçã o definida se uma exceçã o ocorreu. Retorna NULL ** sem
** uma exceçã o definida se a chave nã o estiver presente.
PyObject *PyDict_GetItemString(PyObject *p, const char *key)
Retorna valor: Referência emprestada. Parte da ABI Está vel. É o mesmo que PyDict_GetItem(), mas key
é especificada como uma string de bytes const char* codificada em UTF-8, em vez de um PyObject*.
® Nota
Exceçõ es que ocorrem ao chamar os mé todos __hash__() e __eq__() ou ao criar objetos tem-
porá rios da classe str sã o ignoradas silenciosamente. Ao invé s disso, prefira usar a funçã o
PyDict_GetItemWithError() com sua pró pria key de PyUnicode_FromString().
int PyDict_GetItemStringRef(PyObject *p, const char *key, PyObject **result)
Parte da ABI Está vel desde a versão 3.13. Similar a PyDict_GetItemRef(), mas key é especificada como
uma string de bytes const char* codificada em UTF-8, em vez de um PyObject*.
Adicionado na versã o 3.13.
PyObject *PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)
Retorna valor: Referência emprestada. Isso é o mesmo que o dict.setdefault() de nível Python. Se
presente, ele retorna o valor correspondente a key do dicioná rio p. Se a chave nã o estiver no dict, ela será
inserida com o valor defaultobj e defaultobj será retornado. Esta funçã o avalia a funçã o hash de key apenas
uma vez, em vez de avaliá -la independentemente para a pesquisa e a inserçã o.
Adicionado na versã o 3.4.
int PyDict_SetDefaultRef(PyObject *p, PyObject *key, PyObject *default_value, PyObject **result)
Insere default_value no dicioná rio p com uma chave key se a chave ainda nã o estiver presente no dicioná rio.
Se result nã o for NULL, entã o *result é definido como uma referência forte para default_value, se a chave nã o
estiver presente, ou para o valor existente, se key já estava presente no dicioná rio. Retorna 1 se a chave estava
presente e default_value nã o foi inserido, ou 0 se a chave nã o estava presente e default_value foi inserido. Em
caso de falha, retorna -1, define uma exceçã o e define *result como NULL.
Para maior clareza: se você tiver uma referê ncia forte para default_value antes de chamar esta funçã o, entã o
depois que ela retornar, você terá uma referê ncia forte para default_value e *result (se nã o for NULL). Estes
podem referir-se ao mesmo objeto: nesse caso você manté m duas referê ncias separadas para ele.
Adicionado na versã o 3.13.
int PyDict_Pop(PyObject *p, PyObject *key, PyObject **result)
Remove key do dicioná rio p e, opcionalmente, retorna o valor removido. Nã o levanta KeyError se a chave
estiver ausente.
• Se a chave estiver presente, define *result como uma nova referê ncia para o valor se result nã o for NULL
e retorna 1.
• Se a chave estiver ausente, define *result como NULL se result nã o for NULL e retorna 0.
• Em caso de erro, levanta uma exceçã o e retorna -1.
172 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Similar a dict.pop(), mas sem o valor padrã o e sem levantar KeyError se a chave estiver ausente.
Adicionado na versã o 3.13.
int PyDict_PopString(PyObject *p, const char *key, PyObject **result)
Similar a PyDict_Pop(), mas key é especificada como uma string de bytes const char* codificada em
UTF-8, em vez de um PyObject*.
Adicionado na versã o 3.13.
PyObject *PyDict_Items(PyObject *p)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um PyListObject contendo todos os itens
do dicioná rio.
PyObject *PyDict_Keys(PyObject *p)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um PyListObject contendo todas as chaves
do dicioná rio.
PyObject *PyDict_Values(PyObject *p)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um PyListObject contendo todos os valores
do dicioná rio p.
Py_ssize_t PyDict_Size(PyObject *p)
Parte da ABI Está vel. Retorna o nú mero de itens no dicioná rio. Isso é equivalente a len(p) em um dicioná rio.
int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Parte da ABI Está vel. Itera todos os pares de valores-chave no dicioná rio p. O Py_ssize_t referido por ppos
deve ser inicializado para 0 antes da primeira chamada para esta funçã o para iniciar a iteraçã o; a funçã o retorna
true para cada par no dicioná rio e false quando todos os pares forem relatados. Os parâ metros pkey e pvalue
devem apontar para variá veis de PyObject* que serã o preenchidas com cada chave e valor, respectivamente,
ou podem ser NULL. Todas as referê ncias retornadas por meio deles sã o emprestadas. ppos nã o deve ser alterado
durante a iteraçã o. Seu valor representa deslocamentos dentro da estrutura do dicioná rio interno e, como a
estrutura é esparsa, os deslocamentos nã o sã o consecutivos.
Por exemplo:
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(self->dict, &pos, &key, &value)) {
/* fazer algo de interessante com os valores... */
...
}
O dicioná rio p nã o deve sofrer mutaçã o durante a iteraçã o. É seguro modificar os valores das chaves à medida
que você itera no dicioná rio, mas apenas enquanto o conjunto de chaves nã o mudar. Por exemplo:
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;
(continua na pró xima pá gina)
8.4. Coleções 173
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
}
Py_DECREF(o);
}
A funçã o nã o é segura para thread na construçã o com threads livres sem sincronizaçã o externa. Você pode
usar Py_BEGIN_CRITICAL_SECTION para travar o dicioná rio enquanto itera sobre ele:
Py_BEGIN_CRITICAL_SECTION(self->dict);
while (PyDict_Next(self->dict, &pos, &key, &value)) {
...
}
Py_END_CRITICAL_SECTION();
int PyDict_Merge(PyObject *a, PyObject *b, int override)
Parte da ABI Está vel. Itera sobre o objeto de mapeamento b adicionando pares de valores-chave ao dicioná rio
a. b pode ser um dicioná rio, ou qualquer objeto que suporte PyMapping_Keys() e PyObject_GetItem().
Se override for verdadeiro, os pares existentes em a serã o substituídos se uma chave correspondente for en-
contrada em b, caso contrá rio, os pares serã o adicionados apenas se nã o houver uma chave correspondente em
a. Retorna 0 em caso de sucesso ou -1 se uma exceçã o foi levantada.
int PyDict_Update(PyObject *a, PyObject *b)
Parte da ABI Está vel. É o mesmo que PyDict_Merge(a, b, 1) em C, e é semelhante a a.update(b) em
Python, exceto que PyDict_Update() nã o cai na iteraçã o em uma sequê ncia de pares de valores de chave
se o segundo argumento nã o tiver o atributo “keys”. Retorna 0 em caso de sucesso ou -1 se uma exceçã o foi
levantada.
int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
Parte da ABI Está vel. Atualiza ou mescla no dicioná rio a, a partir dos pares de chave-valor em seq2. seq2 deve
ser um objeto iterá vel produzindo objetos iterá veis de comprimento 2, vistos como pares chave-valor. No caso
de chaves duplicadas, a ú ltima vence se override for verdadeiro, caso contrá rio, a primeira vence. Retorne 0
em caso de sucesso ou -1 se uma exceçã o foi levantada. Python equivalente (exceto para o 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)
Registra callback como um observador de dicioná rio. Retorna um ID inteiro nã o negativo que deve ser passado
para futuras chamadas a PyDict_Watch(). Em caso de erro (por exemplo, nã o há mais IDs de observador
disponíveis), retorna -1 e define uma exceçã o.
Adicionado na versã o 3.12.
int PyDict_ClearWatcher(int watcher_id)
Limpa o observador identificado por watcher_id retornado anteriormente de PyDict_AddWatcher(). Re-
torna 0 em caso de sucesso, -1 em caso de erro (por exemplo, se o watcher_id fornecido nunca foi registrado).
Adicionado na versã o 3.12.
int PyDict_Watch(int watcher_id, PyObject *dict)
Marca o dicioná rio dict como observado. A funçã o de retorno concedida a watcher_id por
PyDict_AddWatcher() será chamada quando dict for modificado ou desalocado. Retorna 0 em caso de
sucesso ou -1 em caso de erro.
Adicionado na versã o 3.12.
int PyDict_Unwatch(int watcher_id, PyObject *dict)
Marca o dicioná rio dict como nã o mais observado. A funçã o de retorno concedida a watcher_id por
174 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
PyDict_AddWatcher() será chamada quando dict for modificado ou desalocado. O dicioná rio deve ter
sido observado anteriormente por este observador. Retorna 0 em caso de sucesso ou -1 em caso de erro.
Adicionado na versã o 3.12.
type PyDict_WatchEvent
Enumeraçã o de possíveis eventos de observador de dicioná rio: PyDict_EVENT_ADDED,
PyDict_EVENT_MODIFIED, PyDict_EVENT_DELETED, PyDict_EVENT_CLONED,
PyDict_EVENT_CLEARED ou PyDict_EVENT_DEALLOCATED.
Adicionado na versã o 3.12.
typedef int (*PyDict_WatchCallback)(PyDict_WatchEvent event, PyObject *dict, PyObject *key, PyObject
*new_value)
Tipo de uma funçã o de retorno de chamada de observador de dicioná rio.
Se event for PyDict_EVENT_CLEARED ou PyDict_EVENT_DEALLOCATED, tanto key quanto new_value se-
rã o NULL. Se event for PyDict_EVENT_ADDED ou PyDict_EVENT_MODIFIED, new_value será o novo valor
de key. Se event for PyDict_EVENT_DELETED, key estará sendo excluída do dicioná rio e new_value será
NULL.
PyDict_EVENT_CLONED ocorre quando dict estava anteriormente vazio e outro dict é mesclado a ele. Para
manter a eficiê ncia dessa operaçã o, os eventos PyDict_EVENT_ADDED por chave nã o sã o emitidos nesse caso;
em vez disso, um ú nico PyDict_EVENT_CLONED é emitido e key será o dicioná rio de origem.
A funçã o de retorno pode inspecionar, mas nã o deve modificar o dict; isso pode ter efeitos imprevisíveis,
inclusive recursã o infinita. Nã o acione a execuçã o do có digo Python na funçã o de retorno, pois isso poderia
modificar o dict como um efeito colateral.
Se event for PyDict_EVENT_DEALLOCATED, a obtençã o de uma nova referê ncia na funçã o de retorno para
o dicioná rio prestes a ser destruído o ressuscitará e impedirá que ele seja liberado nesse momento. Quando
o objeto ressuscitado for destruído mais tarde, quaisquer funçõ es de retorno do observador ativos naquele
momento serã o chamados novamente.
As funçõ es de retorno ocorrem antes que a modificaçã o notificada no dict ocorra, de modo que o estado anterior
do dict possa ser inspecionado.
Se a funçã o de retorno definir uma exceçã o, ela deverá retornar -1. Essa exceçã o será exibida como uma
exceçã o nã o levantá vel usando PyErr_WriteUnraisable(). Caso contrá rio, deverá retornar 0.
É possível que já exista uma exceçã o pendente definida na entrada da funçã o de retorno. Nesse caso, a funçã o
de retorno deve retornar 0 com a mesma exceçã o ainda definida. Isso significa que a funçã o de retorno nã o pode
chamar nenhuma outra API que possa definir uma exceçã o, a menos que salve e limpe o estado da exceçã o
primeiro e restaure a exceçã o antes de retornar.
Adicionado na versã o 3.12.
8.4.2 Objeto Set
Esta seçã o detalha a API pú blica para os objetos set e frozenset. Qualquer funcionalidade nã o listada
abaixo é melhor acessada usando o protocolo de objeto abstrato (incluindo PyObject_CallMethod(),
PyObject_RichCompareBool(), PyObject_Hash(), PyObject_Repr(), PyObject_IsTrue(),
PyObject_Print() e PyObject_GetIter()) ou o protocolo abstrato de nú mero (incluindo PyNumber_And(),
PyNumber_Subtract(), PyNumber_Or(), PyNumber_Xor(), PyNumber_InPlaceAnd(),
PyNumber_InPlaceSubtract(), PyNumber_InPlaceOr() e PyNumber_InPlaceXor()).
type PySetObject
Este subtipo de PyObject é usado para manter os dados internos para ambos os objetos set e frozenset.
É como um PyDictObject em que tem um tamanho fixo para conjuntos pequenos (muito parecido com o
armazenamento de tupla) e apontará para um bloco de memó ria de tamanho variá vel separado para conjuntos
de tamanho mé dio e grande (muito parecido com lista armazenamento). Nenhum dos campos desta estrutura
deve ser considerado pú blico e todos estã o sujeitos a alteraçõ es. Todo o acesso deve ser feito por meio da API
documentada, em vez de manipular os valores na estrutura.
8.4. Coleções 175
The Python/C API, Release 3.13.7
PyTypeObject PySet_Type
Parte da ABI Está vel. Essa é uma instâ ncia de PyTypeObject representando o tipo Python set
PyTypeObject PyFrozenSet_Type
Parte da ABI Está vel. Esta é uma instâ ncia de PyTypeObject representando o tipo Python frozenset.
As macros de verificaçã o de tipo a seguir funcionam em ponteiros para qualquer objeto Python. Da mesma forma,
as funçõ es construtoras funcionam com qualquer objeto Python iterá vel.
int PySet_Check(PyObject *p)
Retorna verdadeiro se p for um objeto set ou uma instâ ncia de um subtipo. Esta funçã o sempre tem sucesso.
int PyFrozenSet_Check(PyObject *p)
Retorna verdadeiro se p for um objeto frozenset ou uma instâ ncia de um subtipo. Esta funçã o sempre tem
sucesso.
int PyAnySet_Check(PyObject *p)
Retorna verdadeiro se p for um objeto set, um objeto frozenset ou uma instâ ncia de um subtipo. Esta
funçã o sempre tem sucesso.
int PySet_CheckExact(PyObject *p)
Retorna verdadeiro se p for um objeto set, mas nã o uma instâ ncia de um subtipo. Esta funçã o sempre tem
sucesso.
Adicionado na versã o 3.10.
int PyAnySet_CheckExact(PyObject *p)
Retorna verdadeiro se p for um objeto set ou um objeto frozenset, mas nã o uma instâ ncia de um subtipo.
Esta funçã o sempre tem sucesso.
int PyFrozenSet_CheckExact(PyObject *p)
Retorna verdadeiro se p for um objeto frozenset, mas nã o uma instâ ncia de um subtipo. Esta funçã o sempre
tem sucesso.
PyObject *PySet_New(PyObject *iterable)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna uma nova set contendo objetos retornados
pelo iterá vel iterable. O iterable pode ser NULL para criar um novo conjunto vazio. Retorna o novo conjunto
em caso de sucesso ou NULL em caso de falha. Levanta TypeError se iterable nã o for realmente iterá vel. O
construtor també m é ú til para copiar um conjunto (c=set(s)).
PyObject *PyFrozenSet_New(PyObject *iterable)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna uma nova frozenset contendo objetos
retornados pelo iterá vel iterable. O iterable pode ser NULL para criar um novo frozenset vazio. Retorna o novo
conjunto em caso de sucesso ou NULL em caso de falha. Levanta TypeError se iterable nã o for realmente
iterá vel.
As seguintes funçõ es e macros estã o disponíveis para instâ ncias de set ou frozenset ou instâ ncias de seus subtipos.
Py_ssize_t PySet_Size(PyObject *anyset)
Parte da ABI Está vel. Retorna o comprimento de um objeto set ou frozenset. Equivalente a
len(anyset). Levanta um SystemError se anyset nã o for um set, frozenset, ou uma instâ ncia de
um subtipo.
Py_ssize_t PySet_GET_SIZE(PyObject *anyset)
Forma macro de PySet_Size() sem verificaçã o de erros.
int PySet_Contains(PyObject *anyset, PyObject *key)
Parte da ABI Está vel. Retorna 1 se encontrado, 0 se nã o encontrado, e -1 se um erro é encontrado. Ao contrá -
rio do mé todo Python __contains__(), esta funçã o nã o converte automaticamente conjuntos nã o hasheá veis
em frozensets temporá rios. Levanta um TypeError se a key nã o for hasheá vel. Levanta SystemError se
anyset nã o é um set, frozenset, ou uma instâ ncia de um subtipo.
176 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PySet_Add(PyObject *set, PyObject *key)
Parte da ABI Está vel. Adiciona key a uma instâ ncia de set. També m funciona com instâ ncias de frozenset
(como PyTuple_SetItem(), ele pode ser usado para preencher os valores de novos conjuntos de congela-
mentos antes que eles sejam expostos a outro có digo). Retorna 0 em caso de sucesso ou -1 em caso de falha.
Levanta um TypeError se a key nã o for hasheá vel. Levanta uma MemoryError se nã o houver espaço para
crescer. Levanta uma SystemError se set nã o for uma instâ ncia de set ou seu subtipo.
As seguintes funçõ es estã o disponíveis para instâ ncias de set ou seus subtipos, mas nã o para instâ ncias de
frozenset ou seus subtipos.
int PySet_Discard(PyObject *set, PyObject *key)
Parte da ABI Está vel. Retorna 1 se encontrado e removido, 0 se nã o encontrado (nenhuma açã o realizada) e
-1 se um erro for encontrado. Nã o levanta KeyError para chaves ausentes. Levanta uma TypeError se a key
nã o for hasheá vel. Ao contrá rio do mé todo Python discard(), esta funçã o nã o converte automaticamente
conjuntos nã o hasheá veis em frozensets temporá rios. Levanta SystemError se set nã o é uma instâ ncia de
set ou seu subtipo.
PyObject *PySet_Pop(PyObject *set)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna uma nova referê ncia a um objeto arbitrá rio no
set e remove o objeto do set. Retorna NULL em caso de falha. Levanta KeyError se o conjunto estiver vazio.
Levanta uma SystemError se set nã o for uma instâ ncia de set ou seu subtipo.
int PySet_Clear(PyObject *set)
Parte da ABI Está vel. Esvazia um conjunto existente de todos os elementos. Retorna 0 em caso de sucesso.
Retorna -1 e levanta SystemError se set nã o for uma instâ ncia de set ou seu subtipo.
8.5 Objetos Function
8.5.1 Objetos Function
Existem algumas funçõ es específicas para as funçõ es do Python.
type PyFunctionObject
A estrutura C usada para funçõ es.
PyTypeObject PyFunction_Type
Esta é uma instâ ncia de PyTypeObject e representa o tipo de funçã o Python. Está exposta a programadores
Python como types.FunctionType.
int PyFunction_Check(PyObject *o)
Retorna verdadeiro se o for um objeto funçã o (tem tipo PyFunction_Type). O parâ metro nã o deve ser NULL.
Esta funçã o sempre obté m sucesso.
PyObject *PyFunction_New(PyObject *code, PyObject *globals)
Retorna valor: Nova referência. Retorna um novo objeto funçã o associado ao objeto có digo code. globals deve
ser um dicioná rio com as variá veis globais acessíveis à funçã o.
O nome e docstring da funçã o sã o adquiridos pelo objeto có digo. O atributo __module__ é adquirido por
meio de globals. Os valores-padrã o de argumentos, anotaçõ es, e fechamento sã o definidos como NULL. O
atributo __qualname__ é definido com o mesmo valor do campo co_qualname de um objeto có digo.
PyObject *PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
Retorna valor: Nova referência. Similar a PyFunction_New(), mas també m permite definir o atributo
__qualname__ do objeto funçã o. qualname deve ser um objeto Unicode ou NULL. Se NULL, o atributo
__qualname__ é definido com o mesmo valor do campo co_qualname do objeto có digo.
Adicionado na versã o 3.3.
PyObject *PyFunction_GetCode(PyObject *op)
Retorna valor: Referência emprestada. Retorna o objeto có digo associado ao objeto funçã o op.
8.5. Objetos Function 177
The Python/C API, Release 3.13.7
PyObject *PyFunction_GetGlobals(PyObject *op)
Retorna valor: Referência emprestada. Retorna o dicioná rio global associado ao objeto funçã o op.
PyObject *PyFunction_GetModule(PyObject *op)
Retorna valor: Referência emprestada. Retorna uma referência emprestada ao atributo __module__ do objeto
funçã o op. Pode ser NULL.
Normalmente, trata-se de um string contendo o nome do mó dulo, mas pode ser definido como qualquer
outro objeto pelo có digo Python.
PyObject *PyFunction_GetDefaults(PyObject *op)
Retorna valor: Referência emprestada. Retorna os valores-padrã o de argumentos do objeto funçã o op. Pode
ser uma tupla de argumentos ou NULL.
int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
Define os valores-padrã o dos argumentos do objeto funçã o op. defaults deve ser Py_None ou uma tupla.
Levanta SystemError e retorna -1 em caso de falha.
void PyFunction_SetVectorcall(PyFunctionObject *func, vectorcallfunc vectorcall)
Define o campo vectorcall de um objeto funçã o func.
Atençã o: extensõ es que usam essa API devem preservar o comportamento inalterado (padrã o) de uma funçã o
vectorcall!
Adicionado na versã o 3.12.
PyObject *PyFunction_GetKwDefaults(PyObject *op)
Retorna valor: Referência emprestada. Retorna os valores-padrã o de argumentos somente-nomeados do objeto
funçã o op. Pode ser um dicioná rio de argumentos ou NULL.
PyObject *PyFunction_GetClosure(PyObject *op)
Retorna valor: Referência emprestada. Retorna o fechamento associado ao objeto funçã o op. Pode ser NULL
ou uma tupla de objetos cé lula.
int PyFunction_SetClosure(PyObject *op, PyObject *closure)
Define o fechamento associado ao objeto funçã o op. closure deve ser Py_None ou uma tupla de objetos de
cé lula.
Levanta SystemError e retorna -1 em caso de falha.
PyObject *PyFunction_GetAnnotations(PyObject *op)
Retorna valor: Referência emprestada. Retorna as anotaçõ es do objeto funçã o op. Este pode ser um dicioná rio
mutá vel ou NULL.
int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
Define as anotaçõ es para o objeto funçã o op. annotations deve ser um dicioná rio ou Py_None.
Levanta SystemError e retorna -1 em caso de falha.
PyObject *PyFunction_GET_CODE(PyObject *op)
PyObject *PyFunction_GET_GLOBALS(PyObject *op)
PyObject *PyFunction_GET_MODULE(PyObject *op)
PyObject *PyFunction_GET_DEFAULTS(PyObject *op)
PyObject *PyFunction_GET_KW_DEFAULTS(PyObject *op)
PyObject *PyFunction_GET_CLOSURE(PyObject *op)
PyObject *PyFunction_GET_ANNOTATIONS(PyObject *op)
Retorna valor: Referência emprestada. Essas funçõ es sã o semelhantes à s suas contrapartes
PyFunction_Get*, mas nã o realizam verificaçã o de tipos. Passar qualquer coisa que nã o seja uma
instâ ncia de PyFunction_Type é um comportamento indefinido.
178 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyFunction_AddWatcher(PyFunction_WatchCallback callback)
Registra callback como uma sentinela de funçã o para o interpretador atual. Retorna um ID que pode ser
passado para PyFunction_ClearWatcher(). Em caso de erro (por exemplo, sem novos IDs de sentinelas
disponíveis), retorna -1 e define uma exceçã o.
Adicionado na versã o 3.12.
int PyFunction_ClearWatcher(int watcher_id)
Cancela o registro da sentinela identificada pelo watcher_id retornado por PyFunction_AddWatcher() para
o interpretador atual. Retorna 0 em caso de sucesso, ou -1 e define uma exceçã o em caso de erro (por exemplo,
ao receber um watcher_id desconhecido.)
Adicionado na versã o 3.12.
type PyFunction_WatchEvent
Enumeraçã o de possíveis eventos do observador de funçõ es:
• PyFunction_EVENT_CREATE
• PyFunction_EVENT_DESTROY
• PyFunction_EVENT_MODIFY_CODE
• PyFunction_EVENT_MODIFY_DEFAULTS
• PyFunction_EVENT_MODIFY_KWDEFAULTS
Adicionado na versã o 3.12.
typedef int (*PyFunction_WatchCallback)(PyFunction_WatchEvent event, PyFunctionObject *func, PyObject
*new_value)
Tipo de uma funçã o de retorno de sentinela de funçã o.
Se event for PyFunction_EVENT_CREATE ou PyFunction_EVENT_DESTROY, new_value será NULL. Se-
nã o, new_value portará uma referência emprestada ao novo valor prestes a ser guardado em func para o atributo
que está sendo modificado.
A funçã o de retorno poderá somente inspecionar, e nã o modificar func. Caso contrá rio, poderíamos ter efeitos
imprevisíveis, incluindo recursã o infinita.
Se event for PyFunction_EVENT_CREATE, a funçã o de retorno será invocada apó s func ter sido completa-
mente inicializada. Caso contrá rio, a funçã o de retorno será invocada antes de modificar func, entã o o estado
anterior de func poderá ser inspecionado. O ambiente de execuçã o pode otimizar a criaçã o de objetos funçã o,
quando possível, ao ignorá -las. Nesses casos, nenhum evento será emitido. Apesar de decisõ es de otimizaçã o
criarem diferenças de comportamento em tempo de execuçã o, elas nã o mudam a semâ ntica do có digo Python
sendo executado.
Se event for PyFunction_EVENT_DESTROY, entã o obter uma referê ncia dentro da funçã o de retorno para
a funçã o prestes a ser destruída irá revivê -la, impedindo que esta funçã o seja liberada nesse tempo. Quando
o objeto revivido for destruído, quaisquer funçõ es de retorno sentinelas ativas nesse momento poderã o ser
chamadas novamente.
Se a funçã o de retorno definir uma exceçã o, ela deverá retornar -1. Essa exceçã o será exibida como uma
exceçã o nã o levantá vel usando PyErr_WriteUnraisable(). Caso contrá rio, deverá retornar 0.
É possível que já exista uma exceçã o pendente definida na entrada da funçã o de retorno. Nesse caso, a funçã o
de retorno deve retornar 0 com a mesma exceçã o ainda definida. Isso significa que a funçã o de retorno nã o pode
chamar nenhuma outra API que possa definir uma exceçã o, a menos que salve e limpe o estado da exceçã o
primeiro e restaure a exceçã o antes de retornar.
Adicionado na versã o 3.12.
8.5. Objetos Function 179
The Python/C API, Release 3.13.7
8.5.2 Objetos de Método de Instância
Um mé todo de instâ ncia é um invó lucro para um PyCFunction e a nova maneira de vincular um PyCFunction a
um objeto classe. Ele substitui a chamada anterior PyMethod_New(func, NULL, class).
PyTypeObject PyInstanceMethod_Type
Esta instâ ncia de PyTypeObject representa o tipo de mé todo de instâ ncia Python. Nã o é exposto a programas
Python.
int PyInstanceMethod_Check(PyObject *o)
Retorna verdadeiro se o é um objeto de mé todo de instâ ncia (tem tipo PyInstanceMethod_Type). O parâ -
metro nã o deve ser NULL. Esta funçã o sempre tem sucesso.
PyObject *PyInstanceMethod_New(PyObject *func)
Retorna valor: Nova referência. Retorna um novo objeto de mé todo de instâ ncia, com func sendo qualquer
objeto chamá vel. func é a funçã o que será chamada quando o mé todo de instâ ncia for chamado.
PyObject *PyInstanceMethod_Function(PyObject *im)
Retorna valor: Referência emprestada. Retorna o objeto funçã o associado ao mé todo de instâ ncia im.
PyObject *PyInstanceMethod_GET_FUNCTION(PyObject *im)
Retorna valor: Referência emprestada. Versã o macro de PyInstanceMethod_Function() que evita a
verificaçã o de erros.
8.5.3 Objetos método
Mé todos sã o objetos funçã o vinculados. Os mé todos sã o sempre associados a uma instâ ncia de uma classe definida
pelo usuá rio. Mé todos nã o vinculados (mé todos vinculados a um objeto de classe) nã o estã o mais disponíveis.
PyTypeObject PyMethod_Type
Esta instâ ncia de PyTypeObject representa o tipo de mé todo Python. Isso é exposto a programas Python
como types.MethodType.
int PyMethod_Check(PyObject *o)
Retorna verdadeiro se o é um objeto de mé todo (tem tipo PyMethod_Type). O parâ metro nã o deve ser NULL.
Esta funçã o sempre tem sucesso.
PyObject *PyMethod_New(PyObject *func, PyObject *self)
Retorna valor: Nova referência. Retorna um novo objeto de mé todo, com func sendo qualquer objeto chamá vel
e self a instâ ncia à qual o mé todo deve ser vinculado. func é a funçã o que será chamada quando o mé todo for
chamado. self nã o deve ser NULL.
PyObject *PyMethod_Function(PyObject *meth)
Retorna valor: Referência emprestada. Retorna o objeto funçã o associado ao mé todo meth.
PyObject *PyMethod_GET_FUNCTION(PyObject *meth)
Retorna valor: Referência emprestada. Versã o macro de PyMethod_Function() que evita a verificaçã o de
erros.
PyObject *PyMethod_Self(PyObject *meth)
Retorna valor: Referência emprestada. Retorna a instâ ncia associada com o mé todo meth.
PyObject *PyMethod_GET_SELF(PyObject *meth)
Retorna valor: Referência emprestada. Versã o macro de PyMethod_Self() que evita a verificaçã o de erros.
8.5.4 Objeto célula
Objetos “cell” sã o usados para implementar variá veis referenciadas por mú ltiplos escopos. Para cada variá vel, um
objeto cé lula é criado para armazenar o valor; as variá veis locais de cada quadro de pilha que referencia o valor conté m
uma referê ncia para as cé lulas de escopos externos que també m usam essa variá vel. Quando o valor é acessado, o
valor contido na cé lula é usado em vez do pró prio objeto da cé lula. Essa des-referê ncia do objeto da cé lula requer
suporte do có digo de bytes gerado; estes nã o sã o automaticamente desprezados quando acessados. Objetos de cé lulas
provavelmente nã o serã o ú teis em outro lugar.
180 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
type PyCellObject
A estrutura C usada para objetos cé lula.
PyTypeObject PyCell_Type
O objeto de tipo correspondente aos objetos cé lula.
int PyCell_Check(PyObject *ob)
Retorna verdadeiro se ob for um objeto cé lula; ob nã o deve ser NULL. Esta funçã o sempre tem sucesso.
PyObject *PyCell_New(PyObject *ob)
Retorna valor: Nova referência. Cria e retorna um novo objeto cé lula contendo o valor ob. O parâ metro pode
ser NULL.
PyObject *PyCell_Get(PyObject *cell)
Retorna valor: Nova referência. Retorna o conteú do da cé lula cell, que pode ser NULL. Se cell nã o for um
objeto cé lula, retorna NULL com um conjunto de exceçõ es.
PyObject *PyCell_GET(PyObject *cell)
Retorna valor: Referência emprestada. Retorna o conteú do da cé lula cell, mas sem verificar se cell nã o é NULL
e um objeto cé lula.
int PyCell_Set(PyObject *cell, PyObject *value)
Define o conteú do do objeto da cé lula cell como value. Isso libera a referê ncia a qualquer conteú do atual da
cé lula. value pode ser NULL. cell nã o pode ser NULL.
Em caso de sucesso, retorna 0. Se cell nã o for um objeto cé lula, define uma exceçã o e retorna -1.
void PyCell_SET(PyObject *cell, PyObject *value)
Define o valor do objeto da cé lula cell como value. Nenhuma contagem de referê ncia é ajustada e nenhuma
verificaçã o é feita quanto à segurança; cell nã o pode ser NULL e deve ser um objeto cé lula.
8.5.5 Objetos código
Os objetos có digo sã o um detalhe de baixo nível da implementaçã o do CPython. Cada um representa um pedaço de
có digo executá vel que ainda nã o foi vinculado a uma funçã o.
type PyCodeObject
A estrutura C dos objetos usados para descrever objetos có digo. Os campos deste tipo estã o sujeitos a alteraçõ es
a qualquer momento.
PyTypeObject PyCode_Type
Esta é uma instâ ncia de PyTypeObject representando o objeto có digo Python.
int PyCode_Check(PyObject *co)
Retorna verdadeiro se co for um objeto có digo. Esta funçã o sempre tem sucesso.
Py_ssize_t PyCode_GetNumFree(PyCodeObject *co)
Retorna o nú mero de variáveis livres (de clausura) em um objeto có digo.
int PyUnstable_Code_GetFirstFree(PyCodeObject *co)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Retorna a posiçã o da primeira variável livre (de clausura) em um objeto có digo.
Alterado na versã o 3.13: Renomeado de PyCode_GetFirstFree como parte da API C Instável. O nome
antigo foi descontinuado, mas continuará disponível até que a assinatura mude novamente.
8.5. Objetos Function 181
The Python/C API, Release 3.13.7
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)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Devolve um novo objeto có digo. Se precisar de um objeto có digo vazio para criar um quadro, use
PyCode_NewEmpty()
Como a definiçã o de bytecode muda constantemente, chamar PyUnstable_Code_New() diretamente pode
vinculá -lo a uma versã o de Python específica.
Os vá rios argumentos desta funçã o sã o inter-dependentes de maneiras complexas, significando que mesmo
alteraçõ es discretas de valor tem chances de resultar em execuçã o incorreta ou erros fatais de VM. Tenha
extremo cuidado ao usar esta funçã o.
Alterado na versã o 3.11: Adicionou os parâ metros qualname e exceptiontable
Alterado na versã o 3.12: Renomeado de PyCode_New como parte da API C Instável. O nome antigo foi
descontinuado, mas continuará disponível até que a assinatura mude novamente.
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)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Similar a PyUnstable_Code_New(), mas com um “posonlyargcount” extra para argumentos somente-
-posicionais. As mesmas ressalvas que se aplicam a PyUnstable_Code_New també m se aplicam a essa
funçã o.
Adicionado na versã o 3.8: Como PyCode_NewWithPosOnlyArgs
Alterado na versã o 3.11: Adicionados os parâ metros qualname e exceptiontable
Alterado na versã o 3.12: Renomeado para PyUnstable_Code_NewWithPosOnlyArgs. O nome antigo foi
descontinuado, mas continuará disponível até que a assinatura mude novamente.
PyCodeObject *PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
Retorna valor: Nova referência. Retorna um novo objeto có digo vazio com o nome de arquivo, nome da
funçã o e nú mero da primeira linha especificados. O objeto có digo resultante irá levantar uma Exception se
executado.
int PyCode_Addr2Line(PyCodeObject *co, int byte_offset)
Retorna o nú mero da linha da instruçã o que ocorre em ou antes de byte_offset e termina depois disso. Se
você só precisa do nú mero da linha de um quadro, use PyFrame_GetLineNumber().
Para iterar eficientemente sobre os nú meros de linha em um objeto có digo, use a API descrita na PEP 626 .
182 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyCode_Addr2Location(PyObject *co, int byte_offset, int *start_line, int *start_column, int *end_line, int
*end_column)
Define os ponteiros int passados para a linha do có digo-fonte e os nú meros da coluna para a instruçã o em
byte_offset. Define o valor como 0 quando as informaçõ es nã o estã o disponíveis para nenhum elemento
em particular.
Retorna 1 se a funçã o for bem-sucedida e 0 caso contrá rio.
Adicionado na versã o 3.11.
PyObject *PyCode_GetCode(PyCodeObject *co)
Equivalente ao có digo Python getattr(co, 'co_code'). Retorna uma referê ncia forte a um
PyBytesObject representando o bytecode em um objeto có digo. Em caso de erro, NULL é retornado e
uma exceçã o é levantada.
Este PyBytesObject pode ser criado sob demanda pelo interpretador e nã o representa necessariamente o
bytecode realmente executado pelo CPython. O caso de uso primá rio para esta funçã o sã o depuradores e
criadores de perfil.
Adicionado na versã o 3.11.
PyObject *PyCode_GetVarnames(PyCodeObject *co)
Equivalente ao có digo Python getattr(co, 'co_varnames'). Retorna uma nova referê ncia a um
PyTupleObject contendo os nomes das variá veis locais. Em caso de erro, NULL é retornado e uma exceçã o
é levantada.
Adicionado na versã o 3.11.
PyObject *PyCode_GetCellvars(PyCodeObject *co)
Equivalente ao có digo Python getattr(co, 'co_cellvars'). Retorna uma nova referê ncia a um
PyTupleObject contendo os nomes das variá veis locais referenciadas por funçõ es aninhadas. Em caso de
erro, NULL é retornado e uma exceçã o é levantada.
Adicionado na versã o 3.11.
PyObject *PyCode_GetFreevars(PyCodeObject *co)
Equivalente ao có digo Python getattr(co, 'co_freevars'). Retorna uma nova referê ncia a um
PyTupleObject contendo os nomes das variáveis livres (de clausura). Em caso de erro, NULL é retornado e
uma exceçã o é levantada.
Adicionado na versã o 3.11.
int PyCode_AddWatcher(PyCode_WatchCallback callback)
Registra callback como um observador do objeto có digo para o interpretador atual. Devolve um ID que pode
ser passado para PyCode_ClearWatcher(). Em caso de erro (por exemplo, nã o há IDs de observadores
disponíveis), devolve -1 e define uma exceçã o.
Adicionado na versã o 3.12.
int PyCode_ClearWatcher(int watcher_id)
Libera o observador identificado por watcher_id anteriormente retornado por PyCode_AddWatcher() para
o interpretador atual. Retorna 0 em caso de sucesso ou -1 em caso de erro e levanta uma exceçã o (ex., se o
watcher_id dado nã o foi registrado.)
Adicionado na versã o 3.12.
type PyCodeEvent
Enumeraçã o dos possíveis eventos de observador do objeto có digo: PY_CODE_EVENT_CREATE -
PY_CODE_EVENT_DESTROY
Adicionado na versã o 3.12.
8.5. Objetos Function 183
The Python/C API, Release 3.13.7
typedef int (*PyCode_WatchCallback)(PyCodeEvent event, PyCodeObject *co)
Tipo de uma funçã o de callback de observador de objeto có digo.
Se evento é PY_CODE_EVENT_CREATE, entã o a funçã o de retorno é invocada apó s co ter sido completamente
inicializado. Senã o, a funçã o de retorno é invocada antes que a destruiçã o de co ocorra, para que o estado
anterior de co possa ser inspecionado.
Se evento for PY_CODE_EVENT_DESTROY, obter uma referê ncia para a funçã o de retorno do objeto-a-ser-
-destruído irá reativá -lo e impedirá que o objeto seja liberado. Quando o objeto reativado é posteriormente
destruído, qualquer observador de funçõ es de retorno ativos naquele momento serã o chamados novamente.
Usuá rios desta API nã o devem depender de detalhes internos de implementaçã o em tempo de execuçã o. Tais
detalhes podem incluir, mas nã o estã o limitados a: o ordem e o momento exatos da criaçã o e destruiçã o de
objetos có digo. Enquanto alteraçõ es nestes detalhes podem resultar em diferenças que sã o visíveis para os
observadores (incluindo se uma funçã o de retorno é chamada ou nã o), isso nã o muda a semâ ntica do có digo
Python executado.
Se a funçã o de retorno definir uma exceçã o, ela deverá retornar -1. Essa exceçã o será exibida como uma
exceçã o nã o levantá vel usando PyErr_WriteUnraisable(). Caso contrá rio, deverá retornar 0.
É possível que já exista uma exceçã o pendente definida na entrada da funçã o de retorno. Nesse caso, a funçã o
de retorno deve retornar 0 com a mesma exceçã o ainda definida. Isso significa que a funçã o de retorno nã o pode
chamar nenhuma outra API que possa definir uma exceçã o, a menos que salve e limpe o estado da exceçã o
primeiro e restaure a exceçã o antes de retornar.
Adicionado na versã o 3.12.
8.5.6 Sinalizadores de objetos código
Objetos có digo contê m um campo de bits de sinalizadores, que podem ser recuperados como o atributo Python
co_flags (por exemplo, usando PyObject_GetAttrString()) e definidos usando um argumento flags para
PyUnstable_Code_New() e funçõ es semelhantes.
Os sinalizadores cujos nomes começam com CO_FUTURE_ correspondem a recursos normalmente selecioná veis por
instruçõ es future. Esses sinalizadores podem ser usados em PyCompilerFlags.cf_flags. Observe que muitos
sinalizadores CO_FUTURE_ sã o obrigató rios nas versõ es atuais do Python, e defini-los nã o tem efeito.
Os seguintes sinalizador estã o disponíveis. Para saber o significado delas, consulte a documentaçã o vinculada de seus
equivalentes em Python.
184 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Sinalizador Significado
inspect.CO_OPTIMIZED
CO_OPTIMIZED
inspect.CO_NEWLOCALS
CO_NEWLOCALS
inspect.CO_VARARGS
CO_VARARGS
inspect.CO_VARKEYWORDS
CO_VARKEYWORDS
inspect.CO_NESTED
CO_NESTED
inspect.CO_GENERATOR
CO_GENERATOR
inspect.CO_COROUTINE
CO_COROUTINE
inspect.CO_ITERABLE_COROUTINE
CO_ITERABLE_COROUTINE
inspect.CO_ASYNC_GENERATOR
CO_ASYNC_GENERATOR
sem efeito (__future__.division)
CO_FUTURE_DIVISION
sem efeito (__future__.absolute_import)
CO_FUTURE_ABSOLUTE_IMPORT
sem efeito (__future__.with_statement)
CO_FUTURE_WITH_STATEMENT
sem efeito (__future__.print_function)
CO_FUTURE_PRINT_FUNCTION
sem efeito (__future__.unicode_literals)
CO_FUTURE_UNICODE_LITERALS
sem efeito (__future__.generator_stop)
CO_FUTURE_GENERATOR_STOP
__future__.annotations
CO_FUTURE_ANNOTATIONS
8.5.7 Informação adicional
Para oferece suporte a extensõ es de baixo nível de avaliaçã o de quadro (frame), tais como compiladores “just-in-
-time”, é possível anexar dados arbitrá rios adicionais a objetos có digo.
Estas funçõ es sã o parte da camada instá vel da API C: Essa funcionalidade é um detalhe de implementaçã o do
CPython, e a API pode mudar sem avisos de descontinuidade.
8.5. Objetos Function 185
The Python/C API, Release 3.13.7
Py_ssize_t PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Retorna um novo e opaco valor de índice usado para adicionar dados a objetos có digo.
Geralmente, você chama esta funçã o apenas uma vez (por interpretador) e usa o resultado com
PyCode_GetExtra e PyCode_SetExtra para manipular dados em objetos có digo individuais.
Se free nã o for NULL: quando o objeto có digo é desalocado, free será chamado em dados nã o-NULL armaze-
nados sob o novo índice. Use Py_DecRef() quando armazenar PyObject.
Adicionado na versã o 3.6: como _PyEval_RequestCodeExtraIndex
Alterado na versã o 3.12: Renomeado para PyUnstable_Eval_RequestCodeExtraIndex. O nome antigo
nome privado foi descontinuado, mas continuará disponível até a mudança da API.
int PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Define extra para os dados adicionais armazenados sob o novo índice dado. Retorna 0 em caso de sucesso.
Define uma exceçã o e retorna -1 em caso de erro.
Se nenhum dado foi determinado sob o índice, define extra como NULL e retorna 0 sem definir nenhuma
exceçã o.
Adicionado na versã o 3.6: como _PyCode_GetExtra
Alterado na versã o 3.12: Renomeado para PyUnstable_Code_GetExtra. O nome antigo privado foi des-
continuado, mas continuará disponível até a mudança da API.
int PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Define os dados extras armazenados sob o índice dado a extra. Retorna 0 em caso de sucesso. Define uma
exceçã o e retorna -1 em caso de erro.
Adicionado na versã o 3.6: como _PyCode_SetExtra
Alterado na versã o 3.12: Renomeado para PyUnstable_Code_SetExtra. O nome antigo privado foi des-
continuado, mas continuará disponível até a mudança da API.
8.6 Outros Objetos
8.6.1 Objetos arquivos
Essas APIs sã o uma emulaçã o mínima da API C do Python 2 para objetos arquivo embutidos, que costumavam
depender do suporte de E/S em buffer (FILE*) da biblioteca C padrã o. No Python 3, arquivos e streams usam o
novo mó dulo io, que define vá rias camadas sobre a E/S sem buffer de baixo nível do sistema operacional. As funçõ es
descritas a seguir sã o invó lucros de conveniê ncia para o C sobre essas novas APIs e sã o destinadas principalmente
para relató rios de erros internos no interpretador; có digo de terceiros é recomendado para acessar as APIs de io.
186 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
PyObject *PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const
char *errors, const char *newline, int closefd)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um objeto arquivo Python a partir do descritor de
arquivo de um arquivo já aberto fd. Os argumentos name, encoding, errors and newline podem ser NULL para
usar os padrõ es; buffering pode ser -1 para usar o padrã o. name é ignorado e mantido para compatibilidade
com versõ es anteriores. Retorna NULL em caso de falha. Para uma descriçã o mais abrangente dos argumentos,
consulte a documentaçã o da funçã o io.open().
Á Aviso
Como os streams do Python tê m sua pró pria camada de buffer, combiná -los com os descritores de arquivo
no nível do sistema operacional pode produzir vá rios problemas (como ordenaçã o inesperada de dados).
Alterado na versã o 3.2: Ignora atributo name.
int PyObject_AsFileDescriptor(PyObject *p)
Parte da ABI Está vel. Retorna o descritor de arquivo associado a p como um int. Se o objeto for um inteiro,
seu valor será retornado. Caso contrá rio, o mé todo fileno() do objeto será chamado se existir; o mé todo
deve retornar um inteiro, que é retornado como o valor do descritor de arquivo. Define uma exceçã o e retorna
-1 em caso de falha.
PyObject *PyFile_GetLine(PyObject *p, int n)
Retorna valor: Nova referência. Parte da ABI Está vel. Equivalente a p.readline([n]), esta funçã o lê uma
linha do objeto p. p pode ser um objeto arquivo ou qualquer objeto com um mé todo readline(). Se n for 0,
exatamente uma linha é lida, independentemente do comprimento da linha. Se n for maior que 0, nã o mais do
que n bytes serã o lidos do arquivo; uma linha parcial pode ser retornada. Em ambos os casos, uma string vazia
é retornada se o final do arquivo for alcançado imediatamente. Se n for menor que 0, entretanto, uma linha
é lida independentemente do comprimento, mas EOFError é levantada se o final do arquivo for alcançado
imediatamente.
int PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction handler)
Substitui o comportamento normal de io.open_code() para passar seu parâ metro por meio do manipulador
fornecido.
O handler é uma funçã o do tipo:
typedef PyObject *(*Py_OpenCodeHookFunction)(PyObject*, void*)
Equivalente de PyObject *(*)(PyObject *path, void *userData), sendo path garantido
como sendo PyUnicodeObject.
O ponteiro userData é passado para a funçã o de gancho. Como as funçõ es de gancho podem ser chamadas de
diferentes tempos de execuçã o, esse ponteiro nã o deve se referir diretamente ao estado do Python.
Como este gancho é usado intencionalmente durante a importaçã o, evite importar novos mó dulos durante sua
execuçã o, a menos que eles estejam congelados ou disponíveis em sys.modules.
Uma vez que um gancho foi definido, ele nã o pode ser removido ou substituído, e chamadas posteriores para
PyFile_SetOpenCodeHook() irã o falhar. Em caso de falha, a funçã o retorna -1 e define uma exceçã o se o
interpretador foi inicializado.
É seguro chamar esta funçã o antes Py_Initialize().
Levanta um evento de auditoria setopencodehook sem argumentos.
Adicionado na versã o 3.8.
int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
Parte da ABI Está vel. Escreve o objeto obj no objeto arquivo p. O ú nico sinalizador suportado para flags é
Py_PRINT_RAW ; se fornecido, o str() do objeto é escrito em vez de repr(). Retorna 0 em caso de sucesso
ou -1 em caso de falha; a exceçã o apropriada será definida.
8.6. Outros Objetos 187
The Python/C API, Release 3.13.7
int PyFile_WriteString(const char *s, PyObject *p)
Parte da ABI Está vel. Escreve a string s no objeto arquivo p. Retorna 0 em caso de sucesso ou -1 em caso de
falha; a exceçã o apropriada será definida.
8.6.2 Objetos do Módulo
PyTypeObject PyModule_Type
Parte da ABI Está vel. Esta instâ ncia de PyTypeObject representa o tipo de mó dulo Python. Isso é exposto
a programas Python como types.ModuleType.
int PyModule_Check(PyObject *p)
Retorna true se p for um objeto de mó dulo ou um subtipo de um objeto de mó dulo. Esta funçã o sempre é
bem-sucedida.
int PyModule_CheckExact(PyObject *p)
Retorna true se p for um objeto de mó dulo, mas nã o um subtipo de PyModule_Type. Essa funçã o é sempre
bem-sucedida.
PyObject *PyModule_NewObject(PyObject *name)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Retorna um novo objeto de mó -
dulo com module.__name__ definido como name. Os atributos __name__, __doc__, __package__ e
__loader__ do mó dulo sã o preenchidos (todos, exceto __name__, sã o definidos como None). O chamador
é responsá vel por definir um atributo __file__.
Retorna NULL com uma exceçã o definida em caso de erro.
Adicionado na versã o 3.3.
Alterado na versã o 3.4: __package__ e __loader__ agora estã o definidos como None.
PyObject *PyModule_New(const char *name)
Retorna valor: Nova referência. Parte da ABI Está vel. Semelhante a PyModule_NewObject(), mas o nome
é uma string codificada em UTF-8 em vez de um objeto Unicode.
PyObject *PyModule_GetDict(PyObject *module)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Retorna o objeto dicioná rio que implementa o
espaço de nomes de module; este objeto é o mesmo que o atributo __dict__ do objeto de mó dulo. Se module
nã o for um objeto de mó dulo (ou um subtipo de um objeto de mó dulo), SystemError é levantada e NULL é
retornado.
É recomendado que as extensõ es usem outras funçõ es PyModule_* e PyObject_* em vez de manipular
diretamente o __dict__ de um mó dulo.
PyObject *PyModule_GetNameObject(PyObject *module)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Retorna o valor __name__ do
module. Se o mó dulo nã o fornecer um, ou se nã o for uma string, SystemError é levantada e NULL é retornado.
Adicionado na versã o 3.3.
const char *PyModule_GetName(PyObject *module)
Parte da ABI Está vel. Semelhante a PyModule_GetNameObject() mas retorna o nome codificado em
'utf-8'
void *PyModule_GetState(PyObject *module)
Parte da ABI Está vel. Retorna o “estado” do mó dulo, ou seja, um ponteiro para o bloco de memó ria alocado
no momento de criaçã o do mó dulo, ou NULL. Ver PyModuleDef.m_size.
PyModuleDef *PyModule_GetDef(PyObject *module)
Parte da ABI Está vel. Retorna um ponteiro para a estrutura PyModuleDef da qual o mó dulo foi criado, ou
NULL se o mó dulo nã o foi criado de uma definiçã o.
188 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
PyObject *PyModule_GetFilenameObject(PyObject *module)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna o nome do arquivo do qual o module foi
carregado usando o atributo __file__ do module. Se nã o estiver definido, ou se nã o for uma string unicode,
levanta SystemError e retorna NULL; Caso contrá rio, retorna uma referê ncia a um objeto Unicode.
Adicionado na versã o 3.2.
const char *PyModule_GetFilename(PyObject *module)
Parte da ABI Está vel. Semelhante a PyModule_GetFilenameObject() mas retorna o nome do arquivo
codificado em ‘utf-8’.
Descontinuado desde a versã o 3.2: PyModule_GetFilename(): levanta UnicodeEncodeError quando
há nomes de arquivos nã o codificá veis, use PyModule_GetFilenameObject().
Inicializando módulos C
Objetos de mó dulos sã o geralmente criados a partir de mó dulos de extensã o (bibliotecas compartilhadas que ex-
portam uma funçã o de inicializaçã o), ou mó dulos compilados (onde a funçã o de inicializaçã o é adicionada usando
PyImport_AppendInittab()). Ver building ou extending-with-embedding para mais detalhes.
A funçã o de inicializaçã o pode passar uma instâ ncia de definiçã o de mó dulo para PyModule_Create() e retornar
o objeto de mó dulo resultante ou solicitar “inicializaçã o multifá sica” retornando a pró pria estrutura de definiçã o.
type PyModuleDef
Parte da ABI Está vel (incluindo todos os membros). A estrutura de definiçã o de mó dulo, que conté m todas
as informaçõ es necessá ria para criar um objeto de mó dulo. Geralmente, há apenas uma variá vel inicializada
estaticamente desse tipo para cada mó dulo.
PyModuleDef_Base m_base
Sempre inicializa este membro para PyModuleDef_HEAD_INIT.
const char *m_name
Nome para o novo mó dulo.
const char *m_doc
Docstring para o mó dulo; geralmente uma variá vel docstring criada com PyDoc_STRVAR é usada.
Py_ssize_t m_size
O estado do mó dulo pode ser mantido em uma á rea de memó ria por mó dulo que pode ser recuperada
com PyModule_GetState(), em vez de em globais está ticos. Isso torna os mó dulos seguros para uso
em vá rios subinterpretadores.
Esta á rea de memó ria é alocada com base em m_size na criaçã o do mó dulo e liberada quando o objeto
do mó dulo é desalocado, apó s a funçã o m_free ter sido chamada, se presente.
Definir m_size como -1 significa que o mó dulo nã o oferece suporte a subinterpretadores, porque ele
tem estado global.
Defini-lo como um valor nã o negativo significa que o mó dulo pode ser reinicializado e especifica a quan-
tidade adicional de memó ria necessá ria para seu estado. m_size nã o negativo é necessá rio para inicia-
lizaçã o multifá sica.
Ver PEP 3121 para mais detalhes.
PyMethodDef *m_methods
Um ponteiro para uma tabela de funçõ es de nível de mó dulo, descritas por valores PyMethodDef . Pode
ser NULL se nenhuma funçã o estiver presente.
PyModuleDef_Slot *m_slots
Uma matriz de definiçõ es de slot para inicializaçã o multifá sica, terminada por uma entrada {0, NULL}.
Ao usar inicializaçã o monofá sica, m_slots deve ser NULL.
Alterado na versã o 3.5: Antes da versã o 3.5, esse membro era sempre definido como NULL e era definido
como:
8.6. Outros Objetos 189
The Python/C API, Release 3.13.7
inquiry m_reload
traverseproc m_traverse
Uma funçã o de travessia para chamar durante a travessia do GC do objeto do mó dulo, ou NULL se nã o
for necessá rio.
Esta funçã o nã o é mais chamada se o estado do mó dulo foi solicitado, mas ainda nã o está alocado. Este é o
caso imediatamente apó s o mó dulo ser criado e antes de o mó dulo ser executado (funçã o Py_mod_exec).
Mais precisamente, esta funçã o nã o é chamada se m_size for maior que 0 e o estado do mó dulo (como
retornado por PyModule_GetState()) for NULL.
Alterado na versã o 3.9: Nã o é mais chamado antes que o estado do mó dulo seja alocado.
inquiry m_clear
Uma funçã o de limpeza para chamar durante a limpeza do GC do objeto do mó dulo, ou NULL se nã o for
necessá rio.
Esta funçã o nã o é mais chamada se o estado do mó dulo foi solicitado, mas ainda nã o está alocado. Este é o
caso imediatamente apó s o mó dulo ser criado e antes de o mó dulo ser executado (funçã o Py_mod_exec).
Mais precisamente, esta funçã o nã o é chamada se m_size for maior que 0 e o estado do mó dulo (como
retornado por PyModule_GetState()) for NULL.
Assim como PyTypeObject.tp_clear, esta funçã o nã o é sempre chamada antes de um mó dulo ser
desalocado. Por exemplo, quando a contagem de referê ncias é suficiente para determinar que um objeto
nã o é mais usado, o coletor de lixo cíclico nã o é envolvido e m_free é chamado diretamente.
Alterado na versã o 3.9: Nã o é mais chamado antes que o estado do mó dulo seja alocado.
freefunc m_free
Uma funçã o para ser chamada durante a desalocaçã o do objeto do mó dulo, ou NULL se nã o for necessá rio.
Esta funçã o nã o é mais chamada se o estado do mó dulo foi solicitado, mas ainda nã o está alocado. Este é o
caso imediatamente apó s o mó dulo ser criado e antes de o mó dulo ser executado (funçã o Py_mod_exec).
Mais precisamente, esta funçã o nã o é chamada se m_size for maior que 0 e o estado do mó dulo (como
retornado por PyModule_GetState()) for NULL.
Alterado na versã o 3.9: Nã o é mais chamado antes que o estado do mó dulo seja alocado.
inicialização de fase única
A funçã o de inicializaçã o do mó dulo pode criar e retornar o objeto do mó dulo diretamente. Isso é chamado de
“inicializaçã o de fase ú nica” e usa uma das duas funçõ es de criaçã o de mó dulo a seguir:
PyObject *PyModule_Create(PyModuleDef *def)
Retorna valor: Nova referência. Cria um novo objeto de mó dulo, dada a definiçã o em def. Isso se comporta
como PyModule_Create2() com module_api_version definido como PYTHON_API_VERSION
PyObject *PyModule_Create2(PyModuleDef *def, int module_api_version)
Retorna valor: Nova referência. Parte da ABI Está vel. Create a new module object, given the definition in
def, assuming the API version module_api_version. If that version does not match the version of the running
interpreter, a RuntimeWarning is emitted.
Retorna NULL com uma exceçã o definida em caso de erro.
® Nota
A maioria dos usos dessa funçã o deve ser feita com PyModule_Create(); use-o apenas se tiver certeza
de que precisa.
Before it is returned from in the initialization function, the resulting module object is typically populated using
functions like PyModule_AddObjectRef().
190 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Inicialização multifásica
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. For example, if the sys.
modules entry is removed and the module is re-imported, a new module object is created, and typically populated
with fresh method and type objects. The old module is subject to normal garbage collection. This mirrors the behavior
of pure-Python modules.
Additional module instances may be created in sub-interpreters or after after Python runtime reinitialization
(Py_Finalize() and Py_Initialize()). In these cases, sharing Python objects between module instances
would likely cause crashes or undefined behavior.
To avoid such issues, each instance of an extension module should be isolated: changes to one instance should not
implicitly affect the others, and all state, including references to Python objects, should be specific to a particular
module instance. See isolating-extensions-howto for more details and a practical guide.
Uma maneira mais simples de evitar esses problemas é levantar um erro na inicializaçã o repetida.
All modules created using multi-phase initialization are expected to support sub-interpreters, or otherwise explicitly
signal a lack of support. This is usually achieved by isolation or blocking repeated initialization, as above. A module
may also be limited to the main interpreter using the Py_mod_multiple_interpreters slot.
To request multi-phase initialization, the initialization function (PyInit_modulename) returns a PyModuleDef ins-
tance with non-empty m_slots. Before it is returned, the PyModuleDef instance must be initialized with the
following function:
PyObject *PyModuleDef_Init(PyModuleDef *def)
Retorna valor: Referência emprestada. Parte da ABI Está vel desde a versão 3.5. Garante que uma definiçã o
de mó dulo é um objeto Python devidamente inicializado que reporta corretamente seu tipo e contagem de
referê ncias.
Returns def cast to PyObject*, or NULL if an error occurred.
Adicionado na versã o 3.5.
The m_slots member of the module definition must point to an array of PyModuleDef_Slot structures:
type PyModuleDef_Slot
int slot
Um ID de lot, escolhido a partir dos valores disponíveis explicados abaixo.
void *value
Valor do slot, cujo significado depende do ID do slot.
Adicionado na versã o 3.5.
The m_slots array must be terminated by a slot with id 0.
Os tipos de slot disponíveis sã o:
Py_mod_create
Specifies a function that is called to create the module object itself. The value pointer of this slot must point
to a function of the signature:
PyObject *create_module(PyObject *spec, PyModuleDef *def)
The function receives a ModuleSpec instance, as defined in PEP 451, and the module definition. It should
return a new module object, or set an error and return NULL.
This function should be kept minimal. In particular, it should not call arbitrary Python code, as trying to import
the same module again may result in an infinite loop.
8.6. Outros Objetos 191
The Python/C API, Release 3.13.7
Mú ltiplos slots Py_mod_create podem nã o estar especificados em uma definiçã o de mó dulo.
If Py_mod_create is not specified, the import machinery will create a normal module object using
PyModule_New(). The name is taken from spec, not the definition, to allow extension modules to dyna-
mically adjust to their place in the module hierarchy and be imported under different names through symlinks,
all while sharing a single module definition.
There is no requirement for the returned object to be an instance of PyModule_Type. Any type can be used,
as long as it supports setting and getting import-related attributes. However, only PyModule_Type instances
may be returned if the PyModuleDef has non-NULL m_traverse, m_clear, m_free; non-zero m_size; or
slots other than Py_mod_create.
Py_mod_exec
Specifies a function that is called to execute the module. This is equivalent to executing the code of a Python
module: typically, this function adds classes and constants to the module. The signature of the function is:
int exec_module(PyObject *module)
Se vá rios slots Py_mod_exec forem especificados, eles serã o processados na ordem em que aparecem no vetor
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 isola-
ting-extensions-howto.)
This slot determines whether or not importing this module in a subinterpreter will fail.
Multiple Py_mod_multiple_interpreters slots may not be specified in one module definition.
If Py_mod_multiple_interpreters is not specified, the import machinery defaults to
Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED.
Adicionado na versã o 3.12.
Py_mod_gil
Specifies one of the following values:
Py_MOD_GIL_USED
The module depends on the presence of the global interpreter lock (GIL), and may access global state
without synchronization.
Py_MOD_GIL_NOT_USED
The module is safe to run without an active GIL.
This slot is ignored by Python builds not configured with --disable-gil. Otherwise, it determines whether
or not importing this module will cause the GIL to be automatically enabled. See whatsnew313-free-threaded-
-cpython for more detail.
Multiple Py_mod_gil slots may not be specified in one module definition.
If Py_mod_gil is not specified, the import machinery defaults to Py_MOD_GIL_USED.
Adicionado na versã o 3.13.
Ver PEP 489 para obter mais detalhes sobre a inicializaçã o multifá sica.
192 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Funções de criação de módulo de baixo nível
The following functions are called under the hood when using multi-phase initialization. They can be used direc-
tly, for example when creating module objects dynamically. Note that both PyModule_FromDefAndSpec and
PyModule_ExecDef must be called to fully initialize a module.
PyObject *PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)
Retorna valor: Nova referência. 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.
Adicionado na versã o 3.5.
PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 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.
Retorna NULL com uma exceçã o definida em caso de erro.
® Nota
Most uses of this function should be using PyModule_FromDefAndSpec() instead; only use this if you
are sure you need it.
Adicionado na versã o 3.5.
int PyModule_ExecDef(PyObject *module, PyModuleDef *def)
Parte da ABI Está vel desde a versão 3.7. Process any execution slots (Py_mod_exec) given in def.
Adicionado na versã o 3.5.
int PyModule_SetDocString(PyObject *module, const char *docstring)
Parte da ABI Está vel desde a versão 3.7. Set the docstring for module to docstring. This function is
called automatically when creating a module from PyModuleDef, using either PyModule_Create or
PyModule_FromDefAndSpec.
Adicionado na versã o 3.5.
int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)
Parte da ABI Está vel desde a versão 3.7. Add the functions from the NULL terminated functions array to mo-
dule. Refer to the PyMethodDef documentation for details on individual entries (due to the lack of a shared
module namespace, module level “functions” implemented in C typically receive the module as their first para-
meter, making them similar to instance methods on Python classes). This function is called automatically when
creating a module from PyModuleDef, using either PyModule_Create or PyModule_FromDefAndSpec.
Adicionado na versã o 3.5.
Support functions
The module initialization function (if using single phase initialization) or a function called from a module execution
slot (if using multi-phase initialization), can use the following functions to help initialize the module state:
int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
Parte da ABI Está vel desde a versão 3.10. Add an object to module as name. This is a convenience function
which can be used from the module’s initialization function.
On success, return 0. On error, raise an exception and return -1.
Exemplo de uso:
8.6. Outros Objetos 193
The Python/C API, Release 3.13.7
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;
}
To be convenient, the function accepts NULL value with an exception set. In this case, return -1 and just leave
the raised exception unchanged.
O exemplo també m pode ser escrito sem verificar explicitamente se obj é 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 that Py_XDECREF() should be used instead of Py_DECREF() in this case, since obj can be NULL.
The number of different name strings passed to this function should be kept small, usually by
only using statically allocated strings as name. For names that aren’t known at compile time, pre-
fer calling PyUnicode_FromString() and PyObject_SetAttr() directly. For more details, see
PyUnicode_InternFromString(), which may be used internally to create a key object.
Adicionado na versã o 3.10.
int PyModule_Add(PyObject *module, const char *name, PyObject *value)
Parte da ABI Está vel desde a versão 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.
Exemplo de uso:
if (PyModule_Add(module, "spam", PyBytes_FromString(value)) < 0) {
goto error;
}
Adicionado na versã o 3.13.
int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
Parte da ABI Está vel. Similar to PyModule_AddObjectRef(), but steals a reference to value on success (if
it returns 0).
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.
194 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
This means that its return value must be checked, and calling code must Py_XDECREF() value manually
on error.
Exemplo 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.
Descontinuado desde a versã o 3.13: PyModule_AddObject() is soft deprecated.
int PyModule_AddIntConstant(PyObject *module, const char *name, long value)
Parte da ABI Está vel. Add an integer constant to module as name. This convenience function can be used
from the module’s initialization function. Return -1 with an exception set on error, 0 on success.
This is a convenience function that calls PyLong_FromLong() and PyModule_AddObjectRef(); see their
documentation for details.
int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
Parte da ABI Está vel. Add a string constant to module as name. This convenience function can be used from
the module’s initialization function. The string value must be NULL-terminated. Return -1 with an exception
set on error, 0 on success.
This is a convenience function that calls PyUnicode_InternFromString() and
PyModule_AddObjectRef(); see their documentation for details.
PyModule_AddIntMacro(module, macro)
Add an int constant to module. The name and the value are taken from macro. For example
PyModule_AddIntMacro(module, AF_INET) adds the int constant AF_INET with the value of AF_INET
to module. Return -1 with an exception set on error, 0 on success.
PyModule_AddStringMacro(module, macro)
Add a string constant to module.
int PyModule_AddType(PyObject *module, PyTypeObject *type)
Parte da ABI Está vel desde a versão 3.10. Add a type object to module. The type object is finalized by calling
internally PyType_Ready(). The name of the type object is taken from the last component of tp_name after
dot. Return -1 with an exception set on error, 0 on success.
Adicionado na versã o 3.9.
int PyUnstable_Module_SetGIL(PyObject *module, void *gil)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Indicate that module does or does not support running without the global interpreter lock (GIL), using one
of the values from Py_mod_gil. It must be called during module’s initialization function. If this function is
not called during module initialization, the import machinery assumes the module does not support running
without the GIL. This function is only available in Python builds configured with --disable-gil. Return
-1 with an exception set on error, 0 on success.
8.6. Outros Objetos 195
The Python/C API, Release 3.13.7
Adicionado na versã o 3.13.
Pesquisa por módulos
Single-phase initialization creates singleton modules that can be looked up in the context of the current interpreter.
This allows the module object to be retrieved later with only a reference to the module definition.
These functions will not work on modules created using multi-phase initialization, since multiple such modules can
be created from a single definition.
PyObject *PyState_FindModule(PyModuleDef *def)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Returns the module object that was created from
def for the current interpreter. This method requires that the module object has been attached to the interpreter
state with PyState_AddModule() beforehand. In case the corresponding module object is not found or has
not been attached to the interpreter state yet, it returns NULL.
int PyState_AddModule(PyObject *module, PyModuleDef *def)
Parte da ABI Está vel desde a versão 3.3. Attaches the module object passed to the function to the interpreter
state. This allows the module object to be accessible via PyState_FindModule().
Only effective on modules created using single-phase initialization.
Python calls PyState_AddModule automatically after importing a module, so it is unnecessary (but harm-
less) to call it from module initialization code. An explicit call is needed only if the module’s own init code
subsequently calls PyState_FindModule. The function is mainly intended for implementing alternative im-
port mechanisms (either by calling it directly, or by referring to its implementation for details of the required
state updates).
The caller must hold the GIL.
Retorna -1 com uma exceçã o definida em caso de erro, 0 em caso de sucesso.
Adicionado na versã o 3.3.
int PyState_RemoveModule(PyModuleDef *def)
Parte da ABI Está vel desde a versão 3.3. Removes the module object created from def from the interpreter
state. Return -1 with an exception set on error, 0 on success.
The caller must hold the GIL.
Adicionado na versã o 3.3.
8.6.3 Objetos Iteradores
O Python fornece dois objetos iteradores de propó sito geral. O primeiro, um iterador de sequê ncia, trabalha com
uma sequê ncia arbitrá ria suportando o mé todo __getitem__(). O segundo trabalha com um objeto chamá vel e
um valor de sentinela, chamando o chamá vel para cada item na sequê ncia e finalizando a iteraçã o quando o valor de
sentinela é retornado.
PyTypeObject PySeqIter_Type
Parte da ABI Está vel. Objeto de tipo para objetos iteradores retornados por PySeqIter_New() e a forma de
um argumento da funçã o embutida iter() para os tipos de sequê ncia embutidos.
int PySeqIter_Check(PyObject *op)
Retorna true se o tipo de op for PySeqIter_Type. Esta funçã o sempre é bem-sucedida.
PyObject *PySeqIter_New(PyObject *seq)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um iterador que funcione com um objeto
de sequê ncia geral, seq. A iteraçã o termina quando a sequê ncia levanta IndexError para a operaçã o de
assinatura.
PyTypeObject PyCallIter_Type
Parte da ABI Está vel. Objeto de tipo para objetos iteradores retornados por PyCallIter_New() e a forma
de dois argumentos da funçã o embutida iter().
196 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyCallIter_Check(PyObject *op)
Retorna true se o tipo de op for PyCallIter_Type. Esta funçã o sempre é bem-sucedida.
PyObject *PyCallIter_New(PyObject *callable, PyObject *sentinel)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo iterador. O primeiro parâ metro,
callable, pode ser qualquer objeto chamá vel do Python que possa ser chamado sem parâ metros; cada chamada
deve retornar o pró ximo item na iteraçã o. Quando callable retorna um valor igual a sentinel, a iteraçã o será
encerrada.
8.6.4 Objetos Descritores
“Descritores” sã o objetos que descrevem algum atributo de um objeto. Eles sã o encontrados no dicioná rio de objetos
de tipo.
PyTypeObject PyProperty_Type
Parte da ABI Está vel. O tipo de objeto para os tipos de descritores embutidos.
PyObject *PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
Retorna valor: Nova referência. Parte da ABI Está vel.
PyObject *PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
Retorna valor: Nova referência. Parte da ABI Está vel.
PyObject *PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
Retorna valor: Nova referência. Parte da ABI Está vel.
PyObject *PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
Retorna valor: Nova referência.
PyObject *PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
Retorna valor: Nova referência. Parte da ABI Está vel.
int PyDescr_IsData(PyObject *descr)
Retorna nã o-zero se os objetos descritores descr descrevem um atributo de dados, ou 0 se os mesmos descrevem
um mé todo. descr deve ser um objeto descritor; nã o há verificaçã o de erros.
PyObject *PyWrapper_New(PyObject*, PyObject*)
Retorna valor: Nova referência. Parte da ABI Está vel.
8.6.5 Objetos Slice
PyTypeObject PySlice_Type
Parte da ABI Está vel. Tipo de objeto para objetos fatia. Isso é o mesmo que slice na camada Python.
int PySlice_Check(PyObject *ob)
Retorna true se ob for um objeto fatia; ob nã o deve ser NULL. Esta funçã o sempre tem sucesso.
PyObject *PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um novo objeto fatia com os valores fornecidos.
Os parâ metros start, stop e step sã o usados como os valores dos atributos do objeto fatia com os mesmos nomes.
Qualquer um dos valores pode ser NULL, caso em que None será usado para o atributo correspondente.
Retorna NULL com uma exceçã o definida se o novo objeto nã o puder ser alocado.
int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t
*step)
Parte da ABI Está vel. Recupera os índices de início, parada e intermediá rio do objeto fatia slice, presumindo
uma sequê ncia de comprimento length. Trata índices maiores que length como erros.
Retorna 0 em caso de sucesso e -1 em caso de erro sem exceçã o definida (a menos que um dos índices nã o
fosse None e falhou ao ser convertido para um inteiro, neste caso -1 é retornado com uma exceçã o definida).
8.6. Outros Objetos 197
The Python/C API, Release 3.13.7
Você provavelmente nã o deseja usar esta funçã o.
Alterado na versã o 3.2: O tipo de parâ metro para o parâ metro slice era antes de PySliceObject*.
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)
Parte da ABI Está vel. Substituiçã o utilizá vel para PySlice_GetIndices(). Recupera os índices de início,
parada e intermediá rio do objeto fatia slice presumindo uma sequê ncia de comprimento length e armazena
o comprimento da fatia em slicelength. Indices ́ fora dos limites sã o cortados de maneira consistente com o
tratamento de fatias normais.
Retorna 0 em caso de sucesso e -1 em caso de erro com uma exceçã o definida.
® Nota
Esta funçã o nã o é considerada segura para sequê ncias redimensioná veis. Sua invocaçã o deve ser substituída
por uma combinaçã o de PySlice_Unpack() e PySlice_AdjustIndices() sendo
if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength)
,→< 0) {
// retorna erro
}
substituído por
if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {
// retorna erro
}
slicelength = PySlice_AdjustIndices(length, &start, &stop, step);
Alterado na versã o 3.2: O tipo de parâ metro para o parâ metro slice era antes de PySliceObject*.
Alterado na versã o 3.6.1: Se Py_LIMITED_API nã o estiver definido ou estiver definido com um valor entre
0x03050400 e 0x03060000 (nã o incluso) ou 0x03060100 ou mais alto, PySlice_GetIndicesEx() é
implementado como uma macro usando PySlice_Unpack() e PySlice_AdjustIndices(). Os argu-
mentos start, stop e step sã o avaliados mais de uma vez.
Descontinuado desde a versã o 3.6.1: Se Py_LIMITED_API estiver definido para um valor menor que
0x03050400 ou entre 0x03060000 e 0x03060100 (nã o incluso), PySlice_GetIndicesEx() é uma fun-
çã o descontinuada.
int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
Parte da ABI Está vel desde a versão 3.7. Extrai os membros de dados de início, parada e in-
termediá rio de um objeto fatia como C inteiros. Reduz silenciosamente os valores maiores do que
PY_SSIZE_T_MAX para PY_SSIZE_T_MAX, aumenta silenciosamente os valores de início e parada meno-
res que PY_SSIZE_T_MIN para PY_SSIZE_T_MIN, e silenciosamente aumenta os valores de intermediá rio
menores que -PY_SSIZE_T_MAX para -PY_SSIZE_T_MAX.
Retorna -1 com uma exceçã o definida em caso de erro, 0 em caso de sucesso.
Adicionado na versã o 3.6.1.
Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)
Parte da ABI Está vel desde a versão 3.7. Ajusta os índices de fatias inicial/final presumindo uma sequê ncia
́
do comprimento especificado. Indices fora dos limites sã o cortados de maneira consistente com o tratamento
de fatias normais.
Retorna o comprimento da fatia. Sempre bem-sucedido. Nã o chama o có digo Python.
Adicionado na versã o 3.6.1.
198 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
Objeto Ellipsis
PyTypeObject PyEllipsis_Type
Parte da ABI Está vel. O tipo do objeto Python Ellipsis. O mesmo que types.EllipsisType na camada
Python.
PyObject *Py_Ellipsis
O objeto Python Ellipsis. Este objeto nã o tem mé todos. Como Py_None, é um objeto singleton imortal.
Alterado na versã o 3.12: Py_Ellipsis é imortal.
8.6.6 Objetos MemoryView
Um objeto memoryview expõ e a interface de buffer a nível de C como um objeto Python que pode ser passado como
qualquer outro objeto.
PyObject *PyMemoryView_FromObject(PyObject *obj)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um objeto memoryview a partir de um objeto que
fornece a interface do buffer. Se obj tiver suporte a exportaçõ es de buffer gravá veis, o objeto memoryview será
de leitura/gravaçã o; caso contrá rio, poderá ser somente leitura ou leitura/gravaçã o, a crité rio do exportador.
PyBUF_READ
Sinalizador para solicitar um buffer de somente leitura.
PyBUF_WRITE
Sinalizador para solicitar um buffer gravá vel.
PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.7. Cria um objeto memoryview usando
mem como o buffer subjacente. flags pode ser um dos seguintes PyBUF_READ ou PyBUF_WRITE.
Adicionado na versã o 3.3.
PyObject *PyMemoryView_FromBuffer(const Py_buffer *view)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.11. Cria um objeto
de memoryview envolvendo a estrutura de buffer view fornecida. Para buffers de bytes simples,
PyMemoryView_FromMemory() é a funçã o preferida.
PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um objeto memoryview para um pedaço contíguo
de memó ria (na ordem ‘C’ ou ‘F’ortran, representada por order) a partir de um objeto que define a interface do
buffer. Se a memó ria for contígua, o objeto memoryview apontará para a memó ria original. Caso contrá rio, é
feita uma có pia e a visualizaçã o da memó ria aponta para um novo objeto bytes.
buffertype pode ser um entre PyBUF_READ ou PyBUF_WRITE.
int PyMemoryView_Check(PyObject *obj)
Retorna true se o objeto obj for um objeto memoryview. Atualmente, nã o é permitido criar subclasses de
memoryview. Esta funçã o sempre tem sucesso.
Py_buffer *PyMemoryView_GET_BUFFER(PyObject *mview)
Retorna um ponteiro para a có pia privada da memó ria do buffer do exportador. mview deve ser uma instâ ncia
de memoryview; Se essa macro nã o verificar seu tipo, faça você mesmo ou corre o risco de travar.
PyObject *PyMemoryView_GET_BASE(PyObject *mview)
Retorna um ponteiro para o objeto de exportaçã o no qual a memó ria é baseada ou NULL se a memó ria tiver sido
criada por uma das funçõ es PyMemoryView_FromMemory() ou PyMemoryView_FromBuffer(). mview
deve ser uma instâ ncia de memoryview.
8.6. Outros Objetos 199
The Python/C API, Release 3.13.7
8.6.7 Objetos referência fraca
O Python oferece suporte a referências fracas como objetos de primeira classe. Existem dois tipos de objetos espe-
cíficos que implementam diretamente referê ncias fracas. O primeiro é um objeto de referê ncia simples, e o segundo
atua como um intermediá rio ao objeto original tanto quanto ele pode.
int PyWeakref_Check(PyObject *ob)
Retorna nã o zero se ob for um objeto referê ncia ou um objeto intermediá rio. Esta funçã o sempre tem sucesso.
int PyWeakref_CheckRef(PyObject *ob)
Retorna nã o zero se ob for um objeto referê ncia. Esta funçã o sempre tem sucesso.
int PyWeakref_CheckProxy(PyObject *ob)
Retorna nã o zero se ob for um objeto intermediá rio. Esta funçã o sempre tem sucesso.
PyObject *PyWeakref_NewRef(PyObject *ob, PyObject *callback)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um objeto de referê ncia fraco para o objeto
ob. Isso sempre retornará uma nova referê ncia, mas nã o é garantido para criar um novo objeto; um objeto
de referê ncia existente pode ser retornado. O segundo parâ metro, callback, pode ser um objeto chamá vel
que recebe notificaçã o quando ob for lixo coletado; ele deve aceitar um ú nico parâ metro, que será o objeto
de referê ncia fraco propriamente dito. callback també m pode ser None ou NULL. Se ob nã o for um objeto
fracamente referenciá vel, ou se callback nã o for um chamá vel, None, ou NULL, isso retornará NULL e levantará
a TypeError.
PyObject *PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
Retorna valor: Nova referência. Parte da ABI Está vel. Retorna um objeto de proxy de referê ncia fraca para
o objeto ob. Isso sempre retornará uma nova referê ncia, mas nã o é garantido para criar um novo objeto; um
objeto de proxy existente pode ser retornado. O segundo parâ metro, callback, pode ser um objeto chamá vel
que recebe notificaçã o quando ob for lixo coletado; ele deve aceitar um ú nico parâ metro, que será o objeto
de referê ncia fraco propriamente dito. callback també m pode ser None ou NULL. Se ob nã o for um objeto
referê ncia fraca, ou se callback nã o for um chamá vel, None, ou NULL, isso retornará NULL e levantará a
TypeError.
int PyWeakref_GetRef(PyObject *ref, PyObject **pobj)
Parte da ABI Está vel desde a versão 3.13. Obté m uma referência forte para o objeto referenciado a partir de
uma referê ncia fraca, ref, em *pobj.
• Em caso de sucesso, define *pobj como uma nova referência forte para o objeto referenciado e retorna 1.
• Se a referê ncia estiver quebrada, define *pobj como NULL e retorna 0.
• Em caso de erro, levanta uma exceçã o e retorna -1.
Adicionado na versã o 3.13.
PyObject *PyWeakref_GetObject(PyObject *ref)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Retorna uma referência emprestada ao objeto
referenciado a partir de uma referê ncia fraca, ref. Se o referente nã o estiver mais em tempo real, retorna
Py_None.
® Nota
Esta funçã o retorna uma referência emprestada para o objeto referenciado. Isso significa que você deve
sempre chamar Py_INCREF() no objeto, exceto quando ele nã o puder ser destruído antes do ú ltimo uso
da referê ncia emprestada.
Deprecated since version 3.13, will be removed in version 3.15: Usa PyWeakref_GetRef().
PyObject *PyWeakref_GET_OBJECT(PyObject *ref)
Retorna valor: Referência emprestada. Semelhante a PyWeakref_GetObject(), mas nã o verifica erros.
Deprecated since version 3.13, will be removed in version 3.15: Usa PyWeakref_GetRef().
200 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
void PyObject_ClearWeakRefs(PyObject *object)
Parte da ABI Está vel. Esta funçã o é chamada pelo tratador tp_dealloc para limpar referê ncias fracas.
Isso itera pelas referê ncias fracas para object e chama retornos de chamada para as referê ncias que possuem
um. Ele retorna quando todos os retornos de chamada foram tentados.
void PyUnstable_Object_ClearWeakRefsNoCallbacks(PyObject *object)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Limpa as referê ncias fracas para object sem chamar as funçõ es de retorno
Esta funçã o é chamada pelo manipulador tp_dealloc para tipos com finalizadores (por exemplo,
__del__()). O manipulador para esses objetos primeiro chama PyObject_ClearWeakRefs() para lim-
par referê ncias fracas e chamar suas funçõ es de retorno, depois o finalizador e, finalmente, esta funçã o para
limpar quaisquer referê ncias fracas que possam ter sido criadas pelo finalizador.
Na maioria das circunstâ ncias, é mais apropriado usar PyObject_ClearWeakRefs() para limpar referê ncias
fracas em vez desta funçã o.
Adicionado na versã o 3.13.
8.6.8 Capsules
Consulte using-capsules para obter mais informaçõ es sobre o uso desses objetos.
Adicionado na versã o 3.1.
type PyCapsule
Este subtipo de PyObject representa um valor opaco, ú til para mó dulos de extensã o C que precisam passar
um valor opaco (como ponteiro void*) atravé s do có digo Python para outro có digo C . É frequentemente
usado para disponibilizar um ponteiro de funçã o C definido em um mó dulo para outros mó dulos, para que
o mecanismo de importaçã o regular possa ser usado para acessar APIs C definidas em mó dulos carregados
dinamicamente.
type PyCapsule_Destructor
Parte da ABI Está vel. O tipo de um retorno de chamada destruidor para uma cá psula. Definido como:
typedef void (*PyCapsule_Destructor)(PyObject *);
Veja PyCapsule_New() para a semâ ntica dos retornos de chamada PyCapsule_Destructor.
int PyCapsule_CheckExact(PyObject *p)
Retorna true se seu argumento é um PyCapsule. Esta funçã o sempre tem sucesso.
PyObject *PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor)
Retorna valor: Nova referência. Parte da ABI Está vel. Cria um PyCapsule que encapsula o ponteiro. O
argumento pointer pode nã o ser NULL.
Em caso de falha, define uma exceçã o e retorna NULL.
A string name pode ser NULL ou um ponteiro para uma string C vá lida. Se nã o for NULL, essa string deverá
sobreviver à cá psula. (Embora seja permitido liberá -lo dentro do descructor.)
Se o argumento destructor nã o for NULL, ele será chamado com a cá psula como argumento quando for des-
truído.
Se esta cá psula for armazenada como um atributo de um mó dulo, o name deve ser especificado
como modulename.attributename. Isso permitirá que outros mó dulos importem a cá psula usando
PyCapsule_Import().
8.6. Outros Objetos 201
The Python/C API, Release 3.13.7
void *PyCapsule_GetPointer(PyObject *capsule, const char *name)
Parte da ABI Está vel. Recupera o pointer armazenado na cá psula. Em caso de falha, define uma exceçã o e
retorna NULL.
O parâ metro name deve ser comparado exatamente com o nome armazenado na cá psula. Se o nome armaze-
nado na cá psula for NULL, o name passado també m deve ser NULL. Python usa a funçã o C strcmp() para
comparar nomes de cá psulas.
PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule)
Parte da ABI Está vel. Retorna o destruidor atual armazenado na cá psula. Em caso de falha, define uma exceçã o
e retorna NULL.
É legal para uma cá psula ter um destruidor NULL. Isso torna um có digo de retorno NULL um tanto ambíguo;
use PyCapsule_IsValid() ou PyErr_Occurred() para desambiguar.
void *PyCapsule_GetContext(PyObject *capsule)
Parte da ABI Está vel. Retorna o contexto atual armazenado na cá psula. Em caso de falha, define uma exceçã o
e retorna NULL.
É legal para uma cá psula ter um contexto NULL. Isso torna um có digo de retorno NULL um tanto ambíguo; use
PyCapsule_IsValid() ou PyErr_Occurred() para desambiguar.
const char *PyCapsule_GetName(PyObject *capsule)
Parte da ABI Está vel. Retorna o nome atual armazenado na cá psula. Em caso de falha, define uma exceçã o e
retorna NULL.
É legal para uma cá psula ter um nome NULL. Isso torna um có digo de retorno NULL um tanto ambíguo; use
PyCapsule_IsValid() ou PyErr_Occurred() para desambiguar.
void *PyCapsule_Import(const char *name, int no_block)
Parte da ABI Está vel. Importa um ponteiro para um objeto C de um atributo de cá psula em um mó dulo.
O parâ metro name deve especificar o nome completo do atributo, como em module.attribute. O name
armazenado na cá psula deve corresponder exatamente a essa string.
Esta funçã o divide name no caractere . e importa o primeiro elemento. Em seguida, processa os elementos
seguintes usando pesquisas de atributos.
Retorna o ponteiro interno pointer da cá psula com sucesso. Em caso de falha, define uma exceçã o e retorna
NULL.
® Nota
Se name apontar para um atributo de algum submó dulo ou subpacote, esse submó dulo ou subpacote deverá
ser importado previamente usando outros meios (por exemplo, usando PyImport_ImportModule())
para que as pesquisas de atributos sejam bem-sucedidas.
Alterado na versã o 3.3: no_block nã o tem mais efeito.
int PyCapsule_IsValid(PyObject *capsule, const char *name)
Parte da ABI Está vel. Determina se capsule é ou nã o uma cá psula vá lida. Uma cá psula vá lida é diferente de
NULL, passa PyCapsule_CheckExact(), possui um ponteiro diferente de NULL armazenado e seu nome
interno corresponde ao parâ metro name. (Consulte PyCapsule_GetPointer() para obter informaçõ es
sobre como os nomes das cá psulas sã o comparados.)
Em outras palavras, se PyCapsule_IsValid() retornar um valor verdadeiro, as chamadas para qualquer um
dos acessadores (qualquer funçã o que comece com PyCapsule_Get) terã o ê xito garantido.
Retorna um valor diferente de zero se o objeto for vá lido e corresponder ao nome passado. Retorna 0 caso
contrá rio. Esta funçã o nã o falhará .
202 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyCapsule_SetContext(PyObject *capsule, void *context)
Parte da ABI Está vel. Define o ponteiro de contexto dentro de capsule para context.
Retorna 0 em caso de sucesso. Retorna diferente de zero e define uma exceçã o em caso de falha.
int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor)
Parte da ABI Está vel. Define o destrutor dentro de capsule para destructor.
Retorna 0 em caso de sucesso. Retorna diferente de zero e define uma exceçã o em caso de falha.
int PyCapsule_SetName(PyObject *capsule, const char *name)
Parte da ABI Está vel. Define o nome dentro de capsule como name. Se nã o for NULL, o nome deve sobreviver
à cá psula. Se o name anterior armazenado na cá psula nã o era NULL, nenhuma tentativa será feita para liberá -lo.
Retorna 0 em caso de sucesso. Retorna diferente de zero e define uma exceçã o em caso de falha.
int PyCapsule_SetPointer(PyObject *capsule, void *pointer)
Parte da ABI Está vel. Define o ponteiro nulo dentro de capsule para pointer. O ponteiro nã o pode ser NULL.
Retorna 0 em caso de sucesso. Retorna diferente de zero e define uma exceçã o em caso de falha.
8.6.9 Objetos Frame
type PyFrameObject
Parte da API Limitada (como uma estrutura opaca). A estrutura C dos objetos usados para descrever objetos
frame.
Nã o há membros pú blicos nesta estrutura.
Alterado na versã o 3.11: Os membros dessa estrutura foram removidos da API C pú blica. Consulte a entrada
O Que há de Novo para detalhes.
As funçõ es PyEval_GetFrame() e PyThreadState_GetFrame() podem ser utilizadas para obter um objeto
frame.
Veja també m Reflexão.
PyTypeObject PyFrame_Type
O tipo de objetos frame. É o mesmo objeto que types.FrameType na camada Python.
Alterado na versã o 3.11: Anteriormente, este tipo só estava disponível apó s incluir <frameobject.h>.
int PyFrame_Check(PyObject *obj)
Retorna diferente de zero se obj é um objeto frame
Alterado na versã o 3.11: Anteriormente, esta funçã o só estava disponível apó s incluir <frameobject.h>.
PyFrameObject *PyFrame_GetBack(PyFrameObject *frame)
Retorna valor: Nova referência. Obté m o frame pró ximo ao quadro externo.
Retorna uma referência forte ou NULL se frame nã o tiver quadro externo.
Adicionado na versã o 3.9.
PyObject *PyFrame_GetBuiltins(PyFrameObject *frame)
Retorna valor: Nova referência. Get the frame’s f_builtins attribute.
Retorna uma referência forte. O resultado nã o pode ser NULL.
Adicionado na versã o 3.11.
PyCodeObject *PyFrame_GetCode(PyFrameObject *frame)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.10. Obté m o có digo de frame.
Retorna uma referência forte.
O resultado (có digo do frame) nã o pode ser NULL.
Adicionado na versã o 3.9.
8.6. Outros Objetos 203
The Python/C API, Release 3.13.7
PyObject *PyFrame_GetGenerator(PyFrameObject *frame)
Retorna valor: Nova referência. Obté m o gerador, corrotina ou gerador assíncrono que possui este frame, ou
NULL se o frame nã o pertence a um gerador. Nã o levanta exceçã o, mesmo que o valor retornado seja NULL.
Retorna uma referência forte, ou NULL.
Adicionado na versã o 3.11.
PyObject *PyFrame_GetGlobals(PyFrameObject *frame)
Retorna valor: Nova referência. Get the frame’s f_globals attribute.
Retorna uma referência forte. O resultado nã o pode ser NULL.
Adicionado na versã o 3.11.
int PyFrame_GetLasti(PyFrameObject *frame)
Get the frame’s f_lasti attribute.
Retorna -1 se frame.f_lasti é None.
Adicionado na versã o 3.11.
PyObject *PyFrame_GetVar(PyFrameObject *frame, PyObject *name)
Retorna valor: Nova referência. 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.
Adicionado na versã o 3.12.
PyObject *PyFrame_GetVarString(PyFrameObject *frame, const char *name)
Retorna valor: Nova referência. Similar to PyFrame_GetVar(), but the variable name is a C string encoded
in UTF-8.
Adicionado na versã o 3.12.
PyObject *PyFrame_GetLocals(PyFrameObject *frame)
Retorna valor: Nova referência. Get the frame’s f_locals attribute. If the frame refers to an optimized scope,
this returns a write-through proxy object that allows modifying the locals. In all other cases (classes, modules,
exec(), eval()) it returns the mapping representing the frame locals directly (as described for locals()).
Retorna uma referência forte.
Adicionado na versã o 3.11.
Alterado na versã o 3.13: As part of PEP 667, return an instance of PyFrameLocalsProxy_Type.
int PyFrame_GetLineNumber(PyFrameObject *frame)
Parte da ABI Está vel desde a versão 3.10. Retorna o nú mero da linha do frame atualmente em execuçã o.
Frame Locals Proxies
Adicionado na versã o 3.13.
The f_locals attribute on a frame object is an instance of a “frame-locals proxy”. The proxy object exposes a
write-through view of the underlying locals dictionary for the frame. This ensures that the variables exposed by
f_locals are always up to date with the live local variables in the frame itself.
See PEP 667 for more information.
PyTypeObject PyFrameLocalsProxy_Type
The type of frame locals() proxy objects.
204 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyFrameLocalsProxy_Check(PyObject *obj)
Return non-zero if obj is a frame locals() proxy.
Internal Frames
Unless using PEP 523, you will not need this.
struct _PyInterpreterFrame
The interpreter’s internal frame representation.
Adicionado na versã o 3.11.
PyObject *PyUnstable_InterpreterFrame_GetCode(struct _PyInterpreterFrame *frame);
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Return a strong reference to the code object for the frame.
Adicionado na versã o 3.12.
int PyUnstable_InterpreterFrame_GetLasti(struct _PyInterpreterFrame *frame);
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Return the byte offset into the last executed instruction.
Adicionado na versã o 3.12.
int PyUnstable_InterpreterFrame_GetLine(struct _PyInterpreterFrame *frame);
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Return the currently executing line number, or -1 if there is no line number.
Adicionado na versã o 3.12.
8.6.10 Objetos Geradores
Objetos geradores sã o o que o Python usa para implementar iteradores geradores. Eles sã o normalmente cri-
ados por iteraçã o sobre uma funçã o que produz valores, em vez de invocar explicitamente PyGen_New() ou
PyGen_NewWithQualName().
type PyGenObject
A estrutura C usada para objetos geradores.
PyTypeObject PyGen_Type
O objeto de tipo correspondendo a objetos geradores.
int PyGen_Check(PyObject *ob)
Retorna verdadeiro se ob for um objeto gerador; ob nã o deve ser NULL. Esta funçã o sempre tem sucesso.
8.6. Outros Objetos 205
The Python/C API, Release 3.13.7
int PyGen_CheckExact(PyObject *ob)
Retorna verdadeiro se o tipo do ob é PyGen_Type; ob nã o deve ser NULL. Esta funçã o sempre tem sucesso.
PyObject *PyGen_New(PyFrameObject *frame)
Retorna valor: Nova referência. Cria e retorna um novo objeto gerador com base no objeto frame. Uma
referê ncia a quadro é roubada por esta funçã o. O argumento nã o deve ser NULL.
PyObject *PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname)
Retorna valor: Nova referência. Cria e retorna um novo objeto gerador com base no objeto frame, com
__name__ e __qualname__ definidos como name e qualname. Uma referê ncia a frame é roubada por esta
funçã o. O argumento frame nã o deve ser NULL.
8.6.11 Objetos corrotina
Adicionado na versã o 3.5.
Os objetos corrotina sã o aquelas funçõ es declaradas com um retorno de palavra-chave async.
type PyCoroObject
A estrutura C utilizada para objetos corrotinas.
PyTypeObject PyCoro_Type
O tipo de objeto correspondente a objetos corrotina.
int PyCoro_CheckExact(PyObject *ob)
Retorna true se o tipo do ob é PyCoro_Type; ob nã o deve ser NULL. Esta funçã o sempre tem sucesso.
PyObject *PyCoro_New(PyFrameObject *frame, PyObject *name, PyObject *qualname)
Retorna valor: Nova referência. Cria e retorna um novo objeto de corrotina com base no objeto frame, com
__name__ e __qualname__ definido como name e qualname. Uma referê ncia a frame é roubada por esta
funçã o. O argumento frame nã o deve ser NULL.
8.6.12 Objetos de variáveis de contexto
Adicionado na versã o 3.7.
Alterado na versã o 3.7.1:
® Nota
No Python 3.7.1, as assinaturas de todas as APIs C de variá veis de contexto foram alteradas para usar ponteiros
PyObject em vez de PyContext, PyContextVar e PyContextToken. Por exemplo:
// no 3.7.0:
PyContext *PyContext_New(void);
// no 3.7.1+:
PyObject *PyContext_New(void);
Veja bpo-34762 para mais detalhes.
Esta seçã o detalha a API C pú blica para o mó dulo contextvars.
type PyContext
A estrutura C usada para representar um objeto contextvars.Context.
type PyContextVar
A estrutura C usada para representar um objeto contextvars.ContextVar.
type PyContextToken
A estrutura C usada para representar um objeto contextvars.Token
206 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
PyTypeObject PyContext_Type
O objeto de tipo que representa o tipo de contexto.
PyTypeObject PyContextVar_Type
O objeto de tipo que representa o tipo de variável de contexto.
PyTypeObject PyContextToken_Type
O objeto de tipo que representa o tipo de token de variável de contexto.
Macros de verificaçã o de tipo:
int PyContext_CheckExact(PyObject *o)
Retorna verdadeiro se o for do tipo PyContext_Type. o nã o deve ser NULL. Esta funçã o sempre tem sucesso.
int PyContextVar_CheckExact(PyObject *o)
Retorna verdadeiro se o for do tipo PyContextVar_Type. o nã o deve ser NULL. Esta funçã o sempre tem
sucesso.
int PyContextToken_CheckExact(PyObject *o)
Retorna verdadeiro se o for do tipo PyContextToken_Type. o nã o deve ser NULL. Esta funçã o sempre tem
sucesso.
Funçõ es de gerenciamento de objetos de contexto:
PyObject *PyContext_New(void)
Retorna valor: Nova referência. Cria um novo objeto de contexto vazio. Retorna NULL se um erro ocorreu.
PyObject *PyContext_Copy(PyObject *ctx)
Retorna valor: Nova referência. Cria uma có pia rasa do objeto de contexto ctx passado. Retorna NULL se um
erro ocorreu.
PyObject *PyContext_CopyCurrent(void)
Retorna valor: Nova referência. Cria uma có pia rasa do contexto da thread atual. Retorna NULL se um erro
ocorreu.
int PyContext_Enter(PyObject *ctx)
Defina ctx como o contexto atual para o thread atual. Retorna 0 em caso de sucesso e -1 em caso de erro.
int PyContext_Exit(PyObject *ctx)
Desativa o contexto ctx e restaura o contexto anterior como o contexto atual para a thread atual. Retorna 0 em
caso de sucesso e -1 em caso de erro.
Funçõ es de variá vel de contexto:
PyObject *PyContextVar_New(const char *name, PyObject *def)
Retorna valor: Nova referência. Cria um novo objeto ContextVar. O parâ metro name é usado para fins de
introspecçã o e depuraçã o. O parâ metro def especifica um valor padrã o para a variá vel de contexto, ou NULL
para nenhum padrã o. Se ocorrer um erro, esta funçã o retorna NULL.
int PyContextVar_Get(PyObject *var, PyObject *default_value, PyObject **value)
Obté m o valor de uma variá vel de contexto. Retorna -1 se um erro ocorreu durante a pesquisa, e 0 se nenhum
erro ocorreu, se um valor foi encontrado ou nã o.
Se a variá vel de contexto foi encontrada, value será um ponteiro para ela. Se a variá vel de contexto não foi
encontrada, value apontará para:
• default_value, se nã o for NULL;
• o valor padrã o de var, se nã o for NULL;
• NULL
Exceto para NULL, a funçã o retorna uma nova referê ncia.
8.6. Outros Objetos 207
The Python/C API, Release 3.13.7
PyObject *PyContextVar_Set(PyObject *var, PyObject *value)
Retorna valor: Nova referência. Define o valor de var como value no contexto atual. Retorna um novo objeto
token para esta alteraçã o, ou NULL se um erro ocorreu.
int PyContextVar_Reset(PyObject *var, PyObject *token)
Redefine o estado da variá vel de contexto var para o estado que anterior a PyContextVar_Set() que retor-
nou o token foi chamado. Esta funçã o retorna 0 em caso de sucesso e -1 em caso de erro.
8.6.13 Objetos DateTime
Vá rios objetos de data e hora sã o fornecidos pelo mó dulo datetime. Antes de usar qualquer uma dessas funçõ es, o
arquivo de cabeçalho datetime.h deve ser incluído na sua fonte (observe que isso nã o é incluído por Python.h)
e a macro PyDateTime_IMPORT deve ser chamada, geralmente como parte da funçã o de inicializaçã o do mó dulo.
A macro coloca um ponteiro para uma estrutura C em uma variá vel está tica, PyDateTimeAPI, usada pelas macros
a seguir.
type PyDateTime_Date
Esta é uma instâ ncia de PyObject representando o objeto data do Python.
type PyDateTime_DateTime
Esta é uma instâ ncia de PyObject representando o objeto datetime do Python.
type PyDateTime_Time
Esta é uma instâ ncia de PyObject representando o objeto hora do Python.
type PyDateTime_Delta
Esta é uma instâ ncia de PyObject representando a diferença entre dois valores de datetime.
PyTypeObject PyDateTime_DateType
Esta instâ ncia de PyTypeObject representa o tipo data do Python; é o mesmo objeto que datetime.date
na camada de Python.
PyTypeObject PyDateTime_DateTimeType
Esta instâ ncia de PyTypeObject representa o tipo datetime do Python; é o mesmo objeto que datetime.
datetime na camada de Python.
PyTypeObject PyDateTime_TimeType
Esta instâ ncia de PyTypeObject representa o tipo hora do Python; é o mesmo objeto que datetime.time
na camada de Python.
PyTypeObject PyDateTime_DeltaType
Esta instâ ncia de PyTypeObject representa o tipo Python para a diferença entre dois valores de datetime; é
o mesmo objeto que datetime.timedelta na camada de Python.
PyTypeObject PyDateTime_TZInfoType
Esta instâ ncia de PyTypeObject representa o tipo fuso horá rio do Python; é o mesmo objeto que datetime.
tzinfo na camada de Python.
Macro para acesso ao singleton UTC:
PyObject *PyDateTime_TimeZone_UTC
Retorna um singleton do fuso horá rio representando o UTC, o mesmo objeto que datetime.timezone.utc.
Adicionado na versã o 3.7.
Macros de verificaçã o de tipo:
int PyDate_Check(PyObject *ob)
Retorna verdadeiro se ob for do tipo PyDateTime_DateType ou um subtipo de PyDateTime_DateType.
ob nã o deve ser NULL. Esta funçã o sempre tem sucesso.
208 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyDate_CheckExact(PyObject *ob)
Retorna verdadeiro se ob for do tipo PyDateTime_DateType. ob nã o deve ser NULL. Esta funçã o sempre
tem sucesso.
int PyDateTime_Check(PyObject *ob)
Retorna verdadeiro se ob é do tipo PyDateTime_DateTimeType ou um subtipo de
PyDateTime_DateTimeType. ob nã o deve ser NULL. Esta funçã o sempre tem sucesso.
int PyDateTime_CheckExact(PyObject *ob)
Retorna verdadeiro se ob for do tipo PyDateTime_DateTimeType. ob nã o deve ser NULL. Esta funçã o
sempre tem sucesso.
int PyTime_Check(PyObject *ob)
Retorna verdadeiro se ob é do tipo PyDateTime_TimeType ou um subtipo de PyDateTime_TimeType. ob
nã o deve ser NULL. Esta funçã o sempre tem sucesso.
int PyTime_CheckExact(PyObject *ob)
Retorna verdadeiro se ob for do tipo PyDateTime_TimeType. ob nã o deve ser NULL. Esta funçã o sempre
tem sucesso.
int PyDelta_Check(PyObject *ob)
Retorna verdadeiro se ob for do tipo PyDateTime_DeltaType ou um subtipo de PyDateTime_DeltaType.
ob nã o pode ser NULL. Esta funçã o sempre tem sucesso.
int PyDelta_CheckExact(PyObject *ob)
Retorna verdadeiro se ob for do tipo PyDateTime_DeltaType. ob nã o deve ser NULL. Esta funçã o sempre
tem sucesso.
int PyTZInfo_Check(PyObject *ob)
Retorna verdadeiro se ob for do tipo PyDateTime_TZInfoType ou um subtipo de
PyDateTime_TZInfoType. ob nã o pode ser NULL. Esta funçã o sempre tem sucesso.
int PyTZInfo_CheckExact(PyObject *ob)
Retorna verdadeiro se ob for do tipo PyDateTime_TZInfoType. ob nã o deve ser NULL. Esta funçã o sempre
tem sucesso.
Macros para criar objetos:
PyObject *PyDate_FromDate(int year, int month, int day)
Retorna valor: Nova referência. Retorna um objeto datetime.date com o ano, mê s e dia especificados.
PyObject *PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int
usecond)
Retorna valor: Nova referência. Retorna um objeto datetime.datetime com o ano, mê s, dia, hora, minuto,
segundo, microssegundo especificados.
PyObject *PyDateTime_FromDateAndTimeAndFold(int year, int month, int day, int hour, int minute, int
second, int usecond, int fold)
Retorna valor: Nova referência. Retorna um objeto datetime.datetime com o ano, mê s, dia, hora, minuto,
segundo, microssegundo e a dobra especificados.
Adicionado na versã o 3.6.
PyObject *PyTime_FromTime(int hour, int minute, int second, int usecond)
Retorna valor: Nova referência. Retorna um objeto datetime.time com a hora, minuto, segundo e micros-
segundo especificados.
PyObject *PyTime_FromTimeAndFold(int hour, int minute, int second, int usecond, int fold)
Retorna valor: Nova referência. Retorna um objeto datetime.time com a hora, minuto, segundo, micros-
segundo e a dobra especificados.
Adicionado na versã o 3.6.
8.6. Outros Objetos 209
The Python/C API, Release 3.13.7
PyObject *PyDelta_FromDSU(int days, int seconds, int useconds)
Retorna valor: Nova referência. Retorna um objeto datetime.timedelta representando o nú mero espe-
cificado de dias, segundos e microssegundos. A normalizaçã o é realizada para que o nú mero resultante de
microssegundos e segundos esteja nos intervalos documentados para objetos de datetime.timedelta.
PyObject *PyTimeZone_FromOffset(PyObject *offset)
Retorna valor: Nova referência. Retorna um objeto datetime.timezone com um deslocamento fixo sem
nome representado pelo argumento offset.
Adicionado na versã o 3.7.
PyObject *PyTimeZone_FromOffsetAndName(PyObject *offset, PyObject *name)
Retorna valor: Nova referência. Retorna um objeto datetime.timezone com um deslocamento fixo repre-
sentado pelo argumento offset e com tzname name.
Adicionado na versã o 3.7.
Macros para extrair campos de objetos date. O argumento deve ser uma instâ ncia de PyDateTime_Date, inclusive
subclasses (como PyDateTime_DateTime). O argumento nã o deve ser NULL, e o tipo nã o é verificado:
int PyDateTime_GET_YEAR(PyDateTime_Date *o)
Retorna o ano, como um inteiro positivo.
int PyDateTime_GET_MONTH(PyDateTime_Date *o)
Retorna o mê s, como um inteiro de 1 a 12.
int PyDateTime_GET_DAY(PyDateTime_Date *o)
Retorna o dia, como um inteiro de 1 a 31.
Macros para extrair campos de objetos datetime. O argumento deve ser uma instâ ncia de PyDateTime_DateTime,
inclusive subclasses. O argumento nã o deve ser NULL, e o tipo nã o é verificado:
int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)
Retorna a hora, como um inteiro de 0 a 23.
int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)
Retorna o minuto, como um inteiro de 0 a 59.
int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)
Retorna o segundo, como um inteiro de 0 a 59.
int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o)
Retorna o microssegundo, como um inteiro de 0 a 999999.
int PyDateTime_DATE_GET_FOLD(PyDateTime_DateTime *o)
Retorna a dobra, como um inteiro de 0 a 1.
Adicionado na versã o 3.6.
PyObject *PyDateTime_DATE_GET_TZINFO(PyDateTime_DateTime *o)
Retorna o tzinfo (que pode ser None).
Adicionado na versã o 3.10.
Macros para extrair campos de objetos time. O argumento deve ser uma instâ ncia de PyDateTime_Time, inclusive
subclasses. O argumento nã o deve ser NULL, e o tipo nã o é verificado:
int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o)
Retorna a hora, como um inteiro de 0 a 23.
int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o)
Retorna o minuto, como um inteiro de 0 a 59.
int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o)
Retorna o segundo, como um inteiro de 0 a 59.
210 Capítulo 8. Camada de Objetos Concretos
The Python/C API, Release 3.13.7
int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o)
Retorna o microssegundo, como um inteiro de 0 a 999999.
int PyDateTime_TIME_GET_FOLD(PyDateTime_Time *o)
Retorna a dobra, como um inteiro de 0 a 1.
Adicionado na versã o 3.6.
PyObject *PyDateTime_TIME_GET_TZINFO(PyDateTime_Time *o)
Retorna o tzinfo (que pode ser None).
Adicionado na versã o 3.10.
Macros para extrair campos de objetos time delta. O argumento deve ser uma instâ ncia de PyDateTime_Delta,
inclusive subclasses. O argumento nã o deve ser NULL, e o tipo nã o é verificado:
int PyDateTime_DELTA_GET_DAYS(PyDateTime_Delta *o)
Retorna o nú mero de dias, como um inteiro de -999999999 a 999999999.
Adicionado na versã o 3.3.
int PyDateTime_DELTA_GET_SECONDS(PyDateTime_Delta *o)
Retorna o nú mero de segundos, como um inteiro de 0 a 86399.
Adicionado na versã o 3.3.
int PyDateTime_DELTA_GET_MICROSECONDS(PyDateTime_Delta *o)
Retorna o nú mero de microssegundos, como um inteiro de 0 a 999999.
Adicionado na versã o 3.3.
Macros para a conveniê ncia de mó dulos implementando a API de DB:
PyObject *PyDateTime_FromTimestamp(PyObject *args)
Retorna valor: Nova referência. Cria e retorna um novo objeto datetime.datetime dado uma tupla de
argumentos que possa ser passada ao mé todo datetime.datetime.fromtimestamp().
PyObject *PyDate_FromTimestamp(PyObject *args)
Retorna valor: Nova referência. Cria e retorna um novo objeto datetime.date dado uma tupla de argu-
mentos que possa ser passada ao mé todo datetime.date.fromtimestamp().
8.6.14 Objetos de indicação de tipos
Sã o fornecidos vá rios tipos embutidos para sugestã o de tipo. Atualmente, dois tipos existem – GenericAlias e Union.
Apenas GenericAlias está exposto ao C.
PyObject *Py_GenericAlias(PyObject *origin, PyObject *args)
Parte da ABI Está vel desde a versão 3.9. Cria um objeto GenericAlias. Equivalente a chamar a
classe Python types.GenericAlias. Os argumentos origin e args definem os atributos __origin__ e
__args__ de GenericAlias respectivamente. origin deve ser um PyTypeObject*, e args pode ser um
PyTupleObject* ou qualquer PyObject*. Se args passado nã o for uma tupla, uma tupla de 1 elemento
é construída automaticamente e __args__ é definido como (args,). A verificaçã o mínima é feita para os
argumentos, entã o a funçã o terá sucesso mesmo se origin nã o for um tipo. O atributo __parameters__ de
GenericAlias é construído lentamente a partir de __args__. Em caso de falha, uma exceçã o é levantada
e NULL é retornado.
Aqui está um exemplo de como tornar um tipo de extensã o gené rico:
...
static PyMethodDef my_obj_methods[] = {
// Outros métodos.
...
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, "Veja PEP 585"}
(continua na pró xima pá gina)
8.6. Outros Objetos 211
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
...
}
µ Ver também
O mé todo de modelo de dados __class_getitem__().
Adicionado na versã o 3.9.
PyTypeObject Py_GenericAliasType
Parte da ABI Está vel desde a versão 3.9. O tipo C do objeto retornado por Py_GenericAlias(). Equivalente
a types.GenericAlias no Python.
Adicionado na versã o 3.9.
212 Capítulo 8. Camada de Objetos Concretos
CAPÍTULO 9
Inicialização, finalização e threads
Veja Configuração de inicialização do Python para detalhes sobre como configurar o interpretador antes da iniciali-
zaçã o.
9.1 Antes da inicialização do Python
Em uma aplicaçã o que incorpora Python, a funçã o Py_Initialize() deve ser chamada antes de usar qualquer
outra funçã o da API Python/C; com exceçã o de algumas funçõ es e as variáveis globais de configuração.
As seguintes funçõ es podem ser seguramente chamadas antes da inicializaçã o do Python.
• Funçõ es que inicializam o interpretador:
– Py_Initialize()
– Py_InitializeEx()
– Py_InitializeFromConfig()
– Py_BytesMain()
– Py_Main()
– as funçõ es de pré -inicializaçã o de tempo de execuçã o cobertas em Configuração de Inicialização do
Python
• Funçõ es de configuraçã o:
– PyImport_AppendInittab()
– PyImport_ExtendInittab()
– PyInitFrozenExtensions()
– PyMem_SetAllocator()
– PyMem_SetupDebugHooks()
– PyObject_SetArenaAllocator()
– Py_SetProgramName()
– Py_SetPythonHome()
– PySys_ResetWarnOptions()
213
The Python/C API, Release 3.13.7
– as funçõ es de configuraçã o cobertas em Configuração de Inicialização do Python
• Funçõ es informativas:
– Py_IsInitialized()
– PyMem_GetAllocator()
– PyObject_GetArenaAllocator()
– Py_GetBuildInfo()
– Py_GetCompiler()
– Py_GetCopyright()
– Py_GetPlatform()
– Py_GetVersion()
– Py_IsInitialized()
• Utilitá rios:
– Py_DecodeLocale()
– o relató rio de status é funçõ es utilitá rias cobertas em Configuração de Inicialização do Python
• Alocadores de memó ria:
– PyMem_RawMalloc()
– PyMem_RawRealloc()
– PyMem_RawCalloc()
– PyMem_RawFree()
• Sincronizaçã o:
– PyMutex_Lock()
– PyMutex_Unlock()
® Nota
Apesar de sua aparente semelhança com algumas das funçõ es listadas acima, as seguintes funçõ es não devem
ser chamadas antes que o interpretador tenha sido inicializado: Py_EncodeLocale(), Py_GetPath(),
Py_GetPrefix(), Py_GetExecPrefix(), Py_GetProgramFullPath(), Py_GetPythonHome(),
Py_GetProgramName(), PyEval_InitThreads(), e Py_RunMain().
9.2 Variáveis de configuração global
Python tem variá veis para a configuraçã o global a fim de controlar diferentes características e opçõ es. Por padrã o,
estes sinalizadores sã o controlados por opçõ es de linha de comando.
Quando um sinalizador é definido por uma opçã o, o valor do sinalizador é o nú mero de vezes que a opçã o foi definida.
Por exemplo,“-b“ define Py_BytesWarningFlag para 1 e -bb define Py_BytesWarningFlag para 2.
int Py_BytesWarningFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.
bytes_warning deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Emite um aviso ao comparar bytes ou bytearray com str ou bytes com int. Emite um erro se for maior
ou igual a 2.
Definida pela opçã o -b.
Deprecated since version 3.12, will be removed in version 3.14.
214 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
int Py_DebugFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.parser_debug
deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Ativa a saída de depuraçã o do analisador sintá tico (somente para especialistas, dependendo das opçõ es de
compilaçã o).
Definida pela a opçã o -d e a variá vel de ambiente PYTHONDEBUG.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_DontWriteBytecodeFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.
write_bytecode deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Se definida como diferente de zero, o Python nã o tentará escrever arquivos .pyc na importaçã o de mó dulos
fonte.
Definida pela opçã o -B e pela variá vel de ambiente PYTHONDONTWRITEBYTECODE.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_FrozenFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.
pathconfig_warnings deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Suprime mensagens de erro ao calcular o caminho de pesquisa do mó dulo em Py_GetPath().
Sinalizador privado usado pelos programas _freeze_module e frozenmain.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_HashRandomizationFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o de PyConfig.hash_seed
e PyConfig.use_hash_seed deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Definida como 1 se a variá vel de ambiente PYTHONHASHSEED estiver definida como uma string nã o vazia.
Se o sinalizador for diferente de zero, lê a variá vel de ambiente PYTHONHASHSEED para inicializar a semente
de hash secreta.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_IgnoreEnvironmentFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.
use_environment deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Ignora todas as variá veis de ambiente PYTHON*, por exemplo PYTHONPATH e PYTHONHOME, que podem estar
definidas.
Definida pelas opçõ es -E e -I.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_InspectFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.inspect deve
ser usada em seu lugar, consulte Configuração de inicialização do Python.
Quando um script é passado como primeiro argumento ou a opçã o -c é usada, entre no modo interativo apó s
executar o script ou o comando, mesmo quando sys.stdin nã o parece ser um terminal.
Definida pela opçã o -i e pela variá vel de ambiente PYTHONINSPECT.
Deprecated since version 3.12, will be removed in version 3.14.
9.2. Variáveis de configuração global 215
The Python/C API, Release 3.13.7
int Py_InteractiveFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.interactive
deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Definida pela opçã o -i.
Deprecated since version 3.12, will be removed in version 3.15.
int Py_IsolatedFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.isolated deve
ser usada em seu lugar, consulte Configuração de inicialização do Python.
Executa o Python no modo isolado. No modo isolado, sys.path nã o conté m nem o diretó rio do script nem
o diretó rio de pacotes de sites do usuá rio.
Definida pela opçã o -I.
Adicionado na versã o 3.4.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_LegacyWindowsFSEncodingFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyPreConfig.
legacy_windows_fs_encoding deve ser usada em seu lugar, consulte Configuração de inicialização do
Python.
Se o sinalizador for diferente de zero, use a codificaçã o mbcs com o tratador de erros replace, em vez da
codificaçã o UTF-8 com o tratador de erros surrogatepass, para a codificaçã o do sistema de arquivos e
tratador de erros e codificação do sistema de arquivos.
Definida como 1 se a variá vel de ambiente PYTHONLEGACYWINDOWSFSENCODING estiver definida como uma
string nã o vazia.
Veja PEP 529 para mais detalhes.
Disponibilidade: Windows.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_LegacyWindowsStdioFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.
legacy_windows_stdio deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Se o sinalizador for diferente de zero, usa io.FileIO em vez de io._WindowsConsoleIO para fluxos
padrã o sys.
Definida como 1 se a variá vel de ambiente PYTHONLEGACYWINDOWSSTDIO estiver definida como uma string
nã o vazia.
Veja a PEP 528 para mais detalhes.
Disponibilidade: Windows.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_NoSiteFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.site_import
deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Desabilita a importaçã o do mó dulo site e as manipulaçõ es dependentes do site de sys.path que isso acar-
reta. També m desabilita essas manipulaçõ es se site for explicitamente importado mais tarde (chame site.
main() se você quiser que eles sejam acionados).
Definida pela opçã o -S.
Deprecated since version 3.12, will be removed in version 3.14.
216 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
int Py_NoUserSiteDirectory
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.
user_site_directory deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Nã o adiciona o diretório site-packages de usuário a sys.path.
Definida pelas opçõ es -s e -I, e pela variá vel de ambiente PYTHONNOUSERSITE.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_OptimizeFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.
optimization_level deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Definida pela opçã o -O e pela variá vel de ambiente PYTHONOPTIMIZE.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_QuietFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.quiet deve ser
usada em seu lugar, consulte Configuração de inicialização do Python.
Nã o exibe as mensagens de direitos autorais e de versã o nem mesmo no modo interativo.
Definida pela opçã o -q.
Adicionado na versã o 3.2.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_UnbufferedStdioFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.
buffered_stdio deve ser usada em seu lugar, consulte Configuração de inicialização do Python.
Força os fluxos stdout e stderr a nã o serem armazenados em buffer.
Definida pela opçã o -u e pela variá vel de ambiente PYTHONUNBUFFERED.
Deprecated since version 3.12, will be removed in version 3.14.
int Py_VerboseFlag
Esta API é mantida para compatibilidade com versõ es anteriores: a configuraçã o PyConfig.verbose deve
ser usada em seu lugar, consulte Configuração de inicialização do Python.
Exibe uma mensagem cada vez que um mó dulo é inicializado, mostrando o local (nome do arquivo ou mó dulo
embutido) de onde ele é carregado. Se maior ou igual a 2, exibe uma mensagem para cada arquivo que é
verificado durante a busca por um mó dulo. També m fornece informaçõ es sobre a limpeza do mó dulo na saída.
Definida pela a opçã o -v e a variá vel de ambiente PYTHONVERBOSE.
Deprecated since version 3.12, will be removed in version 3.14.
9.3 Inicializando e encerrando o interpretador
void Py_Initialize()
Parte da ABI Está vel. Inicializa o interpretador Python. Em uma aplicaçã o que incorpora o Python, isto deve
ser chamado antes do uso de qualquer outra funçã o do Python/C API; veja Antes da Inicialização do Python
para algumas exceçõ es.
Isso inicializa a tabela de mó dulos carregados (sys.modules) e cria os mó dulos fundamentais builtins,
__main__ e sys. També m inicializa o caminho de pesquisa de mó dulos (sys.path). Isso nã o define sys.
argv; use a API da Configuração de inicialização do Python para isso. Isso é um no-op quando chamado
pela segunda vez (sem chamar Py_FinalizeEx() primeiro). Nã o há valor de retorno; é um erro fatal se a
inicializaçã o falhar.
Usa Py_InitializeFromConfig() para personalizar a Configuração de inicialização do Python.
9.3. Inicializando e encerrando o interpretador 217
The Python/C API, Release 3.13.7
® Nota
No Windows, altera o modo do console de O_TEXT para O_BINARY, o que també m afetará usos nã o Python
do console usando o Runtime C.
void Py_InitializeEx(int initsigs)
Parte da ABI Está vel. Esta funçã o funciona como Py_Initialize() se initsigs for 1. Se initsigs for 0, ela
pula o registro de inicializaçã o de manipuladores de sinal, o que pode ser ú til quando o CPython é incorporado
como parte de uma aplicaçã o maior.
Usa Py_InitializeFromConfig() para personalizar a Configuração de inicialização do Python.
PyStatus Py_InitializeFromConfig(const PyConfig *config)
Inicializa o Python a partir da configuraçã o config, conforme descrito em Initialization with PyConfig.
Consulte a seçã o Configuração de Inicialização do Python para obter detalhes sobre como pré -inicializar o
interpretador, preencher a estrutura de configuraçã o do tempo de execuçã o e consultar a estrutura de status
retornada.
int Py_IsInitialized()
Parte da ABI Está vel. Retorna true (diferente de zero) quando o interpretador Python foi inicializado, false
(zero) se nã o. Apó s Py_FinalizeEx() ser chamado, isso retorna false até que Py_Initialize() seja
chamado novamente.
int Py_IsFinalizing()
Parte da ABI Está vel desde a versão 3.13. Retorna verdadeiro (diferente de zero) se o interpretador Python
principal estiver em desligamento. Retorna falso (zero) caso contrá rio.
Adicionado na versã o 3.13.
int Py_FinalizeEx()
Parte da ABI Está vel desde a versão 3.6. Undo all initializations made by Py_Initialize() and subse-
quent use of Python/C API functions, and destroy all sub-interpreters (see Py_NewInterpreter() below)
that were created and not yet destroyed since the last call to Py_Initialize(). Ideally, this frees all me-
mory allocated by the Python interpreter. This is a no-op when called for a second time (without calling
Py_Initialize() again first).
Como isso é o inverso de Py_Initialize(), ele deve ser chamado na mesma thread com o mesmo interpre-
tador ativo. Isso significa a thread principal e o interpretador principal. Isso nunca deve ser chamado enquanto
Py_RunMain() estiver em execuçã o.
Normalmente, o valor de retorno é 0. Se houver erros durante a finalizaçã o (limpeza de dados armazenados
em buffer), -1 será retornado.
Esta funçã o é fornecida por vá rios motivos. Uma aplicaçã o de incorporaçã o pode querer reiniciar o Python
sem precisar reiniciar a pró pria aplicaçã o. Uma aplicaçã o que carregou o interpretador Python de uma bibli-
oteca carregá vel dinamicamente (ou DLL) pode querer liberar toda a memó ria alocada pelo Python antes de
descarregar a DLL. Durante uma busca por vazamentos de memó ria em uma aplicaçã o, um desenvolvedor
pode querer liberar toda a memó ria alocada pelo Python antes de sair da aplicaçã o.
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 re-
ferences 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. Py_FinalizeEx() must
not be called recursively from within itself. Therefore, it must not be called by any code that may be run as
part of the interpreter shutdown process, such as atexit handlers, object finalizers, or any code that may be
run while flushing the stdout and stderr files.
Levanta um evento de auditoria cpython._PySys_ClearAuditHooks sem argumentos.
218 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
Adicionado na versã o 3.6.
void Py_Finalize()
Parte da ABI Está vel. Esta é uma versã o compatível com retrocompatibilidade de Py_FinalizeEx() que
desconsidera o valor de retorno.
int Py_BytesMain(int argc, char **argv)
Parte da ABI Está vel desde a versão 3.8. Semelhante a Py_Main(), mas argv é um vetor de strings de bytes,
permitindo que o aplicativo de chamada delegue a etapa de decodificaçã o de texto ao tempo de execuçã o do
CPython.
Adicionado na versã o 3.8.
int Py_Main(int argc, wchar_t **argv)
Parte da ABI Está vel. O programa principal para o interpretador padrã o, encapsulando um ciclo completo de
inicializaçã o/finalizaçã o, bem como comportamento adicional para implementar a leitura de configuraçõ es do
ambiente e da linha de comando e, em seguida, executar __main__ de acordo com using-on-cmdline.
Isso é disponibilizado para programas que desejam oferecer suporte à interface de linha de comando completa
do CPython, em vez de apenas incorporar um tempo de execuçã o do Python em uma aplicaçã o maior.
Os parâ metros argc e argv sã o semelhantes aos passados para a funçã o main() de um programa C, exceto
que as entradas argv sã o primeiro convertidas para wchar_t usando Py_DecodeLocale(). També m é
importante observar que as entradas da lista de argumentos podem ser modificadas para apontar para strings
diferentes daquelas passadas (no entanto, o conteú do das strings apontadas pela lista de argumentos nã o é
modificado).
The return value is 2 if the argument list does not represent a valid Python command line, and otherwise the
same as Py_RunMain().
Em termos das APIs de configuraçã o de tempo de execuçã o do CPython documentadas na seçã o de confi-
guração de runtime (e sem levar em conta o tratamento de erros), Py_Main é aproximadamente equivalente
a:
PyConfig config;
PyConfig_InitPythonConfig(&config);
PyConfig_SetArgv(&config, argc, argv);
Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
Py_RunMain();
Em uso normal, uma aplicaçã o de incorporaçã o chamará esta funçã o em vez de chamar Py_Initialize(),
Py_InitializeEx() ou Py_InitializeFromConfig() diretamente, e todas as configuraçõ es serã o apli-
cadas conforme descrito em outra parte desta documentaçã o. Se esta funçã o for chamada após uma chamada
anterior à API de inicializaçã o do runtime, as configuraçõ es de ambiente e de linha de comando que serã o
atualizadas dependem da versã o (pois dependem de quais configuraçõ es oferecem suporte corretamente à
modificaçã o apó s já terem sido definidas uma vez na primeira inicializaçã o do runtime).
int Py_RunMain(void)
Executes the main module in a fully configured CPython runtime.
Executes the command (PyConfig.run_command), the script (PyConfig.run_filename) or the module
(PyConfig.run_module) specified on the command line or in the configuration. If none of these values are
set, runs the interactive Python prompt (REPL) using the __main__ module’s global namespace.
If PyConfig.inspect is not set (the default), the return value will be 0 if the interpreter exits normally (that
is, without raising an exception), the exit status of an unhandled SystemExit, or 1 for any other unhandled
exception.
If PyConfig.inspect is set (such as when the -i option is used), rather than returning when the interpreter
exits, execution will instead resume in an interactive Python prompt (REPL) using the __main__ module’s
global namespace. If the interpreter exited with an exception, it is immediately raised in the REPL session.
9.3. Inicializando e encerrando o interpretador 219
The Python/C API, Release 3.13.7
The function return value is then determined by the way the REPL session terminates: 0, 1, or the status of a
SystemExit, as specified above.
This function always finalizes the Python interpreter before it returns.
See Python Configuration for an example of a customized Python that always runs in isolated mode using
Py_RunMain().
int PyUnstable_AtExit(PyInterpreterState *interp, void (*func)(void*), void *data)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Register an atexit callback for the target interpreter interp. This is similar to Py_AtExit(), but takes an
explicit interpreter and data pointer for the callback.
The GIL must be held for interp.
Adicionado na versã o 3.13.
9.4 Process-wide parameters
void Py_SetProgramName(const wchar_t *name)
Parte da ABI Está vel. This API is kept for backward compatibility: setting PyConfig.program_name
should be used instead, see Python Initialization Configuration.
Esta funçã o deve ser chamada antes de Py_Initialize() ser chamada pela primeira vez, caso seja solicitada.
Ela diz ao interpretador o valor do argumento argv[0] para a funçã o main() do programa (convertido em
caracteres amplos). Isto é utilizado por Py_GetPath() e algumas outras funçõ es abaixo para encontrar as
bibliotecas de tempo de execuçã o relativas ao executá vel do interpretador. O valor padrã o é 'python'. O
argumento deve apontar para um caractere string amplo terminado em zero no armazenamento está tico, cujo
conteú do nã o mudará durante a execuçã o do programa. Nenhum có digo no interpretador Python mudará o
conteú do deste armazenamento.
Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.
Descontinuado desde a versã o 3.11.
wchar_t *Py_GetProgramName()
Parte da ABI Está vel. 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.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Alterado na versã o 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Get sys.executable instead.
wchar_t *Py_GetPrefix()
Parte da ABI Está vel. Return the prefix for installed platform-independent files. This is derived through a num-
ber of complicated rules from the program name set with PyConfig.program_name and some environment
variables; for example, if the program name is '/usr/local/bin/python', the prefix is '/usr/local'.
The returned string points into static storage; the caller should not modify its value. This corresponds to the
prefix variable in the top-level Makefile and the --prefix argument to the configure script at build
time. The value is available to Python code as sys.base_prefix. It is only useful on Unix. See also the
next function.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Alterado na versã o 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Get sys.base_prefix instead, or sys.
prefix if virtual environments need to be handled.
220 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
wchar_t *Py_GetExecPrefix()
Parte da ABI Está vel. 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 en-
vironment 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
corresponds 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.base_exec_prefix. It
is only useful on Unix.
Background: The exec-prefix differs from the prefix when platform dependent files (such as executables and
shared libraries) are installed in a different directory tree. In a typical installation, platform dependent files may
be installed in the /usr/local/plat subtree while platform independent may be installed in /usr/local.
Generally speaking, a platform is a combination of hardware and software families, e.g. Sparc machines run-
ning the Solaris 2.x operating system are considered the same platform, but Intel machines running Solaris
2.x are another platform, and Intel machines running Linux are yet another platform. Different major revisi-
ons of the same operating system generally also form different platforms. Non-Unix operating systems are a
different story; the installation strategies on those systems are so different that the prefix and exec-prefix are
meaningless, and set to the empty string. Note that compiled Python bytecode files are platform independent
(but not independent from the Python version by which they were compiled!).
System administrators will know how to configure the mount or automount programs to share /usr/local
between platforms while having /usr/local/plat be a different filesystem for each platform.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Alterado na versã o 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Get sys.base_exec_prefix instead, or
sys.exec_prefix if virtual environments need to be handled.
wchar_t *Py_GetProgramFullPath()
Parte da ABI Está vel. 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.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Alterado na versã o 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Get sys.executable instead.
wchar_t *Py_GetPath()
Parte da ABI Está vel. 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.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Alterado na versã o 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Get sys.path instead.
const char *Py_GetVersion()
Parte da ABI Está vel. Retorna a verã o deste interpretador Python. Esta é uma string que se parece com
"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
The first word (up to the first space character) is the current Python version; the first characters are the major
and minor version separated by a period. The returned string points into static storage; the caller should not
modify its value. The value is available to Python code as sys.version.
9.4. Process-wide parameters 221
The Python/C API, Release 3.13.7
See also the Py_Version constant.
const char *Py_GetPlatform()
Parte da ABI Está vel. Return the platform identifier for the current platform. On Unix, this is formed from
the “official” name of the operating system, converted to lower case, followed by the major revision number;
e.g., for Solaris 2.x, which is also known as SunOS 5.x, the value is 'sunos5'. On macOS, it is 'darwin'.
On Windows, it is 'win'. The returned string points into static storage; the caller should not modify its value.
The value is available to Python code as sys.platform.
const char *Py_GetCopyright()
Parte da ABI Está vel. Retorna a string oficial de direitos autoriais para a versã o atual do Python, por exemplo
'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'
The returned string points into static storage; the caller should not modify its value. The value is available to
Python code as sys.copyright.
const char *Py_GetCompiler()
Parte da ABI Está vel. Retorna uma indicaçã o do compilador usado para construir a atual versã o do Python,
em colchetes, por exemplo:
"[GCC 2.7.2.2]"
The returned string points into static storage; the caller should not modify its value. The value is available to
Python code as part of the variable sys.version.
const char *Py_GetBuildInfo()
Parte da ABI Está vel. Retorna informaçã o sobre o nú mero de sequê ncia e a data e hora da construçã o da
instâ ncia atual do interpretador Python, por exemplo
"#67, Aug 1 1997, 22:34:28"
The returned string points into static storage; the caller should not modify its value. The value is available to
Python code as part of the variable sys.version.
void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Parte da ABI Está vel. This API is kept for backward compatibility: setting PyConfig.argv , PyConfig.
parse_argv and PyConfig.safe_path should be used instead, see Python Initialization Configuration.
Set sys.argv based on argc and 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 execu-
table hosting the Python interpreter. If there isn’t a script that will be run, the first entry in argv can be an empty
string. If this function fails to initialize sys.argv, a fatal condition is signalled using Py_FatalError().
Se updatepath é zero, isto é tudo o que a funçã o faz. Se updatepath nã o é zero, a funçã o també m modifica
sys.path de acordo com o seguinte algoritmo:
• If the name of an existing script is passed in argv[0], the absolute path of the directory where the script
is located is prepended to sys.path.
• Otherwise (that is, if argc is 0 or argv[0] doesn’t point to an existing file name), an empty string is
prepended to sys.path, which is the same as prepending the current working directory (".").
Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.
See also PyConfig.orig_argv and PyConfig.argv members of the Python Initialization Configuration.
® Nota
It is recommended that applications embedding the Python interpreter for purposes other than executing a
single script pass 0 as updatepath, and update sys.path themselves if desired. See CVE 2008-5983.
On versions before 3.1.3, you can achieve the same effect by manually popping the first sys.path element
after having called PySys_SetArgv(), for example using:
222 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
PyRun_SimpleString("import sys; sys.path.pop(0)\n");
Adicionado na versã o 3.1.3.
Descontinuado desde a versã o 3.11.
void PySys_SetArgv(int argc, wchar_t **argv)
Parte da ABI Está vel. This API is kept for backward compatibility: setting PyConfig.argv and PyConfig.
parse_argv should be used instead, see Python Initialization Configuration.
This function works like PySys_SetArgvEx() with updatepath set to 1 unless the python interpreter was
started with the -I.
Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.
See also PyConfig.orig_argv and PyConfig.argv members of the Python Initialization Configuration.
Alterado na versã o 3.4: The updatepath value depends on -I.
Descontinuado desde a versã o 3.11.
void Py_SetPythonHome(const wchar_t *home)
Parte da ABI Está vel. This API is kept for backward compatibility: setting PyConfig.home should be used
instead, see Python Initialization Configuration.
Set the default “home” directory, that is, the location of the standard Python libraries. See PYTHONHOME for
the meaning of the argument string.
The argument should point to a zero-terminated character string in static storage whose contents will not change
for the duration of the program’s execution. No code in the Python interpreter will change the contents of this
storage.
Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.
Descontinuado desde a versã o 3.11.
wchar_t *Py_GetPythonHome()
Parte da ABI Está vel. Return the default “home”, that is, the value set by PyConfig.home, or the value of
the PYTHONHOME environment variable if it is set.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Alterado na versã o 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Get PyConfig.home or PYTHONHOME envi-
ronment variable instead.
9.5 Estado de thread e a trava global do interpretador
The Python interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there’s a global
lock, called the global interpreter lock or GIL, that must be held by the current thread before it can safely access
Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program:
for example, when two threads simultaneously increment the reference count of the same object, the reference count
could end up being incremented only once instead of twice.
Portanto, existe a regra de que somente a thread que adquiriu a GIL pode operar em objetos Python ou chamar
funçõ es da API C/Python. Para emular a simultaneidade de execuçã o, o interpretador tenta alternar threads regular-
mente (consulte sys.setswitchinterval()). A trava també m é liberada em operaçõ es de E/S potencialmente
bloqueantes, como ler ou escrever um arquivo, para que outras threads Python possam ser executadas enquanto isso.
The Python interpreter keeps some thread-specific bookkeeping information inside a data structure called
PyThreadState. There’s also one global variable pointing to the current PyThreadState: it can be retrieved
using PyThreadState_Get().
9.5. Estado de thread e a trava global do interpretador 223
The Python/C API, Release 3.13.7
9.5.1 Releasing the GIL from extension code
A maioria dos có digos de extensã o que manipulam a GIL tem a seguinte estrutura:
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.
Isso é tã o comum que existe um par de macros para simplificá -lo:
Py_BEGIN_ALLOW_THREADS
... Faça alguma operação de E/S com bloqueio...
Py_END_ALLOW_THREADS
A macro Py_BEGIN_ALLOW_THREADS abre um novo bloco e declara uma variá vel local oculta; a macro
Py_END_ALLOW_THREADS fecha o bloco.
O bloco acima se expande para o seguinte có digo:
PyThreadState *_save;
_save = PyEval_SaveThread();
... Faça alguma operação de E/S com bloqueio...
PyEval_RestoreThread(_save);
Here is how these functions work: the global interpreter lock is used to protect the pointer to the current thread
state. When releasing the lock and saving the thread state, the current thread state pointer must be retrieved before
the lock is released (since another thread could immediately acquire the lock and store its own thread state in the
global variable). Conversely, when acquiring the lock and restoring the thread state, the lock must be acquired before
storing the thread state pointer.
® Nota
Calling system I/O functions is the most common use case for releasing the GIL, but it can also be useful before
calling long-running computations which don’t need access to Python objects, such as compression or crypto-
graphic functions operating over memory buffers. For example, the standard zlib and hashlib modules release
the GIL when compressing or hashing data.
9.5.2 Non-Python created threads
When threads are created using the dedicated Python APIs (such as the threading module), a thread state is
automatically associated to them and the code showed above is therefore correct. However, when threads are created
from C (for example by a third-party library with its own thread management), they don’t hold the GIL, nor is there
a thread state structure for them.
If you need to call Python code from these threads (often this will be part of a callback API provided by the afo-
rementioned third-party library), you must first register these threads with the interpreter by creating a thread state
data structure, then acquiring the GIL, and finally storing their thread state pointer, before you can start using the
Python/C API. When you are done, you should reset the thread state pointer, release the GIL, and finally free the
thread state data structure.
The PyGILState_Ensure() and PyGILState_Release() functions do all of the above automatically. The
typical idiom for calling into Python from a C thread is:
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
(continua na pró xima pá gina)
224 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */
/* Release the thread. No Python API allowed beyond this point. */
PyGILState_Release(gstate);
Note that the PyGILState_* functions assume there is only one global interpreter (created automatically by
Py_Initialize()). Python supports the creation of additional interpreters (using Py_NewInterpreter()),
but mixing multiple interpreters and the PyGILState_* API is unsupported.
9.5.3 Cuidados com o uso de fork()
Another important thing to note about threads is their behaviour in the face of the C fork() call. On most systems
with fork(), after a process forks only the thread that issued the fork will exist. This has a concrete impact both on
how locks must be handled and on all stored state in CPython’s runtime.
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.
The fact that all other threads go away also means that CPython’s runtime state there must be cleaned up properly,
which os.fork() does. This means finalizing all other PyThreadState objects belonging to the current interpreter
and all other PyInterpreterState objects. Due to this and the special nature of the “main” interpreter, fork()
should only be called in that interpreter’s “main” thread, where the CPython global runtime was originally initialized.
The only exception is if exec() will be called immediately after.
9.5.4 Cautions regarding runtime finalization
In the late stage of interpreter shutdown, after attempting to wait for non-daemon threads to exit (though this can
be interrupted by KeyboardInterrupt) and running the atexit functions, the runtime is marked as finalizing:
Py_IsFinalizing() and sys.is_finalizing() return true. At this point, only the finalization thread that
initiated finalization (typically the main thread) is allowed to acquire the GIL.
If any thread, other than the finalization thread, attempts to acquire the GIL during finalization,
either explicitly via PyGILState_Ensure(), Py_END_ALLOW_THREADS, PyEval_AcquireThread(), or
PyEval_AcquireLock(), or implicitly when the interpreter attempts to reacquire it after having yielded it, the
thread enters a permanently blocked state where it remains until the program exits. In most cases this is harmless,
but this can result in deadlock if a later stage of finalization attempts to acquire a lock owned by the blocked thread,
or otherwise waits on the blocked thread.
Gross? Yes. This prevents random crashes and/or unexpectedly skipped C++ finalizations further up the call stack
when such threads were forcibly exited here in CPython 3.13.7 and earlier. The CPython runtime GIL acquiring C
APIs have never had any error reporting or handling expectations at GIL acquisition time that would’ve allowed for
graceful exit from this situation. Changing that would require new stable C APIs and rewriting the majority of C
code in the CPython ecosystem to use those with error handling.
9.5.5 High-level API
Estes sã o os tipos e as funçõ es mais comumente usados na escrita de um có digo de extensã o em C, ou ao incorporar
o interpretador Python:
type PyInterpreterState
Parte da API Limitada (como uma estrutura opaca). This data structure represents the state shared by a number
9.5. Estado de thread e a trava global do interpretador 225
The Python/C API, Release 3.13.7
of cooperating threads. Threads belonging to the same interpreter share their module administration and a few
other internal items. There are no public members in this structure.
Threads belonging to different interpreters initially share nothing, except process state like available memory,
open file descriptors and such. The global interpreter lock is also shared by all threads, regardless of to which
interpreter they belong.
type PyThreadState
Parte da API Limitada (como uma estrutura opaca). This data structure represents the state of a single thread.
The only public data member is:
PyInterpreterState *interp
This thread’s interpreter state.
void PyEval_InitThreads()
Parte da ABI Está vel. Funçã o descontinuada que nã o faz nada.
In Python 3.6 and older, this function created the GIL if it didn’t exist.
Alterado na versã o 3.9: The function now does nothing.
Alterado na versã o 3.7: Esta funçã o agora é chamada por Py_Initialize(), entã o nã o há mais necessidade
de você chamá -la.
Alterado na versã o 3.2: Esta funçã o nã o pode mais ser chamada antes de Py_Initialize().
Descontinuado desde a versã o 3.9.
PyThreadState *PyEval_SaveThread()
Parte da ABI Está vel. Release the global interpreter lock (if it has been created) and reset the thread state to
NULL, returning the previous thread state (which is not NULL). If the lock has been created, the current thread
must have acquired it.
void PyEval_RestoreThread(PyThreadState *tstate)
Parte da ABI Está vel. Acquire the global interpreter lock (if it has been created) and set the thread state to
tstate, which must not be NULL. If the lock has been created, the current thread must not have acquired it,
otherwise deadlock ensues.
® Nota
Calling this function from a thread when the runtime is finalizing will hang the thread until the program
exits, even if the thread was not created by Python. Refer to Cautions regarding runtime finalization for
more details.
Alterado na versã o 3.13.7 (unreleased): Hangs the current thread, rather than terminating it, if called while
the interpreter is finalizing.
PyThreadState *PyThreadState_Get()
Parte da ABI Está vel. Return the current thread state. The global interpreter lock must be held. When the
current thread state is NULL, this issues a fatal error (so that the caller needn’t check for 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.
Adicionado na versã o 3.13: In Python 3.5 to 3.12, the function was private and known as
_PyThreadState_UncheckedGet().
PyThreadState *PyThreadState_Swap(PyThreadState *tstate)
Parte da ABI Está vel. Swap the current thread state with the thread state given by the argument tstate, which
may be NULL.
226 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
The GIL does not need to be held, but will be held upon returning if tstate is non-NULL.
The following functions use thread-local storage, and are not compatible with sub-interpreters:
PyGILState_STATE PyGILState_Ensure()
Parte da ABI Está vel. Certifique-se de que a thread atual esteja pronta para chamar a API Python C, in-
dependentemente do estado atual do Python ou da trava global do interpretador (GIL). Isso pode ser cha-
mado quantas vezes desejar por uma thread, desde que cada chamada corresponda a uma chamada para
PyGILState_Release(). Em geral, outras APIs relacionadas a threads podem ser usadas entre chama-
das PyGILState_Ensure() e PyGILState_Release() desde que o estado da thread seja restaurado ao
seu estado anterior antes de Release(). Por exemplo, o uso normal das macros Py_BEGIN_ALLOW_THREADS
e Py_END_ALLOW_THREADS é aceitá vel.
The return value is an opaque “handle” to the thread state when PyGILState_Ensure() was called, and
must be passed to PyGILState_Release() to ensure Python is left in the same state. Even though recursive
calls are allowed, these handles cannot be shared - each unique call to PyGILState_Ensure() must save the
handle for its call to PyGILState_Release().
When the function returns, the current thread will hold the GIL and be able to call arbitrary Python code.
Failure is a fatal error.
® Nota
Calling this function from a thread when the runtime is finalizing will hang the thread until the program
exits, even if the thread was not created by Python. Refer to Cautions regarding runtime finalization for
more details.
Alterado na versã o 3.13.7 (unreleased): Hangs the current thread, rather than terminating it, if called while
the interpreter is finalizing.
void PyGILState_Release(PyGILState_STATE)
Parte da ABI Está vel. Release any resources previously acquired. After this call, Python’s state will be the same
as it was prior to the corresponding PyGILState_Ensure() call (but generally this state will be unknown to
the caller, hence the use of the GILState API).
Every call to PyGILState_Ensure() must be matched by a call to PyGILState_Release() on the same
thread.
PyThreadState *PyGILState_GetThisThreadState()
Parte da ABI Está vel. Get the current thread state for this thread. May return NULL if no GILState API
has been used on the current thread. Note that the main thread always has such a thread-state, even if no
auto-thread-state call has been made on the main thread. This is mainly a helper/diagnostic function.
int PyGILState_Check()
Return 1 if the current thread is holding the GIL and 0 otherwise. This function can be called from any thread
at any time. Only if it has had its Python thread state initialized and currently is holding the GIL will it return
1. This is mainly a helper/diagnostic function. It can be useful for example in callback contexts or memory
allocation functions when knowing that the GIL is locked can allow the caller to perform sensitive actions or
otherwise behave differently.
Adicionado na versã o 3.4.
The following macros are normally used without a trailing semicolon; look for example usage in the Python source
distribution.
Py_BEGIN_ALLOW_THREADS
Parte da ABI Está vel. Esta macro se expande para { PyThreadState *_save; _save =
PyEval_SaveThread();. Observe que ele conté m uma chave de abertura; ele deve ser combinado com
a seguinte macro Py_END_ALLOW_THREADS. Veja acima para uma discussã o mais aprofundada desta macro.
9.5. Estado de thread e a trava global do interpretador 227
The Python/C API, Release 3.13.7
Py_END_ALLOW_THREADS
Parte da ABI Está vel. Esta macro se expande para PyEval_RestoreThread(_save); }. Observe que
ele conté m uma chave de fechamento; ele deve ser combinado com uma macro Py_BEGIN_ALLOW_THREADS
anterior. Veja acima para uma discussã o mais aprofundada desta macro.
Py_BLOCK_THREADS
Parte da ABI Está vel. Esta macro se expande para PyEval_RestoreThread(_save);: é equivalente a
Py_END_ALLOW_THREADS sem a chave de fechamento.
Py_UNBLOCK_THREADS
Parte da ABI Está vel. Esta macro se expande para _save = PyEval_SaveThread();: é equivalente a
Py_BEGIN_ALLOW_THREADS sem a chave de abertura e declaraçã o de variá vel.
9.5.6 Low-level API
All of the following functions must be called after Py_Initialize().
Alterado na versã o 3.7: Py_Initialize() now initializes the GIL.
PyInterpreterState *PyInterpreterState_New()
Parte da ABI Está vel. Create a new interpreter state object. The global interpreter lock need not be held, but
may be held if it is necessary to serialize calls to this function.
Levanta um evento de auditoria cpython.PyInterpreterState_New sem argumentos.
void PyInterpreterState_Clear(PyInterpreterState *interp)
Parte da ABI Está vel. Reset all information in an interpreter state object. The global interpreter lock must be
held.
Levanta um evento de auditoria cpython.PyInterpreterState_Clear sem argumentos.
void PyInterpreterState_Delete(PyInterpreterState *interp)
Parte da ABI Está vel. Destroy an interpreter state object. The global interpreter lock need not be held. The
interpreter state must have been reset with a previous call to PyInterpreterState_Clear().
PyThreadState *PyThreadState_New(PyInterpreterState *interp)
Parte da ABI Está vel. Create a new thread state object belonging to the given interpreter object. The global
interpreter lock need not be held, but may be held if it is necessary to serialize calls to this function.
void PyThreadState_Clear(PyThreadState *tstate)
Parte da ABI Está vel. Reset all information in a thread state object. The global interpreter lock must be held.
Alterado na versã o 3.9: This function now calls the PyThreadState.on_delete callback. Previously, that
happened in PyThreadState_Delete().
Alterado na versã o 3.13: The PyThreadState.on_delete callback was removed.
void PyThreadState_Delete(PyThreadState *tstate)
Parte da ABI Está vel. Destroy a thread state object. The global interpreter lock need not be held. The thread
state must have been reset with a previous call to PyThreadState_Clear().
void PyThreadState_DeleteCurrent(void)
Destroy the current thread state and release the global interpreter lock. Like PyThreadState_Delete(),
the global interpreter lock must be held. The thread state must have been reset with a previous call to
PyThreadState_Clear().
PyFrameObject *PyThreadState_GetFrame(PyThreadState *tstate)
Parte da ABI Está vel desde a versão 3.10. Get the current frame of the Python thread state tstate.
Return a strong reference. Return NULL if no frame is currently executing.
See also PyEval_GetFrame().
tstate must not be NULL.
Adicionado na versã o 3.9.
228 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
uint64_t PyThreadState_GetID(PyThreadState *tstate)
Parte da ABI Está vel desde a versão 3.10. Get the unique thread state identifier of the Python thread state
tstate.
tstate must not be NULL.
Adicionado na versã o 3.9.
PyInterpreterState *PyThreadState_GetInterpreter(PyThreadState *tstate)
Parte da ABI Está vel desde a versão 3.10. Get the interpreter of the Python thread state tstate.
tstate must not be NULL.
Adicionado na versã o 3.9.
void PyThreadState_EnterTracing(PyThreadState *tstate)
Suspend tracing and profiling in the Python thread state tstate.
Resume them using the PyThreadState_LeaveTracing() function.
Adicionado na versã o 3.11.
void PyThreadState_LeaveTracing(PyThreadState *tstate)
Resume tracing and profiling in the Python thread state tstate suspended by the
PyThreadState_EnterTracing() function.
See also PyEval_SetTrace() and PyEval_SetProfile() functions.
Adicionado na versã o 3.11.
PyInterpreterState *PyInterpreterState_Get(void)
Parte da ABI Está vel desde a versão 3.9. Get the current interpreter.
Issue a fatal error if there no current Python thread state or no current interpreter. It cannot return NULL.
The caller must hold the GIL.
Adicionado na versã o 3.9.
int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
Parte da ABI Está vel desde a versão 3.7. Return the interpreter’s unique ID. If there was any error in doing so
then -1 is returned and an error is set.
The caller must hold the GIL.
Adicionado na versã o 3.7.
PyObject *PyInterpreterState_GetDict(PyInterpreterState *interp)
Parte da ABI Está vel desde a versão 3.8. Return a dictionary in which interpreter-specific data may be stored.
If this function returns NULL then no exception has been raised and the caller should assume no interpreter-
-specific dict is available.
This is not a replacement for PyModule_GetState(), which extensions should use to store interpreter-
-specific state information.
Adicionado na versã o 3.8.
PyObject *PyUnstable_InterpreterState_GetMainModule(PyInterpreterState *interp)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Return a strong reference to the __main__ module object for the given interpreter.
The caller must hold the GIL.
Adicionado na versã o 3.13.
9.5. Estado de thread e a trava global do interpretador 229
The Python/C API, Release 3.13.7
typedef PyObject *(*_PyFrameEvalFunction)(PyThreadState *tstate, _PyInterpreterFrame *frame, int
throwflag)
Type of a frame evaluation function.
The throwflag parameter is used by the throw() method of generators: if non-zero, handle the current ex-
ception.
Alterado na versã o 3.9: The function now takes a tstate parameter.
Alterado na versã o 3.11: The frame parameter changed from PyFrameObject* to
_PyInterpreterFrame*.
_PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
Get the frame evaluation function.
See the PEP 523 “Adding a frame evaluation API to CPython”.
Adicionado na versã o 3.9.
void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunction
eval_frame)
Set the frame evaluation function.
See the PEP 523 “Adding a frame evaluation API to CPython”.
Adicionado na versã o 3.9.
PyObject *PyThreadState_GetDict()
Retorna valor: Referência emprestada. Parte da ABI Está vel. Return a dictionary in which extensions can
store thread-specific state information. Each extension should use a unique key to use to store state in the
dictionary. It is okay to call this function when no current thread state is available. If this function returns
NULL, no exception has been raised and the caller should assume no current thread state is available.
int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
Parte da ABI Está vel. 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.
Alterado na versã o 3.7: The type of the id parameter changed from long to unsigned long.
void PyEval_AcquireThread(PyThreadState *tstate)
Parte da ABI Está vel. Acquire the global interpreter lock and set the current thread state to tstate, which must
not be NULL. The lock must have been created earlier. If this thread already has the lock, deadlock ensues.
® Nota
Calling this function from a thread when the runtime is finalizing will hang the thread until the program
exits, even if the thread was not created by Python. Refer to Cautions regarding runtime finalization for
more details.
Alterado na versã o 3.8: Updated to be consistent with PyEval_RestoreThread(),
Py_END_ALLOW_THREADS(), and PyGILState_Ensure(), and terminate the current thread if cal-
led while the interpreter is finalizing.
Alterado na versã o 3.13.7 (unreleased): Hangs the current thread, rather than terminating it, if called while
the interpreter is finalizing.
PyEval_RestoreThread() is a higher-level function which is always available (even when threads have not
been initialized).
230 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
void PyEval_ReleaseThread(PyThreadState *tstate)
Parte da ABI Está vel. Reset the current thread state to NULL and release the global interpreter lock. The lock
must have been created earlier and must be held by the current thread. The tstate argument, which must not
be NULL, is only used to check that it represents the current thread state — if it isn’t, a fatal error is reported.
PyEval_SaveThread() is a higher-level function which is always available (even when threads have not
been initialized).
9.6 Sub-interpreter support
While in most uses, you will only embed a single Python interpreter, there are cases where you need to create several
independent interpreters in the same process and perhaps even in the same thread. Sub-interpreters allow you to do
that.
The “main” interpreter is the first one created when the runtime initializes. It is usually the only Python interpreter in a
process. Unlike sub-interpreters, the main interpreter has unique process-global responsibilities like signal handling.
It is also responsible for execution during runtime initialization and is usually the active interpreter during runtime
finalization. The PyInterpreterState_Main() function returns a pointer to its state.
You can switch between sub-interpreters using the PyThreadState_Swap() function. You can create and destroy
them using the following functions:
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.
Adicionado na versã o 3.12.
Campos de estrutura:
int use_main_obmalloc
If this is 0 then the sub-interpreter will use its own “object” allocator state. Otherwise it will use (share)
the main interpreter’s.
If this is 0 then check_multi_interp_extensions must be 1 (non-zero). If this is 1 then gil must
not be PyInterpreterConfig_OWN_GIL.
int allow_fork
If this is 0 then the runtime will not support forking the process in any thread where the sub-interpreter
is currently active. Otherwise fork is unrestricted.
Note that the subprocess module still works when fork is disallowed.
int allow_exec
If this is 0 then the runtime will not support replacing the current process via exec (e.g. os.execv())
in any thread where the sub-interpreter is currently active. Otherwise exec is unrestricted.
Note that the subprocess module still works when exec is disallowed.
int allow_threads
If this is 0 then the sub-interpreter’s threading module won’t create threads. Otherwise threads are
allowed.
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.
9.6. Sub-interpreter support 231
The Python/C API, Release 3.13.7
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)
Create a new sub-interpreter. This is an (almost) totally separate environment for the execution of Python
code. In particular, the new interpreter has separate, independent versions of all imported modules, including
the fundamental modules builtins, __main__ and sys. The table of loaded modules (sys.modules) and
the module search path (sys.path) are also separate. The new environment has no sys.argv variable. It
has new standard I/O stream file objects sys.stdin, sys.stdout and sys.stderr (however these refer
to the same underlying file descriptors).
The given config controls the options with which the interpreter is initialized.
Upon success, tstate_p will be set to the first thread state created in the new sub-interpreter. This thread state
is made in the current thread state. Note that no actual thread is created; see the discussion of thread states
below. If creation of the new interpreter is unsuccessful, tstate_p is set to NULL; no exception is set since the
exception state is stored in the current thread state and there may not be a current thread state.
Like all other Python/C API functions, the global interpreter lock must be held before calling this function
and is still held when it returns. Likewise a current thread state must be set on entry. On success, the returned
thread state will be set as current. If the sub-interpreter is created with its own GIL then the GIL of the calling
interpreter will be released. When the function returns, the new interpreter’s GIL will be held by the current
thread and the previously interpreter’s GIL will remain released here.
Adicionado na versã o 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 = NULL;
PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
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.
Extension modules are shared between (sub-)interpreters as follows:
232 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
• For modules using multi-phase initialization, e.g. PyModule_FromDefAndSpec(), a separate module
object is created and initialized for each interpreter. Only C-level static and global variables are shared
between these module objects.
• For modules using single-phase initialization, e.g. PyModule_Create(), the first time a particular ex-
tension is imported, it is initialized normally, and a (shallow) copy of its module’s dictionary is squirreled
away. When the same extension is imported by another (sub-)interpreter, a new module is initialized and
filled with the contents of this copy; the extension’s init function is not called. Objects in the module’s
dictionary thus end up shared across (sub-)interpreters, which might cause unwanted behavior (see Bugs
and caveats below).
Note that this is different from what happens when an extension is imported after the interpreter has
been completely re-initialized by calling Py_FinalizeEx() and Py_Initialize(); in that case, the
extension’s initmodule function is called again. As with multi-phase initialization, this means that only
C-level static and global variables are shared between these modules.
PyThreadState *Py_NewInterpreter(void)
Parte da ABI Está vel. 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)
Parte da ABI Está vel. Destroy the (sub-)interpreter represented by the given thread state. The given thread state
must be the current thread state. See the discussion of thread states below. When the call returns, the current
thread state is NULL. All thread states associated with this interpreter are destroyed. The global interpreter
lock used by the target interpreter must be held before calling this function. No GIL is held when it returns.
Py_FinalizeEx() will destroy all sub-interpreters that haven’t been explicitly destroyed at that point.
9.6.1 A Per-Interpreter GIL
Using Py_NewInterpreterFromConfig() you can create a sub-interpreter that is completely isolated from other
interpreters, including having its own GIL. The most important benefit of this isolation is that such an interpreter
can execute Python code without being blocked by other interpreters or blocking any others. Thus a single Python
process can truly take advantage of multiple CPU cores when running Python code. The isolation also encourages a
different approach to concurrency than that of just using threads. (See PEP 554.)
Using an isolated interpreter requires vigilance in preserving that isolation. That especially means not sharing any
objects or mutable state without guarantees about thread-safety. Even objects that are otherwise immutable (e.g.
None, (1, 5)) can’t normally be shared because of the refcount. One simple but less-efficient approach around
this is to use a global lock around all use of some state (or object). Alternately, effectively immutable objects (like
integers or strings) can be made safe in spite of their refcounts by making them immortal. In fact, this has been done
for the builtin singletons, small integers, and a number of other builtin objects.
Se você preservar o isolamento, terá acesso à computaçã o multi-core adequada, sem as complicaçõ es que acompa-
nham o uso de threads livres. A falha em preservar o isolamento traz a exposiçã o a todas as consequê ncias de threads
livres, incluindo corridas e travamentos difíceis de depurar.
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.
Adicionado na versã o 3.12.
9.6.2 Bugs and caveats
Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isn’t
perfect — for example, using low-level file operations like os.close() they can (accidentally or maliciously) affect
each other’s open files. Because of the way extensions are shared between (sub-)interpreters, some extensions may not
work properly; this is especially likely when using single-phase initialization or (static) global variables. It is possible
9.6. Sub-interpreter support 233
The Python/C API, Release 3.13.7
to insert objects created in one sub-interpreter into a namespace of another (sub-)interpreter; this should be avoided
if possible.
Special care should be taken to avoid sharing user-defined functions, methods, instances or classes between sub-
-interpreters, since import operations executed by such objects may affect the wrong (sub-)interpreter’s dictionary of
loaded modules. It is equally important to avoid sharing objects from which the above are reachable.
Also note that combining this functionality with PyGILState_* APIs is delicate, because these APIs assume a bi-
jection between Python thread states and OS-level threads, an assumption broken by the presence of sub-interpreters.
It is highly recommended that you don’t switch sub-interpreters between a pair of matching PyGILState_Ensure()
and PyGILState_Release() calls. Furthermore, extensions (such as ctypes) using these APIs to allow calling
of Python code from non-Python created threads will probably be broken when using sub-interpreters.
9.7 Notificações assíncronas
A mechanism is provided to make asynchronous notifications to the main interpreter thread. These notifications take
the form of a function pointer and a void pointer argument.
int Py_AddPendingCall(int (*func)(void*), void *arg)
Parte da ABI Está vel. Schedule a function to be called from the main interpreter thread. On success, 0 is
returned and func is queued for being called in the main thread. On failure, -1 is returned without setting any
exception.
When successfully queued, func will be eventually called from the main interpreter thread with the argument
arg. It will be called asynchronously with respect to normally running Python code, but with both these con-
ditions met:
• on a bytecode boundary;
• with the main thread holding the global interpreter lock (func can therefore use the full C API).
func must return 0 on success, or -1 on failure with an exception set. func won’t be interrupted to perform
another asynchronous notification recursively, but it can still be interrupted to switch threads if the global
interpreter lock is released.
This function doesn’t need a current thread state to run, and it doesn’t need the global interpreter lock.
To call this function in a subinterpreter, the caller must hold the GIL. Otherwise, the function func can be
scheduled to be called from the wrong interpreter.
Á Aviso
This is a low-level function, only useful for very special cases. There is no guarantee that func will be
called as quick as possible. If the main thread is busy executing a system call, func won’t be called before
the system call returns. This function is generally not suitable for calling Python code from arbitrary C
threads. Instead, use the PyGILState API.
Adicionado na versã o 3.1.
Alterado na versã o 3.9: If this function is called in a subinterpreter, the function func is now scheduled to be
called from the subinterpreter, rather than being called from the main interpreter. Each subinterpreter now has
its own list of scheduled calls.
9.8 Profiling and Tracing
The Python interpreter provides some low-level support for attaching profiling and execution tracing facilities. These
are used for profiling, debugging, and coverage analysis tools.
This C interface allows the profiling or tracing code to avoid the overhead of calling through Python-level callable
objects, making a direct C function call instead. The essential attributes of the facility have not changed; the interface
234 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
allows trace functions to be installed per-thread, and the basic events reported to the trace function are the same as
had been reported to the Python-level trace functions in previous versions.
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 ob-
ject 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:
Value of what Meaning of arg
PyTrace_CALL Always Py_None.
PyTrace_EXCEPTION Exception information as returned by sys.exc_info().
PyTrace_LINE Always Py_None.
PyTrace_RETURN Value being returned to the caller, or NULL if caused by an exception.
PyTrace_C_CALL Function object being called.
PyTrace_C_EXCEPTION Function object being called.
PyTrace_C_RETURN Function object being called.
PyTrace_OPCODE Always Py_None.
int PyTrace_CALL
The value of the what parameter to a Py_tracefunc function when a new call to a function or method is
being reported, or a new entry into a generator. Note that the creation of the iterator for a generator function
is not reported as there is no control transfer to the Python bytecode in the corresponding frame.
int PyTrace_EXCEPTION
The value of the what parameter to a Py_tracefunc function when an exception has been raised. The
callback function is called with this value for what when after any bytecode is processed after which the
exception becomes set within the frame being executed. The effect of this is that as exception propagation
causes the Python stack to unwind, the callback is called upon return to each frame as the exception propagates.
Only trace functions receives these events; they are not needed by the profiler.
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
The value for the what parameter to Py_tracefunc functions when a call is about to return.
int PyTrace_C_CALL
The value for the what parameter to Py_tracefunc functions when a C function is about to be called.
int PyTrace_C_EXCEPTION
The value for the what parameter to Py_tracefunc functions when a C function has raised an exception.
int PyTrace_C_RETURN
The value for the what parameter to Py_tracefunc functions when a C function has returned.
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 .
9.8. Profiling and Tracing 235
The Python/C API, Release 3.13.7
See also the sys.setprofile() function.
The caller must hold the GIL.
void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)
Like PyEval_SetProfile() but sets the profile function in all running threads belonging to the current
interpreter instead of the setting it only on the current thread.
The caller must hold the GIL.
As PyEval_SetProfile(), this function ignores any exceptions raised while setting the profile functions in
all threads.
Adicionado na versã o 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.
See also the sys.settrace() function.
The caller must hold the 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.
The caller must hold the GIL.
As PyEval_SetTrace(), this function ignores any exceptions raised while setting the trace functions in all
threads.
Adicionado na versã o 3.12.
9.9 Reference tracing
Adicionado na versã o 3.13.
typedef int (*PyRefTracer)(PyObject*, int event, void *data)
The type of the trace function registered using PyRefTracer_SetTracer(). The first parameter is a Python
object that has been just created (when event is set to PyRefTracer_CREATE) or about to be destroyed (when
event is set to PyRefTracer_DESTROY ). The data argument is the opaque pointer that was provided when
PyRefTracer_SetTracer() was called.
Adicionado na versã o 3.13.
int PyRefTracer_CREATE
The value for the event parameter to PyRefTracer functions when a Python object has been created.
int PyRefTracer_DESTROY
The value for the event parameter to PyRefTracer functions when a Python object has been destroyed.
int PyRefTracer_SetTracer(PyRefTracer tracer, void *data)
Register a reference tracer function. The function will be called when a new Python has been created or when
an object is going to be destroyed. If data is provided it must be an opaque pointer that will be provided when
the tracer function is called. Return 0 on success. Set an exception and return -1 on error.
Not that tracer functions must not create Python objects inside or otherwise the call will be re-entrant. The
tracer also must not clear any existing exception or set an exception. The GIL will be held every time the
tracer function is called.
The GIL must be held when calling this function.
Adicionado na versã o 3.13.
236 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
PyRefTracer PyRefTracer_GetTracer(void **data)
Get the registered reference tracer function and the value of the opaque data pointer that was registered when
PyRefTracer_SetTracer() was called. If no tracer was registered this function will return NULL and will
set the data pointer to NULL.
The GIL must be held when calling this function.
Adicionado na versã o 3.13.
9.10 Advanced Debugger Support
These functions are only intended to be used by advanced debugging tools.
PyInterpreterState *PyInterpreterState_Head()
Return the interpreter state object at the head of the list of all such objects.
PyInterpreterState *PyInterpreterState_Main()
Return the main interpreter state object.
PyInterpreterState *PyInterpreterState_Next(PyInterpreterState *interp)
Return the next interpreter state object after interp from the list of all such objects.
PyThreadState *PyInterpreterState_ThreadHead(PyInterpreterState *interp)
Return the pointer to the first PyThreadState object in the list of threads associated with the interpreter
interp.
PyThreadState *PyThreadState_Next(PyThreadState *tstate)
Return the next thread state object after tstate from the list of all such objects belonging to the same
PyInterpreterState object.
9.11 Thread Local Storage Support
The Python interpreter provides low-level support for thread-local storage (TLS) which wraps the underlying native
TLS implementation to support the Python-level thread local storage API (threading.local). The CPython C
level APIs are similar to those offered by pthreads and Windows: use a thread key and functions to associate a void*
value per thread.
The GIL does not need to be held when calling these functions; they supply their own locking.
Note that Python.h does not include the declaration of the TLS APIs, you need to include pythread.h to use
thread-local storage.
® Nota
None of these API functions handle memory management on behalf of the void* values. You need to allocate
and deallocate them yourself. If the void* values happen to be PyObject*, these functions don’t do refcount
operations on them either.
9.11.1 Thread Specific Storage (TSS) API
TSS API is introduced to supersede the use of the existing TLS API within the CPython interpreter. This API uses
a new type Py_tss_t instead of int to represent thread keys.
Adicionado na versã o 3.7.
µ Ver também
“A New C-API for Thread-Local Storage in CPython” (PEP 539)
9.10. Advanced Debugger Support 237
The Python/C API, Release 3.13.7
type Py_tss_t
This data structure represents the state of a thread key, the definition of which may depend on the underlying
TLS implementation, and it has an internal field representing the key’s initialization state. There are no public
members in this structure.
Quando Py_LIMITED_API nã o é definido, a alocaçã o está tica deste tipo por Py_tss_NEEDS_INIT é permi-
tida.
Py_tss_NEEDS_INIT
This macro expands to the initializer for Py_tss_t variables. Note that this macro won’t be defined with
Py_LIMITED_API.
Alocação dinâmica
Dynamic allocation of the Py_tss_t, required in extension modules built with Py_LIMITED_API, where static
allocation of this type is not possible due to its implementation being opaque at build time.
Py_tss_t *PyThread_tss_alloc()
Parte da ABI Está vel desde a versão 3.7. Retorna um valor que é o mesmo estado de um valor inicializado
com Py_tss_NEEDS_INIT , ou NULL no caso de falha de alocaçã o dinâ mica.
void PyThread_tss_free(Py_tss_t *key)
Parte da ABI Está vel desde a versão 3.7. Free the given key allocated by PyThread_tss_alloc(), after
first calling PyThread_tss_delete() to ensure any associated thread locals have been unassigned. This is
a no-op if the key argument is NULL.
® Nota
A freed key becomes a dangling pointer. You should reset the key to NULL.
Métodos
The parameter key of these functions must not be NULL. Moreover, the behaviors of PyThread_tss_set()
and PyThread_tss_get() are undefined if the given Py_tss_t has not been initialized by
PyThread_tss_create().
int PyThread_tss_is_created(Py_tss_t *key)
Parte da ABI Está vel desde a versão 3.7. Return a non-zero value if the given Py_tss_t has been initialized
by PyThread_tss_create().
int PyThread_tss_create(Py_tss_t *key)
Parte da ABI Está vel desde a versão 3.7. Retorna um valor zero na inicializaçã o bem-sucedida de uma
chave TSS. O comportamento é indefinido se o valor apontado pelo argumento key nã o for inicializado por
Py_tss_NEEDS_INIT . Essa funçã o pode ser chamada repetidamente na mesma tecla – chamá -la em uma
tecla já inicializada nã o funciona e retorna imediatamente com sucesso.
void PyThread_tss_delete(Py_tss_t *key)
Parte da ABI Está vel desde a versão 3.7. Destroy a TSS key to forget the values associated with the key across
all threads, and change the key’s initialization state to uninitialized. A destroyed key is able to be initialized
again by PyThread_tss_create(). This function can be called repeatedly on the same key – calling it on
an already destroyed key is a no-op.
int PyThread_tss_set(Py_tss_t *key, void *value)
Parte da ABI Está vel desde a versão 3.7. Return a zero value to indicate successfully associating a void*
value with a TSS key in the current thread. Each thread has a distinct mapping of the key to a void* value.
void *PyThread_tss_get(Py_tss_t *key)
Parte da ABI Está vel desde a versão 3.7. Return the void* value associated with a TSS key in the current
thread. This returns NULL if no value is associated with the key in the current thread.
238 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
9.11.2 Thread Local Storage (TLS) API
Descontinuado desde a versã o 3.7: This API is superseded by Thread Specific Storage (TSS) API.
® Nota
This version of the API does not support platforms where the native TLS key is defined in a way that cannot be
safely cast to int. On such platforms, PyThread_create_key() will return immediately with a failure status,
and the other TLS functions will all be no-ops on such platforms.
Due to the compatibility problem noted above, this version of the API should not be used in new code.
int PyThread_create_key()
Parte da ABI Está vel.
void PyThread_delete_key(int key)
Parte da ABI Está vel.
int PyThread_set_key_value(int key, void *value)
Parte da ABI Está vel.
void *PyThread_get_key_value(int key)
Parte da ABI Está vel.
void PyThread_delete_key_value(int key)
Parte da ABI Está vel.
void PyThread_ReInitTLS()
Parte da ABI Está vel.
9.12 Synchronization Primitives
The C-API provides a basic mutual exclusion lock.
type PyMutex
A mutual exclusion lock. The PyMutex should be initialized to zero to represent the unlocked state. For
example:
PyMutex mutex = {0};
Instances of PyMutex should not be copied or moved. Both the contents and address of a PyMutex are
meaningful, and it must remain at a fixed, writable location in memory.
® Nota
A PyMutex currently occupies one byte, but the size should be considered unstable. The size may change
in future Python releases without a deprecation period.
Adicionado na versã o 3.13.
void PyMutex_Lock(PyMutex *m)
Lock mutex m. If another thread has already locked it, the calling thread will block until the mutex is unlocked.
While blocked, the thread will temporarily release the GIL if it is held.
Adicionado na versã o 3.13.
void PyMutex_Unlock(PyMutex *m)
Unlock mutex m. The mutex must be locked — otherwise, the function will issue a fatal error.
Adicionado na versã o 3.13.
9.12. Synchronization Primitives 239
The Python/C API, Release 3.13.7
9.12.1 Python Critical Section API
The critical section API provides a deadlock avoidance layer on top of per-object locks for free-threaded CPython.
They are intended to replace reliance on the global interpreter lock, and are no-ops in versions of Python with the
global interpreter lock.
Critical sections are intended to be used for custom types implemented in C-API extensions. They should generally
not be used with built-in types like list and dict because their public C-APIs already use critical sections internally,
with the notable exception of PyDict_Next(), which requires critical section to be acquired externally.
Critical sections avoid deadlocks by implicitly suspending active critical sections, hence, they do not provide exclusive
access such as provided by traditional locks like PyMutex. When a critical section is started, the per-object lock for
the object is acquired. If the code executed inside the critical section calls C-API functions then it can suspend the
critical section thereby releasing the per-object lock, so other threads can acquire the per-object lock for the same
object.
The functions and structs used by the macros are exposed for cases where C macros are not available. They should
only be used as in the given macro expansions. Note that the sizes and contents of the structures may change in future
Python versions.
® Nota
Operations that need to lock two objects at once must use Py_BEGIN_CRITICAL_SECTION2. You cannot use
nested critical sections to lock more than one object at once, because the inner critical section may suspend the
outer critical sections. This API does not provide a way to lock more than two objects at once.
Exemplo de uso:
static PyObject *
set_field(MyObject *self, PyObject *value)
{
Py_BEGIN_CRITICAL_SECTION(self);
Py_SETREF(self->field, Py_XNewRef(value));
Py_END_CRITICAL_SECTION();
Py_RETURN_NONE;
}
In the above example, Py_SETREF calls Py_DECREF , which can call arbitrary code through an object’s deallo-
cation function. The critical section API avoids potential deadlocks due to reentrancy and lock ordering by al-
lowing the runtime to temporarily suspend the critical section if the code triggered by the finalizer blocks and calls
PyEval_SaveThread().
Py_BEGIN_CRITICAL_SECTION(op)
Acquires the per-object lock for the object op and begins a critical section.
In the free-threaded build, this macro expands to:
{
PyCriticalSection _py_cs;
PyCriticalSection_Begin(&_py_cs, (PyObject*)(op))
In the default build, this macro expands to {.
Adicionado na versã o 3.13.
Py_END_CRITICAL_SECTION()
Ends the critical section and releases the per-object lock.
In the free-threaded build, this macro expands to:
240 Capítulo 9. Inicialização, finalização e threads
The Python/C API, Release 3.13.7
PyCriticalSection_End(&_py_cs);
}
In the default build, this macro expands to }.
Adicionado na versã o 3.13.
Py_BEGIN_CRITICAL_SECTION2(a, b)
Acquires the per-objects locks for the objects a and b and begins a critical section. The locks are acquired in
a consistent order (lowest address first) to avoid lock ordering deadlocks.
In the free-threaded build, this macro expands to:
{
PyCriticalSection2 _py_cs2;
PyCriticalSection2_Begin(&_py_cs2, (PyObject*)(a), (PyObject*)(b))
In the default build, this macro expands to {.
Adicionado na versã o 3.13.
Py_END_CRITICAL_SECTION2()
Ends the critical section and releases the per-object locks.
In the free-threaded build, this macro expands to:
PyCriticalSection2_End(&_py_cs2);
}
In the default build, this macro expands to }.
Adicionado na versã o 3.13.
9.12. Synchronization Primitives 241
The Python/C API, Release 3.13.7
242 Capítulo 9. Inicialização, finalização e threads
CAPÍTULO 10
Configuração de Inicialização do Python
Adicionado na versã o 3.8.
Python pode ser inicializado com Py_InitializeFromConfig() e a estrutura PyConfig . Pode ser pré -
-inicializado com Py_PreInitialize() e a estrutura PyPreConfig .
Existem dois tipos de configuraçã o:
• A Python Configuration pode ser usada para construir um Python personalizado que se comporta como um
Python comum. Por exemplo, variá veis de ambiente e argumento de linha de comando sã o usados para con-
figurar Python.
• A Configuração isolada pode ser usada para incorporar Python em uma aplicaçã o. Isso isola Python de um
sistema. Por exemplo, variá veis de ambiente sã o ignoradas, a variá vel local LC_CTYPE fica inalterada e
nenhum manipulador de sinal é registrado.
A funçã o Py_RunMain() pode ser usada para escrever um programa Python personalizado.
Veja també m Inicialização, Finalização e Threads.
µ Ver também
PEP 587 “Configuraçã o da inicializaçã o do Python”.
10.1 Exemplo
Exemplo de Python personalizado sendo executado sempre em um modo isolado:
int main(int argc, char **argv)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;
/* Decode command line arguments.
Implicitly preinitialize Python (in isolated mode). */
(continua na pró xima pá gina)
243
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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 strings wchar_t*.
Se length é diferente de zero, items deve ser diferente de NULL e todas as strings devem ser diferentes de NULL.
Mé todos:
PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)
Anexa item a list.
Python deve ser inicializado previamente antes de chamar essa funçã o.
PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)
Insere item na list na posiçã o index.
Se index for maior ou igual ao comprimento da list, anexa o item a list.
index deve ser maior que ou igual a 0.
Python deve ser inicializado previamente antes de chamar essa funçã o.
Campos de estrutura:
Py_ssize_t length
Comprimento da lista.
wchar_t **items
Itens da lista.
10.3 PyStatus
244 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
type PyStatus
Estrutura para armazenar o status de uma funçã o de inicializaçã o: sucesso, erro ou saída.
Para um erro, ela pode armazenar o nome da funçã o C que criou o erro.
Campos de estrutura:
int exitcode
Có digo de saída. Argumento passado para exit().
const char *err_msg
Mensagem de erro.
const char *func
Nome da funçã o que criou um erro. Pode ser NULL.
Funçõ es para criar um status:
PyStatus PyStatus_Ok(void)
Sucesso.
PyStatus PyStatus_Error(const char *err_msg)
Erro de inicializaçã o com uma mensagem.
err_msg nã o deve ser NULL.
PyStatus PyStatus_NoMemory(void)
Falha de alocaçã o de memó ria (sem memó ria).
PyStatus PyStatus_Exit(int exitcode)
Sai do Python com o có digo de saída especificado.
Funçõ es para manipular um status:
int PyStatus_Exception(PyStatus status)
O status é um erro ou uma saída? Se verdadeiro, a exceçã o deve ser tratada; chamando
Py_ExitStatusException(), por exemplo.
int PyStatus_IsError(PyStatus status)
O resultado é um erro?
int PyStatus_IsExit(PyStatus status)
O resultado é uma saída?
void Py_ExitStatusException(PyStatus status)
Chama exit(exitcode) se status for uma saída. Exibe a mensagem de erro e sai com
um có digo de saída diferente de zero se status for um erro. Deve ser chamado apenas se
PyStatus_Exception(status) for diferente de zero.
® Nota
Internamente, Python usa macros que definem PyStatus.func, enquanto funçõ es para criar um status definem
func para NULL.
Exemplo:
PyStatus alloc(void **ptr, size_t size)
{
*ptr = PyMem_RawMalloc(size);
if (*ptr == NULL) {
return PyStatus_NoMemory();
}
(continua na pró xima pá gina)
10.3. PyStatus 245
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
return PyStatus_Ok();
}
int main(int argc, char **argv)
{
void *ptr;
PyStatus status = alloc(&ptr, 16);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
PyMem_Free(ptr);
return 0;
}
10.4 PyPreConfig
type PyPreConfig
Estrutura usada para pré -inicializar o Python.
A funçã o para inicializar uma pré -configuraçã o:
void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
Inicializa a pré -configuraçã o com Configuração do Python.
void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
Inicializa a pré -configuraçã o com Configuração isolada.
Campos de estrutura:
int allocator
Nome de alocadores de memó ria em Python:
• PYMEM_ALLOCATOR_NOT_SET (0): nã o altera os alocadores de memó ria (usa o padrã o).
• PYMEM_ALLOCATOR_DEFAULT (1): alocadores de memória padrão.
• PYMEM_ALLOCATOR_DEBUG (2): alocadores de memória padrão com ganchos de depuração.
• PYMEM_ALLOCATOR_MALLOC (3): usa malloc() da biblioteca C.
• PYMEM_ALLOCATOR_MALLOC_DEBUG (4): força uso de malloc() com ganchos de depuração.
• PYMEM_ALLOCATOR_PYMALLOC (5): alocador de memória do Python pymalloc.
• PYMEM_ALLOCATOR_PYMALLOC_DEBUG (6): alocador de memória deo Python pymalloc com gan-
chos de depuração.
• PYMEM_ALLOCATOR_MIMALLOC (6): usa mimalloc, um substituto rá pido do malloc.
• PYMEM_ALLOCATOR_MIMALLOC_DEBUG (7): use mimalloc, um substituto rá pido do malloc com
ganchos de depuração.
PYMEM_ALLOCATOR_PYMALLOC e PYMEM_ALLOCATOR_PYMALLOC_DEBUG nã o sã o suportados se o
Python estiver configurado usando --without-pymalloc.
PYMEM_ALLOCATOR_MIMALLOC e PYMEM_ALLOCATOR_MIMALLOC_DEBUG nã o sã o suportados se o
Python estiver configurado usando --without-mimalloc ou se suporte atô mico subjacente nã o
estiver disponível.
Veja Gerenciamento de memória.
Padrã o: PYMEM_ALLOCATOR_NOT_SET.
246 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
int configure_locale
Define a localidade LC_CTYPE para a localidade preferida do usuá rio.
Se igual a 0, define os membros coerce_c_locale e coerce_c_locale_warn para 0.
Veja a codificação da localidade.
Padrã o: 1 na configuraçã o do Python, 0 na configuraçã o isolada.
int coerce_c_locale
Se igual a 2, força a localidade para C.
Se for igual a 1, lê a localidade LC_CTYPE para decidir se deve ser forçado.
Veja a codificação da localidade.
Padrã o: -1 na configuraçã o do Python, 0 na configuraçã o isolada.
int coerce_c_locale_warn
Se diferente de zero, emite um aviso se a localidade C for forçada.
Padrã o: -1 na configuraçã o do Python, 0 na configuraçã o isolada.
int dev_mode
Modo de desenvolvimento do Python: veja PyConfig.dev_mode.
Padrã o: -1 no modo do Python, 0 no modo isolado.
int isolated
Modo isolado: veja PyConfig.isolated.
Padrã o: 0 no modo do Python, 1 no modo isolado.
int legacy_windows_fs_encoding
Se nã o zero:
• Define PyPreConfig.utf8_mode para 0,
• Define PyConfig.filesystem_encoding para "mbcs",
• Define PyConfig.filesystem_errors para "replace".
Initialized from the PYTHONLEGACYWINDOWSFSENCODING environment variable value.
Disponível apenas no Windows. A macro #ifdef MS_WINDOWS pode ser usada para có digo específico
do Windows.
Padrã o: 0.
int parse_argv
Se diferente de zero, Py_PreInitializeFromArgs() e Py_PreInitializeFromBytesArgs()
analisam seu argumento argv da mesma forma que o Python regular analisa argumentos de linha de
comando: veja Argumentos de linha de comando.
Padrã o: 1 na configuraçã o do Python, 0 na configuraçã o isolada.
int use_environment
Usar variá veis de ambiente? Veja PyConfig.use_environment.
Padrã o: 1 na configuraçã o do Python e 0 na configuraçã o isolada.
int utf8_mode
Se nã o zero, habilita o modo UTF-8 do Python.
Define para 0 ou 1 pela opçã o de linha de comando -X utf8 e a variá vel de ambiente PYTHONUTF8.
També m define como 1 se a localidade LC_CTYPE for C ou POSIX.
Padrã o: -1 na configuraçã o do Python e 0 na configuraçã o isolada.
10.4. PyPreConfig 247
The Python/C API, Release 3.13.7
10.5 Pré-inicializar Python com PyPreConfig
A pré -inicializaçã o do Python:
• Define os alocadores de memó ria Python (PyPreConfig.allocator)
• Configura a localidade LC_CTYPE (codificação da localidade)
• Define o Modo UTF-8 do Python (PyPreConfig.utf8_mode)
A pré -configuraçã o atual (tipo PyPreConfig) é armazenada em _PyRuntime.preconfig.
Funçõ es para pré -inicializar Python:
PyStatus Py_PreInitialize(const PyPreConfig *preconfig)
Pré -inicializa o Python a partir da pré -configuraçã o preconfig.
preconfig nã o pode ser NULL..
PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char *const *argv)
Pré -inicializa o Python a partir da pré -configuraçã o preconfig.
Analisa argumentos de linha de comando argv (strings de bytes) se parse_argv de preconfig for diferente de
zero.
preconfig nã o pode ser NULL..
PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t *const *argv)
Pré -inicializa o Python a partir da pré -configuraçã o preconfig.
Analisa argumentos de linha de comando argv (strings largas) se parse_argv de preconfig for diferente de
zero.
preconfig nã o pode ser NULL..
O chamador é responsá vel por manipular exceçõ es (erro ou saída) usando PyStatus_Exception() e
Py_ExitStatusException().
Para configuração do Python (PyPreConfig_InitPythonConfig()), se o Python for inicializado com argumen-
tos de linha de comando, os argumentos de linha de comando també m devem ser passados para pré -inicializar o
Python, pois eles tê m um efeito na pré -configuraçã o como codificaçõ es. Por exemplo, a opçã o de linha de comando
-X utf8 habilita o Modo UTF-8 do Python.
PyMem_SetAllocator() pode ser chamado depois de Py_PreInitialize() e antes de
Py_InitializeFromConfig() para instalar um alocador de memó ria personalizado. Ele pode ser chamado antes
de Py_PreInitialize() se PyPreConfig.allocator estiver definido como PYMEM_ALLOCATOR_NOT_SET.
Funçõ es de alocaçã o de memó ria do Python como PyMem_RawMalloc() nã o devem ser usadas an-
tes da pré -inicializaçã o do Python, enquanto chamar diretamente malloc() e free() é sempre seguro.
Py_DecodeLocale() nã o deve ser chamado antes da pré -inicializaçã o do Python.
Exemplo usando a pré -inicializaçã o para habilitar o modo UTF-8 do Python.
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 */
(continua na pró xima pá gina)
248 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();
10.6 PyConfig
type PyConfig
Estrutura contendo a maioria dos parâ metros para configurar o Python.
Ao terminar, a funçã o PyConfig_Clear() deve ser usada para liberar a memó ria de configuraçã o.
Structure methods:
void PyConfig_InitPythonConfig(PyConfig *config)
Initialize configuration with the Python Configuration.
void PyConfig_InitIsolatedConfig(PyConfig *config)
Initialize configuration with the Isolated Configuration.
PyStatus PyConfig_SetString(PyConfig *config, wchar_t *const *config_str, const wchar_t *str)
Copy the wide character string str into *config_str.
Preinitialize Python if needed.
PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t *const *config_str, const char *str)
Decode str using Py_DecodeLocale() and set the result into *config_str.
Preinitialize Python if needed.
PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t *const *argv)
Set command line arguments (argv member of config) from the argv list of wide character strings.
Preinitialize Python if needed.
PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char *const *argv)
Set command line arguments (argv member of config) from the argv list of bytes strings. Decode bytes
using Py_DecodeLocale().
Preinitialize Python if needed.
PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length,
wchar_t **items)
Set the list of wide strings list to length and items.
Preinitialize Python if needed.
PyStatus PyConfig_Read(PyConfig *config)
Read all Python configuration.
Fields which are already initialized are left unchanged.
Fields for path configuration are no longer calculated or modified when calling this function, as of Python
3.11.
The PyConfig_Read() function only parses PyConfig.argv arguments once: PyConfig.
parse_argv is set to 2 after arguments are parsed. Since Python arguments are stripped from
PyConfig.argv , parsing arguments twice would parse the application options as Python options.
Preinitialize Python if needed.
Alterado na versã o 3.10: The PyConfig.argv arguments are now only parsed once, PyConfig.
parse_argv is set to 2 after arguments are parsed, and arguments are only parsed if PyConfig.
parse_argv equals 1.
10.6. PyConfig 249
The Python/C API, Release 3.13.7
Alterado na versã o 3.11: PyConfig_Read() no longer calculates all paths, and so fields listed under
Python Path Configuration may no longer be updated until Py_InitializeFromConfig() is called.
void PyConfig_Clear(PyConfig *config)
Release configuration memory.
Most PyConfig methods preinitialize Python if needed. In that case, the Python preinitialization configuration
(PyPreConfig ) in based on the PyConfig . If configuration fields which are in common with PyPreConfig
are tuned, they must be set before calling a PyConfig method:
• PyConfig.dev_mode
• PyConfig.isolated
• PyConfig.parse_argv
• PyConfig.use_environment
Moreover, if PyConfig_SetArgv() or PyConfig_SetBytesArgv() is used, this method must be cal-
led before other methods, since the preinitialization configuration depends on command line arguments (if
parse_argv is non-zero).
The caller of these methods is responsible to handle exceptions (error or exit) using PyStatus_Exception()
and Py_ExitStatusException().
Campos de estrutura:
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.
Set parse_argv to 1 to parse argv the same way the regular Python parses Python command line
arguments and then to strip Python arguments from argv .
If argv is empty, an empty string is added to ensure that sys.argv always exists and is never empty.
Padrã o: NULL.
See also the orig_argv member.
int safe_path
If equals to zero, Py_RunMain() prepends a potentially unsafe path to sys.path at startup:
• If argv[0] is equal to L"-m" (python -m module), prepend the current working directory.
• If running a script (python script.py), prepend the script’s directory. If it’s a symbolic link,
resolve symbolic links.
• Otherwise (python -c code and python), prepend an empty string, which means the current
working directory.
Set to 1 by the -P command line option and the PYTHONSAFEPATH environment variable.
Default: 0 in Python config, 1 in isolated config.
Adicionado na versã o 3.11.
wchar_t *base_exec_prefix
sys.base_exec_prefix.
Padrã o: NULL.
Part of the Python Path Configuration output.
See also PyConfig.exec_prefix.
250 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
wchar_t *base_executable
Python base executable: sys._base_executable.
Set by the __PYVENV_LAUNCHER__ environment variable.
Set from PyConfig.executable if NULL.
Padrã o: NULL.
Part of the Python Path Configuration output.
See also PyConfig.executable.
wchar_t *base_prefix
sys.base_prefix.
Padrã o: NULL.
Part of the Python Path Configuration output.
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 is always opened in buffered mode.
Padrã o: 1.
int bytes_warning
If equals to 1, issue a warning when comparing bytes or bytearray with str, or comparing bytes
with int.
If equal or greater to 2, raise a BytesWarning exception in these cases.
Incremented by the -b command line option.
Padrã o: 0.
int warn_default_encoding
If non-zero, emit a EncodingWarning warning when io.TextIOWrapper uses its default encoding.
See io-encoding-warning for details.
Padrã o: 0.
Adicionado na versã o 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 com-
mand line option.
Padrã o: 1.
Adicionado na versã o 3.11.
wchar_t *check_hash_pycs_mode
Control the validation behavior of hash-based .pyc files: value of the --check-hash-based-pycs
command line option.
Valores vá lidos:
• L"always": Hash the source file for invalidation regardless of value of the ‘check_source’ flag.
• L"never": Assume that hash-based pycs always are valid.
10.6. PyConfig 251
The Python/C API, Release 3.13.7
• L"default": The ‘check_source’ flag in hash-based pycs determines invalidation.
Default: L"default".
See also PEP 552 “Deterministic pycs”.
int configure_c_stdio
If non-zero, configure C standard streams:
• On Windows, set the binary mode (O_BINARY) on stdin, stdout and stderr.
• If buffered_stdio equals zero, disable buffering of stdin, stdout and stderr streams.
• If interactive is non-zero, enable stream buffering on stdin and stdout (only stdout on Windows).
Padrã o: 1 na configuraçã o do Python, 0 na configuraçã o isolada.
int dev_mode
If non-zero, enable the Python Development Mode.
Set to 1 by the -X dev option and the PYTHONDEVMODE environment variable.
Padrã o: -1 no modo do Python, 0 no modo isolado.
int dump_refs
Dump Python references?
If non-zero, dump all objects which are still alive at exit.
Set to 1 by the PYTHONDUMPREFS environment variable.
Needs a special build of Python with the Py_TRACE_REFS macro defined: see the configure
--with-trace-refs option.
Padrã o: 0.
wchar_t *exec_prefix
The site-specific directory prefix where the platform-dependent Python files are installed: sys.
exec_prefix.
Padrã o: NULL.
Part of the Python Path Configuration output.
See also PyConfig.base_exec_prefix.
wchar_t *executable
The absolute path of the executable binary for the Python interpreter: sys.executable.
Padrã o: NULL.
Part of the Python Path Configuration output.
See also PyConfig.base_executable.
int faulthandler
Enable faulthandler?
If non-zero, call faulthandler.enable() at startup.
Set to 1 by -X faulthandler and the PYTHONFAULTHANDLER environment variable.
Padrã o: -1 no modo do Python, 0 no modo isolado.
wchar_t *filesystem_encoding
Filesystem encoding: sys.getfilesystemencoding().
On macOS, Android and VxWorks: use "utf-8" by default.
On Windows: use "utf-8" by default, or "mbcs" if legacy_windows_fs_encoding of
PyPreConfig is non-zero.
252 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
Default encoding on other platforms:
• "utf-8" if PyPreConfig.utf8_mode is non-zero.
• "ascii" if Python detects that nl_langinfo(CODESET) announces the ASCII encoding, whe-
reas the mbstowcs() function decodes from a different encoding (usually Latin1).
• "utf-8" if nl_langinfo(CODESET) returns an empty string.
• Otherwise, use the locale encoding: nl_langinfo(CODESET) result.
At Python startup, the encoding name is normalized to the Python codec name. For example, "ANSI_X3.
4-1968" is replaced with "ascii".
See also the filesystem_errors member.
wchar_t *filesystem_errors
Filesystem error handler: sys.getfilesystemencodeerrors().
On Windows: use "surrogatepass" by default, or "replace" if legacy_windows_fs_encoding
of PyPreConfig is non-zero.
On other platforms: use "surrogateescape" by default.
Supported error handlers:
• "strict"
• "surrogateescape"
• "surrogatepass" (only supported with the UTF-8 encoding)
See also the filesystem_encoding member.
unsigned long hash_seed
int use_hash_seed
Randomized hash function seed.
If use_hash_seed is zero, a seed is chosen randomly at Python startup, and hash_seed is ignored.
Set by the PYTHONHASHSEED environment variable.
Default use_hash_seed value: -1 in Python mode, 0 in isolated mode.
wchar_t *home
Set the default Python “home” directory, that is, the location of the standard Python libraries (see
PYTHONHOME).
Set by the PYTHONHOME environment variable.
Padrã o: NULL.
Part of the Python Path Configuration input.
int import_time
If non-zero, profile import time.
Set the 1 by the -X importtime option and the PYTHONPROFILEIMPORTTIME environment variable.
Padrã o: 0.
int inspect
Enter interactive mode after executing a script or a command.
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.
Incremented by the -i command line option. Set to 1 if the PYTHONINSPECT environment variable is
non-empty.
10.6. PyConfig 253
The Python/C API, Release 3.13.7
Padrã o: 0.
int install_signal_handlers
Install Python signal handlers?
Default: 1 in Python mode, 0 in isolated mode.
int interactive
If greater than 0, enable the interactive mode (REPL).
Incremented by the -i command line option.
Padrã o: 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.
Adicionado na versã o 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 envi-
ronment variable.
Default: -1.
Adicionado na versã o 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 doesn’t import readline nor enable default readline configuration on interactive
prompts.
Set to 1 by the -I command line option.
Padrã o: 0 no modo do Python, 1 no modo isolado.
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.
Definida como 1 se a variá vel de ambiente PYTHONLEGACYWINDOWSSTDIO estiver definida como uma
string nã o vazia.
Disponível apenas no Windows. A macro #ifdef MS_WINDOWS pode ser usada para có digo específico
do Windows.
Padrã o: 0.
254 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
See also the PEP 528 (Change Windows console encoding to UTF-8).
int malloc_stats
If non-zero, dump statistics on Python pymalloc memory allocator at exit.
Set to 1 by the PYTHONMALLOCSTATS environment variable.
The option is ignored if Python is configured using the --without-pymalloc option.
Padrã o: 0.
wchar_t *platlibdir
Platform library directory name: sys.platlibdir.
Set by the PYTHONPLATLIBDIR environment variable.
Default: value of the PLATLIBDIR macro which is set by the configure --with-platlibdir
option (default: "lib", or "DLLs" on Windows).
Part of the Python Path Configuration input.
Adicionado na versã o 3.9.
Alterado na versã o 3.11: This macro is now used on Windows to locate the standard library extension
modules, typically under DLLs. However, for compatibility, note that this value is ignored for any non-
-standard layouts, including in-tree builds and virtual environments.
wchar_t *pythonpath_env
Module search paths (sys.path) as a string separated by DELIM (os.pathsep).
Set by the PYTHONPATH environment variable.
Padrã o: NULL.
Part of the Python Path Configuration input.
PyWideStringList module_search_paths
int module_search_paths_set
Module search paths: 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.
Default: empty list (module_search_paths) and 0 (module_search_paths_set).
Part of the Python Path Configuration output.
int optimization_level
Compilation optimization level:
• 0: Peephole optimizer, set __debug__ to True.
• 1: Level 0, remove assertions, set __debug__ to False.
• 2: Level 1, strip docstrings.
Incremented by the -O command line option. Set to the PYTHONOPTIMIZE environment variable value.
Padrã o: 0.
PyWideStringList orig_argv
The list of the original command line arguments passed to the Python executable: sys.orig_argv.
If orig_argv list is empty and argv is not a list only containing an empty string, PyConfig_Read()
copies argv into orig_argv before modifying argv (if parse_argv is non-zero).
See also the argv member and the Py_GetArgcArgv() function.
Padrã o: lista vazia.
Adicionado na versã o 3.10.
10.6. PyConfig 255
The Python/C API, Release 3.13.7
int parse_argv
Parse command line arguments?
If equals to 1, parse argv the same way the regular Python parses command line arguments, and strip
Python arguments from argv .
The PyConfig_Read() function only parses PyConfig.argv arguments once: PyConfig.
parse_argv is set to 2 after arguments are parsed. Since Python arguments are stripped from
PyConfig.argv , parsing arguments twice would parse the application options as Python options.
Default: 1 in Python mode, 0 in isolated mode.
Alterado na versã o 3.10: The PyConfig.argv arguments are now only parsed if PyConfig.
parse_argv equals to 1.
int parser_debug
Parser debug mode. If greater than 0, turn on parser debugging output (for expert only, depending on
compilation options).
Incremented by the -d command line option. Set to the PYTHONDEBUG environment variable value.
Needs a debug build of Python (the Py_DEBUG macro must be defined).
Padrã o: 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.
Default: 1 in Python mode, 0 in isolated mode.
Part of the Python Path Configuration input.
Alterado na versã o 3.11: Now also applies on Windows.
wchar_t *prefix
The site-specific directory prefix where the platform independent Python files are installed: sys.
prefix.
Padrã o: NULL.
Part of the Python Path Configuration output.
See also PyConfig.base_prefix.
wchar_t *program_name
Program name used to initialize executable and in early error messages during Python initialization.
• On macOS, use PYTHONEXECUTABLE environment variable if set.
• If the WITH_NEXT_FRAMEWORK macro is defined, use __PYVENV_LAUNCHER__ environment va-
riable if set.
• Use argv[0] of argv if available and non-empty.
• Otherwise, use L"python" on Windows, or L"python3" on other platforms.
Padrã o: NULL.
Part of the Python Path Configuration input.
wchar_t *pycache_prefix
Directory where cached .pyc files are written: sys.pycache_prefix.
Set by the -X pycache_prefix=PATH command line option and the PYTHONPYCACHEPREFIX envi-
ronment variable. The command-line option takes precedence.
If NULL, sys.pycache_prefix is set to None.
Padrã o: NULL.
256 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
int quiet
Quiet mode. If greater than 0, don’t display the copyright and version at Python startup in interactive
mode.
Incremented by the -q command line option.
Padrã o: 0.
wchar_t *run_command
Value of the -c command line option.
Used by Py_RunMain().
Padrã o: 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.
Padrã o: NULL.
wchar_t *run_module
Value of the -m command line option.
Used by Py_RunMain().
Padrã o: 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 environ-
ment variable. The command-line option takes precedence.
Needs a debug build of Python (the Py_DEBUG macro must be defined).
Padrã o: 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).
Padrã o: 0.
int site_import
Import the site module at startup?
If equal to zero, disable the import of the module site and the site-dependent manipulations of sys.path
that it entails.
Also disable these manipulations if the site module is explicitly imported later (call site.main() if
you want them to be triggered).
Set to 0 by the -S command line option.
sys.flags.no_site is set to the inverted value of site_import.
Padrã o: 1.
10.6. PyConfig 257
The Python/C API, Release 3.13.7
int skip_source_first_line
If non-zero, skip the first line of the PyConfig.run_filename source.
It allows the usage of non-Unix forms of #!cmd. This is intended for a DOS specific hack only.
Set to 1 by the -x command line option.
Padrã o: 0.
wchar_t *stdio_encoding
wchar_t *stdio_errors
Encoding and encoding errors of sys.stdin, sys.stdout and sys.stderr (but sys.stderr
always uses "backslashreplace" error handler).
Use the PYTHONIOENCODING environment variable if it is non-empty.
Codificaçã o padrã o:
• "UTF-8" if PyPreConfig.utf8_mode is non-zero.
• Otherwise, use the locale encoding.
Tratador de erros padrã o:
• On Windows: use "surrogateescape".
• "surrogateescape" if PyPreConfig.utf8_mode is non-zero, or if the LC_CTYPE locale is
“C” or “POSIX”.
• "strict" otherwise.
See also PyConfig.legacy_windows_stdio.
int tracemalloc
Enable tracemalloc?
If non-zero, call tracemalloc.start() at startup.
Set by -X tracemalloc=N command line option and by the PYTHONTRACEMALLOC environment va-
riable.
Padrã o: -1 no modo do Python, 0 no modo isolado.
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 PYTHON_PERF_JIT_SUPPORT environment va-
riable for perf support with stack pointers and -X perf_jit command-line option and by the
PYTHON_PERF_JIT_SUPPORT environment variable for perf support with DWARF JIT information.
Default: -1.
Adicionado na versã o 3.12.
int use_environment
Use environment variables?
If equals to zero, ignore the environment variables.
Set to 0 by the -E environment variable.
Padrã o: 1 na configuraçã o do Python e 0 na configuraçã o isolada.
258 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
int user_site_directory
If non-zero, add the user site directory to sys.path.
Set to 0 by the -s and -I command line options.
Set to 0 by the PYTHONNOUSERSITE environment variable.
Default: 1 in Python mode, 0 in isolated mode.
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.
Incremented by the -v command line option.
Set by the PYTHONVERBOSE environment variable value.
Padrã o: 0.
PyWideStringList warnoptions
Options of the warnings module to build warnings filters, lowest to highest priority: sys.
warnoptions.
The warnings module adds sys.warnoptions in the reverse order: the last PyConfig.
warnoptions item becomes the first item of warnings.filters which is checked first (highest
priority).
The -W command line options adds its value to warnoptions, it can be used multiple times.
The PYTHONWARNINGS environment variable can also be used to add warning options. Multiple options
can be specified, separated by commas (,).
Padrã o: lista vazia.
int write_bytecode
If equal to 0, Python won’t try to write .pyc files on the import of source modules.
Set to 0 by the -B command line option and the PYTHONDONTWRITEBYTECODE environment variable.
sys.dont_write_bytecode is initialized to the inverted value of write_bytecode.
Padrã o: 1.
PyWideStringList xoptions
Values of the -X command line options: sys._xoptions.
Padrã o: lista vazia.
If parse_argv is non-zero, argv arguments are parsed the same way the regular Python parses command line
arguments, and Python arguments are stripped from argv .
The xoptions options are parsed to set other options: see the -X command line option.
Alterado na versã o 3.9: The show_alloc_count field has been removed.
10.7 Initialization with PyConfig
Initializing the interpreter from a populated configuration struct is handled by calling
Py_InitializeFromConfig().
O chamador é responsá vel por manipular exceçõ es (erro ou saída) usando PyStatus_Exception() e
Py_ExitStatusException().
10.7. Initialization with PyConfig 259
The Python/C API, Release 3.13.7
If PyImport_FrozenModules(), PyImport_AppendInittab() or PyImport_ExtendInittab() are used,
they must be set or called after Python preinitialization and before the Python initialization. If Python is initi-
alized multiple times, PyImport_AppendInittab() or PyImport_ExtendInittab() must be called before
each Python initialization.
The current configuration (PyConfig type) is stored in PyInterpreterState.config.
Example setting the program name:
void init_python(void)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
/* Set the program name. Implicitly preinitialize Python. */
status = PyConfig_SetString(&config, &config.program_name,
L"/path/to/my_program");
if (PyStatus_Exception(status)) {
goto exception;
}
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return;
exception:
PyConfig_Clear(&config);
Py_ExitStatusException(status);
}
More complete example modifying the default configuration, read the configuration, and then override some para-
meters. Note that since 3.11, many parameters are not calculated until initialization, and so values cannot be read
from the configuration structure. Any values set before initialize is called will be left unchanged by initialization:
PyStatus init_python(const char *program_name)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
/* Set the program name before reading the configuration
(decode byte string from the locale encoding).
Implicitly preinitialize Python. */
status = PyConfig_SetBytesString(&config, &config.program_name,
program_name);
if (PyStatus_Exception(status)) {
goto done;
}
/* Read all configuration at once */
status = PyConfig_Read(&config);
if (PyStatus_Exception(status)) {
(continua na pró xima pá gina)
260 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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;
}
status = Py_InitializeFromConfig(&config);
done:
PyConfig_Clear(&config);
return status;
}
10.8 Isolated Configuration
PyPreConfig_InitIsolatedConfig() and PyConfig_InitIsolatedConfig() functions create a configu-
ration to isolate Python from the system. For example, to embed Python into an application.
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.
Configuration files are still used with this configuration to determine paths that are unspecified. Ensure PyConfig.
home is specified to avoid computing the default path configuration.
10.9 Configuração do Python
PyPreConfig_InitPythonConfig() and PyConfig_InitPythonConfig() functions create a configuration
to build a customized Python which behaves as the regular Python.
Environments variables and command line arguments are used to configure Python, whereas global configuration
variables are ignored.
This function enables C locale coercion (PEP 538) and Python UTF-8 Mode (PEP 540) depending on the
LC_CTYPE locale, PYTHONUTF8 and PYTHONCOERCECLOCALE environment variables.
10.8. Isolated Configuration 261
The Python/C API, Release 3.13.7
10.10 Python Path Configuration
PyConfig contains multiple fields for the path configuration:
• Path configuration inputs:
– PyConfig.home
– PyConfig.platlibdir
– PyConfig.pathconfig_warnings
– PyConfig.program_name
– PyConfig.pythonpath_env
– current working directory: to get absolute paths
– PATH environment variable to get the program full path (from PyConfig.program_name)
– __PYVENV_LAUNCHER__ environment variable
– (Windows only) Application paths in the registry under “SoftwarePythonPythonCoreX.YPythonPath” of
HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE (where X.Y is the Python version).
• Path configuration output fields:
– 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
If at least one “output field” is not set, Python calculates the path configuration to fill unset fi-
elds. If module_search_paths_set is equal to 0, module_search_paths is overridden and
module_search_paths_set is set to 1.
It is possible to completely ignore the function calculating the default path configuration by setting explici-
tly 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).
If base_prefix or base_exec_prefix fields are not set, they inherit their value from prefix and exec_prefix
respectively.
Py_RunMain() and Py_Main() modify sys.path:
• If run_filename is set and is a directory which contains a __main__.py script, prepend run_filename
to sys.path.
• If isolated is zero:
– If run_module is set, prepend the current directory to sys.path. Do nothing if the current directory
cannot be read.
– If run_filename is set, prepend the directory of the filename to sys.path.
– Otherwise, prepend an empty string to sys.path.
262 Capítulo 10. Configuração de Inicialização do Python
The Python/C API, Release 3.13.7
If site_import is non-zero, sys.path can be modified by the site module. If user_site_directory is
non-zero and the user’s site-package directory exists, the site module appends the user’s site-package directory to
sys.path.
The following configuration files are used by the path configuration:
• pyvenv.cfg
• ._pth file (ex: python._pth)
• pybuilddir.txt (Unix only)
If a ._pth file is present:
• 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.
10.11 Py_GetArgcArgv()
void Py_GetArgcArgv(int *argc, wchar_t ***argv)
Get the original command line arguments, before Python modified them.
See also PyConfig.orig_argv member.
10.12 Multi-Phase Initialization Private Provisional API
This section is a private provisional API introducing multi-phase initialization, the core feature of PEP 432:
• “Core” initialization phase, “bare minimum Python”:
– Builtin types;
– Builtin exceptions;
– Builtin and frozen modules;
– The sys module is only partially initialized (ex: sys.path doesn’t exist yet).
• “Main” initialization phase, Python is fully initialized:
– Install and configure importlib;
– Apply the Path Configuration;
– Install signal handlers;
– Finish sys module initialization (ex: create sys.stdout and sys.path);
– Enable optional features like faulthandler and tracemalloc;
– Import the site module;
– etc.
Private provisional API:
• PyConfig._init_main: if set to 0, Py_InitializeFromConfig() stops at the “Core” initialization
phase.
10.11. Py_GetArgcArgv() 263
The Python/C API, Release 3.13.7
PyStatus _Py_InitializeMain(void)
Move to the “Main” initialization phase, finish the Python initialization.
No module is imported during the “Core” phase and the importlib module is not configured: the Path Configuration
is only applied during the “Main” phase. It may allow to customize Python in Python to override or tune the Path
Configuration, maybe install a custom sys.meta_path importer or an import hook, 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.
The “Core” phase is not properly defined: what should be and what should not be available at this phase is not
specified yet. The API is marked as private and provisional: the API can be modified or even be removed anytime
until a proper public API is designed.
Example running Python code between “Core” and “Main” initialization phases:
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);
}
}
264 Capítulo 10. Configuração de Inicialização do Python
CAPÍTULO 11
Gerenciamento de Memória
11.1 Visão Geral
Zarządzanie pamięcią w Pythonie zakłada prywatną stertę zawierającą wszystkie obiekty i struktury danych Pythona.
Zarządzanie tą prywatną stertą jest zapewniane wewnętrznie przez zarządcę pamięci Pythona. Zarządca pamięci
Pythona ma ró żne komponenty któ re radzą sobie z ró żnymi aspektami dynamicznego przechowywania, jak wspó łd-
zielenie, segmentacja, alokacja wstępna i kieszeniowanie.
Na najniższym poziomie, przedmiot przydzielający pamięć “na-surowo” zapewnia że będzie dość pamięci na
prywatnej stercie dla przechowania wszystkich związanych-z-językiem-pytonowskim danych przez wspó łdziałanie z
zarządcą pamięci systemu operacyjnego. Ponad zarządcą surowej pamięci, kilka szczegó lnych dla danych typó w pr-
zedmiotó w zarządcó w operuje na tej samej stercie i wypełnia szczegó lne zasady zarządzania pamięcią dostosowane
do szczegó lnych własności każdego rodzaju przedmiotu. Dla przykładu przedmioty liczb całkowitych są zarząd-
zane inaczej wewnątrz sterty niż ciągi znakó w, krotki czy słowniki gdyż liczby całkowite zakładają inne wymagania
przechowywania i wady i zalety prędkości/zajętej przestrzeni. Zarządca pamięcią Pythona zatem odprawia pewną
ilość nakładó w pracy dla szczegó lnych dla przedmiotó w ró żnych typó w zarządcó w, ale zapewnia że te drugie będą
operować wewnątrz ograniczeń prywatnej sterty.
Важливо розуміти, що керування купою Python виконується самим інтерпретатором і що користувач не
має контролю над нею, навіть якщо вони регулярно маніпулюють покажчиками об’єктів на блоки пам’яті
всередині цієї купи. Виділення простору купи для об’єктів Python та інших внутрішніх буферів виконується
на вимогу менеджером пам’яті Python за допомогою функцій API Python/C, перелічених у цьому документі.
Щоб уникнути пошкодження пам’яті, автори розширень ніколи не повинні намагатися працювати з об’єктами
Python за допомогою функцій, експортованих бібліотекою C: malloc(), calloc(), realloc() і free().
Це призведе до змішаних викликів між розподільником C і диспетчером пам’яті Python із фатальними
наслідками, оскільки вони реалізують різні алгоритми та працюють із різними купами. Однак можна
безпечно виділяти та звільняти блоки пам’яті за допомогою розподільника бібліотеки C для окремих цілей,
як показано в наступному прикладі:
PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyBytes_FromString(buf);
(continua na pró xima pá gina)
265
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
free(buf); /* malloc'ed */
return res;
У цьому прикладі запит пам’яті для буфера введення/виведення обробляється розподільником бібліотеки C.
Менеджер пам’яті Python бере участь лише у розподілі об’єкта bytes, який повертається в результаті.
In most situations, however, it is recommended to allocate memory from the Python heap specifically because the
latter is under control of the Python memory manager. For example, this is required when the interpreter is extended
with new object types written in C. Another reason for using the Python heap is the desire to inform the Python
memory manager about the memory needs of the extension module. Even when the requested memory is used
exclusively for internal, highly specific purposes, delegating all memory requests to the Python memory manager
causes the interpreter to have a more accurate image of its memory footprint as a whole. Consequently, under certain
circumstances, the Python memory manager may or may not trigger appropriate actions, like garbage collection,
memory compaction or other preventive procedures. Note that by using the C library allocator as shown in the
previous example, the allocated memory for the I/O buffer escapes completely the Python memory manager.
µ Ver também
Змінну середовища PYTHONMALLOC можна використовувати для налаштування розподільників пам’яті,
які використовує Python.
Змінну середовища PYTHONMALLOCSTATS можна використовувати для виведення статистики
розподільника пам’яті pymalloc кожного разу, коли створюється нова арена об’єкта pymalloc, і
після завершення роботи.
11.2 Allocator Domains
All allocating functions belong to one of three different “domains” (see also PyMemAllocatorDomain). These
domains represent different allocation strategies and are optimized for different purposes. The specific details on how
every domain allocates memory or what internal functions each domain calls is considered an implementation detail,
but for debugging purposes a simplified table can be found at here. The APIs used to allocate and free a block of
memory must be from the same domain. For example, PyMem_Free() must be used to free memory allocated using
PyMem_Malloc().
The three allocation domains are:
• Raw domain: intended for allocating memory for general-purpose memory buffers where the allocation must
go to the system allocator or where the allocator can operate without the GIL. The memory is requested directly
from the system. See Raw Memory Interface.
• “Mem” domain: intended for allocating memory for Python buffers and general-purpose memory buffers where
the allocation must be performed with the GIL held. The memory is taken from the Python private heap. See
Memory Interface.
• Object domain: intended for allocating memory for Python objects. The memory is taken from the Python
private heap. See Object allocators.
® Nota
The free-threaded build requires that only Python objects are allocated using the “object” domain and that all
Python objects are allocated using that domain. This differs from the prior Python versions, where this was only
a best practice and not a hard requirement.
For example, buffers (non-Python objects) should be allocated using PyMem_Malloc(), PyMem_RawMalloc(),
or malloc(), but not PyObject_Malloc().
See Memory Allocation APIs.
266 Capítulo 11. Gerenciamento de Memória
The Python/C API, Release 3.13.7
11.3 Інтерфейс необробленої пам’яті
The following function sets are wrappers to the system allocator. These functions are thread-safe, the GIL does not
need to be held.
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.
Adicionado na versã o 3.4.
void *PyMem_RawMalloc(size_t n)
Parte da ABI Está vel desde a versão 3.13. Allocates n bytes and returns a pointer of type void* to the allocated
memory, or NULL if the request fails.
Запит нульових байтів повертає окремий вказівник, відмінний від NULL, якщо це можливо, ніби замість
цього було викликано PyMem_RawMalloc(1). Пам’ять жодним чином не буде ініціалізовано.
void *PyMem_RawCalloc(size_t nelem, size_t elsize)
Parte da ABI Está vel desde a versão 3.13. Allocates nelem elements each whose size in bytes is elsize and returns
a pointer of type void* to the allocated memory, or NULL if the request fails. The memory is initialized to
zeros.
Запит нульових елементів або елементів розміром нуль байтів повертає окремий вказівник, відмінний
від NULL, якщо це можливо, ніби замість цього було викликано PyMem_RawCalloc(1, 1).
Adicionado na versã o 3.5.
void *PyMem_RawRealloc(void *p, size_t n)
Parte da ABI Está vel desde a versão 3.13. Змінює розмір блоку пам’яті, на який вказує p, до n байтів.
Вміст буде незмінним до мінімуму старого та нового розмірів.
Якщо p має значення NULL, виклик еквівалентний PyMem_RawMalloc(n); інакше, якщо n дорівнює
нулю, розмір блоку пам’яті змінюється, але не звільняється, а повернутий вказівник не є NULL.
Якщо p не має значення NULL, воно має бути повернуто попереднім викликом PyMem_RawMalloc(),
PyMem_RawRealloc() або PyMem_RawCalloc().
Якщо запит завершується невдало, PyMem_RawRealloc() повертає NULL, а p залишається дійсним
покажчиком на попередню область пам’яті.
void PyMem_RawFree(void *p)
Parte da ABI Está vel desde a versão 3.13. Звільняє блок пам’яті, на який вказує p, який
мав бути повернутий попереднім викликом PyMem_RawMalloc(), PyMem_RawRealloc() або
PyMem_RawCalloc(). В іншому випадку, або якщо PyMem_RawFree(p) був викликаний раніше,
виникає невизначена поведінка.
Якщо p має значення NULL, жодна операція не виконується.
11.4 Interface da Memória
Наступні набори функцій, створені за стандартом ANSI C, але вказуючи поведінку під час запиту нульових
байтів, доступні для виділення та звільнення пам’яті з купи Python.
розподільник пам’яті за замовчуванням використовує розподільник пам’яті pymalloc.
Á Aviso
The GIL must be held when using these functions.
Alterado na versã o 3.6: Типовим розподільником тепер є pymalloc замість system malloc().
11.3. Інтерфейс необробленої пам’яті 267
The Python/C API, Release 3.13.7
void *PyMem_Malloc(size_t n)
Parte da ABI Está vel. Allocates n bytes and returns a pointer of type void* to the allocated memory, or NULL
if the request fails.
Запит нульових байтів повертає окремий вказівник, відмінний від NULL, якщо це можливо, ніби замість
цього було викликано PyMem_Malloc(1). Пам’ять жодним чином не буде ініціалізовано.
void *PyMem_Calloc(size_t nelem, size_t elsize)
Parte da ABI Está vel desde a versão 3.7. Allocates nelem elements each whose size in bytes is elsize and returns
a pointer of type void* to the allocated memory, or NULL if the request fails. The memory is initialized to
zeros.
Запит нульових елементів або елементів розміром нуль байтів повертає окремий вказівник, відмінний
від NULL, якщо це можливо, як якщо б замість цього було викликано PyMem_Calloc(1, 1).
Adicionado na versã o 3.5.
void *PyMem_Realloc(void *p, size_t n)
Parte da ABI Está vel. Змінює розмір блоку пам’яті, на який вказує p, до n байтів. Вміст буде незмінним
до мінімуму старого та нового розмірів.
Якщо p має значення NULL, виклик еквівалентний PyMem_Malloc(n); інакше, якщо n дорівнює нулю,
розмір блоку пам’яті змінюється, але не звільняється, а повернутий вказівник не є NULL.
Якщо p не має значення NULL, воно має бути повернуто попереднім викликом PyMem_Malloc(),
PyMem_Realloc() або PyMem_Calloc().
Якщо запит не вдається, PyMem_Realloc() повертає NULL, а p залишається дійсним покажчиком на
попередню область пам’яті.
void PyMem_Free(void *p)
Parte da ABI Está vel. Звільняє блок пам’яті, на який вказує p, який мав бути повернутий попереднім
викликом PyMem_Malloc(), PyMem_Realloc() або PyMem_Calloc(). В іншому випадку, або якщо
PyMem_Free(p) був викликаний раніше, виникає невизначена поведінка.
Якщо p має значення NULL, жодна операція не виконується.
Następujące makropolecenia zorientowane-według-typu dostarczone są dla wygody. Zauważ że TYP odnosi się do
dowolnego typu 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.
Це макрос препроцесора C; p завжди перепризначається. Збережіть початкове значення p, щоб
уникнути втрати пам’яті під час обробки помилок.
void PyMem_Del(void *p)
Sama seperti PyMem_Free().
Dodać należy, że następujący zbió r makropoleceń dostarczony jest aby odwoływać się do programu przydzielają-
cego pamięć w języku pytonowskim bezpośrednio, bez udziału zadań sprzęgu C wymienionych powyżej. Jednakże,
zauważ, że ich użycie nie zachowuje wzajemnej zgodności binarnej pomiędzy wersjami Pythona i z tego też powodu
ich użycie jest niewskazane w modułach rozszerzających.
• PyMem_MALLOC(size)
• PyMem_NEW(type, size)
• PyMem_REALLOC(ptr, size)
• PyMem_RESIZE(ptr, type, size)
268 Capítulo 11. Gerenciamento de Memória
The Python/C API, Release 3.13.7
• PyMem_FREE(ptr)
• PyMem_DEL(ptr)
11.5 Alocadores de objeto
Наступні набори функцій, створені за стандартом ANSI C, але вказуючи поведінку під час запиту нульових
байтів, доступні для виділення та звільнення пам’яті з купи Python.
® Nota
There is no guarantee that the memory returned by these allocators can be successfully cast to a Python object
when intercepting the allocating functions in this domain by the methods described in the Customize Memory
Allocators section.
розподільник об’єктів за замовчуванням використовує розподільник пам’яті pymalloc.
Á Aviso
The GIL must be held when using these functions.
void *PyObject_Malloc(size_t n)
Parte da ABI Está vel. Allocates n bytes and returns a pointer of type void* to the allocated memory, or NULL
if the request fails.
Запит нульових байтів повертає окремий покажчик, відмінний від NULL, якщо це можливо, ніби замість
цього було викликано PyObject_Malloc(1). Пам’ять жодним чином не буде ініціалізовано.
void *PyObject_Calloc(size_t nelem, size_t elsize)
Parte da ABI Está vel desde a versão 3.7. Allocates nelem elements each whose size in bytes is elsize and returns
a pointer of type void* to the allocated memory, or NULL if the request fails. The memory is initialized to
zeros.
Запит нульових елементів або елементів розміром нуль байтів повертає окремий вказівник, відмінний
від NULL, якщо це можливо, як якщо б замість цього було викликано PyObject_Calloc(1, 1).
Adicionado na versã o 3.5.
void *PyObject_Realloc(void *p, size_t n)
Parte da ABI Está vel. Змінює розмір блоку пам’яті, на який вказує p, до n байтів. Вміст буде незмінним
до мінімуму старого та нового розмірів.
Якщо p має значення NULL, виклик еквівалентний PyObject_Malloc(n); інакше, якщо n дорівнює
нулю, розмір блоку пам’яті змінюється, але не звільняється, а повернутий вказівник не є NULL.
Якщо p не має значення NULL, воно має бути повернуто попереднім викликом PyObject_Malloc(),
PyObject_Realloc() або PyObject_Calloc().
Якщо запит не вдається, PyObject_Realloc() повертає NULL, а p залишається дійсним покажчиком
на попередню область пам’яті.
void PyObject_Free(void *p)
Parte da ABI Está vel. Звільняє блок пам’яті, на який вказує p, який мав бути повернутий
попереднім викликом PyObject_Malloc(), PyObject_Realloc() або PyObject_Calloc(). В
іншому випадку, або якщо PyObject_Free(p) був викликаний раніше, виникає невизначена
поведінка.
Якщо p має значення NULL, жодна операція не виконується.
11.5. Alocadores de objeto 269
The Python/C API, Release 3.13.7
11.6 Alocadores de memória padrão
Alocadores de memó ria padrã o:
Configuração Nome Py- PyMem_Malloc PyObject_Malloc
Mem_RawMalloc
Реліз збірки "pymalloc" malloc pymalloc pymalloc
Налагодити збірку "pymalloc_debug"
malloc + pymalloc + pymalloc +
налагодження налагодження налагодження
Випуск збірки без py- "malloc" malloc malloc malloc
malloc
Збірка налагодження "malloc_debug"malloc + malloc + malloc +
без pymalloc налагодження налагодження налагодження
Legenda:
• Name: value for PYTHONMALLOC environment variable.
• malloc: system allocators from the standard C library, C functions: malloc(), calloc(), realloc() and
free().
• pymalloc: pymalloc memory allocator.
• mimalloc: mimalloc memory allocator. The pymalloc allocator will be used if mimalloc support isn’t availa-
ble.
• “+ debug”: with debug hooks on the Python memory allocators.
• “Debug build”: Python build in debug mode.
11.7 Alocadores de memória
Adicionado na versã o 3.4.
type PyMemAllocatorEx
Структура, яка використовується для опису розподілювача блоків пам’яті. Структура має такі поля:
Campo Significado
void *ctx контекст користувача, переданий як
перший аргумент
void* malloc(void *ctx, size_t size) виділити блок пам’яті
void* calloc(void *ctx, size_t nelem, виділити блок пам’яті, ініціалізований
size_t elsize) нулями
void* realloc(void *ctx, void *ptr, виділити або змінити розмір блоку пам’яті
size_t new_size)
void free(void *ctx, void *ptr) звільнити блок пам’яті
Alterado na versã o 3.5: The PyMemAllocator structure was renamed to PyMemAllocatorEx and a new
calloc field was added.
type PyMemAllocatorDomain
Enum використовується для визначення домену розподілювача. Домени:
PYMEM_DOMAIN_RAW
Funçõ es:
• PyMem_RawMalloc()
• PyMem_RawRealloc()
270 Capítulo 11. Gerenciamento de Memória
The Python/C API, Release 3.13.7
• PyMem_RawCalloc()
• PyMem_RawFree()
PYMEM_DOMAIN_MEM
Funçõ es:
• PyMem_Malloc(),
• PyMem_Realloc()
• PyMem_Calloc()
• PyMem_Free()
PYMEM_DOMAIN_OBJ
Funçõ es:
• PyObject_Malloc()
• PyObject_Realloc()
• PyObject_Calloc()
• PyObject_Free()
void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Отримати розподільник блоків пам’яті вказаного домену.
void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Установіть розподільник блоків пам’яті для вказаного домену.
Новий розподільник має повертати окремий покажчик, відмінний від NULL, коли запитує нульові
байти.
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
interpreters that do not share a GIL.
Якщо новий розподільник не є хуком (не викликає попереднього розподільника), необхідно викликати
функцію PyMem_SetupDebugHooks(), щоб перевстановити налагоджувальні хуки поверх нового
розподільника.
See also PyPreConfig.allocator and Preinitialize Python with PyPreConfig.
Á Aviso
PyMem_SetAllocator() does have the following contract:
• It can be called after Py_PreInitialize() and before Py_InitializeFromConfig() to ins-
tall 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.
Alterado na versã o 3.12: All allocators must be thread-safe.
void PyMem_SetupDebugHooks(void)
Setup debug hooks in the Python memory allocators to detect memory errors.
11.7. Alocadores de memória 271
The Python/C API, Release 3.13.7
11.8 Debug hooks on the Python memory allocators
When Python is built in debug mode, the PyMem_SetupDebugHooks() function is called at the Python preinitiali-
zation to setup debug hooks on Python memory allocators to detect memory errors.
The PYTHONMALLOC environment variable can be used to install debug hooks on a Python compiled in release mode
(ex: PYTHONMALLOC=debug).
The PyMem_SetupDebugHooks() function can be used to set debug hooks after calling
PyMem_SetAllocator().
These debug hooks fill dynamically allocated memory blocks with special, recognizable bit patterns. Newly
allocated memory is filled with the byte 0xCD (PYMEM_CLEANBYTE), freed memory is filled with the byte
0xDD (PYMEM_DEADBYTE). Memory blocks are surrounded by “forbidden bytes” filled with the byte 0xFD
(PYMEM_FORBIDDENBYTE). Strings of these bytes are unlikely to be valid addresses, floats, or ASCII strings.
Checagens em Tempo de Execuçã o:
• Detect API violations. For example, detect if PyObject_Free() is called on a memory block allocated by
PyMem_Malloc().
• Detect write before the start of the buffer (buffer underflow).
• Detect write after the end of the buffer (buffer overflow).
• 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.
У разі помилки хуки налагодження використовують модуль tracemalloc, щоб отримати зворотне
відстеження, де було виділено блок пам’яті. Зворотне відстеження відображається, лише якщо
tracemalloc відстежує виділення пам’яті Python і блок пам’яті відстежується.
Let S = sizeof(size_t). 2*S bytes are added at each end of each block of N bytes requested. The memory layout
is like so, where p represents the address returned by a malloc-like or realloc-like function (p[i:j] means the slice
of bytes from *(p+i) inclusive up to *(p+j) exclusive; note that the treatment of negative indices differs from a
Python slice):
p[-2*S:-S]
Number of bytes originally asked for. This is a size_t, big-endian (easier to read in a memory dump).
p[-S]
API identifier (ASCII character):
• 'r' for PYMEM_DOMAIN_RAW .
• 'm' for PYMEM_DOMAIN_MEM .
• 'o' for PYMEM_DOMAIN_OBJ .
p[-S+1:0]
Copies of PYMEM_FORBIDDENBYTE. Used to catch under- writes and reads.
p[0:N]
The requested memory, filled with copies of PYMEM_CLEANBYTE, used to catch reference to uninitialized
memory. When a realloc-like function is called requesting a larger memory block, the new excess bytes are
also filled with PYMEM_CLEANBYTE. When a free-like function is called, these are overwritten with PY-
MEM_DEADBYTE, to catch reference to freed memory. When a realloc- like function is called requesting a
smaller memory block, the excess old bytes are also filled with PYMEM_DEADBYTE.
p[N:N+S]
Copies of PYMEM_FORBIDDENBYTE. Used to catch over- writes and reads.
p[N+S:N+2*S]
Only used if the PYMEM_DEBUG_SERIALNO macro is defined (not defined by default).
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,
272 Capítulo 11. Gerenciamento de Memória
The Python/C API, Release 3.13.7
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.
A realloc-like or free-like function first checks that the PYMEM_FORBIDDENBYTE bytes at each end are intact.
If they’ve been altered, diagnostic output is written to stderr, and the program is aborted via Py_FatalError(). The
other main failure mode is provoking a memory error when a program reads up one of the special bit patterns and
tries to use it as an address. If you get in a debugger then and look at the object, you’re likely to see that it’s entirely
filled with PYMEM_DEADBYTE (meaning freed memory is getting used) or PYMEM_CLEANBYTE (meaning
uninitialized memory is getting used).
Alterado na versã o 3.6: The PyMem_SetupDebugHooks() function now also works on Python compiled in re-
lease 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.
Alterado na versã o 3.8: Byte patterns 0xCB (PYMEM_CLEANBYTE), 0xDB (PYMEM_DEADBYTE) and 0xFB
(PYMEM_FORBIDDENBYTE) have been replaced with 0xCD, 0xDD and 0xFD to use the same values than Windows
CRT debug malloc() and free().
11.9 Розподільник 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.
Розподільник арени використовує такі функції:
• VirtualAlloc() and VirtualFree() on Windows,
• mmap() and munmap() if available,
• malloc() e free() do contrá rio.
This allocator is disabled if Python is configured with the --without-pymalloc option. It can also be disabled at
runtime using the PYTHONMALLOC environment variable (ex: PYTHONMALLOC=malloc).
Typically, it makes sense to disable the pymalloc allocator when building Python with AddressSanitizer
(--with-address-sanitizer) which helps uncover low level bugs within the C code.
11.9.1 Налаштувати pymalloc Arena Allocator
Adicionado na versã o 3.4.
type PyObjectArenaAllocator
Структура, яка використовується для опису розподільника арен. Структура має три поля:
Campo Significado
void *ctx контекст користувача, переданий як перший
аргумент
void* alloc(void *ctx, size_t size) виділити арену розміром байт
void free(void *ctx, void *ptr, size_t звільнити арену
size)
void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
Отримайте розподільник арен.
void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
Встановіть розподільник арен.
11.9. Розподільник pymalloc 273
The Python/C API, Release 3.13.7
11.10 The mimalloc allocator
Adicionado na versã o 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
Adicionado na versã o 3.7.
int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size)
Відстежуйте виділений блок пам’яті в модулі tracemalloc.
Повертає 0 у разі успіху, повертає -1 у разі помилки (не вдалося виділити пам’ять для збереження
трасування). Повертає -2, якщо tracemalloc вимкнено.
Якщо блок пам’яті вже відстежується, оновіть наявне трасування.
int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)
Скасувати відстеження виділеного блоку пам’яті в модулі tracemalloc. Нічого не робити, якщо блок
не відстежується.
Повертає -2, якщо tracemalloc вимкнено, інакше повертає 0.
11.12 Exemplos
Tutaj jest przykład z sekcji “przeglądu pamięci” - z ang. - Visão Geral, przepisane, tak aby przestrzeń wejścia/wyjścia
była przydzielona ze sterty Pythona używając pierwszego zestawu zadań:
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;
ten sam kod przy użyciu zorientowanych na typ zbioró w zadań:
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;
Zauważ, że w dwó ch powyższych przykładach, przestrzeń wymiany jest zawsze zmieniana przez zadania należące do
tego samego zbioru. Właściwie, jest wymagane użycie tej samej rodziny sprzęgó w zarządzania pamięcią (z ang. -
memory API) dla danego obszaru pamięci, tak, że ryzyko pomieszania ró żnych programó w lokujących zmniejszone
jest do minimum. Następująca sekwencja zawiera dwa błędy, jeden z któ rych określony jest jako krytyczny ponieważ
miesza dwa ró żne programy lokujące pamięć działające na ró żnych stertach.
274 Capítulo 11. Gerenciamento de Memória
The Python/C API, Release 3.13.7
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().
Te zostaną wyjaśnione w następnym rozdziale o określaniu i realizowaniu nowych typó w obiektó w w języku C.
11.12. Exemplos 275
The Python/C API, Release 3.13.7
276 Capítulo 11. Gerenciamento de Memória
CAPÍTULO 12
Suporte a implementação de Objetos
Este capítulo descreve as funçõ es, tipos e macros usados ao definir novos tipos de objeto.
12.1 Alocando objetos na heap
PyObject *_PyObject_New(PyTypeObject *type)
Retorna valor: Nova referência.
PyVarObject *_PyObject_NewVar(PyTypeObject *type, Py_ssize_t size)
Retorna valor: Nova referência.
PyObject *PyObject_Init(PyObject *op, PyTypeObject *type)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Inicializa um objeto op recé m-alocado com seu
tipo e referê ncia inicial. Retorna o objeto inicializado. Outros campos do objeto nã o sã o afetados.
PyVarObject *PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size)
Retorna valor: Referência emprestada. Parte da ABI Está vel. Isto faz tudo que o PyObject_Init() faz e
també m inicializa a informaçã o de comprimento para um objeto de tamanho variá vel.
PyObject_New(TYPE, typeobj)
Aloca um novo objeto Python usando o tipo de estrutura do C TYPE e o objeto Python do tipo typeobj
(PyTypeObject*). Campos nã o definidos pelo cabeçalho do objeto Python nã o sã o inicializados. O chama-
dor será dono da apenas a referê ncia ao objeto (isto é , sua contagem de referê ncias será uma). O tamanho da
alocaçã o de memó ria é determinado do campo tp_basicsize do objeto tipo.
Note que esta funçã o nã o é adequada se typeobj tiver Py_TPFLAGS_HAVE_GC definido. Para tais objetos, use
PyObject_GC_New() em vez disso.
PyObject_NewVar(TYPE, typeobj, size)
Aloca um novo objeto Python usando o tipo de estrutura do C TYPE e o objeto Python do tipo typeobj
(PyTypeObject*). Campos nã o definidos pelo cabeçalho do objeto Python nã o sã o inicializados. A me-
mó ria alocada permite a estrutura TYPE e os campos size (Py_ssize_t) do tamanho dado pelo campo
tp_itemsize do tipo typeobj. Isto é ú til para implementar objetos como tuplas, as quais sã o capazes de
determinar seu tamanho no tempo da construçã o. Incorporando o vetor de campos dentro da mesma alocaçã o
diminuindo o numero de alocaçõ es, melhorando a eficiê ncia do gerenciamento de memó ria.
Note que esta funçã o nã o é adequada se typeobj tiver Py_TPFLAGS_HAVE_GC definido. Para tais objetos, use
PyObject_GC_NewVar() em vez disso.
277
The Python/C API, Release 3.13.7
void PyObject_Del(void *op)
Libera memó ria alocada a um objeto usando PyObject_New ou PyObject_NewVar. Isto é normalmente
chamado pelo manipulador de tp_dealloc especificado no tipo do objeto. Os campos do objeto nã o devem
ser acessados apó s esta chamada como a memó ria nã o é mais um objeto Python vá lido.
PyObject _Py_NoneStruct
Objeto o qual é visível no Python como None. Isto só deve ser acessado usando a macro Py_None, o qual
avalia como um ponteiro para este objeto.
µ Ver também
Objetos do Módulo
Para alocar e criar mó dulos de extensã o.
12.2 Estruturas comuns de objetos
Existe um grande nú mero de estruturas usadas para a definiçã o de tipos objeto para o Python. Esta seçã o descreve
essas estruturas e como sã o usadas.
12.2.1 Base object types and macros
Todos os objetos Python por fim compartilham um pequeno nú mero de campos no começo da representaçã o o objeto
na memó ria. Esses sã o representados pelos tipos PyObject e PyVarObject, que sã o definidos, por sua vez, pelas
expansõ es de alguns macros també m, utilizados, direta ou indiretamente, na definiçã o de todos outros objetos Python.
Macros adicionais podem ser encontrados em contagem de referências.
type PyObject
Parte da API Limitada. (Somente alguns membros são parte da ABI estável.) 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
Parte da API Limitada. (Somente alguns membros são parte da ABI estável.) Esta é uma extensã o de PyObject
que adiciona o campo ob_size. Isso é usado apenas para objetos que tê m alguma noçã o de comprimento.
Esse tipo nã o costuma aparecer na API Python/C. O acesso aos membros deve ser feito atravé s das macros
Py_REFCNT , Py_TYPE, e Py_SIZE.
PyObject_HEAD
Este é um macro usado ao declarar novos tipos que representam objetos sem comprimento variá vel. O macro
PyObject_HEAD se expande para:
PyObject ob_base;
Veja documentaçã o de PyObject acima.
PyObject_VAR_HEAD
This is a macro used when declaring new types which represent objects with a length that varies from instance
to instance. The PyObject_VAR_HEAD macro expands to:
PyVarObject ob_base;
Veja documentaçã o de PyVarObject acima.
PyTypeObject PyBaseObject_Type
Parte da ABI Está vel. The base class of all other objects, the same as object in Python.
278 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
int Py_Is(PyObject *x, PyObject *y)
Parte da ABI Está vel desde a versão 3.10. Testa se o objeto x é o objeto y, o mesmo que x is y em Python.
Adicionado na versã o 3.10.
int Py_IsNone(PyObject *x)
Parte da ABI Está vel desde a versão 3.10. Test if an object is the None singleton, the same as x is None in
Python.
Adicionado na versã o 3.10.
int Py_IsTrue(PyObject *x)
Parte da ABI Está vel desde a versão 3.10. Test if an object is the True singleton, the same as x is True in
Python.
Adicionado na versã o 3.10.
int Py_IsFalse(PyObject *x)
Parte da ABI Está vel desde a versão 3.10. Test if an object is the False singleton, the same as x is False
in Python.
Adicionado na versã o 3.10.
PyTypeObject *Py_TYPE(PyObject *o)
Retorna valor: Referência emprestada. Get the type of the Python object o.
Return a borrowed reference.
Use the Py_SET_TYPE() function to set an object type.
Alterado na versã o 3.11: Py_TYPE() is changed to an inline static function. The parameter type is no longer
const PyObject*.
int Py_IS_TYPE(PyObject *o, PyTypeObject *type)
Return non-zero if the object o type is type. Return zero otherwise. Equivalent to: Py_TYPE(o) == type.
Adicionado na versã o 3.9.
void Py_SET_TYPE(PyObject *o, PyTypeObject *type)
Set the object o type to type.
Adicionado na versã o 3.9.
Py_ssize_t Py_SIZE(PyVarObject *o)
Get the size of the Python object o.
Use the Py_SET_SIZE() function to set an object size.
Alterado na versã o 3.11: Py_SIZE() is changed to an inline static function. The parameter type is no longer
const PyVarObject*.
void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size)
Set the object o size to size.
Adicionado na versã o 3.9.
PyObject_HEAD_INIT(type)
This is a macro which expands to initialization values for a new PyObject type. This macro expands to:
_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:
12.2. Estruturas comuns de objetos 279
The Python/C API, Release 3.13.7
_PyObject_EXTRA_INIT
1, type, size,
12.2.2 Implementing functions and methods
type PyCFunction
Parte da ABI Está vel. 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.
A assinatura da funçã o é :
PyObject *PyCFunction(PyObject *self,
PyObject *args);
type PyCFunctionWithKeywords
Parte da ABI Está vel. 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
Parte da ABI Está vel desde a versão 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
Parte da ABI Está vel desde a versão 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:
PyObject *PyCMethod(PyObject *self,
PyTypeObject *defining_class,
PyObject *const *args,
Py_ssize_t nargs,
PyObject *kwnames)
Adicionado na versã o 3.9.
type PyMethodDef
Parte da ABI Está vel (incluindo todos os membros). Structure used to describe a method of an extension type.
This structure has four fields:
280 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
const char *ml_name
Nome do mé todo.
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.
There are these calling conventions:
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
Methods with these flags must be of type PyCFunctionWithKeywords. The function expects three parame-
ters: self, args, kwargs where kwargs is a dictionary of all the keyword arguments or possibly NULL if there are
no keyword arguments. The parameters are typically processed using 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).
Adicionado na versã o 3.7.
Alterado na versã o 3.10: METH_FASTCALL is now part of the stable ABI.
METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL supporting also keyword arguments, with methods of type
PyCFunctionFastWithKeywords. Keyword arguments are passed the same way as in the 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.
Adicionado na versã o 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).
The method needs to be of type PyCMethod, the same as for METH_FASTCALL | METH_KEYWORDS with
defining_class argument added after self.
12.2. Estruturas comuns de objetos 281
The Python/C API, Release 3.13.7
Adicionado na versã o 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.
The function must have 2 parameters. Since the second parameter is unused, Py_UNUSED can be used to
prevent a compiler warning.
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.
These two constants are not used to indicate the calling convention but the binding when use with methods of classes.
These may not be used for functions defined for modules. At most one of these flags may be set for any given method.
METH_CLASS
The method will be passed the type object as the first parameter rather than an instance of the type. This is
used to create class methods, similar to what is created when using the classmethod() built-in function.
METH_STATIC
The method will be passed NULL as the first parameter rather than an instance of the type. This is used to
create static methods, similar to what is created when using the staticmethod() built-in function.
One other constant controls whether a method is loaded in place of another definition with the same method name.
METH_COEXIST
The method will be loaded in place of existing definitions. Without METH_COEXIST, the default is to skip
repeated definitions. Since slot wrappers are loaded before the method table, the existence of a sq_contains
slot, for example, would generate a wrapped method named __contains__() and preclude the loading of
a corresponding PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in
place of the wrapper object and will co-exist with the slot. This is helpful because calls to PyCFunctions are
optimized more than wrapper object calls.
PyObject *PyCMethod_New(PyMethodDef *ml, PyObject *self, PyObject *module, PyTypeObject *cls)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 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 também
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.
Adicionado na versã o 3.9.
PyObject *PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module)
Retorna valor: Nova referência. Parte da ABI Está vel. Equivalente a PyCMethod_New(ml, self,
module, NULL).
282 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
PyObject *PyCFunction_New(PyMethodDef *ml, PyObject *self)
Retorna valor: Nova referência. Parte da ABI Está vel desde a versão 3.4. Equivalente a PyCMethod_New(ml,
self, NULL, NULL).
12.2.3 Accessing attributes of extension types
type PyMemberDef
Parte da ABI Está vel (incluindo todos os membros). Structure which describes an attribute of a type which
corresponds to a C struct member. When defining a class, put a NULL-terminated array of these structures in
the tp_members slot.
Its fields are, in order:
const char *name
Name of the member. A NULL value marks the end of a PyMemberDef[] array.
The string should be static, no copy is made of it.
int type
The type of the member in the C struct. See Member types for the possible values.
Py_ssize_t offset
The offset in bytes that the member is located on the type’s object struct.
int flags
Zero or more of the Member flags, combined using bitwise OR.
const char *doc
The docstring, or NULL. The string should be static, no copy is made of it. Typically, it is defined using
PyDoc_STR.
By default (when flags is 0), members allow both read and write access. Use the Py_READONLY flag for
read-only access. Certain types, like Py_T_STRING , imply Py_READONLY . Only Py_T_OBJECT_EX (and
legacy T_OBJECT ) members can be deleted.
For heap-allocated types (created using PyType_FromSpec() or similar), PyMemberDef may contain a de-
finition 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.
Alterado na versã o 3.12: PyMemberDef is always available. Previously, it required including
"structmember.h".
PyObject *PyMember_GetOne(const char *obj_addr, struct PyMemberDef *m)
Parte da ABI Está vel. Get an attribute belonging to the object at address obj_addr. The attribute is described
by PyMemberDef m. Returns NULL on error.
Alterado na versã o 3.12: PyMember_GetOne is always available. Previously, it required including
"structmember.h".
12.2. Estruturas comuns de objetos 283
The Python/C API, Release 3.13.7
int PyMember_SetOne(char *obj_addr, struct PyMemberDef *m, PyObject *o)
Parte da ABI Está vel. Set an attribute belonging to the object at address obj_addr to object o. The attribute
to set is described by PyMemberDef m. Returns 0 if successful and a negative value on failure.
Alterado na versã o 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.
Alterado na versã o 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.
Alterado na versã o 3.12: The READONLY macro was renamed to Py_READONLY . The PY_AUDIT_READ macro was
renamed with the Py_ prefix. The new names are now always available. Previously, these required #include
"structmember.h". The header is still available and it provides the old names.
Member types
PyMemberDef.type can be one of the following macros corresponding to various C types. When the member is
accessed in Python, it will be converted to the equivalent Python type. When it is set from Python, it will be converted
back to the C type. If that is not possible, an exception such as TypeError or ValueError is raised.
Unless marked (D), attributes defined this way cannot be deleted using e.g. del or delattr().
284 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
Macro name Tipo em C Tipo em Python
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 (escrito como 0 ou 1) bool
Py_T_BOOL
const char* (*) str (RO)
Py_T_STRING
const char[] (*) str (RO)
Py_T_STRING_INPLACE
char (0-127) str (**)
Py_T_CHAR
PyObject* object (D)
Py_T_OBJECT_EX
(*): Zero-terminated, UTF8-encoded C string. With Py_T_STRING the C representation is a pointer;
with Py_T_STRING_INPLACE the string is stored directly in the structure.
12.2. Estruturas comuns de objetos 285
The Python/C API, Release 3.13.7
(**): String of length 1. Only ASCII is accepted.
(RO): implica Py_READONLY .
(D): pode ser deletado, neste caso o ponteiro é definido para NULL. Ler um ponteiro NULL levanta uma
exceçã o AttributeError.
Adicionado na versã o 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
Sempre None. Deve ser usado com Py_READONLY .
Defining Getters and Setters
type PyGetSetDef
Parte da ABI Está vel (incluindo todos os membros). Structure to define property-like access for a type. See
also description of the PyTypeObject.tp_getset slot.
const char *name
attribute name
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
optional docstring
void *closure
Optional user data pointer, providing additional data for getter and setter.
typedef PyObject *(*getter)(PyObject*, void*)
Parte da ABI Está vel. The get function takes one PyObject* parameter (the instance) and a user data pointer
(the associated closure):
It should return a new reference on success or NULL with a set exception on failure.
typedef int (*setter)(PyObject*, PyObject*, void*)
Parte da ABI Está vel. set functions take two PyObject* parameters (the instance and the value to be set)
and a user data pointer (the associated closure):
In case the attribute should be deleted the second parameter is NULL. Should return 0 on success or -1 with a
set exception on failure.
12.3 Type Object Structures
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.
Os objetos de tipo sã o bastante grandes em comparaçã o com a maioria dos tipos padrã o. A razã o para o tamanho é
que cada objeto de tipo armazena um grande nú mero de valores, principalmente indicadores de funçã o C, cada um
dos quais implementa uma pequena parte da funcionalidade do tipo. Os campos do objeto de tipo sã o examinados
em detalhes nesta seçã o. Os campos serã o descritos na ordem em que ocorrem na estrutura.
286 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
Alé m da referê ncia rá pida a seguir, a seçã o Exemplos fornece uma visã o geral do significado e uso de PyTypeObject.
12.3.1 Referências rápidas
“slots tp”
Slot de PyTypeOb- Tipo métodos/atributos especiais InfoPá gina 288, 2
jectPá gina 288, 1 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-slots %
tp_repr reprfunc __repr__ X X X
tp_as_number PyNumberMethods * sub-slots %
tp_as_sequence PySequenceMethods * sub-slots %
tp_as_mapping PyMappingMethods * 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 * sub-slots %
tp_flags unsigned long X X ?
tp_doc const char * __doc__ X X
tp_traverse traverseproc X G
tp_clear inquiry X G
tp_richcompare richcmpfunc __lt__, __le__, __eq__, __ne__, X G
__gt__, __ge__
(tp_weaklistoffset) Py_ssize_t X ?
tp_iter getiterfunc __iter__ X
tp_iternext iternextfunc __next__ X
tp_methods PyMethodDef [] X X
tp_members PyMemberDef [] X
tp_getset PyGetSetDef [] X X
tp_base PyTypeObject * __base__ X
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
continua na próxima página
12.3. Type Object Structures 287
The Python/C API, Release 3.13.7
Tabela 1 – continuação da página anterior
1
Slot de PyTypeObject Tipo métodos/atributos especiais Info2
O T D I
tp_vectorcall vectorcallfunc
[tp_watched] unsigned char
sub-slots
Slot Tipo special methods
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__
continua na próxima página
1 (): A slot name in parentheses indicates it is (effectively) deprecated.
<>: Names in angle brackets should be initially set to NULL and treated as read-only.
[]: Names in square brackets are for internal use only.
<R> (as a prefix) means the field is required (must be non-NULL).
2 Columns:
“O”: set on PyBaseObject_Type
“T”: set on PyType_Type
“D”: default (if slot is set to 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”: inheritance
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
Note that some slots are effectively inherited through the normal attribute lookup chain.
288 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
Tabela 2 – continuação da página anterior
Slot Tipo special methods
nb_inplace_and binaryfunc __iand__
nb_xor binaryfunc __xor__ __rxor__
nb_inplace_xor binaryfunc __ixor__
nb_or binaryfunc __or__ __ror__
nb_inplace_or binaryfunc __ior__
nb_int unaryfunc __int__
nb_reserved void *
nb_float unaryfunc __float__
nb_floor_divide binaryfunc __floordiv__
nb_inplace_floor_divide binaryfunc __ifloordiv__
nb_true_divide binaryfunc __truediv__
nb_inplace_true_divide binaryfunc __itruediv__
nb_index unaryfunc __index__
nb_matrix_multiply binaryfunc __matmul__ __rmat-
mul__
nb_inplace_matrix_multiply binaryfunc __imatmul__
mp_length lenfunc __len__
mp_subscript binaryfunc __getitem__
mp_ass_subscript objobjargproc __setitem__, __deli-
tem__
sq_length lenfunc __len__
sq_concat binaryfunc __add__
sq_repeat ssizeargfunc __mul__
sq_item ssizeargfunc __getitem__
sq_ass_item ssizeobjargproc __setitem__ __deli-
tem__
sq_contains objobjproc __contains__
sq_inplace_concat binaryfunc __iadd__
sq_inplace_repeat ssizeargfunc __imul__
bf_getbuffer getbufferproc() __buffer__
bf_releasebuffer releasebufferproc() __release_buffer__
12.3. Type Object Structures 289
The Python/C API, Release 3.13.7
slot typedefs
typedef Parameter Types Return Type
allocfunc PyObject *
PyTypeObject *
Py_ssize_t
destructor PyObject * void
freefunc void * void
traverseproc int
PyObject *
visitproc
void *
newfunc PyObject *
PyTypeObject *
PyObject *
PyObject *
initproc int
PyObject *
PyObject *
PyObject *
reprfunc PyObject * PyObject *
getattrfunc PyObject *
PyObject *
const char *
setattrfunc int
PyObject *
const char *
PyObject *
getattrofunc PyObject *
PyObject *
PyObject *
setattrofunc int
PyObject *
PyObject *
PyObject *
descrgetfunc PyObject *
PyObject *
PyObject *
PyObject *
descrsetfunc int
PyObject *
PyObject *
290 PyObject * Capítulo 12. Suporte a implementação de Objetos
hashfunc PyObject * Py_hash_t
richcmpfunc PyObject *
The Python/C API, Release 3.13.7
See Slot Type typedefs below for more detail.
12.3.2 PyTypeObject Definition
The structure definition for PyTypeObject can be found in Include/cpython/object.h. For convenience of
reference, this repeats the definition found there:
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;
(continua na pró xima pá gina)
12.3. Type Object Structures 291
The Python/C API, Release 3.13.7
(continuaçã o da 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 PyObject Slots
The type object structure extends the PyVarObject structure. The ob_size field is used for dynamic types (cre-
ated 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
Parte da ABI Está vel. 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.
Inheritance:
This field is not inherited by subtypes.
PyTypeObject *PyObject.ob_type
Parte da ABI Está vel. This is the type’s type, in other words its metatype. It is initialized by the argument to the
PyObject_HEAD_INIT macro, and its value should normally be &PyType_Type. However, for dynamically
loadable extension modules that must be usable on Windows (at least), the compiler complains that this is not
a valid initializer. Therefore, the convention is to pass NULL to the PyObject_HEAD_INIT macro and to
292 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
initialize this field explicitly at the start of the module’s initialization function, before doing anything else. This
is typically done like this:
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.
Inheritance:
This field is inherited by subtypes.
12.3.4 PyVarObject Slots
Py_ssize_t PyVarObject.ob_size
Parte da ABI Está vel. For statically allocated type objects, this should be initialized to zero. For dynamically
allocated type objects, this field has a special internal meaning.
This field should be accessed using the Py_SIZE() and Py_SET_SIZE() macros.
Inheritance:
This field is not inherited by subtypes.
12.3.5 PyTypeObject Slots
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".
For dynamically allocated type objects, this should just be the type name, and the module name explicitly stored
in the type dict as the value for key '__module__'.
For statically allocated type objects, the tp_name field should contain a dot. Everything before the last dot
is made accessible as the __module__ attribute, and everything after the last dot is made accessible as the
__name__ attribute.
If no dot is present, the entire tp_name field is made accessible as the __name__ attribute, and the
__module__ attribute is undefined (unless explicitly set in the dictionary, as explained above). This me-
ans your type will be impossible to pickle. Additionally, it will not be listed in module documentations created
with pydoc.
This field must not be NULL. It is the only required field in PyTypeObject() (other than potentially
tp_itemsize).
Inheritance:
This field is not inherited by subtypes.
Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize
These fields allow calculating the size in bytes of instances of the type.
There are two kinds of types: types with fixed-length instances have a zero tp_itemsize field, types
with variable-length instances have a non-zero tp_itemsize field. For a type with fixed-length instan-
ces, all instances have the same size, given in tp_basicsize. (Exceptions to this rule can be made using
PyUnstable_Object_GC_NewWithExtraData().)
12.3. Type Object Structures 293
The Python/C API, Release 3.13.7
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.
Functions like PyObject_NewVar() will take the value of N as an argument, and store in the instance’s
ob_size field. Note that the ob_size field may later be used for other purposes. For example, int instances
use the bits of ob_size in an implementation-defined way; the underlying storage and its size should be
accessed using PyLong_Export().
® Nota
The ob_size field should be accessed using the Py_SIZE() and Py_SET_SIZE() macros.
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 list type has fixed-length instances, yet those instances have a ob_size field. (As
with int, avoid reading lists’ ob_size directly. Call PyList_Size() instead.)
The tp_basicsize includes size needed for data of the type’s tp_base, plus any extra data needed by each
instance.
The correct way to set tp_basicsize is to use the sizeof operator on the struct used to declare the instance
layout. This struct must include the struct used to declare the base type. In other words, tp_basicsize must
be greater than or equal to the base’s tp_basicsize.
Since every type is a subtype of object, this struct must include PyObject or PyVarObject (depen-
ding on whether ob_size should be included). These are usually defined by the macro PyObject_HEAD
or PyObject_VAR_HEAD, respectively.
The basic size does not include the GC header size, as that header is not part of PyObject_HEAD.
For cases where struct used to declare the base type is unknown, see PyType_Spec.basicsize and
PyType_FromMetaclass().
Notes about alignment:
• tp_basicsize must be a multiple of _Alignof(PyObject). When using sizeof on a struct that
includes PyObject_HEAD, as recommended, the compiler ensures this. When not using a C struct,
or when using compiler extensions like __attribute__((packed)), it is up to you.
• If the variable items require a particular alignment, tp_basicsize and tp_itemsize must each be a
multiple of that alignment. For example, if a type’s variable part stores a double, it is your responsibility
that both fields are a multiple of _Alignof(double).
Inheritance:
These fields are inherited separately by subtypes. (That is, if the field is set to zero, PyType_Ready() will
copy the value from the base type, indicating that the instances do not need additional storage.)
If the base type has a non-zero tp_itemsize, it is generally not safe to set tp_itemsize to a different
non-zero value in a subtype (though this depends on the implementation of the base type).
destructor PyTypeObject.tp_dealloc
A pointer to the instance destructor function. This function must be defined unless the type guarantees that
its instances will never be deallocated (as is the case for the singletons None and Ellipsis). The function
signature is:
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
function should free all references which the instance owns, free all memory buffers owned by the instance
(using the freeing function corresponding to the allocation function used to allocate the buffer), and call the
type’s tp_free function. If the type is not subtypable (doesn’t have the Py_TPFLAGS_BASETYPE flag bit set),
it is permissible to call the object deallocator directly instead of via tp_free. The object deallocator should
be the one used to allocate the instance; this is normally PyObject_Del() if the instance was allocated
294 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
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);
}
Finally, if the type is heap allocated (Py_TPFLAGS_HEAPTYPE), the deallocator should release the owned
reference to its type object (via Py_DECREF()) after calling the type deallocator. In order to avoid dangling
pointers, the recommended way to achieve this is:
static void foo_dealloc(foo_object *self) {
PyTypeObject *tp = Py_TYPE(self);
// free references and buffers here
tp->tp_free(self);
Py_DECREF(tp);
}
Á Aviso
In a garbage collected Python, tp_dealloc may be called from any Python thread, not just the thread
which created the object (if the object becomes part of a refcount cycle, that cycle might be collected by a
garbage collection on any thread). This is not a problem for Python API calls, since the thread on which
tp_dealloc is called will own the Global Interpreter Lock (GIL). However, if the object being destroyed
in turn destroys objects from some other C or C++ library, care should be taken to ensure that destroying
those objects on the thread which called tp_dealloc will not violate any assumptions of the library.
Inheritance:
This field is inherited by subtypes.
Py_ssize_t PyTypeObject.tp_vectorcall_offset
An optional offset to a per-instance function that implements calling the object using the vectorcall protocol, a
more efficient alternative of the simpler 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.
Any class that sets Py_TPFLAGS_HAVE_VECTORCALL must also set tp_call and make sure its behaviour is
consistent with the vectorcallfunc function. This can be done by setting tp_call to PyVectorcall_Call().
Alterado na versã o 3.8: Before version 3.8, this slot was named tp_print. In Python 2.x, it was used for
printing to a file. In Python 3.0 to 3.7, it was unused.
Alterado na versã o 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.
Inheritance:
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.
12.3. Type Object Structures 295
The Python/C API, Release 3.13.7
getattrfunc PyTypeObject.tp_getattr
An optional pointer to the get-attribute-string function.
This field is deprecated. When it is defined, it should point to a function that acts the same as the tp_getattro
function, but taking a C string instead of a Python string object to give the attribute name.
Inheritance:
Group: tp_getattr, tp_getattro
This field is inherited by subtypes together with tp_getattro: a subtype inherits both tp_getattr and
tp_getattro from its base type when the subtype’s tp_getattr and tp_getattro are both NULL.
setattrfunc PyTypeObject.tp_setattr
An optional pointer to the function for setting and deleting attributes.
This field is deprecated. When it is defined, it should point to a function that acts the same as the tp_setattro
function, but taking a C string instead of a Python string object to give the attribute name.
Inheritance:
Group: tp_setattr, tp_setattro
This field is inherited by subtypes together with tp_setattro: a subtype inherits both tp_setattr and
tp_setattro from its base type when the subtype’s tp_setattr and tp_setattro are both NULL.
PyAsyncMethods *PyTypeObject.tp_as_async
Pointer to an additional structure that contains fields relevant only to objects which implement awaitable and
asynchronous iterator protocols at the C-level. See Async Object Structures for details.
Adicionado na versã o 3.5: Formerly known as tp_compare and tp_reserved.
Inheritance:
The tp_as_async field is not inherited, but the contained fields are inherited individually.
reprfunc PyTypeObject.tp_repr
An optional pointer to a function that implements the built-in function repr().
The signature is the same as for PyObject_Repr():
PyObject *tp_repr(PyObject *self);
The function must return a string or a Unicode object. Ideally, this function should return a string that, when
passed to eval(), given a suitable environment, returns an object with the same value. If this is not feasible,
it should return a string starting with '<' and ending with '>' from which both the type and the value of the
object can be deduced.
Inheritance:
This field is inherited by subtypes.
Padrão:
When this field is not set, a string of the form <%s object at %p> is returned, where %s is replaced by the
type name, and %p by the object’s memory address.
PyNumberMethods *PyTypeObject.tp_as_number
Pointer to an additional structure that contains fields relevant only to objects which implement the number
protocol. These fields are documented in Number Object Structures.
Inheritance:
The tp_as_number field is not inherited, but the contained fields are inherited individually.
296 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
PySequenceMethods *PyTypeObject.tp_as_sequence
Pointer to an additional structure that contains fields relevant only to objects which implement the sequence
protocol. These fields are documented in Sequence Object Structures.
Inheritance:
The tp_as_sequence field is not inherited, but the contained fields are inherited individually.
PyMappingMethods *PyTypeObject.tp_as_mapping
Pointer to an additional structure that contains fields relevant only to objects which implement the mapping
protocol. These fields are documented in Mapping Object Structures.
Inheritance:
The tp_as_mapping field is not inherited, but the contained fields are inherited individually.
hashfunc PyTypeObject.tp_hash
An optional pointer to a function that implements the built-in function hash().
The signature is the same as for PyObject_Hash():
Py_hash_t tp_hash(PyObject *);
The value -1 should not be returned as a normal return value; when an error occurs during the computation
of the hash value, the function should set an exception and return -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().
This field can be set explicitly to PyObject_HashNotImplemented() to block inheritance of the hash
method from a parent type. This is interpreted as the equivalent of __hash__ = None at the Python level,
causing isinstance(o, collections.Hashable) to correctly return False. Note that the converse is
also true - setting __hash__ = None on a class at the Python level will result in the tp_hash slot being set
to PyObject_HashNotImplemented().
Inheritance:
Group: tp_hash, tp_richcompare
This field is inherited by subtypes together with tp_richcompare: a subtype inherits both of
tp_richcompare and tp_hash, when the subtype’s tp_richcompare and tp_hash are both NULL.
Padrão:
PyBaseObject_Type uses PyObject_GenericHash().
ternaryfunc PyTypeObject.tp_call
An optional pointer to a function that implements calling the object. This should be NULL if the object is not
callable. The signature is the same as for PyObject_Call():
PyObject *tp_call(PyObject *self, PyObject *args, PyObject *kwargs);
Inheritance:
This field is inherited by subtypes.
reprfunc PyTypeObject.tp_str
An optional pointer to a function that implements the built-in operation str(). (Note that str is a type now,
and str() calls the constructor for that type. This constructor calls PyObject_Str() to do the actual work,
and PyObject_Str() will call this handler.)
The signature is the same as for PyObject_Str():
PyObject *tp_str(PyObject *self);
12.3. Type Object Structures 297
The Python/C API, Release 3.13.7
The function must return a string or a Unicode object. It should be a “friendly” string representation of the
object, as this is the representation that will be used, among other things, by the print() function.
Inheritance:
This field is inherited by subtypes.
Padrão:
When this field is not set, PyObject_Repr() is called to return a string representation.
getattrofunc PyTypeObject.tp_getattro
An optional pointer to the get-attribute function.
The signature is the same as for PyObject_GetAttr():
PyObject *tp_getattro(PyObject *self, PyObject *attr);
It is usually convenient to set this field to PyObject_GenericGetAttr(), which implements the normal
way of looking for object attributes.
Inheritance:
Group: tp_getattr, tp_getattro
This field is inherited by subtypes together with tp_getattr: a subtype inherits both tp_getattr and
tp_getattro from its base type when the subtype’s tp_getattr and tp_getattro are both NULL.
Padrão:
PyBaseObject_Type uses PyObject_GenericGetAttr().
setattrofunc PyTypeObject.tp_setattro
An optional pointer to the function for setting and deleting attributes.
The signature is the same as for PyObject_SetAttr():
int tp_setattro(PyObject *self, PyObject *attr, PyObject *value);
In addition, setting value to NULL to delete an attribute must be supported. It is usually convenient to set this
field to PyObject_GenericSetAttr(), which implements the normal way of setting object attributes.
Inheritance:
Group: tp_setattr, tp_setattro
This field is inherited by subtypes together with tp_setattr: a subtype inherits both tp_setattr and
tp_setattro from its base type when the subtype’s tp_setattr and tp_setattro are both NULL.
Padrão:
PyBaseObject_Type uses PyObject_GenericSetAttr().
PyBufferProcs *PyTypeObject.tp_as_buffer
Pointer to an additional structure that contains fields relevant only to objects which implement the buffer
interface. These fields are documented in Buffer Object Structures.
Inheritance:
The tp_as_buffer field is not inherited, but the contained fields are inherited individually.
unsigned long PyTypeObject.tp_flags
This field is a bit mask of various flags. Some flags indicate variant semantics for certain situations; others
are used to indicate that certain fields in the type object (or in the extension structures referenced via
tp_as_number, tp_as_sequence, tp_as_mapping , and tp_as_buffer) that were historically not
always present are valid; if such a flag bit is clear, the type fields it guards must not be accessed and must
be considered to have a zero or NULL value instead.
Inheritance:
298 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag
bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if
the extension structure is inherited, i.e. the base type’s value of the flag bit is copied into the subtype together
with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the
tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and
the tp_traverse and tp_clear fields in the subtype exist and have NULL values. .. XXX are most flag bits
really inherited individually?
Padrão:
PyBaseObject_Type uses Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE.
Bit Masks:
The following bit masks are currently defined; these can be ORed together using the | operator to form the
value of the tp_flags field. The macro PyType_HasFeature() takes a type and a flags value, tp and f,
and checks whether tp->tp_flags & f is non-zero.
Py_TPFLAGS_HEAPTYPE
This bit is set when the type object itself is allocated on the heap, for example, types created dynamically
using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference
to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when
an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the
instance’s ob_type gets INCREF’ed or DECREF’ed). Heap types should also support garbage collection
as they can form a reference cycle with their own module object.
Inheritance:
???
Py_TPFLAGS_BASETYPE
This bit is set when the type can be used as the base type of another type. If this bit is clear, the type
cannot be subtyped (similar to a “final” class in Java).
Inheritance:
???
Py_TPFLAGS_READY
This bit is set when the type object has been fully initialized by PyType_Ready().
Inheritance:
???
Py_TPFLAGS_READYING
This bit is set while PyType_Ready() is in the process of initializing the type object.
Inheritance:
???
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 Suporte
a Coleta Cíclica de Lixo. This bit also implies that the GC-related fields tp_traverse and tp_clear
are present in the type object.
Inheritance:
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. Type Object Structures 299
The Python/C API, Release 3.13.7
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.
Inheritance:
???
Py_TPFLAGS_METHOD_DESCRIPTOR
This bit indicates that objects behave like unbound methods.
If this flag is set for type(meth), then:
• meth.__get__(obj, cls)(*args, **kwds) (with obj not None) must be equivalent to
meth(obj, *args, **kwds).
• meth.__get__(None, cls)(*args, **kwds) must be equivalent to meth(*args,
**kwds).
This flag enables an optimization for typical method calls like obj.meth(): it avoids creating a tempo-
rary “bound method” object for obj.meth.
Adicionado na versã o 3.8.
Inheritance:
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 dicti-
onary 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().
Adicionado na versã o 3.12.
Inheritance:
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.
Adicionado na versã o 3.12.
Inheritance:
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.
Adicionado na versã o 3.12.
Inheritance:
This flag is inherited.
300 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
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
These flags are used by functions such as PyLong_Check() to quickly determine if a type is a subclass
of a built-in type; such specific checks are faster than a generic check, like PyObject_IsInstance().
Custom types that inherit from built-ins should have their tp_flags set appropriately, or the code that
interacts with such types will behave differently depending on what kind of check is used.
Py_TPFLAGS_HAVE_FINALIZE
This bit is set when the tp_finalize slot is present in the type structure.
Adicionado na versã o 3.4.
Descontinuado desde a versã o 3.8: This flag isn’t necessary anymore, as the interpreter assumes the
tp_finalize slot is always present in the type structure.
Py_TPFLAGS_HAVE_VECTORCALL
This bit is set when the class implements the vectorcall protocol. See tp_vectorcall_offset for
details.
Inheritance:
This bit is inherited if tp_call is also inherited.
Adicionado na versã o 3.9.
Alterado na versã o 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
This bit is set for type objects that are immutable: type attributes cannot be set nor deleted.
PyType_Ready() automatically applies this flag to static types.
Inheritance:
This flag is not inherited.
Adicionado na versã o 3.10.
Py_TPFLAGS_DISALLOW_INSTANTIATION
Disallow creating instances of the type: set tp_new to NULL and don’t create the __new__ key in the
type dictionary.
The flag must be set before creating the type, not after. For example, it must be set before
PyType_Ready() is called on the type.
The flag is set automatically on static types if tp_base is NULL or &PyBaseObject_Type and tp_new
is NULL.
Inheritance:
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).
12.3. Type Object Structures 301
The Python/C API, Release 3.13.7
® 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.
Adicionado na versã o 3.10.
Py_TPFLAGS_MAPPING
This bit indicates that instances of the class may match mapping patterns when used as the subject of
a match block. It is automatically set when registering or subclassing collections.abc.Mapping,
and unset when registering collections.abc.Sequence.
® Nota
Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error to ena-
ble both flags simultaneously.
Inheritance:
This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.
µ Ver também
PEP 634 – Structural Pattern Matching: Specification
Adicionado na versã o 3.10.
Py_TPFLAGS_SEQUENCE
This bit indicates that instances of the class may match sequence patterns when used as the subject of
a match block. It is automatically set when registering or subclassing collections.abc.Sequence,
and unset when registering collections.abc.Mapping.
® Nota
Py_TPFLAGS_MAPPING and Py_TPFLAGS_SEQUENCE are mutually exclusive; it is an error to ena-
ble both flags simultaneously.
Inheritance:
This flag is inherited by types that do not already set Py_TPFLAGS_MAPPING .
µ Ver também
PEP 634 – Structural Pattern Matching: Specification
Adicionado na versã o 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()
Á Aviso
This flag is present in header files, but is not be used. It will be removed in a future version of CPython
302 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
const char *PyTypeObject.tp_doc
An optional pointer to a NUL-terminated C string giving the docstring for this type object. This is exposed as
the __doc__ attribute on the type and instances of the type.
Inheritance:
This field is not inherited by subtypes.
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);
More information about Python’s garbage collection scheme can be found in section Suporte a Coleta Cíclica
de Lixo.
The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical implemen-
tation 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;
}
Note that Py_VISIT() is called only on those members that can participate in reference cycles. Although
there is also a self->key member, it can only be NULL or a Python string and therefore cannot be part of a
reference cycle.
On the other hand, even if you know a member can never be part of a cycle, as a debugging aid you may want
to visit it anyway just so the gc module’s get_referents() function will include it.
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 conditional:
#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);
Á Aviso
When implementing tp_traverse, only the members that the instance owns (by having strong references
to them) must be visited. For instance, if an object supports weak references via the tp_weaklist slot,
the pointer supporting the linked list (what tp_weaklist points to) must not be visited as the instance does
not directly own the weak references to itself (the weakreference list is there to support the weak reference
12.3. Type Object Structures 303
The Python/C API, Release 3.13.7
machinery, but the instance has no strong reference to the elements inside it, as they are allowed to be
removed even if the instance is still alive).
Note that Py_VISIT() requires the visit and arg parameters to local_traverse() to have these specific
names; don’t name them just anything.
Instances of heap-allocated types hold a reference to their type. Their traversal function must therefore either
visit Py_TYPE(self), or delegate this responsibility by calling tp_traverse of another heap-allocated type
(such as a heap-allocated superclass). If they do not, the type object may not be garbage-collected.
Alterado na versã o 3.9: Heap-allocated types are expected to visit Py_TYPE(self) in tp_traverse. In
earlier versions of Python, due to bug 40217, doing this may lead to crashes in subclasses.
Inheritance:
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 *);
The tp_clear member function is used to break reference cycles in cyclic garbage detected by the garbage
collector. Taken together, all tp_clear functions in the system must combine to break all reference cycles.
This is subtle, and if in any doubt supply a tp_clear function. For example, the tuple type does not implement
a tp_clear function, because it’s possible to prove that no reference cycle can be composed entirely of tuples.
Therefore the tp_clear functions of other types must be sufficient to break any cycle containing a tuple. This
isn’t immediately obvious, and there’s rarely a good reason to avoid implementing tp_clear.
Implementations of tp_clear should drop the instance’s references to those of its members that may be
Python objects, and set its pointers to those members to NULL, as in the following example:
static int
local_clear(localobject *self)
{
Py_CLEAR(self->key);
Py_CLEAR(self->args);
Py_CLEAR(self->kw);
Py_CLEAR(self->dict);
return 0;
}
The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the contained
object must not be released (via Py_DECREF()) until after the pointer to the contained object is set to NULL.
This is because releasing the reference may cause the contained object to become trash, triggering a chain of
reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks,
associated with the contained object). If it’s possible for such code to reference self again, it’s important that
the pointer to the contained object be NULL at that time, so that self knows the contained object can no longer
be used. The Py_CLEAR() macro performs the operations in a safe order.
If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, the traverse function must call
PyObject_ClearManagedDict() like this:
PyObject_ClearManagedDict((PyObject*)self);
Note that tp_clear is not always called before an instance is deallocated. For example, when reference
counting is enough to determine that an object is no longer used, the cyclic garbage collector is not involved
304 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
and tp_dealloc is called directly.
Because the goal of tp_clear functions is to break reference cycles, it’s not necessary to clear contained
objects like Python strings or Python integers, which can’t participate in reference cycles. On the other hand, it
may be convenient to clear all contained Python objects, and write the type’s tp_dealloc function to invoke
tp_clear.
More information about Python’s garbage collection scheme can be found in section Suporte a Coleta Cíclica
de Lixo.
Inheritance:
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
An optional pointer to the rich comparison function, whose signature is:
PyObject *tp_richcompare(PyObject *self, PyObject *other, int op);
The first parameter is guaranteed to be an instance of the type that is defined by PyTypeObject.
The function should return the result of the comparison (usually Py_True or Py_False). If the comparison
is undefined, it must return Py_NotImplemented, if another error occurred it must return NULL and set an
exception condition.
The following constants are defined to be used as the third argument for tp_richcompare and for
PyObject_RichCompare():
Constante Comparação
<
Py_LT
<=
Py_LE
==
Py_EQ
!=
Py_NE
>
Py_GT
>=
Py_GE
The following macro is defined to ease writing rich comparison functions:
Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)
Return Py_True or Py_False from the function, depending on the result of a comparison. VAL_A
and VAL_B must be orderable by C comparison operators (for example, they may be C ints or floats).
The third argument specifies the requested operation, as for PyObject_RichCompare().
The returned value is a new strong reference.
On error, sets an exception and returns NULL from the function.
Adicionado na versã o 3.7.
12.3. Type Object Structures 305
The Python/C API, Release 3.13.7
Inheritance:
Group: tp_hash, tp_richcompare
This field is inherited by subtypes together with tp_hash: a subtype inherits tp_richcompare and tp_hash
when the subtype’s tp_richcompare and tp_hash are both NULL.
Padrão:
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.
Do not confuse this field with tp_weaklist; that is the list head for weak references to the type object itself.
It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_weaklistoffset.
Inheritance:
This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means
that the subtype uses a different weak reference list head than the base type. Since the list head is always found
via tp_weaklistoffset, this should not be a problem.
Padrão:
If the Py_TPFLAGS_MANAGED_WEAKREF bit is set in the tp_flags 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).
This function has the same signature as PyObject_GetIter():
PyObject *tp_iter(PyObject *self);
Inheritance:
This field is inherited by subtypes.
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);
When the iterator is exhausted, it must return NULL; a StopIteration exception may or may not be set.
When another error occurs, it must return NULL too. Its presence signals that the instances of this type are
iterators.
Iterator types should also define the tp_iter function, and that function should return the iterator instance
itself (not a new iterator instance).
This function has the same signature as PyIter_Next().
Inheritance:
This field is inherited by subtypes.
306 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
struct PyMethodDef *PyTypeObject.tp_methods
An optional pointer to a static NULL-terminated array of PyMethodDef structures, declaring regular methods
of this type.
For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a method
descriptor.
Inheritance:
This field is not inherited by subtypes (methods are inherited through a different mechanism).
struct PyMemberDef *PyTypeObject.tp_members
An optional pointer to a static NULL-terminated array of PyMemberDef structures, declaring regular data
members (fields or slots) of instances of this type.
For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a member
descriptor.
Inheritance:
This field is not inherited by subtypes (members are inherited through a different mechanism).
struct PyGetSetDef *PyTypeObject.tp_getset
An optional pointer to a static NULL-terminated array of PyGetSetDef structures, declaring computed attri-
butes of instances of this type.
For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a getset
descriptor.
Inheritance:
This field is not inherited by subtypes (computed attributes are inherited through a different mechanism).
PyTypeObject *PyTypeObject.tp_base
An optional pointer to a base type from which type properties are inherited. At this level, only single inheritance
is supported; multiple inheritance require dynamically creating a type object by calling the metatype.
® Nota
Slot initialization is subject to the rules of initializing globals. C99 requires the initializers to be “address
constants”. Function designators like PyType_GenericNew(), with implicit conversion to a pointer, are
valid C99 address constants.
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.
Consequently, tp_base should be set in the extension module’s init function.
Inheritance:
This field is not inherited by subtypes (obviously).
Padrão:
This field defaults to &PyBaseObject_Type (which to Python programmers is known as the type object).
PyObject *PyTypeObject.tp_dict
The type’s dictionary is stored here by 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.
12.3. Type Object Structures 307
The Python/C API, Release 3.13.7
Some types may not store their dictionary in this slot. Use PyType_GetDict() to retrieve the dictionary for
an arbitrary type.
Alterado na versã o 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.
Inheritance:
This field is not inherited by subtypes (though the attributes defined in here are inherited through a different
mechanism).
Padrão:
If this field is NULL, PyType_Ready() will assign a new dictionary to it.
Á Aviso
It is not safe to use PyDict_SetItem() on or otherwise modify tp_dict with the dictionary C-API.
descrgetfunc PyTypeObject.tp_descr_get
An optional pointer to a “descriptor get” function.
A assinatura da funçã o é :
PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
Inheritance:
This field is inherited by subtypes.
descrsetfunc PyTypeObject.tp_descr_set
An optional pointer to a function for setting and deleting a descriptor’s value.
A assinatura da funçã o é :
int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);
The value argument is set to NULL to delete the value.
Inheritance:
This field is inherited by subtypes.
Py_ssize_t PyTypeObject.tp_dictoffset
While this field is still supported, Py_TPFLAGS_MANAGED_DICT should be used instead, if at all possible.
If the instances of this type have a dictionary containing instance variables, this field is non-zero and
contains the offset in the instances of the type of the instance variable dictionary; this offset is used by
PyObject_GenericGetAttr().
Do not confuse this field with tp_dict; that is the dictionary for attributes of the type object itself.
The value specifies the offset of the dictionary from the start of the instance structure.
The tp_dictoffset should be regarded as write-only. To get the pointer to the dictionary call
PyObject_GenericGetDict(). Calling PyObject_GenericGetDict() may need to allocate memory
for the dictionary, so it is may be more efficient to call PyObject_GetAttr() when accessing an attribute
on the object.
It is an error to set both the Py_TPFLAGS_MANAGED_DICT bit and tp_dictoffset.
Inheritance:
This field is inherited by subtypes. A subtype should not override this offset; doing so could be un-
safe, if C code tries to access the dictionary at the previous offset. To properly support inheritance, use
Py_TPFLAGS_MANAGED_DICT .
308 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
Padrão:
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.
initproc PyTypeObject.tp_init
An optional pointer to an instance initialization function.
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.
A assinatura da funçã o é :
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__().
The tp_init function, if not NULL, is called when an instance is created normally by calling its type, after
the type’s tp_new function has returned an instance of the type. If the tp_new function returns an instance
of some other type that is not a subtype of the original type, no tp_init function is called; if tp_new returns
an instance of a subtype of the original type, the subtype’s tp_init is called.
Returns 0 on success, -1 and sets an exception on error.
Inheritance:
This field is inherited by subtypes.
Padrão:
For static types this field does not have a default.
allocfunc PyTypeObject.tp_alloc
An optional pointer to an instance allocation function.
A assinatura da funçã o é :
PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems);
Inheritance:
This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement).
Padrão:
For dynamic subtypes, this field is always set to PyType_GenericAlloc(), to force a standard heap alloca-
tion strategy.
For static subtypes, PyBaseObject_Type uses PyType_GenericAlloc(). That is the recommended value
for all statically defined types.
newfunc PyTypeObject.tp_new
An optional pointer to an instance creation function.
A assinatura da funçã o é :
PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds);
The subtype argument is the type of the object being created; the args and kwds arguments represent positional
and keyword arguments of the call to the type. Note that subtype doesn’t have to equal the type whose tp_new
function is called; it may be a subtype of that type (but not an unrelated type).
The tp_new function should call subtype->tp_alloc(subtype, nitems) to allocate space for the ob-
ject, and then do only as much further initialization as is absolutely necessary. Initialization that can safely be
12.3. Type Object Structures 309
The Python/C API, Release 3.13.7
ignored or repeated should be placed in the tp_init handler. A good rule of thumb is that for immutable
types, all initialization should take place in tp_new , while for mutable types, most initialization should be
deferred to tp_init.
Set the Py_TPFLAGS_DISALLOW_INSTANTIATION flag to disallow creating instances of the type in Python.
Inheritance:
This field is inherited by subtypes, except it is not inherited by static types whose tp_base is NULL or
&PyBaseObject_Type.
Padrão:
For static types this field has no default. This means if the slot is defined as NULL, the type cannot be called to
create new instances; presumably there is some other way to create instances, like a factory function.
freefunc PyTypeObject.tp_free
An optional pointer to an instance deallocation function. Its signature is:
void tp_free(void *self);
An initializer that is compatible with this signature is PyObject_Free().
Inheritance:
This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement)
Padrão:
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
An optional pointer to a function called by the garbage collector.
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);
(The only example of this are types themselves. The metatype, PyType_Type, defines this function to distin-
guish between statically and dynamically allocated types.)
Inheritance:
This field is inherited by subtypes.
Padrão:
This slot has no default. If this field is NULL, Py_TPFLAGS_HAVE_GC is used as the functional equivalent.
PyObject *PyTypeObject.tp_bases
Tuple of base types.
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.
310 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
Á Aviso
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.
Inheritance:
This field is not inherited.
PyObject *PyTypeObject.tp_mro
Tuple containing the expanded set of base types, starting with the type itself and ending with object, in
Method Resolution Order.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
Inheritance:
This field is not inherited; it is calculated fresh by PyType_Ready().
PyObject *PyTypeObject.tp_cache
Unused. Internal use only.
Inheritance:
This field is not inherited.
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__().
Alterado na versã o 3.12: For some types, this field does not hold a valid PyObject*. The type was changed
to void* to indicate this.
Inheritance:
This field is not inherited.
PyObject *PyTypeObject.tp_weaklist
Weak reference list head, for weak references to this type object. Not inherited. Internal use only.
Alterado na versã o 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.
Inheritance:
This field is not inherited.
destructor PyTypeObject.tp_del
This field is deprecated. Use tp_finalize instead.
unsigned int PyTypeObject.tp_version_tag
Used to index into the method cache. Internal use only.
Inheritance:
This field is not inherited.
destructor PyTypeObject.tp_finalize
An optional pointer to an instance finalization function. Its signature is:
void tp_finalize(PyObject *self);
12.3. Type Object Structures 311
The Python/C API, Release 3.13.7
If tp_finalize is set, the interpreter calls it once when finalizing an instance. It is called either from the
garbage collector (if the instance is part of an isolated reference cycle) or just before the object is deallocated.
Either way, it is guaranteed to be called before attempting to break reference cycles, ensuring that it finds the
object in a sane state.
tp_finalize should not mutate the current exception status; therefore, a recommended way to write a non-
-trivial finalizer is:
static void
local_finalize(PyObject *self)
{
/* Save the current exception, if any. */
PyObject *exc = PyErr_GetRaisedException();
/* ... */
/* Restore the saved exception. */
PyErr_SetRaisedException(exc);
}
Inheritance:
This field is inherited by subtypes.
Adicionado na versã o 3.4.
Alterado na versã o 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 também
“Finalizaçã o 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.
Inheritance:
This field is never inherited.
Adicionado na versã o 3.9: (the field exists since 3.8 but it’s only used since 3.9)
unsigned char PyTypeObject.tp_watched
Internal. Do not use.
Adicionado na versã o 3.12.
12.3.6 Static Types
Traditionally, types defined in C code are static, that is, a static PyTypeObject structure is defined directly in code
and initialized using PyType_Ready().
This results in types that are limited relative to types defined in Python:
• Static types are limited to one base, i.e. they cannot use multiple inheritance.
• Static type objects (but not necessarily their instances) are immutable. It is not possible to add or modify the
type object’s attributes from Python.
• Static type objects are shared across sub-interpreters, so they should not include any subinterpreter-specific
state.
312 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
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 no heap
An alternative to static types is heap-allocated types, or heap types for short, which correspond closely to classes
created by Python’s class statement. Heap types have the Py_TPFLAGS_HEAPTYPE flag set.
This is done by filling a PyType_Spec structure and calling PyType_FromSpec(),
PyType_FromSpecWithBases(), PyType_FromModuleAndSpec(), or PyType_FromMetaclass().
12.3.8 Number Object Structures
type PyNumberMethods
This structure holds pointers to the functions which an object uses to implement the number protocol. Each
function is used by the function of similar name documented in the Protocolo de número section.
Here is the structure definition:
typedef struct {
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;
unaryfunc nb_negative;
unaryfunc nb_positive;
unaryfunc nb_absolute;
inquiry nb_bool;
unaryfunc nb_invert;
binaryfunc nb_lshift;
binaryfunc nb_rshift;
binaryfunc nb_and;
binaryfunc nb_xor;
binaryfunc nb_or;
unaryfunc nb_int;
void *nb_reserved;
unaryfunc nb_float;
binaryfunc nb_inplace_add;
binaryfunc nb_inplace_subtract;
binaryfunc nb_inplace_multiply;
binaryfunc nb_inplace_remainder;
ternaryfunc nb_inplace_power;
binaryfunc nb_inplace_lshift;
binaryfunc nb_inplace_rshift;
binaryfunc nb_inplace_and;
binaryfunc nb_inplace_xor;
binaryfunc nb_inplace_or;
binaryfunc nb_floor_divide;
binaryfunc nb_true_divide;
binaryfunc nb_inplace_floor_divide;
binaryfunc nb_inplace_true_divide;
unaryfunc nb_index;
(continua na pró xima pá gina)
12.3. Type Object Structures 313
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
binaryfunc nb_matrix_multiply;
binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;
® Nota
Binary and ternary functions must check the type of all their operands, and implement the necessary con-
versions (at least one of the operands is an instance of the defined type). If the operation is not defined
for the given operands, binary and ternary functions must return Py_NotImplemented, if another error
occurred they must return NULL and set an exception.
® Nota
The nb_reserved field should always be NULL. It was previously called nb_long, and was renamed in
Python 3.0.1.
binaryfunc PyNumberMethods.nb_add
binaryfunc PyNumberMethods.nb_subtract
binaryfunc PyNumberMethods.nb_multiply
binaryfunc PyNumberMethods.nb_remainder
binaryfunc PyNumberMethods.nb_divmod
ternaryfunc PyNumberMethods.nb_power
unaryfunc PyNumberMethods.nb_negative
unaryfunc PyNumberMethods.nb_positive
unaryfunc PyNumberMethods.nb_absolute
inquiry PyNumberMethods.nb_bool
unaryfunc PyNumberMethods.nb_invert
binaryfunc PyNumberMethods.nb_lshift
binaryfunc PyNumberMethods.nb_rshift
binaryfunc PyNumberMethods.nb_and
binaryfunc PyNumberMethods.nb_xor
binaryfunc PyNumberMethods.nb_or
unaryfunc PyNumberMethods.nb_int
void *PyNumberMethods.nb_reserved
unaryfunc PyNumberMethods.nb_float
binaryfunc PyNumberMethods.nb_inplace_add
binaryfunc PyNumberMethods.nb_inplace_subtract
314 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
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.3.9 Mapping Object Structures
type PyMappingMethods
This structure holds pointers to the functions which an object uses to implement the mapping protocol. It has
three members:
lenfunc PyMappingMethods.mp_length
This function is used by PyMapping_Size() and PyObject_Size(), and has the same signature. This slot
may be set to NULL if the object has no defined length.
binaryfunc PyMappingMethods.mp_subscript
This function is used by PyObject_GetItem() and PySequence_GetSlice(), and has the same signature
as PyObject_GetItem(). This slot must be filled for the PyMapping_Check() function to return 1, it can
be NULL otherwise.
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.3.10 Sequence Object Structures
type PySequenceMethods
This structure holds pointers to the functions which an object uses to implement the sequence protocol.
lenfunc PySequenceMethods.sq_length
This function is used by PySequence_Size() and PyObject_Size(), and has the same signature. It is
also used for handling negative indices via the sq_item and the sq_ass_item slots.
binaryfunc PySequenceMethods.sq_concat
This function is used by PySequence_Concat() and has the same signature. It is also used by the + operator,
after trying the numeric addition via the nb_add slot.
12.3. Type Object Structures 315
The Python/C API, Release 3.13.7
ssizeargfunc PySequenceMethods.sq_repeat
This function is used by PySequence_Repeat() and has the same signature. It is also used by the * operator,
after trying numeric multiplication via the nb_multiply slot.
ssizeargfunc PySequenceMethods.sq_item
This function is used by PySequence_GetItem() and has the same signature. It is also used by
PyObject_GetItem(), after trying the subscription via the mp_subscript slot. This slot must be filled for
the PySequence_Check() function to return 1, it can be NULL otherwise.
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
This function is used by PySequence_SetItem() and has the same signature. It is also used by
PyObject_SetItem() and PyObject_DelItem(), after trying the item assignment and deletion via the
mp_ass_subscript slot. This slot may be left to NULL if the object does not support item assignment and
deletion.
objobjproc PySequenceMethods.sq_contains
This function may be used by PySequence_Contains() and has the same signature. This slot may be left
to NULL, in this case PySequence_Contains() simply traverses the sequence until it finds a match.
binaryfunc PySequenceMethods.sq_inplace_concat
This function is used by PySequence_InPlaceConcat() and has the same signature. It should modify its
first operand, and return it. This slot may be left to NULL, in this case PySequence_InPlaceConcat() will
fall back to PySequence_Concat(). It is also used by the augmented assignment +=, after trying numeric
in-place addition via the nb_inplace_add slot.
ssizeargfunc PySequenceMethods.sq_inplace_repeat
This function is used by PySequence_InPlaceRepeat() and has the same signature. It should modify its
first operand, and return it. This slot may be left to NULL, in this case PySequence_InPlaceRepeat() will
fall back to PySequence_Repeat(). It is also used by the augmented assignment *=, after trying numeric
in-place multiplication via the nb_inplace_multiply slot.
12.3.11 Buffer Object Structures
type PyBufferProcs
This structure holds pointers to the functions required by the Buffer protocol. The protocol defines how an
exporter object can expose its internal data to consumer objects.
getbufferproc PyBufferProcs.bf_getbuffer
The signature of this function is:
int (PyObject *exporter, Py_buffer *view, int flags);
Handle a request to exporter to fill in view as specified by flags. Except for point (3), an implementation of this
function MUST take these steps:
(1) Check if the request can be met. If not, raise BufferError, set view->obj to NULL and return -1.
(2) Fill in the requested fields.
(3) Increment an internal counter for the number of exports.
(4) Set view->obj to exporter and increment view->obj.
(5) Retorna 0.
If exporter is part of a chain or tree of buffer providers, two main schemes can be used:
• Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference
to itself.
316 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
• 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.
The individual fields of view are described in section Buffer structure, the rules how an exporter must react to
specific requests are in section Buffer request types.
All memory pointed to in the Py_buffer structure belongs to the exporter and must remain valid until there are
no consumers left. format, shape, strides, suboffsets and internal are read-only for the consumer.
PyBuffer_FillInfo() provides an easy way of exposing a simple bytes buffer while dealing correctly with
all request types.
PyObject_GetBuffer() is the interface for the consumer that wraps this function.
releasebufferproc PyBufferProcs.bf_releasebuffer
The signature of this function is:
void (PyObject *exporter, Py_buffer *view);
Handle a request to release the resources of the buffer. If no resources need to be released, PyBufferProcs.
bf_releasebuffer may be NULL. Otherwise, a standard implementation of this function will take these
optional steps:
(1) Decrement an internal counter for the number of exports.
(2) If the counter is 0, free all memory associated with view.
The exporter MUST use the internal field to keep track of buffer-specific resources. This field is guaranteed
to remain constant, while a consumer MAY pass a copy of the original buffer as the view argument.
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() is the interface for the consumer that wraps this function.
12.3.12 Async Object Structures
Adicionado na versã o 3.5.
type PyAsyncMethods
This structure holds pointers to the functions required to implement awaitable and asynchronous iterator ob-
jects.
Here is the structure definition:
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
sendfunc am_send;
} PyAsyncMethods;
unaryfunc PyAsyncMethods.am_await
The signature of this function is:
PyObject *am_await(PyObject *self);
The returned object must be an iterator, i.e. PyIter_Check() must return 1 for it.
This slot may be set to NULL if an object is not an awaitable.
unaryfunc PyAsyncMethods.am_aiter
The signature of this function is:
12.3. Type Object Structures 317
The Python/C API, Release 3.13.7
PyObject *am_aiter(PyObject *self);
Must return an asynchronous iterator object. See __anext__() for details.
This slot may be set to NULL if an object does not implement asynchronous iteration protocol.
unaryfunc PyAsyncMethods.am_anext
The signature of this function is:
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
The signature of this function is:
PySendResult am_send(PyObject *self, PyObject *arg, PyObject **result);
See PyIter_Send() for details. This slot may be set to NULL.
Adicionado na versã o 3.10.
12.3.13 Slot Type typedefs
typedef PyObject *(*allocfunc)(PyTypeObject *cls, Py_ssize_t nitems)
Parte da ABI Está vel. The purpose of this function is to separate memory allocation from memory initiali-
zation. 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.
This function should not do any other instance initialization, not even to allocate additional memory; that should
be done by tp_new .
typedef void (*destructor)(PyObject*)
Parte da ABI Está vel.
typedef void (*freefunc)(void*)
See tp_free.
typedef PyObject *(*newfunc)(PyTypeObject*, PyObject*, PyObject*)
Parte da ABI Está vel. See tp_new .
typedef int (*initproc)(PyObject*, PyObject*, PyObject*)
Parte da ABI Está vel. See tp_init.
typedef PyObject *(*reprfunc)(PyObject*)
Parte da ABI Está vel. See tp_repr.
typedef PyObject *(*getattrfunc)(PyObject *self, char *attr)
Parte da ABI Está vel. Return the value of the named attribute for the object.
typedef int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
Parte da ABI Está vel. Set the value of the named attribute for the object. The value argument is set to NULL
to delete the attribute.
typedef PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)
Parte da ABI Está vel. Return the value of the named attribute for the object.
See tp_getattro.
318 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
typedef int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)
Parte da ABI Está vel. Set the value of the named attribute for the object. The value argument is set to NULL
to delete the attribute.
See tp_setattro.
typedef PyObject *(*descrgetfunc)(PyObject*, PyObject*, PyObject*)
Parte da ABI Está vel. See tp_descr_get.
typedef int (*descrsetfunc)(PyObject*, PyObject*, PyObject*)
Parte da ABI Está vel. See tp_descr_set.
typedef Py_hash_t (*hashfunc)(PyObject*)
Parte da ABI Está vel. See tp_hash.
typedef PyObject *(*richcmpfunc)(PyObject*, PyObject*, int)
Parte da ABI Está vel. See tp_richcompare.
typedef PyObject *(*getiterfunc)(PyObject*)
Parte da ABI Está vel. See tp_iter.
typedef PyObject *(*iternextfunc)(PyObject*)
Parte da ABI Está vel. See tp_iternext.
typedef Py_ssize_t (*lenfunc)(PyObject*)
Parte da ABI Está vel.
typedef int (*getbufferproc)(PyObject*, Py_buffer*, int)
Parte da ABI Está vel desde a versão 3.12.
typedef void (*releasebufferproc)(PyObject*, Py_buffer*)
Parte da ABI Está vel desde a versão 3.12.
typedef PyObject *(*unaryfunc)(PyObject*)
Parte da ABI Está vel.
typedef PyObject *(*binaryfunc)(PyObject*, PyObject*)
Parte da ABI Está vel.
typedef PySendResult (*sendfunc)(PyObject*, PyObject*, PyObject**)
See am_send.
typedef PyObject *(*ternaryfunc)(PyObject*, PyObject*, PyObject*)
Parte da ABI Está vel.
typedef PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)
Parte da ABI Está vel.
typedef int (*ssizeobjargproc)(PyObject*, Py_ssize_t, PyObject*)
Parte da ABI Está vel.
typedef int (*objobjproc)(PyObject*, PyObject*)
Parte da ABI Está vel.
typedef int (*objobjargproc)(PyObject*, PyObject*, PyObject*)
Parte da ABI Está vel.
12.3.14 Exemplos
The following are simple examples of Python type definitions. They include common usage you may encounter.
Some demonstrate tricky corner cases. For more examples, practical info, and a tutorial, see defining-new-types and
new-types-topics.
A basic static type:
12.3. Type Object Structures 319
The Python/C API, Release 3.13.7
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,
};
You may also find older code (especially in the CPython code base) with a more verbose initializer:
static PyTypeObject MyObject_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"mymod.MyObject", /* tp_name */
sizeof(MyObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)myobj_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
(reprfunc)myobj_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
PyDoc_STR("My objects"), /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
myobj_new, /* tp_new */
};
320 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
A type that supports weakrefs, instance dicts, and 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,
};
The simplest static type with fixed-length instances:
typedef struct {
PyObject_HEAD
} MyObject;
static PyTypeObject MyObject_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "mymod.MyObject",
};
The simplest static type with variable-length instances:
typedef struct {
PyObject_VAR_HEAD
(continua na pró xima pá gina)
12.3. Type Object Structures 321
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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.4 Suporte a Coleta Cíclica de Lixo
O suporte do Python para detectar e coletar o lixo, que envolve referencias circulares, requer suporte dos tipos de
objetos que sã o “contê iners” para outros objetos que també m podem ser contê iners. Tipos que nã o armazenam
referê ncias a outros tipos de objetos, ou que apenas armazenam referê ncias a tipos atô micos (como nú meros ou
strings), nã o precisam fornecer nenhum suporte explicito para coleta de lixo.
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
Objetos com esse tipo de sinalizador definido devem estar em conformidade com regras documentadas aqui.
Por conveniê ncia esses objetos serã o referenciados como objetos de contê iner.
Construtores para tipos de contê iner devem obedecer a duas regras:
1. The memory for the object must be allocated using PyObject_GC_New or PyObject_GC_NewVar.
2. Uma vez que todos os campos que podem conter referê ncias a outros containers foram inicializados, deve-se
chamar PyObject_GC_Track().
Da mesma forma, o desalocador para o objeto deve estar em conformidade com regras semelhantes:
1. Antes que os campos que fazer referê ncia a outros containers sejam invalidados, PyObject_GC_UnTrack()
deve ser chamado.
2. A memó ria destinada ao objeto deve ser desalocada usando PyObject_GC_Del().
Á Aviso
If a type adds the Py_TPFLAGS_HAVE_GC, then it must implement at least a tp_traverse handler or
explicitly use one from its subclass or subclasses.
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 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)
322 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
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.
Á Aviso
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.
Adicionado na versã o 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)
Parte da ABI Está vel. Adds the object op to the set of container objects tracked by the collector. The collector
can run at unexpected times so objects must be valid while being tracked. This should be called once all the
fields followed by the tp_traverse handler become valid, usually near the end of the constructor.
int PyObject_IS_GC(PyObject *obj)
Returns non-zero if the object implements the garbage collector protocol, otherwise returns 0.
The object cannot be tracked by the garbage collector if this function returns 0.
int PyObject_GC_IsTracked(PyObject *op)
Parte da ABI Está vel desde a versão 3.9. Returns 1 if the object type of op implements the GC protocol and
op is being currently tracked by the garbage collector and 0 otherwise.
This is analogous to the Python function gc.is_tracked().
Adicionado na versã o 3.9.
int PyObject_GC_IsFinalized(PyObject *op)
Parte da ABI Está vel desde a versão 3.9. Returns 1 if the object type of op implements the GC protocol and
op has been already finalized by the garbage collector and 0 otherwise.
This is analogous to the Python function gc.is_finalized().
Adicionado na versã o 3.9.
void PyObject_GC_Del(void *op)
Parte da ABI Está vel. Releases memory allocated to an object using PyObject_GC_New or
PyObject_GC_NewVar.
void PyObject_GC_UnTrack(void *op)
Parte da ABI Está vel. Remove the object op from the set of container objects tracked by the collector. Note
that PyObject_GC_Track() can be called again on this object to add it back to the set of tracked objects.
The deallocator (tp_dealloc handler) should call this for the object before any of the fields used by the
tp_traverse handler become invalid.
Alterado na versã o 3.8: The _PyObject_GC_TRACK() and _PyObject_GC_UNTRACK() macros have been remo-
ved from the public C API.
12.4. Suporte a Coleta Cíclica de Lixo 323
The Python/C API, Release 3.13.7
The tp_traverse handler accepts a function parameter of this type:
typedef int (*visitproc)(PyObject *object, void *arg)
Parte da ABI Está vel. Type of the visitor function passed to the tp_traverse handler. The function should
be called with an object to traverse as object and the third parameter to the tp_traverse handler as arg. The
Python core uses several visitor functions to implement cyclic garbage detection; it’s not expected that users
will need to write their own visitor functions.
The tp_traverse handler must have the following type:
typedef int (*traverseproc)(PyObject *self, visitproc visit, void *arg)
Parte da ABI Está vel. Traversal function for a container object. Implementations must call the visit function
for each object directly contained by self, with the parameters to visit being the contained object and the arg
value passed to the handler. The visit function must not be called with a NULL object argument. If visit returns
a non-zero value that value should be returned immediately.
To simplify writing tp_traverse handlers, a Py_VISIT() macro is provided. In order to use this macro, the
tp_traverse implementation must name its arguments exactly visit and arg:
Py_VISIT(o)
If the PyObject* o is not NULL, call the visit callback, with arguments o and arg. If visit returns a non-zero
value, then return it. Using this macro, tp_traverse handlers look like:
static int
my_traverse(Noddy *self, visitproc visit, void *arg)
{
Py_VISIT(self->foo);
Py_VISIT(self->bar);
return 0;
}
The tp_clear handler must be of the inquiry type, or NULL if the object is immutable.
typedef int (*inquiry)(PyObject *self)
Parte da ABI Está vel. Drop references that may have created reference cycles. Immutable objects do not
have to define this method since they can never directly create reference cycles. Note that the object must still
be valid after calling this method (don’t just call Py_DECREF() on a reference). The collector will call this
method if it detects that this object is involved in a reference cycle.
12.4.1 Controlando o estado do coletor de lixo
The C-API provides the following functions for controlling garbage collection runs.
Py_ssize_t PyGC_Collect(void)
Parte da ABI Está vel. Perform a full garbage collection, if the garbage collector is enabled. (Note that gc.
collect() runs it unconditionally.)
Returns the number of collected + unreachable objects which cannot be collected. If the garbage collector
is disabled or already collecting, returns 0 immediately. Errors during garbage collection are passed to sys.
unraisablehook. This function does not raise exceptions.
int PyGC_Enable(void)
Parte da ABI Está vel desde a versão 3.10. Enable the garbage collector: similar to gc.enable(). Returns
the previous state, 0 for disabled and 1 for enabled.
Adicionado na versã o 3.10.
int PyGC_Disable(void)
Parte da ABI Está vel desde a versão 3.10. Disable the garbage collector: similar to gc.disable(). Returns
the previous state, 0 for disabled and 1 for enabled.
Adicionado na versã o 3.10.
324 Capítulo 12. Suporte a implementação de Objetos
The Python/C API, Release 3.13.7
int PyGC_IsEnabled(void)
Parte da ABI Está vel desde a versão 3.10. Query the state of the garbage collector: similar to gc.
isenabled(). Returns the current state, 0 for disabled and 1 for enabled.
Adicionado na versã o 3.10.
12.4.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)
Esta é uma API Instável. Isso pode se alterado sem aviso em lançamentos menores.
Run supplied callback on all live GC-capable objects. arg is passed through to all invocations of callback.
Á Aviso
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.
Adicionado na versã o 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 1 to continue iteration, return 0 to stop iteration. Other
return values are reserved for now so behavior on returning anything else is undefined.
Adicionado na versã o 3.12.
12.4. Suporte a Coleta Cíclica de Lixo 325
The Python/C API, Release 3.13.7
326 Capítulo 12. Suporte a implementação de Objetos
CAPÍTULO 13
API e Versionamento de ABI
O CPython expõ e seu nú mero de versã o nas seguintes macros. Note que estes correspondem com o có digo da versã o
que está construída, nã o necessariamente a versã o usada no run time.
Veja Estabilidade da API C para uma discussã o da estabilidade da API e ABI atravé s das versõ es.
PY_MAJOR_VERSION
O 3 em 3.4.1a2.
PY_MINOR_VERSION
O 4 em 3.4.1a2.
PY_MICRO_VERSION
O 1 em 3.4.1a2.
PY_RELEASE_LEVEL
O a em 3.4.1a2. Isto pode ser 0xA para alfa, 0xB para beta, 0xC para o candidato a lançamento ou 0xF
para final.
PY_RELEASE_SERIAL
O 2 em 3.4.1a2. Zero para os lançamentos finais.
PY_VERSION_HEX
O nú mero da versã o do Python codificado em um ú nico inteiro.
As informaçõ es da versã o subjacente podem ser achadas tratando-as como um nú mero de 32 bits da seguinte
maneira:
Bytes Bits (big endian order) 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
Assim 3.4.1a2 é a versã o hex 0x030401a2 e 3.10.0 é a versã os hex 0x030a00f0.
Use isso para comparaçõ es numé ricas como, por exemplo, #if PY_VERSION_HEX >= ....
Esta versã o també m está disponível atravé s do símbolo Py_Version.
327
The Python/C API, Release 3.13.7
const unsigned long Py_Version
Parte da ABI Está vel desde a versão 3.11. O nú mero da versã o do runtime do Python codificado em um ú nico
inteiro constante, com o mesmo formato da macro PY_VERSION_HEX . Ele conté m a versã o do Python usada
em tempo de execuçã o.
Adicionado na versã o 3.11.
Todas as macros dadas estã o definidas em Include/patchlevel.h.
328 Capítulo 13. API e Versionamento de ABI
CAPÍTULO 14
API C de monitoramento
Adicionada na versã o 3.13.
Uma extensã o pode precisar interagir com o sistema de monitoramento de eventos. É possível registrar funçõ es de
retorno e se inscrever para receber eventos atravé s da API Python exposta em sys.monitoring.
329
The Python/C API, Release 3.13.7
330 Capítulo 14. API C de monitoramento
CAPÍTULO 15
Gerando eventos de execução
As funçõ es abaixo permitem que extensõ es dispararem eventos de monitoramento emulando a execuçã o de có digo
Python. Cada uma dessas funçõ es recebe uma estrutura PyMonitoringState que conté m informaçã o concisa
sobre o estado de ativaçã o de eventos, bem como os argumentos dos eventos, que incluem um PyObject* represen-
tando o objeto de có digo, a posiçã o da instruçã o no bytecode, e, em alguns casos, argumentos adicionais específicos
para o evento (veja sys.monitoring para detalhes sobre as assinaturas das funçõ es de retorno de diferentes even-
tos). O argumento codelike deve ser uma instâ ncia da classe types.CodeType ou de um tipo que a emule.
A VM desabilita o rastreamento quando dispara um evento, de forma que nã o há necessidade do có digo do usuá rio
fazer isso.
Funçõ es de monitoramento nã o devem ser chamadas com uma exceçã o definida, exceto as marcadas abaixo como
funçõ es que trabalham com a exceçã o atual.
type PyMonitoringState
Representaçã o do estado de um tipo de evento. Alocada pelo usuá rio, enquanto o seu conteú do é mantido pelas
funçõ es da API de monitoramento descritas abaixo.
Todas as funçõ es abaixo retornam 0 para indicar sucesso e -1 (com uma exceçã o definida) para indicar erro.
Veja sys.monitoring para descriçõ es dos eventos.
int PyMonitoring_FirePyStartEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
Dispara um evento PY_START.
int PyMonitoring_FirePyResumeEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
Dispara um evento PY_RESUME.
int PyMonitoring_FirePyReturnEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
PyObject *retval)
Dispara um evento PY_RETURN.
int PyMonitoring_FirePyYieldEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject
*retval)
Dispara um evento PY_YIELD.
int PyMonitoring_FireCallEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject
*callable, PyObject *arg0)
Dispara um evento CALL.
331
The Python/C API, Release 3.13.7
int PyMonitoring_FireLineEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, int lineno)
Dispara um evento LINE.
int PyMonitoring_FireJumpEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject
*target_offset)
Dispara um evento JUMP.
int PyMonitoring_FireBranchEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject
*target_offset)
Dispara um evento BRANCH.
int PyMonitoring_FireCReturnEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject
*retval)
Dispara um evento C_RETURN.
int PyMonitoring_FirePyThrowEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
Dispara um evento PY_THROW com a exceçã o atual (conforme retornada por
PyErr_GetRaisedException()).
int PyMonitoring_FireRaiseEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
Dispara um evento RAISE com a exceçã o atual (conforme retornada por PyErr_GetRaisedException()).
int PyMonitoring_FireCRaiseEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
Dispara um evento C_RAISE com a exceçã o atual (conforme retornada por
PyErr_GetRaisedException()).
int PyMonitoring_FireReraiseEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
Dispara um evento RERAISE com a exceçã o atual (conforme retornada por
PyErr_GetRaisedException()).
int PyMonitoring_FireExceptionHandledEvent(PyMonitoringState *state, PyObject *codelike, int32_t
offset)
Dispara um evento EXCEPTION_HANDLED com a exceçã o atual (conforme retornada por
PyErr_GetRaisedException()).
int PyMonitoring_FirePyUnwindEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
Dispara um evento PY_UNWIND com a exceçã o atual (conforme retornada por
PyErr_GetRaisedException()).
int PyMonitoring_FireStopIterationEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
PyObject *value)
Dispara um evento STOP_ITERATION. Se value for uma instâ ncia de StopIteration, ele é usado. Caso
contrá rio, uma nova instâ ncia de StopIteration é criada com value como o argumento.
15.1 Gerenciando o Estado de um Monitoramento
Estados de monitoramento podem ser gerenciados com a ajuda de escopos de monitoramento. Um escopo corres-
ponderia tipicamente a um funçã o python.
int PyMonitoring_EnterScope(PyMonitoringState *state_array, uint64_t *version, const uint8_t *event_types,
Py_ssize_t length)
Insere um escopo monitorado. event_types é um vetor de IDs de eventos para eventos que podem ser dispa-
rados do escopo. Por exemplo, a ID de um evento PY_START é o valor PY_MONITORING_EVENT_PY_START,
que é numericamente igual ao logaritmo de base 2 de sys.monitoring.events.PY_START.
state_array é um vetor com uma entrada de estado de monitoramento para cada evento em event_types,
é alocado pelo usuá rio, mas preenchido por PyMonitoring_EnterScope() com informaçõ es sobre o es-
tado de ativaçã o do evento. O tamanho de event_types (e, portanto, també m de state_array) é fornecido
em length.
332 Capítulo 15. Gerando eventos de execução
The Python/C API, Release 3.13.7
O argumento version é um ponteiro para um valor que deve ser alocado pelo usuá -
rio junto com state_array e inicializado como 0, e entã o definido somente pelo pró prio
PyMonitoring_EnterScope(). Ele permite que esta funçã o determine se os estados de eventos
mudaram desde a chamada anterior, e retorne rapidamente se nã o mudaram.
Os escopos mencionados aqui sã o escopos lexicais: uma funçã o, classe ou
mé todo.
PyMonitoring_EnterScope() deve ser chamada sempre que o escopo lexical for inserido. Os es-
copos podem ser inseridos novamente, reutilizando o mesmo state_array e version, em situaçõ es como ao
emular uma funçã o Python recursiva. Quando a execuçã o de um có digo semelhante é pausada, como ao
emular um gerador, o escopo precisa ser encerrado e inserido novamente.
As macros para event_types sã o:
15.1. Gerenciando o Estado de um Monitoramento 333
The Python/C API, Release 3.13.7
Macro Evento
BRANCH
PY_MONITORING_EVENT_BRANCH
CALL
PY_MONITORING_EVENT_CALL
C_RAISE
PY_MONITORING_EVENT_C_RAISE
C_RETURN
PY_MONITORING_EVENT_C_RETURN
EXCEPTION_HANDLED
PY_MONITORING_EVENT_EXCEPTION_HANDLED
INSTRUCTION
PY_MONITORING_EVENT_INSTRUCTION
JUMP
PY_MONITORING_EVENT_JUMP
LINE
PY_MONITORING_EVENT_LINE
PY_RESUME
PY_MONITORING_EVENT_PY_RESUME
PY_RETURN
PY_MONITORING_EVENT_PY_RETURN
PY_START
PY_MONITORING_EVENT_PY_START
PY_THROW
PY_MONITORING_EVENT_PY_THROW
PY_UNWIND
PY_MONITORING_EVENT_PY_UNWIND
PY_YIELD
PY_MONITORING_EVENT_PY_YIELD
RAISE
PY_MONITORING_EVENT_RAISE
RERAISE
PY_MONITORING_EVENT_RERAISE
STOP_ITERATION
PY_MONITORING_EVENT_STOP_ITERATION
int PyMonitoring_ExitScope(void)
Sai do ú ltimo escopo no qual se entrou com PyMonitoring_EnterScope().
int PY_MONITORING_IS_INSTRUMENTED_EVENT(uint8_t ev)
334 Capítulo 15. Gerando eventos de execução
The Python/C API, Release 3.13.7
Retorna verdadeiro se o evento correspondente ao ID do evento ev for um evento local.
Adicionado na versã o 3.13.
Descontinuado desde a versã o 3.13.3: Esta funçã o está suavemente descontinuada.
15.1. Gerenciando o Estado de um Monitoramento 335
The Python/C API, Release 3.13.7
336 Capítulo 15. Gerando eventos de execução
APÊNDICE A
Glossário
>>>
O prompt padrã o do console interativo do Python. Normalmente visto em exemplos de có digo que podem ser
executados interativamente no interpretador.
...
Pode se referir a:
• O prompt padrã o do console interativo do Python ao inserir o có digo para um bloco de có digo recuado,
quando dentro de um par de delimitadores correspondentes esquerdo e direito (parê nteses, colchetes,
chaves ou aspas triplas) ou apó s especificar um decorador.
• A constante embutida Ellipsis.
classe base abstrata
Classes bases abstratas complementam tipagem pato, fornecendo uma maneira de definir interfaces quando
outras té cnicas, como hasattr(), seriam desajeitadas ou sutilmente erradas (por exemplo, com mé todos
má gicos). ABCs introduzem subclasses virtuais, classes que nã o herdam de uma classe mas ainda sã o reconhe-
cidas por isinstance() e issubclass(); veja a documentaçã o do mó dulo abc. Python vem com muitas
ABCs embutidas para estruturas de dados (no mó dulo collections.abc), nú meros (no mó dulo numbers),
fluxos (no mó dulo io), localizadores e carregadores de importaçã o (no mó dulo importlib.abc). Você pode
criar suas pró prias ABCs com o mó dulo abc.
anotação
Um ró tulo associado a uma variá vel, um atributo de classe ou um parâ metro de funçã o ou valor de retorno,
usado por convençã o como dica de tipo.
Anotaçõ es de variá veis locais nã o podem ser acessadas em tempo de execuçã o, mas anotaçõ es de variá veis
globais, atributos de classe e funçõ es sã o armazenadas no atributo especial __annotations__ de mó dulos,
classes e funçõ es, respectivamente.
Veja anotação de variável, anotação de função, PEP 484 e PEP 526, que descrevem esta funcionalidade.
Veja també m annotations-howto para as melhores prá ticas sobre como trabalhar com anotaçõ es.
argumento
Um valor passado para uma função (ou método) ao chamar a funçã o. Existem dois tipos de argumento:
• argumento nomeado: um argumento precedido por um identificador (por exemplo, name=) na chamada
de uma funçã o ou passada como um valor em um dicioná rio precedido por **. Por exemplo, 3 e 5 sã o
ambos argumentos nomeados na chamada da funçã o complex() a seguir:
337
The Python/C API, Release 3.13.7
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
• argumento posicional: um argumento que nã o é um argumento nomeado. Argumentos posicionais po-
dem aparecer no início da lista de argumentos e/ou podem ser passados com elementos de um iterável
precedido por *. Por exemplo, 3 e 5 sã o ambos argumentos posicionais nas chamadas a seguir:
complex(3, 5)
complex(*(3, 5))
Argumentos sã o atribuídos à s variá veis locais nomeadas no corpo da funçã o. Veja a seçã o calls para as regras
de atribuiçã o. Sintaticamente, qualquer expressã o pode ser usada para representar um argumento; avaliada a
expressã o, o valor é atribuído à variá vel local.
Veja també m o termo parâmetro no glossá rio, a pergunta no FAQ sobre a diferença entre argumentos e parâ -
metros e PEP 362.
gerenciador de contexto assíncrono
Um objeto que controla o ambiente envolto numa instruçã o async with por meio da definiçã o dos mé todos
__aenter__() e __aexit__(). Introduzido pela PEP 492.
gerador assíncrono
Uma funçã o que retorna um iterador gerador assíncrono. É parecida com uma funçã o de corrotina definida
com async def exceto pelo fato de conter instruçõ es yield para produzir uma sé rie de valores que podem
ser usados em um laço async for.
Normalmente se refere a uma funçã o geradora assíncrona, mas pode se referir a um iterador gerador assín-
crono em alguns contextos. Em casos em que o significado nã o esteja claro, usar o termo completo evita a
ambiguidade.
Uma funçã o geradora assíncrona pode conter expressõ es await e també m as instruçõ es async for e async
with.
iterador gerador assíncrono
An object created by an asynchronous generator function.
Este é um iterador assíncrono que, quando chamado usando o mé todo __anext__(), retorna um objeto
aguardá vel que executará o corpo da funçã o geradora assíncrona até a pró xima expressã o yield.
Cada yield suspende temporariamente o processamento, lembrando o estado de execuçã o (incluindo variá veis
locais e instruçõ es try pendentes). Quando o iterador gerador assíncrono é efetivamente retomado com outro
aguardá vel retornado por __anext__(), ele inicia de onde parou. Veja PEP 492 e PEP 525.
iterável assíncrono
Um objeto que pode ser usado em uma instruçã o async for. Deve retornar um iterador assíncrono do seu
mé todo __aiter__(). Introduzido por PEP 492.
iterador assíncrono
Um objeto que implementa os mé todos __aiter__() e __anext__(). __anext__() deve retornar um
objeto aguardável. async for resolve os aguardá veis retornados por um mé todo __anext__() do iterador
assíncrono até que ele levante uma exceçã o StopAsyncIteration. Introduzido pela PEP 492.
atributo
Um valor associado a um objeto que é geralmente referenciado pelo nome separado por um ponto. Por exemplo,
se um objeto o tem um atributo a esse seria referenciado como o.a.
É possível dar a um objeto um atributo cujo nome nã o seja um identificador conforme definido por identifiers,
por exemplo usando setattr(), se o objeto permitir. Tal atributo nã o será acessível usando uma expressã o
pontilhada e, em vez disso, precisaria ser recuperado com getattr().
aguardável
Um objeto que pode ser usado em uma expressã o await. Pode ser uma corrotina ou um objeto com um
mé todo __await__(). Veja també m a PEP 492.
338 Apêndice A. Glossário
The Python/C API, Release 3.13.7
BDFL
Abreviaçã o da expressã o da língua inglesa “Benevolent Dictator for Life” (em portuguê s, “Ditador Benevolente
Vitalício”), referindo-se a Guido van Rossum, criador do Python.
arquivo binário
Um objeto arquivo capaz de ler e gravar em objetos bytes ou similares. Exemplos de arquivos biná rios sã o
arquivos abertos no modo biná rio ('rb', 'wb' ou 'rb+'), sys.stdin.buffer, sys.stdout.buffer, e
instâ ncias de io.BytesIO e gzip.GzipFile.
Veja també m arquivo texto para um objeto arquivo capaz de ler e gravar em objetos str.
referência emprestada
Na API C do Python, uma referê ncia emprestada é uma referê ncia a um objeto que nã o é dona da referê ncia.
Ela se torna um ponteiro solto se o objeto for destruído. Por exemplo, uma coleta de lixo pode remover a
ú ltima referência forte para o objeto e assim destruí-lo.
Chamar Py_INCREF() na referência emprestada é recomendado para convertê -lo, internamente, em uma
referência forte, exceto quando o objeto nã o pode ser destruído antes do ú ltimo uso da referê ncia emprestada.
A funçã o Py_NewRef() pode ser usada para criar uma nova referência forte.
objeto bytes ou similar
Um objeto com suporte ao Protocolo de Buffer e que pode exportar um buffer C contíguo. Isso inclui todos os
objetos bytes, bytearray e array.array, alé m de muitos objetos memoryview comuns. Objetos bytes ou
similares podem ser usados para vá rias operaçõ es que funcionam com dados biná rios; isso inclui compactaçã o,
salvamento em um arquivo biná rio e envio por um soquete.
Algumas operaçõ es precisam que os dados biná rios sejam mutá veis. A documentaçã o geralmente se refere a
eles como “objetos bytes ou similares para leitura e escrita”. Exemplos de objetos de buffer mutá vel incluem
bytearray e um memoryview de um bytearray. Outras operaçõ es exigem que os dados biná rios sejam
armazenados em objetos imutá veis (“objetos bytes ou similares para somente leitura”); exemplos disso incluem
bytes e a memoryview de um objeto bytes.
bytecode
O có digo-fonte Python é compilado para bytecode, a representaçã o interna de um programa em Python no
interpretador CPython. O bytecode també m é mantido em cache em arquivos .pyc e .pyo, de forma que
executar um mesmo arquivo é mais rá pido na segunda vez (a recompilaçã o dos fontes para bytecode nã o é
necessá ria). Esta “linguagem intermediá ria” é adequada para execuçã o em uma máquina virtual, que executa
o có digo de má quina correspondente para cada bytecode. Tenha em mente que nã o se espera que bytecodes
sejam executados entre má quinas virtuais Python diferentes, nem que se mantenham está veis entre versõ es de
Python.
Uma lista de instruçõ es bytecode pode ser encontrada na documentaçã o para o mó dulo dis.
chamável
Um chamá vel é um objeto que pode ser chamado, possivelmente com um conjunto de argumentos (veja ar-
gumento), com a seguinte sintaxe:
chamavel(argumento1, argumento2, argumentoN)
Uma função, e por extensã o um método, é um chamá vel. Uma instâ ncia de uma classe que implementa o
mé todo __call__() també m é um chamá vel.
função de retorno
També m conhecida como callback, é uma funçã o sub-rotina que é passada como um argumento a ser executado
em algum ponto no futuro.
classe
Um modelo para criaçã o de objetos definidos pelo usuá rio. Definiçõ es de classe normalmente conté m defini-
çõ es de mé todos que operam sobre instâ ncias da classe.
variável de classe
Uma variá vel definida em uma classe e destinada a ser modificada apenas no nível da classe (ou seja, nã o em
uma instâ ncia da classe).
339
The Python/C API, Release 3.13.7
variável de clausura
Uma variável livre referenciada de um escopo aninhado que é definida em um escopo externo em vez de ser
resolvida em tempo de execuçã o a partir dos espaços de nomes embutido ou globais. Pode ser explicitamente
definida com a palavra reservada nonlocal para permitir acesso de gravaçã o, ou implicitamente definida se
a variá vel estiver sendo somente lida.
Por exemplo, na funçã o interna no có digo a seguir, tanto x quanto print sã o variáveis livres, mas somente
x é uma variável de clausura:
def externa():
x = 0
def interna():
nonlocal x
x += 1
print(x)
return interna
Devido ao atributo codeobject.co_freevars (que, apesar do nome, inclui apenas os nomes das variá veis
de clausura em vez de listar todas as variá veis livres referenciadas), o termo mais geral variável livre à s vezes
é usado mesmo quando o significado pretendido é se referir especificamente à s variá veis de clausura.
número complexo
Uma extensã o ao familiar sistema de nú meros reais em que todos os nú meros sã o expressos como uma soma
de uma parte real e uma parte imaginá ria. Nú meros imaginá rios sã o mú ltiplos reais da unidade imaginá ria
(a raiz quadrada de -1), normalmente escrita como i em matemá tica ou j em engenharia. O Python tem
suporte nativo para nú meros complexos, que sã o escritos com esta ú ltima notaçã o; a parte imaginá ria escrita
com um sufixo j, p.ex., 3+1j. Para ter acesso aos equivalentes para nú meros complexos do mó dulo math,
utilize cmath. O uso de nú meros complexos é uma funcionalidade matemá tica bastante avançada. Se você
nã o sabe se irá precisar deles, é quase certo que você pode ignorá -los sem problemas.
contexto
Este termo tem diferentes significados dependendo de onde e como ele é usado. Alguns significados comuns:
• O estado ou ambiente temporá rio estabelecido por um gerenciador de contexto por meio de uma instruçã o
with.
• A coleçã o de ligaçõ es de chave-valor associadas a um objeto contextvars.Context específico e
acessadas por meio de objetos ContextVar. Veja també m variável de contexto.
• Um objeto contextvars.Context. Veja també m contexto atual.
protocolo de gerenciamento de contexto
Os mé todos __enter__() e __exit__() chamados pela instruçã o with. Veja PEP 343.
gerenciador de contexto
Um objeto que implementa o protocolo de gerenciamento de contexto e controla o ambiente envolto em uma
instruçã o with. Veja PEP 343.
variável de contexto
Uma variá vel cujo valor depende de qual contexto é o contexto atual. Os valores sã o acessados por meio de
objetos contextvars.ContextVar. Variá veis de contexto sã o usadas principalmente para isolar o estado
entre tarefas assíncronas simultâ neas.
contíguo
Um buffer é considerado contíguo exatamente se for contíguo C ou contíguo Fortran. Os buffers de dimensã o
zero sã o contíguos C e Fortran. Em vetores unidimensionais, os itens devem ser dispostos na memó ria pró ximos
um do outro, em ordem crescente de índices, começando do zero. Em vetores multidimensionais contíguos C,
o ú ltimo índice varia mais rapidamente ao visitar itens em ordem de endereço de memó ria. No entanto, nos
vetores contíguos do Fortran, o primeiro índice varia mais rapidamente.
corrotina
Corrotinas sã o uma forma mais generalizada de sub-rotinas. Sub-rotinas tem a entrada iniciada em um ponto,
e a saída em outro ponto. Corrotinas podem entrar, sair, e continuar em muitos pontos diferentes. Elas podem
ser implementadas com a instruçã o async def. Veja també m PEP 492.
340 Apêndice A. Glossário
The Python/C API, Release 3.13.7
função de corrotina
Uma funçã o que retorna um objeto do tipo corrotina. Uma funçã o de corrotina pode ser definida com a instru-
çã o async def, e pode conter as palavras chaves await, async for, e async with. Isso foi introduzido
pela PEP 492.
CPython
A implementaçã o canô nica da linguagem de programaçã o Python, como disponibilizada pelo python.org.
O termo “CPython” é usado quando necessá rio distinguir esta implementaçã o de outras como Jython ou
IronPython.
contexto atual
O contexto (objeto contextvars.Context) que é usado atualmente pelos objetos ContextVar para acessar
(obter ou definir) os valores de variáveis de contexto. Cada thread tem seu pró prio contexto atual. Frameworks
para executar tarefas assíncronas (veja asyncio) associam cada tarefa a um contexto que se torna o contexto
atual sempre que a tarefa inicia ou retoma a execuçã o.
decorador
Uma funçã o que retorna outra funçã o, geralmente aplicada como uma transformaçã o de funçã o usando a
sintaxe @wrapper. Exemplos comuns para decoradores sã o classmethod() e staticmethod().
A sintaxe do decorador é meramente um açú car sintá tico, as duas definiçõ es de funçõ es a seguir sã o semanti-
camente equivalentes:
def f(arg):
...
f = staticmethod(f)
@staticmethod
def f(arg):
...
O mesmo conceito existe para as classes, mas nã o é comumente utilizado. Veja a documentaçã o de definiçõ es
de funçã o e definiçõ es de classe para obter mais informaçõ es sobre decoradores.
descritor
Qualquer objeto que define os mé todos __get__(), __set__() ou __delete__(). Quando um atributo
de classe é um descritor, seu comportamento de associaçã o especial é acionado no acesso a um atributo.
Normalmente, ao se utilizar a.b para se obter, definir ou excluir, um atributo dispara uma busca no objeto
chamado b no dicioná rio de classe de a, mas se b for um descritor, o respectivo mé todo descritor é chamado.
Compreender descritores é a chave para um profundo entendimento de Python pois eles sã o a base de muitas
funcionalidades incluindo funçõ es, mé todos, propriedades, mé todos de classe, mé todos está ticos e referê ncias
para superclasses.
Para obter mais informaçõ es sobre os mé todos dos descritores, veja: descriptors ou o Guia de Descritores.
dicionário
Um vetor associativo em que chaves arbitrá rias sã o mapeadas para valores. As chaves podem ser quaisquer
objetos que possuam os mé todos __hash__() e __eq__(). Isso é chamado de hash em Perl.
compreensão de dicionário
Uma maneira compacta de processar todos ou parte dos elementos de um iterá vel e retornar um dicioná rio com
os resultados. results = {n: n ** 2 for n in range(10)} gera um dicioná rio contendo a chave n
mapeada para o valor n ** 2. Veja comprehensions.
visão de dicionário
Os objetos retornados por dict.keys(), dict.values() e dict.items() sã o chamados de visõ es de
dicioná rio. Eles fornecem uma visã o dinâ mica das entradas do dicioná rio, o que significa que quando o di-
cioná rio é alterado, a visã o reflete essas alteraçõ es. Para forçar a visã o de dicioná rio a se tornar uma lista
completa use list(dictview). Veja dict-views.
docstring
Abreviatura de “documentation string” (string de documentaçã o). Uma string literal que aparece como pri-
meira expressã o numa classe, funçã o ou mó dulo. Ainda que sejam ignoradas quando a suíte é executada, é
341
The Python/C API, Release 3.13.7
reconhecida pelo compilador que a coloca no atributo __doc__ da classe, funçã o ou mó dulo que a encapsula.
Como ficam disponíveis por meio de introspecçã o, docstrings sã o o lugar canô nico para documentaçã o do
objeto.
tipagem pato
També m conhecida como duck-typing, é um estilo de programaçã o que nã o verifica o tipo do objeto para
determinar se ele possui a interface correta; em vez disso, o mé todo ou atributo é simplesmente chamado
ou utilizado (“Se se parece com um pato e grasna como um pato, entã o deve ser um pato.”) Enfatizando
interfaces ao invé s de tipos específicos, o có digo bem desenvolvido aprimora sua flexibilidade por permitir
substituiçã o polimó rfica. Tipagem pato evita necessidade de testes que usem type() ou isinstance().
(Note, poré m, que a tipagem pato pode ser complementada com o uso de classes base abstratas.) Ao invé s
disso, sã o normalmente empregados testes hasattr() ou programaçã o EAFP.
dunder
Uma abreviaçã o informal para “double underscore” (em portuguê s, sublinhado duplo), usada ao se referir a um
método especial. Por exemplo, __init__ é frequentemente pronunciado como “dunder init”.
EAFP
Iniciais da expressã o em inglê s “easier to ask for forgiveness than permission” que significa “é mais fá cil pedir
perdã o que permissã o”. Este estilo de codificaçã o comum no Python presume a existê ncia de chaves ou atribu-
tos vá lidos e captura exceçõ es caso essa premissa se prove falsa. Este estilo limpo e rá pido se caracteriza pela
presença de vá rias instruçõ es try e except. A té cnica diverge do estilo LBYL, comum em outras linguagens
como C, por exemplo.
expressão
Uma parte da sintaxe que pode ser avaliada para algum valor. Em outras palavras, uma expressã o é a acumula-
çã o de elementos de expressã o como literais, nomes, atributos de acesso, operadores ou chamadas de funçõ es,
todos os quais retornam um valor. Em contraste com muitas outras linguagens, nem todas as construçõ es
de linguagem sã o expressõ es. També m existem instruções, as quais nã o podem ser usadas como expressõ es,
como, por exemplo, while. Atribuiçõ es també m sã o instruçõ es, nã o expressõ es.
módulo de extensão
Um mó dulo escrito em C ou C++, usando a API C do Python para interagir tanto com có digo de usuá rio
quanto do nú cleo.
f-string
Literais string prefixadas com 'f' ou 'F' sã o conhecidas como “f-strings” que é uma abreviaçã o de formatted
string literals. Veja també m PEP 498.
objeto arquivo
Um objeto que expõ e uma API orientada a arquivos (com mé todos tais como read() ou write()) para
um recurso subjacente. Dependendo da maneira como foi criado, um objeto arquivo pode mediar o acesso a
um arquivo real no disco ou outro tipo de dispositivo de armazenamento ou de comunicaçã o (por exemplo a
entrada/saída padrã o, buffers em memó ria, soquetes, pipes, etc.). Objetos arquivo també m sã o chamados de
objetos arquivo ou similares ou fluxos.
Atualmente há trê s categorias de objetos arquivo: arquivos binários brutos, arquivos binários em buffer e
arquivos textos. Suas interfaces estã o definidas no mó dulo io. A forma canô nica para criar um objeto arquivo
é usando a funçã o open().
objeto arquivo ou similar
Um sinô nimo do termo objeto arquivo.
tratador de erros e codificação do sistema de arquivos
Tratador de erros e codificaçã o usado pelo Python para decodificar bytes do sistema operacional e codificar
Unicode para o sistema operacional.
A codificaçã o do sistema de arquivos deve garantir a decodificaçã o bem-sucedida de todos os bytes abaixo
de 128. Se a codificaçã o do sistema de arquivos falhar em fornecer essa garantia, as funçõ es da API podem
levantar UnicodeError.
As funçõ es sys.getfilesystemencoding() e sys.getfilesystemencodeerrors() podem ser usa-
das para obter o tratador de erros e codificaçã o do sistema de arquivos.
342 Apêndice A. Glossário
The Python/C API, Release 3.13.7
O tratador de erros e codificação do sistema de arquivos sã o configurados na inicializaçã o do Python pela funçã o
PyConfig_Read(): veja os membros filesystem_encoding e filesystem_errors do PyConfig .
Veja també m codificação da localidade.
localizador
Um objeto que tenta encontrar o carregador para um mó dulo que está sendo importado.
Existem dois tipos de localizador: localizadores de metacaminho para uso com sys.meta_path, e localiza-
dores de entrada de caminho para uso com sys.path_hooks.
Veja finders-and-loaders e importlib para muito mais detalhes.
divisão pelo piso
Divisã o matemá tica que arredonda para baixo para o inteiro mais pró ximo. O operador de divisã o pelo piso é
//. Por exemplo, a expressã o 11 // 4 retorna o valor 2 ao invé s de 2.75, que seria retornado pela divisã o
de ponto flutuante. Note que (-11) // 4 é -3 porque é -2.75 arredondado para baixo. Consulte a PEP
238.
threads livres
Um modelo de threads onde mú ltiplas threads podem simultaneamente executar bytecode Python no mesmo
interpretador. Isso está em contraste com a trava global do interpretador que permite apenas uma thread por
vez executar bytecode Python. Veja PEP 703.
variável livre
Formalmente, conforme definido no modelo de execuçã o de linguagem, uma variá vel livre é qualquer variá vel
usada em um espaço de nomes que nã o seja uma variá vel local naquele espaço de nomes. Veja variável de
clausura para um exemplo. Pragmaticamente, devido ao nome do atributo codeobject.co_freevars, o
termo també m é usado algumas vezes como sinô nimo de variável de clausura.
função
Uma sé rie de instruçõ es que retorna algum valor para um chamador. També m pode ser passado zero ou mais
argumentos que podem ser usados na execuçã o do corpo. Veja també m parâmetro, método e a seçã o function.
anotação de função
Uma anotação de um parâ metro de funçã o ou valor de retorno.
Anotaçõ es de funçã o sã o comumente usados por dicas de tipo: por exemplo, essa funçã o espera receber dois
argumentos int e també m é esperado que devolva um valor int:
def soma_dois_numeros(a: int, b: int) -> int:
return a + b
A sintaxe de anotaçã o de funçã o é explicada na seçã o function.
Veja anotação de variável e PEP 484, que descrevem esta funcionalidade. Veja també m annotations-howto
para as melhores prá ticas sobre como trabalhar com anotaçõ es.
__future__
A instruçã o future, from __future__ import <feature>, direciona o compilador a compilar o mó dulo
atual usando sintaxe ou semâ ntica que será padrã o em uma versã o futura de Python. O mó dulo __future__
documenta os possíveis valores de feature. Importando esse mó dulo e avaliando suas variá veis, você pode ver
quando um novo recurso foi inicialmente adicionado à linguagem e quando será (ou se já é ) o padrã o:
>>> import __future__
>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
coleta de lixo
També m conhecido como garbage collection, é o processo de liberar a memó ria quando ela nã o é mais utilizada.
Python executa a liberaçã o da memó ria atravé s da contagem de referê ncias e um coletor de lixo cíclico que é
capaz de detectar e interromper referê ncias cíclicas. O coletor de lixo pode ser controlado usando o mó dulo
gc.
343
The Python/C API, Release 3.13.7
gerador
Uma funçã o que retorna um iterador gerador. É parecida com uma funçã o normal, exceto pelo fato de conter
expressõ es yield para produzir uma sé rie de valores que podem ser usados em um laço “for” ou que podem
ser obtidos um de cada vez com a funçã o next().
Normalmente refere-se a uma funçã o geradora, mas pode referir-se a um iterador gerador em alguns contextos.
Em alguns casos onde o significado desejado nã o está claro, usar o termo completo evita ambiguidade.
iterador gerador
Um objeto criado por uma funçã o geradora.
Cada yield suspende temporariamente o processamento, memorizando o estado da execuçã o (incluindo va-
riá veis locais e instruçõ es try pendentes). Quando o iterador gerador retorna, ele se recupera do ú ltimo ponto
onde estava (em contrapartida as funçõ es que iniciam uma nova execuçã o a cada vez que sã o invocadas).
expressão geradora
Uma expressão que retorna um iterador. Parece uma expressã o normal, seguido de uma clá usula for definindo
uma variá vel de laço, um intervalo, e uma clá usula if opcional. A expressã o combinada gera valores para uma
funçã o encapsuladora:
>>> sum(i*i for i in range(10)) # soma dos quadrados 0, 1, 4, ... 81
285
função genérica
Uma funçã o composta por vá rias funçõ es implementando a mesma operaçã o para diferentes tipos. Qual im-
plementaçã o deverá ser usada durante a execuçã o é determinada pelo algoritmo de despacho.
Veja també m a entrada despacho único no glossá rio, o decorador functools.singledispatch(), e a PEP
443.
tipo genérico
Um tipo que pode ser parametrizado; tipicamente uma classe contê iner tal como list ou dict. Usado para
dicas de tipo e anotações.
Para mais detalhes, veja tipo apelido gené rico, PEP 483, PEP 484, PEP 585, e o mó dulo typing.
GIL
Veja trava global do interpretador.
trava global do interpretador
O mecanismo utilizado pelo interpretador CPython para garantir que apenas uma thread execute o bytecode
Python por vez. Isto simplifica a implementaçã o do CPython ao fazer com que o modelo de objetos (incluindo
tipos embutidos críticos como o dict) ganhem segurança implícita contra acesso concorrente. Travar todo o
interpretador facilita que o interpretador em si seja multithread, à s custas de muito do paralelismo já provido
por má quinas multiprocessador.
No entanto, alguns mó dulos de extensã o, tanto da biblioteca padrã o quanto de terceiros, sã o desenvolvidos de
forma a liberar a GIL ao realizar tarefas computacionalmente muito intensas, como compactaçã o ou cá lculos
de hash. Alé m disso, a GIL é sempre liberada nas operaçõ es de E/S.
A partir de Python 3.13, o GIL pode ser desabilitado usando a configuraçã o de construçã o --disable-gil.
Depois de construir Python com essa opçã o, o có digo deve ser executado com a opçã o -X gil=0 ou a variá vel
de ambiente PYTHON_GIL=0 deve estar definida. Esse recurso provê um desempenho melhor para aplicaçõ es
com mú ltiplas threads e torna mais fá cil o uso eficiente de CPUs com mú ltiplos nú cleos. Para mais detalhes,
veja PEP 703.
pyc baseado em hash
Um arquivo de cache em bytecode que usa hash ao invé s do tempo, no qual o arquivo de có digo-fonte foi
modificado pela ú ltima vez, para determinar a sua validade. Veja pyc-invalidation.
hasheável
Um objeto é hasheável se tem um valor de hash que nunca muda durante seu ciclo de vida (precisa ter um
mé todo __hash__()) e pode ser comparado com outros objetos (precisa ter um mé todo __eq__()). Objetos
hasheá veis que sã o comparados como iguais devem ter o mesmo valor de hash.
344 Apêndice A. Glossário
The Python/C API, Release 3.13.7
A hasheabilidade faz com que um objeto possa ser usado como uma chave de dicioná rio e como um membro
de conjunto, pois estas estruturas de dados utilizam os valores de hash internamente.
A maioria dos objetos embutidos imutá veis do Python sã o hasheá veis; containers mutá veis (tais como listas
ou dicioná rios) nã o sã o; containers imutá veis (tais como tuplas e frozensets) sã o hasheá veis apenas se os seus
elementos sã o hasheá veis. Objetos que sã o instâ ncias de classes definidas pelo usuá rio sã o hasheá veis por
padrã o. Todos eles comparam de forma desigual (exceto entre si mesmos), e o seu valor hash é derivado a
partir do seu id().
IDLE
Um ambiente de desenvolvimento e aprendizado integrado para Python. idle é um editor bá sico e um ambiente
interpretador que vem junto com a distribuiçã o padrã o do Python.
imortal
Objetos imortais sã o um detalhe da implementaçã o do CPython introduzida na PEP 683.
Se um objeto é imortal, sua contagem de referências nunca é modificada e, portanto, nunca é desalocado en-
quanto o interpretador está em execuçã o. Por exemplo, True e None sã o imortais no CPython.
imutável
Um objeto que possui um valor fixo. Objetos imutá veis incluem nú meros, strings e tuplas. Estes objetos nã o
podem ser alterados. Um novo objeto deve ser criado se um valor diferente tiver de ser armazenado. Objetos
imutá veis tê m um papel importante em lugares onde um valor constante de hash seja necessá rio, como por
exemplo uma chave em um dicioná rio.
caminho de importação
Uma lista de localizaçõ es (ou entradas de caminho) que sã o buscadas pelo localizador baseado no caminho por
mó dulos para importar. Durante a importaçã o, esta lista de localizaçõ es usualmente vem a partir de sys.path,
mas para subpacotes ela també m pode vir do atributo __path__ de pacotes-pai.
importação
O processo pelo qual o có digo Python em um mó dulo é disponibilizado para o có digo Python em outro mó dulo.
importador
Um objeto que localiza e carrega um mó dulo; Tanto um localizador e o objeto carregador.
interativo
Python tem um interpretador interativo, o que significa que você pode digitar instruçõ es e expressõ es no prompt
do interpretador, executá -los imediatamente e ver seus resultados. Apenas execute python sem argumentos
(possivelmente selecionando-o a partir do menu de aplicaçõ es de seu sistema operacional). O interpretador
interativo é uma maneira poderosa de testar novas ideias ou aprender mais sobre mó dulos e pacotes (lembre-se
do comando help(x)). Para saber mais sobre modo interativo, veja tut-interac.
interpretado
Python é uma linguagem interpretada, em oposiçã o à quelas que sã o compiladas, embora esta distinçã o possa
ser nebulosa devido à presença do compilador de bytecode. Isto significa que os arquivos-fontes podem ser
executados diretamente sem necessidade explícita de se criar um arquivo executá vel. Linguagens interpretadas
normalmente tê m um ciclo de desenvolvimento/depuraçã o mais curto que as linguagens compiladas, apesar
de seus programas geralmente serem executados mais lentamente. Veja també m interativo.
desligamento do interpretador
Quando solicitado para desligar, o interpretador Python entra em uma fase especial, onde ele gradualmente
libera todos os recursos alocados, tais como mó dulos e vá rias estruturas internas críticas. Ele també m faz
diversas chamadas para o coletor de lixo. Isto pode disparar a execuçã o de có digo em destrutores definidos
pelo usuá rio ou funçã o de retorno de referê ncia fraca. Có digo executado durante a fase de desligamento pode
encontrar diversas exceçõ es, pois os recursos que ele depende podem nã o funcionar mais (exemplos comuns
sã o os mó dulos de bibliotecas, ou os mecanismos de avisos).
A principal razã o para o interpretador desligar, é que o mó dulo __main__ ou o script sendo executado ter-
minou sua execuçã o.
iterável
Um objeto capaz de retornar seus membros um de cada vez. Exemplos de iterá veis incluem todos os tipos de
sequê ncia (tais como list, str e tuple) e alguns tipos de nã o-sequê ncia, como o dict e objetos arquivo,
345
The Python/C API, Release 3.13.7
alé m dos objetos de quaisquer classes que você definir com um mé todo __iter__() ou __getitem__()
que implementam a semâ ntica de sequência.
Iterá veis podem ser usados em um laço for e em vá rios outros lugares em que uma sequê ncia é necessá ria
(zip(), map(), …). Quando um objeto iterá vel é passado como argumento para a funçã o embutida iter(),
ela retorna um iterador para o objeto. Este iterador é adequado para se varrer todo o conjunto de valores. Ao
usar iterá veis, normalmente nã o é necessá rio chamar iter() ou lidar com os objetos iteradores em si. A
instruçã o for faz isso automaticamente para você , criando uma variá vel temporá ria para armazenar o iterador
durante a execuçã o do laço. Veja també m iterador, sequência, e gerador.
iterador
Um objeto que representa um fluxo de dados. Repetidas chamadas ao mé todo __next__() de um iterador
(ou passando o objeto para a funçã o embutida next()) vã o retornar itens sucessivos do fluxo. Quando nã o
houver mais dados disponíveis uma exceçã o StopIteration será levantada. Neste ponto, o objeto iterador
se esgotou e quaisquer chamadas subsequentes a seu mé todo __next__() vã o apenas levantar a exceçã o
StopIteration novamente. Iteradores precisam ter um mé todo __iter__() que retorne o objeto iterador
em si, de forma que todo iterador també m é iterá vel e pode ser usado na maioria dos lugares em que um iterá vel
é requerido. Uma notá vel exceçã o é có digo que tenta realizar passagens em mú ltiplas iteraçõ es. Um objeto
contê iner (como uma list) produz um novo iterador a cada vez que você passá -lo para a funçã o iter() ou
utilizá -lo em um laço for. Tentar isso com o mesmo iterador apenas iria retornar o mesmo objeto iterador
esgotado já utilizado na iteraçã o anterior, como se fosse um contê iner vazio.
Mais informaçõ es podem ser encontradas em typeiter.
O CPython nã o aplica consistentemente o requisito de que um iterador defina __iter__(). E també m observe
que o CPython com threads livres nã o garante a segurança do thread das operaçõ es do iterador.
função chave
Uma funçã o chave ou funçã o colaçã o é um chamá vel que retorna um valor usado para ordenaçã o ou classifi-
caçã o. Por exemplo, locale.strxfrm() é usada para produzir uma chave de ordenaçã o que leva o locale
em consideraçã o para fins de ordenaçã o.
Uma porçã o de ferramentas no Python aceitam funçõ es chave para controlar como os elementos sã o orde-
nados ou agrupados. Algumas delas incluem min(), max(), sorted(), list.sort(), heapq.merge(),
heapq.nsmallest(), heapq.nlargest() e itertools.groupby().
Há vá rias maneiras de se criar funçõ es chave. Por exemplo, o mé todo str.lower() pode servir como uma
funçã o chave para ordenaçõ es insensíveis à caixa. Alternativamente, uma funçã o chave ad-hoc pode ser cons-
truída a partir de uma expressã o lambda, como lambda r: (r[0], r[2]). Alé m disso, operator.
attrgetter(), operator.itemgetter() e operator.methodcaller() sã o trê s construtores de fun-
çã o chave. Consulte o guia de Ordenaçã o para ver exemplos de como criar e utilizar funçõ es chave.
argumento nomeado
Veja argumento.
lambda
Uma funçã o de linha anô nima consistindo de uma ú nica expressão, que é avaliada quando a funçã o é chamada.
A sintaxe para criar uma funçã o lambda é lambda [parameters]: expression
LBYL
Iniciais da expressã o em inglê s “look before you leap”, que significa algo como “olhe antes de pisar”. Este estilo
de codificaçã o testa as pré -condiçõ es explicitamente antes de fazer chamadas ou buscas. Este estilo contrasta
com a abordagem EAFP e é caracterizada pela presença de muitas instruçõ es if.
Em um ambiente multithread, a abordagem LBYL pode arriscar a introduçã o de uma condiçã o de corrida
entre “o olhar” e “o pisar”. Por exemplo, o có digo if key in mapping: return mapping[key] pode
falhar se outra thread remover key do mapping apó s o teste, mas antes da olhada. Esse problema pode ser
resolvido com travas ou usando a abordagem EAFP.
analisador léxico
Nome formal para o tokenizador; veja token.
lista
Uma sequência embutida no Python. Apesar do seu nome, é mais pró ximo de um vetor em outras linguagens
do que uma lista encadeada, como o acesso aos elementos é da ordem O(1).
346 Apêndice A. Glossário
The Python/C API, Release 3.13.7
compreensão de lista
Uma maneira compacta de processar todos ou parte dos elementos de uma sequê ncia e retornar os resultados
em uma lista. result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] gera
uma lista de strings contendo nú meros hexadecimais (0x..) no intervalo de 0 a 255. A clá usula if é opcional.
Se omitida, todos os elementos no range(256) serã o processados.
carregador
Um objeto que carrega um mó dulo. Ele deve definir os mé todos exec_module() e create_module() para
implementar a interface Loader. Um carregador é normalmente retornado por um localizador. Veja també m:
• finders-and-loaders
• importlib.abc.Loader
• PEP 302
codificação da localidade
No Unix, é a codificaçã o da localidade do LC_CTYPE, que pode ser definida com locale.
setlocale(locale.LC_CTYPE, new_locale).
No Windows, é a pá gina de có digo ANSI (ex: "cp1252").
No Android e no VxWorks, o Python usa "utf-8" como a codificaçã o da localidade.
locale.getencoding() pode ser usado para obter a codificaçã o da localidade.
Veja també m tratador de erros e codificação do sistema de arquivos.
método mágico
Um sinô nimo informal para um método especial.
mapeamento
Um objeto contê iner com suporte a pesquisas de chave arbitrá ria e que implementa os mé todos especifica-
dos nas classes base abstratas collections.abc.Mapping ou collections.abc.MutableMapping.
Exemplos incluem dict, collections.defaultdict, collections.OrderedDict e collections.
Counter.
localizador de metacaminho
Um localizador retornado por uma busca de sys.meta_path. Localizadores de metacaminho sã o relaciona-
dos a, mas diferentes de, localizadores de entrada de caminho.
Veja importlib.abc.MetaPathFinder para os mé todos que localizadores de metacaminho implementam.
metaclasse
A classe de uma classe. Definiçõ es de classe criam um nome de classe, um dicioná rio de classe e uma lista
de classes base. A metaclasse é responsá vel por receber estes trê s argumentos e criar a classe. A maioria das
linguagens de programaçã o orientadas a objetos provê uma implementaçã o default. O que torna o Python
especial é o fato de ser possível criar metaclasses personalizadas. A maioria dos usuá rios nunca vai preci-
sar deste recurso, mas quando houver necessidade, metaclasses possibilitam soluçõ es poderosas e elegantes.
Metaclasses tê m sido utilizadas para gerar registros de acesso a atributos, para incluir proteçã o contra acesso
concorrente, rastrear a criaçã o de objetos, implementar singletons, dentre muitas outras tarefas.
Mais informaçõ es podem ser encontradas em metaclasses.
método
Uma funçã o que é definida dentro do corpo de uma classe. Se chamada como um atributo de uma instâ ncia
daquela classe, o mé todo receberá a instâ ncia do objeto como seu primeiro argumento (que comumente é
chamado de self). Veja função e escopo aninhado.
ordem de resolução de métodos
Ordem de resoluçã o de mé todos é a ordem em que os membros de uma classe base sã o buscados durante a
pesquisa. Veja python_2.3_mro para detalhes do algoritmo usado pelo interpretador do Python desde a versã o
2.3.
módulo
Um objeto que serve como uma unidade organizacional de có digo Python. Os mó dulos tê m um espaço de
347
The Python/C API, Release 3.13.7
nomes contendo objetos Python arbitrá rios. Os mó dulos sã o carregados pelo Python atravé s do processo de
importação.
Veja també m pacote.
spec de módulo
Um espaço de nomes que conté m as informaçõ es relacionadas à importaçã o usadas para carregar um mó dulo.
Uma instâ ncia de importlib.machinery.ModuleSpec.
Veja també m module-specs.
MRO
Veja ordem de resolução de métodos.
mutável
Objeto mutá vel é aquele que pode modificar seus valor mas manter seu id(). Veja també m imutável.
tupla nomeada
O termo “tupla nomeada” é aplicado a qualquer tipo ou classe que herda de tupla e cujos elementos indexá veis
també m sã o acessíveis usando atributos nomeados. O tipo ou classe pode ter outras funcionalidades també m.
Diversos tipos embutidos sã o tuplas nomeadas, incluindo os valores retornados por time.localtime() e
os.stat(). Outro exemplo é sys.float_info:
>>> sys.float_info[1] # acesso indexado
1024
>>> sys.float_info.max_exp # acesso a campo nomeado
1024
>>> isinstance(sys.float_info, tuple) # tipo de tupla
True
Algumas tuplas nomeadas sã o tipos embutidos (tal como os exemplos acima). Alternativamente, uma tupla
nomeada pode ser criada a partir de uma definiçã o de classe regular, que herde de tuple e que defina campos
nomeados. Tal classe pode ser escrita a mã o, ou ela pode ser criada herdando typing.NamedTuple ou com
uma funçã o fá brica collections.namedtuple(). As duas ú ltimas té cnicas també m adicionam alguns
mé todos extras, que podem nã o ser encontrados quando foi escrita manualmente, ou em tuplas nomeadas
embutidas.
espaço de nomes
O lugar em que uma variá vel é armazenada. Espaços de nomes sã o implementados como dicioná rios. Exis-
tem os espaços de nomes local, global e nativo, bem como espaços de nomes aninhados em objetos (em
mé todos). Espaços de nomes suportam modularidade ao prevenir conflitos de nomes. Por exemplo, as fun-
çõ es __builtin__.open() e os.open() sã o diferenciadas por seus espaços de nomes. Espaços de nomes
també m auxiliam na legibilidade e na manutenibilidade ao torar mais claro quais mó dulos implementam uma
funçã o. Escrever random.seed() ou itertools.izip(), por exemplo, deixa claro que estas funçõ es sã o
implementadas pelos mó dulos random e itertools respectivamente.
pacote de espaço de nomes
Um pacote que serve apenas como contê iner para subpacotes. Pacotes de espaços de nomes podem nã o ter
representaçã o física, e especificamente nã o sã o como um pacote regular porque eles nã o tem um arquivo
__init__.py.
Pacotes de espaço de nomes permitem que vá rios pacotes instalá veis individualmente tenham um pacote pai
comum. Caso contrá rio, é recomendado usar um pacote regular.
Para mais informaçõ es, veja PEP 420 e reference-namespace-package.
Veja també m módulo.
escopo aninhado
A habilidade de referir-se a uma variá vel em uma definiçã o de fechamento. Por exemplo, uma funçã o definida
dentro de outra pode referenciar variá veis da funçã o externa. Perceba que escopos aninhados por padrã o
funcionam apenas por referê ncia e nã o por atribuiçã o. Variá veis locais podem ler e escrever no escopo mais
interno. De forma similar, variá veis globais podem ler e escrever para o espaço de nomes global. O nonlocal
permite escrita para escopos externos.
348 Apêndice A. Glossário
The Python/C API, Release 3.13.7
classe estilo novo
Antigo nome para o tipo de classes agora usado para todos os objetos de classes. Em versõ es anteriores
do Python, apenas classes estilo podiam usar recursos novos e versá teis do Python, tais como __slots__,
descritores, propriedades, __getattribute__(), mé todos de classe, e mé todos está ticos.
objeto
Qualquer dado que tenha estado (atributos ou valores) e comportamento definidos (mé todos). També m a
ú ltima classe base de qualquer classe estilo novo.
escopo otimizado
Um escopo no qual os nomes das variá veis locais de destino sã o conhecidos de forma confiá vel pelo compi-
lador quando o có digo é compilado, permitindo a otimizaçã o do acesso de leitura e gravaçã o a esses nomes.
Os espaços de nomes locais para funçõ es, geradores, corrotinas, compreensõ es e expressõ es geradoras sã o
otimizados desta forma. Nota: a maioria das otimizaçõ es de interpretador sã o aplicadas a todos os escopos,
apenas aquelas que dependem de um conjunto conhecido de nomes de variá veis locais e nã o locais sã o restritas
a escopos otimizados.
pacote
Um módulo Python é capaz de conter submó dulos ou recursivamente, subpacotes. Tecnicamente, um pacote
é um mó dulo Python com um atributo __path__.
Veja també m pacote regular e pacote de espaço de nomes.
parâmetro
Uma entidade nomeada na definiçã o de uma função (ou mé todo) que específica um argumento (ou em alguns
casos, argumentos) que a funçã o pode receber. Existem cinco tipos de parâ metros:
• posicional-ou-nomeado: especifica um argumento que pode ser tanto posicional quanto nomeado. Esse
é o tipo padrã o de parâ metro, por exemplo foo e bar a seguir:
def func(foo, bar=None): ...
• somente-posicional: especifica um argumento que pode ser fornecido apenas por posiçã o. Parâ metros
somente-posicionais podem ser definidos incluindo o caractere / na lista de parâ metros da definiçã o da
funçã o apó s eles, por exemplo somentepos1 e somentepos2 a seguir:
def func(somentepos1, somentepos2, /, posicional_ou_nomeado): ...
• somente-nomeado: especifica um argumento que pode ser passado para a funçã o somente por nome.
Parâ metros somente-nomeados podem ser definidos com um simples parâ metro var-posicional ou um *
antes deles na lista de parâ metros na definiçã o da funçã o, por exemplo somente_nom1 and somente_nom2
a seguir:
def func(arg, *, somente_nom1, somente_nom2): ...
• var-posicional: especifica que uma sequê ncia arbitrá ria de argumentos posicionais pode ser fornecida
(em adiçã o a qualquer argumento posicional já aceito por outros parâ metros). Tal parâ metro pode ser
definido colocando um * antes do nome do parâ metro, por exemplo args a seguir:
def func(*args, **kwargs): ...
• var-nomeado: especifica que, arbitrariamente, muitos argumentos nomeados podem ser fornecidos (em
adiçã o a qualquer argumento nomeado já aceito por outros parâ metros). Tal parâ metro pode definido
colocando-se ** antes do nome, por exemplo kwargs no exemplo acima.
Parâ metros podem especificar tanto argumentos opcionais quanto obrigató rios, assim como valores padrã o
para alguns argumentos opcionais.
Veja també m o termo argumento no glossá rio, a pergunta do FAQ sobre a diferença entre argumentos e parâ -
metros, a classe inspect.Parameter, a seçã o function e a PEP 362.
entrada de caminho
Um local ú nico no caminho de importação que o localizador baseado no caminho consulta para encontrar
mó dulos a serem importados.
349
The Python/C API, Release 3.13.7
localizador de entrada de caminho
Um localizador retornado por um chamá vel em sys.path_hooks (ou seja, um gancho de entrada de caminho)
que sabe como localizar os mó dulos entrada de caminho.
Veja importlib.abc.PathEntryFinder para os mé todos que localizadores de entrada de caminho im-
plementam.
gancho de entrada de caminho
Um chamá vel na lista sys.path_hooks que retorna um localizador de entrada de caminho caso saiba como
localizar mó dulos em uma entrada de caminho específica.
localizador baseado no caminho
Um dos localizadores de metacaminho padrã o que procura por um caminho de importação de mó dulos.
objeto caminho ou similar
Um objeto representando um caminho de sistema de arquivos. Um objeto caminho ou similar é ou um objeto
str ou bytes representando um caminho, ou um objeto implementando o protocolo os.PathLike. Um
objeto que suporta o protocolo os.PathLike pode ser convertido para um arquivo de caminho do sistema
str ou bytes, atravé s da chamada da funçã o os.fspath(); os.fsdecode() e os.fsencode() podem
ser usadas para garantir um str ou bytes como resultado, respectivamente. Introduzido na PEP 519.
PEP
Proposta de melhoria do Python. Uma PEP é um documento de design que fornece informaçã o para a co-
munidade Python, ou descreve uma nova funcionalidade para o Python ou seus predecessores ou ambientes.
PEPs devem prover uma especificaçã o té cnica concisa e um racional para funcionalidades propostas.
PEPs tê m a intençã o de ser os mecanismos primá rios para propor novas funcionalidades significativas, para
coletar opiniõ es da comunidade sobre um problema, e para documentar as decisõ es de design que foram
adicionadas ao Python. O autor da PEP é responsá vel por construir um consenso dentro da comunidade e
documentar opiniõ es dissidentes.
Veja PEP 1.
porção
Um conjunto de arquivos em um ú nico diretó rio (possivelmente armazenado em um arquivo zip) que contri-
buem para um pacote de espaço de nomes, conforme definido em PEP 420.
argumento posicional
Veja argumento.
API provisória
Uma API provisó ria é uma API que foi deliberadamente excluída das bibliotecas padrõ es com compatibilidade
retroativa garantida. Enquanto mudanças maiores para tais interfaces nã o sã o esperadas, contanto que elas
sejam marcadas como provisó rias, mudanças retroativas incompatíveis (até e incluindo a remoçã o da interface)
podem ocorrer se consideradas necessá rias pelos desenvolvedores principais. Tais mudanças nã o serã o feitas
gratuitamente – elas irã o ocorrer apenas se sé rias falhas fundamentais forem descobertas, que foram esquecidas
anteriormente a inclusã o da API.
Mesmo para APIs provisó rias, mudanças retroativas incompatíveis sã o vistas como uma “soluçã o em ú ltimo
caso” - cada tentativa ainda será feita para encontrar uma resoluçã o retroativa compatível para quaisquer pro-
blemas encontrados.
Esse processo permite que a biblioteca padrã o continue a evoluir com o passar do tempo, sem se prender em
erros de design problemá ticos por períodos de tempo prolongados. Veja PEP 411 para mais detalhes.
pacote provisório
Veja API provisória.
Python 3000
Apelido para a linha de lançamento da versã o do Python 3.x (cunhada há muito tempo, quando o lançamento
da versã o 3 era algo em um futuro muito distante.) Esse termo possui a seguinte abreviaçã o: “Py3k”.
Pythônico
Uma ideia ou um pedaço de có digo que segue de perto as formas de escritas mais comuns da linguagem
Python, ao invé s de implementar có digos usando conceitos comuns a outras linguagens. Por exemplo, um
formato comum em Python é fazer um laço sobre todos os elementos de uma iterá vel usando a instruçã o for.
350 Apêndice A. Glossário
The Python/C API, Release 3.13.7
Muitas outras linguagens nã o tê m esse tipo de construçã o, entã o as pessoas que nã o estã o familiarizadas com
o Python usam um contador numé rico:
for i in range(len(comida)):
print(comida[i])
Ao contrá rio do mé todo mais limpo, Pythô nico:
for parte in comida:
print(parte)
nome qualificado
Um nome pontilhado (quando 2 termos sã o ligados por um ponto) que mostra o “path” do escopo global de um
mó dulo para uma classe, funçã o ou mé todo definido num determinado mó dulo, conforme definido pela PEP
3155. Para funçõ es e classes de nível superior, o nome qualificado é o mesmo que o nome do objeto:
>>> class C:
... class D:
... def metodo(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.metodo.__qualname__
'C.D.metodo'
Quando usado para se referir a mó dulos, o nome totalmente qualificado significa todo o caminho pontilhado
para o mó dulo, incluindo quaisquer pacotes pai, por exemplo: email.mime.text:
>>> import email.mime.text
>>> email.mime.text.__name__
'email.mime.text'
contagem de referências
O nú mero de referê ncias a um objeto. Quando a contagem de referê ncias de um objeto cai para zero, ele é
desalocado. Alguns objetos sã o imortais e tê m contagens de referê ncias que nunca sã o modificadas e, portanto,
os objetos nunca sã o desalocados. A contagem de referê ncias geralmente nã o é visível para o có digo Python,
mas é um elemento-chave da implementaçã o do CPython. Os programadores podem chamar a funçã o sys.
getrefcount() para retornar a contagem de referê ncias para um objeto específico.
Em CPython, as contagens de referê ncias nã o sã o consideradas valores está veis ou bem definidos; o nú mero de
referê ncias a um objeto e como esse nú mero é afetado pelo có digo Python pode ser diferente entre as versõ es.
pacote regular
Um pacote tradicional, como um diretó rio contendo um arquivo __init__.py.
Veja també m pacote de espaço de nomes.
REPL
Um acrô nimo para “read–eval–print loop”, outro nome para o console interativo do interpretador.
__slots__
Uma declaraçã o dentro de uma classe que economiza memó ria pré -declarando espaço para atributos de ins-
tâ ncias, e eliminando dicioná rios de instâ ncias. Apesar de popular, a té cnica é um tanto quanto complicada
de acertar, e é melhor se for reservada para casos raros, onde existe uma grande quantidade de instâ ncias em
uma aplicaçã o onde a memó ria é crítica.
sequência
Um iterável com suporte para acesso eficiente a seus elementos atravé s de índices inteiros via mé todo es-
pecial __getitem__() e que define o mé todo __len__() que devolve o tamanho da sequê ncia. Alguns
351
The Python/C API, Release 3.13.7
tipos de sequê ncia embutidos sã o: list, str, tuple, e bytes. Note que dict també m tem suporte para
__getitem__() e __len__(), mas é considerado um mapeamento e nã o uma sequê ncia porque a busca
usa uma chave hasheável arbitrá ria em vez de inteiros.
A classe base abstrata collections.abc.Sequence define uma interface mais rica que vai alé m
de apenas __getitem__() e __len__(), adicionando count(), index(), __contains__(), e
__reversed__(). Tipos que implementam essa interface podem ser explicitamente registrados usando
register(). Para mais documentaçã o sobre mé todos de sequê ncias em geral, veja Operaçõ es comuns de
sequê ncias.
compreensão de conjunto
Uma maneira compacta de processar todos ou parte dos elementos em iterá vel e retornar um conjunto com
os resultados. results = {c for c in 'abracadabra' if c not in 'abc'} gera um conjunto de
strings {'r', 'd'}. Veja comprehensions.
despacho único
Uma forma de despacho de função genérica onde a implementaçã o é escolhida com base no tipo de um ú nico
argumento.
fatia
Um objeto geralmente contendo uma parte de uma sequência. Uma fatia é criada usando a notaçã o de subscrito
[] pode conter també m até dois pontos entre nú meros, como em variable_name[1:3:5]. A notaçã o de
suporte (subscrito) utiliza objetos slice internamente.
suavemente descontinuado
Uma API suavemente descontinuada nã o deve ser usada em có digo novo, mas é seguro para có digo já existente
usá -la. A API continua documentada e testada, mas nã o será melhorada.
A descontinuaçã o suave, diferentemente da descontinuaçã o normal, nã o planeja remover a API e nã o emitirá
avisos.
Veja PEP 387: Descontinuaçã o suave.
método especial
Um mé todo que é chamado implicitamente pelo Python para executar uma certa operaçã o em um tipo, como
uma adiçã o por exemplo. Tais mé todos tem nomes iniciando e terminando com dois underscores. Mé todos
especiais estã o documentados em specialnames.
biblioteca padrão
A coleçã o de pacotes, módulos e módulos de extensão distribuída como parte do pacote do interpretador Python
oficial. A relaçã o exata de elementos da coleçã o pode variar de acordo com a plataforma, bibliotecas de sistema
disponíveis ou outros crité rios. A documentaçã o pode ser encontrada em library-index.
Veja també m sys.stdlib_module_names para obter uma lista de todos os possíveis nomes de mó dulos da
biblioteca padrã o.
instrução
Uma instruçã o é parte de uma suíte (um “bloco” de có digo). Uma instruçã o é ou uma expressão ou uma de
vá rias construçõ es com uma palavra reservada, tal como if, while ou for.
verificador de tipo estático
Uma ferramenta externa que lê o có digo Python e o analisa, procurando por problemas como tipos incorretos.
Consulte també m dicas de tipo e o mó dulo typing.
stdlib
Uma abreviaçã o para o termo biblioteca padrão em inglê s (standard library).
referência forte
Na API C do Python, uma referê ncia forte é uma referê ncia a um objeto que pertence ao có digo que conté m a
referê ncia. A referê ncia forte é obtida chamando Py_INCREF() quando a referê ncia é criada e liberada com
Py_DECREF() quando a referê ncia é excluída.
A funçã o Py_NewRef() pode ser usada para criar uma referê ncia forte para um objeto. Normalmente, a
funçã o Py_DECREF() deve ser chamada na referê ncia forte antes de sair do escopo da referê ncia forte, para
evitar o vazamento de uma referê ncia.
352 Apêndice A. Glossário
The Python/C API, Release 3.13.7
Veja també m referência emprestada.
codificador de texto
Uma string em Python é uma sequê ncia de pontos de có digo Unicode (no intervalo U+0000–U+10FFFF). Para
armazenar ou transferir uma string, ela precisa ser serializada como uma sequê ncia de bytes.
A serializaçã o de uma string em uma sequê ncia de bytes é conhecida como “codificaçã o” e a recriaçã o da string
a partir de uma sequê ncia de bytes é conhecida como “decodificaçã o”.
Há uma variedade de diferentes serializaçõ es de texto codecs, que sã o coletivamente chamadas de “codificaçõ es
de texto”.
arquivo texto
Um objeto arquivo apto a ler e escrever objetos str. Geralmente, um arquivo texto, na verdade, acessa um
fluxo de dados de bytes e captura o codificador de texto automaticamente. Exemplos de arquivos texto sã o:
arquivos abertos em modo texto ('r' or 'w'), sys.stdin, sys.stdout, e instâ ncias de io.StringIO.
Veja també m arquivo binário para um objeto arquivo apto a ler e escrever objetos bytes ou similares.
token
Uma pequena unidade de có digo-fonte, gerada pelo analisador lé xico (també m chamado de tokenizador). No-
mes, nú meros, strings, operadores, quebras de linha e similares sã o representados por tokens.
O mó dulo tokenize expõ e o analisador lé xico do Python. O mó dulo token conté m informaçõ es sobre os
vá rios tipos de tokens.
aspas triplas
Uma string que está definida com trê s ocorrê ncias de aspas duplas (”) ou apó strofos (‘). Enquanto elas nã o
fornecem nenhuma funcionalidade nã o disponível com strings de aspas simples, elas sã o ú teis para inú meras
razõ es. Elas permitem que você inclua aspas simples e duplas nã o escapadas dentro de uma string, e elas
podem utilizar mú ltiplas linhas sem o uso de caractere de continuaçã o, fazendo-as especialmente ú teis quando
escrevemos documentaçã o em docstrings.
tipo
O tipo de um objeto Python determina qual classe de objeto ele é ; cada objeto tem um tipo. Um tipo de objeto
é acessível pelo atributo __class__ ou pode ser recuperado com type(obj).
apelido de tipo
Um sinô nimo para um tipo, criado atravé s da atribuiçã o do tipo para um identificador.
Apelidos de tipo sã o ú teis para simplificar dicas de tipo. Por exemplo:
def remove_tons_de_cinza(
cores: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass
pode tornar-se mais legível desta forma:
Cor = tuple[int, int, int]
def remove_tons_de_cinza(cores: list[Cor]) -> list[Cor]:
pass
Veja typing e PEP 484, a qual descreve esta funcionalidade.
dica de tipo
Uma anotação que especifica o tipo esperado para uma variá vel, um atributo de classe, ou um parâ metro de
funçã o ou um valor de retorno.
Dicas de tipo sã o opcionais e nã o sã o forçadas pelo Python, mas elas sã o ú teis para verificadores de tipo estático.
Eles també m ajudam IDEs a completar e refatorar có digo.
Dicas de tipos de variá veis globais, atributos de classes, e funçõ es, mas nã o de variá veis locais, podem ser
acessadas usando typing.get_type_hints().
Veja typing e PEP 484, a qual descreve esta funcionalidade.
353
The Python/C API, Release 3.13.7
novas linhas universais
Uma maneira de interpretar fluxos de textos, na qual todos estes sã o reconhecidos como caracteres de fim de
linha: a convençã o para fim de linha no Unix '\n', a convençã o no Windows '\r\n', e a antiga convençã o
no Macintosh '\r'. Veja PEP 278 e PEP 3116, bem como bytes.splitlines() para uso adicional.
anotação de variável
Uma anotação de uma variá vel ou um atributo de classe.
Ao fazer uma anotaçã o de uma variá vel ou um atributo de classe, a atribuiçã o é opcional:
class C:
campo: 'anotação'
Anotaçõ es de variá veis sã o normalmente usadas para dicas de tipo: por exemplo, espera-se que esta variá vel
receba valores do tipo int:
contagem: int = 0
A sintaxe de anotaçã o de variá vel é explicada na seçã o annassign.
Veja anotação de função, PEP 484 e PEP 526, que descrevem esta funcionalidade. Veja també m annotations-
-howto para as melhores prá ticas sobre como trabalhar com anotaçõ es.
ambiente virtual
Um ambiente de execuçã o isolado que permite usuá rios Python e aplicaçõ es instalarem e atualizarem pacotes
Python sem interferir no comportamento de outras aplicaçõ es Python em execuçã o no mesmo sistema.
Veja també m venv.
máquina virtual
Um computador definido inteiramente em software. A má quina virtual de Python executa o bytecode emitido
pelo compilador de bytecode.
operador morsa
Uma maneira bem-humorada de se referir ao operador da expressã o de atribuiçã o := porque ele se parece um
pouco com uma morsa se você virar a cabeça.
Zen do Python
Lista de princípios de projeto e filosofias do Python que sã o ú teis para a compreensã o e uso da linguagem. A
lista é exibida quando se digita “import this” no console interativo.
354 Apêndice A. Glossário
APÊNDICE B
Sobre esta documentação
A documentaçã o do Python é gerada a partir de fontes reStructuredText usando Sphinx, um gerador de documentaçã o
criado originalmente para Python e agora mantido como um projeto independente.
O desenvolvimento da documentaçã o e de suas ferramentas é um esforço totalmente voluntá rio, como Python em
si. Se você quer contribuir, por favor dê uma olhada na pá gina reporting-bugs para informaçõ es sobre como fazer.
Novos voluntá rios sã o sempre bem-vindos!
Agradecimentos especiais para:
• Fred L. Drake, Jr., o criador do primeiro conjunto de ferramentas para documentar Python e autor de boa
parte do conteú do;
• O projeto Docutils por criar reStructuredText e o pacote Docutils;
• Fredrik Lundh, pelo seu projeto de referê ncia alternativa em Python, do qual Sphinx pegou muitas boas ideias.
B.1 Contribuidores da documentação do Python
Muitas pessoas tem contribuído para a linguagem Python, sua biblioteca padrã o e sua documentaçã o. Veja
Misc/ACKS na distribuiçã o do có digo do Python para ver uma lista parcial de contribuidores.
Tudo isso só foi possível com o esforço e a contribuiçã o da comunidade Python, por isso temos essa maravilhosa
documentaçã o – Obrigado a todos!
355
The Python/C API, Release 3.13.7
356 Apêndice B. Sobre esta documentação
APÊNDICE C
História e Licença
C.1 História do software
Python foi criado no início dos anos 1990 por Guido van Rossum no Stichting Mathematisch Centrum (CWI, veja
https://www.cwi.nl) na Holanda como sucessor de uma linguagem chamada ABC. Guido continua sendo o principal
autor do Python, embora inclua muitas contribuiçõ es de outros.
Em 1995, Guido continuou seu trabalho em Python na Corporation for National Research Initiatives (CNRI, veja
https://www.cnri.reston.va.us) em Reston, Virgínia, onde lançou vá rias versõ es do software.
Em maio de 2000, Guido e a equipe de desenvolvimento do nú cleo Python mudaram-se para BeOpen.com para
formar a equipe BeOpen PythonLabs. Em outubro do mesmo ano, a equipe PythonLabs mudou-se para a Di-
gital Creations, que se tornou Zope Corporation. Em 2001, a Python Software Foundation (PSF, veja https:
//www.python.org/psf/) foi formada, uma organizaçã o sem fins lucrativos criada especificamente para possuir Pro-
priedade Intelectual relacionada ao Python. A Zope Corporation era um membro patrocinador da PSF.
Todas as versõ es do Python sã o de có digo aberto (consulte https://opensource.org para a definiçã o de có digo aberto).
Historicamente, a maioria, mas nã o todas, versõ es do Python també m sã o compatíveis com GPL; a tabela abaixo
resume os vá rios lançamentos.
Versão Derivada de Ano Proprietário Compatível com a GPL? (1)
0.9.0 a 1.2 n/a 1991-1995 CWI sim
1.3 a 1.5.2 1.2 1995-1999 CNRI sim
1.6 1.5.2 2000 CNRI nã o
2.0 1.6 2000 BeOpen.com nã o
1.6.1 1.6 2001 CNRI sim (2)
2.1 2.0+1.6.1 2001 PSF nã o
2.0.1 2.0+1.6.1 2001 PSF sim
2.1.1 2.1+2.0.1 2001 PSF sim
2.1.2 2.1.1 2002 PSF sim
2.1.3 2.1.2 2002 PSF sim
2.2 e acima 2.1.1 2001-agora PSF sim
® Nota
357
The Python/C API, Release 3.13.7
(1) Compatível com a GPL nã o significa que estamos distribuindo Python sob a GPL. Todas as licenças do
Python, ao contrá rio da GPL, permitem distribuir uma versã o modificada sem fazer alteraçõ es em có digo
aberto. As licenças compatíveis com a GPL possibilitam combinar o Python com outro software lançado
sob a GPL; os outros nã o.
(2) De acordo com Richard Stallman, 1.6.1 nã o é compatível com GPL, porque sua licença tem uma clá usula
de escolha de lei. De acordo com a CNRI, no entanto, o advogado de Stallman disse ao advogado da CNRI
que 1.6.1 “nã o é incompatível” com a GPL.
Graças aos muitos voluntá rios externos que trabalharam sob a direçã o de Guido para tornar esses lançamentos pos-
síveis.
C.2 Termos e condições para acessar ou usar Python
O software e a documentaçã o do Python sã o licenciados sob a Python Software Foundation License Versã o 2.
A partir do Python 3.8.6, exemplos, receitas e outros có digos na documentaçã o sã o licenciados duplamente sob o
Licença PSF versã o 2 e a Licença BSD de Zero Cláusula.
Alguns softwares incorporados ao Python estã o sob licenças diferentes. As licenças sã o listadas com o có digo abran-
gido por essa licença. Veja Licenças e Reconhecimentos para Software Incorporado para uma lista incompleta dessas
licenças.
C.2.1 PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
the Individual or Organization ("Licensee") accessing and otherwise using this
software ("Python") 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 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 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 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.
4. PSF is making Python available to Licensee on an "AS IS" basis.
PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, 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.
(continua na pró xima pá gina)
358 Apêndice C. História e Licença
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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, Licensee agrees
to be bound by the terms and conditions of this License Agreement.
C.2.2 ACORDO DE LICENCIAMENTO DA BEOPEN.COM PARA PYTHON 2.0
ACORDO DE LICENCIAMENTO DA BEOPEN DE FONTE ABERTA DO PYTHON VERSÃO 1
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
("Licensee") accessing and otherwise using this software in source or binary
form and its associated documentation ("the Software").
2. Subject to the terms and conditions of this BeOpen Python License Agreement,
BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
to reproduce, analyze, test, perform and/or display publicly, prepare derivative
works, distribute, and otherwise use the Software alone or in any derivative
version, provided, however, that the BeOpen Python License is retained in the
Software, alone or in any derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an "AS IS" basis.
BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF
EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
ADVISED OF THE POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material breach of
its terms and conditions.
6. This License Agreement shall be governed by and interpreted in all respects
by the law of the State of California, excluding conflict of law provisions.
Nothing in this License Agreement shall be deemed to create any relationship of
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. Termos e condições para acessar ou usar Python 359
The Python/C API, Release 3.13.7
C.2.3 CONTRATO DE LICENÇA DA CNRI PARA O PYTHON 1.6.1
1. This LICENSE AGREEMENT is between the Corporation for National Research
Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
("CNRI"), and the Individual or Organization ("Licensee") accessing and
otherwise using Python 1.6.1 software in source or binary form and its
associated documentation.
2. Subject to the terms and conditions of this License Agreement, CNRI hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
prepared by Licensee. Alternately, in lieu of CNRI's License Agreement,
Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
is made available subject to the terms and conditions in CNRI's License
Agreement. This Agreement together with Python 1.6.1 may be located on the
internet using the following unique, persistent identifier (known as a handle):
1895.22/1013. This Agreement may also be obtained from a proxy server on the
internet using the following URL: http://hdl.handle.net/1895.22/1013".
3. In the event Licensee prepares a derivative work that is based on or
incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
work available to others as provided herein, then Licensee hereby agrees to
include in any such work a brief summary of the changes made to Python 1.6.1.
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI
MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE,
BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material breach of
its terms and conditions.
7. This License Agreement shall be governed by the federal intellectual property
law of the United States, including without limitation the federal copyright
law, and, to the extent such U.S. federal law does not apply, by the law of the
Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
Notwithstanding the foregoing, with regard to derivative works based on Python
1.6.1 that incorporate non-separable material that was previously distributed
under the GNU General Public License (GPL), the law of the Commonwealth of
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.
(continua na pró xima pá gina)
360 Apêndice C. História e Licença
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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 ACORDO DE LICENÇA DA CWI PARA PYTHON 0.9.0 A 1.2
Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
Netherlands. All rights reserved.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
publicity pertaining to distribution of the software without specific, written
prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
C.2.5 ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTA-
TION
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 Licenças e Reconhecimentos para Software Incorporado
Esta seçã o é uma lista incompleta, mas crescente, de licenças e reconhecimentos para softwares de terceiros incor-
porados na distribuiçã o do Python.
C.3.1 Mersenne Twister
A extensã o C _random subjacente ao mó dulo random inclui có digo baseado em um download de http://www.math.
sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html. A seguir estã o os comentá rios literais do có digo ori-
ginal:
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)
(continua na pró xima pá gina)
C.3. Licenças e Reconhecimentos para Software Incorporado 361
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
C.3.2 Soquetes
O mó dulo socket usa as funçõ es getaddrinfo() e getnameinfo(), que sã o codificadas em arquivos de origem
separados do Projeto WIDE, https://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.
(continua na pró xima pá gina)
362 Apêndice C. História e Licença
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.3 Serviços de soquete assíncrono
Os mó dulos test.support.asynchat e test.support.asyncore contê m o seguinte 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 Gerenciamento de cookies
O mó dulo http.cookies conté m o seguinte 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
(continua na pró xima pá gina)
C.3. Licenças e Reconhecimentos para Software Incorporado 363
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
C.3.5 Rastreamento de execução
O mó dulo trace conté m o seguinte 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 Funções UUencode e UUdecode
O codec uu conté m o seguinte aviso:
Copyright 1994 by Lance Ellinghouse
Cathedral City, California Republic, United States of America.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
(continua na pró xima pá gina)
364 Apêndice C. História e Licença
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Modified by Jack Jansen, CWI, July 1995:
- Use binascii module to do the actual line-by-line conversion
between ascii and binary. This results in a 1000-fold speedup. The C
version is still 5 times faster, though.
- Arguments more compliant with Python standard
C.3.7 Chamadas de procedimento remoto XML
O mó dulo xmlrpc.client conté m o seguinte 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
O mó dulo test.test_epoll conté m o seguinte 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:
(continua na pró xima pá gina)
C.3. Licenças e Reconhecimentos para Software Incorporado 365
The Python/C API, Release 3.13.7
(continuaçã o da 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.9 kqueue de seleção
O mó dulo select conté m o seguinte aviso para a interface do 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
O arquivo Python/pyhash.c conté m a implementaçã o de Marek Majkowski do algoritmo SipHash24 de Dan
Bernstein. Conté m a seguinte 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.
(continua na pró xima pá gina)
366 Apêndice C. História e Licença
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
</MIT License>
Original location:
https://github.com/majek/csiphash/
Solution inspired by code from:
Samuel Neves (supercop/crypto_auth/siphash24/little)
djb (supercop/crypto_auth/siphash24/little2)
Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)
C.3.11 strtod e dtoa
O arquivo Python/dtoa.c, que fornece as funçõ es C dtoa e strtod para conversã o de duplas de C para e de strings,
é derivado do arquivo com o mesmo nome de David M. Gay, atualmente disponível em https://web.archive.org/
web/20220517033456/http://www.netlib.org/fp/dtoa.c. O arquivo original, conforme recuperado em 16 de março
de 2009, conté m os seguintes avisos de direitos autorais e de licenciamento:
/****************************************************************
*
* 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
Os mó dulos hashlib, posix e ssl usam a biblioteca OpenSSL para desempenho adicional se forem disponibi-
lizados pelo sistema operacional. Alé m disso, os instaladores do Windows e do Mac OS X para Python podem
incluir uma có pia das bibliotecas do OpenSSL, portanto incluímos uma có pia da licença do OpenSSL aqui: Para o
lançamento do OpenSSL 3.0, e lançamentos posteriores derivados deste, se aplica a Apache License v2:
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
(continua na pró xima pá gina)
C.3. Licenças e Reconhecimentos para Software Incorporado 367
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
"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,
(continua na pró xima pá gina)
368 Apêndice C. História e Licença
The Python/C API, Release 3.13.7
(continuaçã o da 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
(continua na pró xima pá gina)
C.3. Licenças e Reconhecimentos para Software Incorporado 369
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
370 Apêndice C. História e Licença
The Python/C API, Release 3.13.7
C.3.13 expat
A extensã o pyexpat é construída usando uma có pia incluída das fontes de expatriadas, a menos que a compilaçã o
esteja 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
A extensã o C _ctypes subjacente ao mó dulo ctypes é construída usando uma có pia incluída das fontes do libffi,
a menos que a construçã o esteja configurada com --with-system-libffi:
Copyright (c) 1996-2008 Red Hat, Inc and others.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
C.3. Licenças e Reconhecimentos para Software Incorporado 371
The Python/C API, Release 3.13.7
C.3.15 zlib
A extensã o zlib é construída usando uma có pia incluída das fontes zlib se a versã o do zlib encontrada no sistema
for muito antiga para ser usada na construçã o:
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
A implementaçã o da tabela de hash usada pelo tracemalloc é baseada no projeto cfuhash:
Copyright (c) 2005 Don Owens
All rights reserved.
This code is released under the BSD license:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
(continua na pró xima pá gina)
372 Apêndice C. História e Licença
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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
A extensã o C _decimal subjacente ao mó dulo decimal é construída usando uma có pia incluída da biblioteca
libmpdec, a menos que a construçã o esteja configurada com --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 testes C14N do W3C
O conjunto de testes C14N 2.0 no pacote test (Lib/test/xmltestdata/c14n-20/) foi recuperado do site do
W3C em https://www.w3.org/TR/xml-c14n2-testcases/ e é distribuído sob a licença BSD de 3 clá usulas:
Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang),
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of works must retain the original copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the W3C nor the names of its contributors may be
(continua na pró xima pá gina)
C.3. Licenças e Reconhecimentos para Software Incorporado 373
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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
Licença MIT:
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 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.20 asyncio
Partes do mó dulo asyncio sã o incorporadas do uvloop 0.16, que é distribuído sob a licença MIT:
Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
(continua na pró xima pá gina)
374 Apêndice C. História e Licença
The Python/C API, Release 3.13.7
(continuaçã o da pá gina anterior)
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)
O arquivo Python/qsbr.c é adaptado do esquema de recuperaçã o de memó ria segura “Global Unbounded Se-
quences” do FreeBSD em subr_smr.c. O arquivo é distribuído sob a licença BSD de 2 clá usulas:
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.
C.3. Licenças e Reconhecimentos para Software Incorporado 375
The Python/C API, Release 3.13.7
376 Apêndice C. História e Licença
APÊNDICE D
Direitos autorais
Python e essa documentaçã o é :
Copyright © 2001-2024 Python Software Foundation. Todos os direitos reservados.
Copyright © 2000 BeOpen.com. Todos os direitos reservados.
Copyright © 1995-2000 Corporation for National Research Initiatives. Todos os direitos reservados.
Copyright © 1991-1995 Stichting Mathematisch Centrum. Todos os direitos reservados.
Veja: História e Licença para informaçõ es completas de licença e permissõ es.
377
The Python/C API, Release 3.13.7
378 Apêndice D. Direitos autorais
Referências Bibliográficas
[win] PyExc_WindowsError is only defined on Windows; protect code that uses this by testing that the prepro-
cessor macro MS_WINDOWS is defined.
379
The Python/C API, Release 3.13.7
380 Referências Bibliográficas
Índice
Não alfabético _thread
..., 337 módulo, 226
>>>, 337
__all__ (package variable), 76
A
__dict__ (atributo de módulo), 188 abort (C function), 76
__doc__ (atributo de módulo), 188 abs
__file__ (atributo de módulo), 188, 189 função embutida, 112
__future__, 343 aguardável, 338
__import__ allocfunc (C type), 318
função embutida, 76 ambiente virtual, 354
__loader__ (atributo de módulo), 188 analisador léxico, 346
__main__ anotação, 337
módulo, 12, 217, 232, 233 anotação de função, 343
__name__ (atributo de módulo), 188 anotação de variável, 354
__package__ (atributo de módulo), 188 apelido de tipo, 353
__PYVENV_LAUNCHER__, 251, 256 API provisória, 350
__slots__, 351 argumento, 337
_frozen (C struct), 79 argumento nomeado, 346
_inittab (C struct), 79 argumento posicional, 350
_inittab.initfunc (C member), 80 argv (in module sys), 222, 250
_inittab.name (C member), 80 arquivo
_Py_c_diff (C function), 143 objeto, 186
_Py_c_neg (C function), 143 arquivo binário, 339
_Py_c_pow (C function), 143 arquivo texto, 353
_Py_c_prod (C function), 143 ascii
_Py_c_quot (C function), 143 função embutida, 103
_Py_c_sum (C function), 143 aspas triplas, 353
_Py_InitializeMain (C function), 263 atributo, 338
_Py_NoneStruct (C var), 278
_PyBytes_Resize (C function), 146
B
_PyCode_GetExtra (função C), 186 BDFL, 339
_PyCode_SetExtra (função C), 186 biblioteca padrão, 352
_PyEval_RequestCodeExtraIndex (função C), 186 binaryfunc (C type), 319
_PyFrameEvalFunction (C type), 230 builtins
_PyInterpreterFrame (C struct), 205 módulo, 12, 217, 232, 233
_PyInterpreterState_GetEvalFrameFunc (C bytearray
function), 230 objeto, 146
_PyInterpreterState_SetEvalFrameFunc (C bytecode, 339
function), 230 bytes
_PyObject_GetDictPtr (C function), 103 função embutida, 104
_PyObject_New (C function), 277 objeto, 144
_PyObject_NewVar (C function), 277
_PyTuple_Resize (C function), 167 C
calloc (C function), 265
381
The Python/C API, Release 3.13.7
caminho dica de tipo, 353
módulo pesquisa, 12, 217, 221 dicionário, 341
caminho de importação, 345 objeto, 170
Cápsula divisão pelo piso, 343
objeto, 201 divmod
carregador, 347 função embutida, 111
chamável, 339 docstring, 341
classe, 339 dunder, 342
classe base abstrata, 337
classe estilo novo, 349 E
classmethod EAFP, 342
função embutida, 282 entrada de caminho, 349
cleanup functions, 76 EOFError (exceção embutida), 187
close (in module os), 233 escopo aninhado, 348
CO_ASYNC_GENERATOR (C macro), 185 escopo otimizado, 349
CO_COROUTINE (C macro), 185 espaço de nomes, 348
CO_FUTURE_ABSOLUTE_IMPORT (C macro), 185 especial
CO_FUTURE_ANNOTATIONS (C macro), 185 método, 352
CO_FUTURE_DIVISION (C macro), 185 exc_info (no módulo sys), 11
CO_FUTURE_GENERATOR_STOP (C macro), 185 executable (in module sys), 221
CO_FUTURE_PRINT_FUNCTION (C macro), 185 exit (C function), 76
CO_FUTURE_UNICODE_LITERALS (C macro), 185 expressão, 342
CO_FUTURE_WITH_STATEMENT (C macro), 185 expressão geradora, 344
CO_GENERATOR (C macro), 185
CO_ITERABLE_COROUTINE (C macro), 185 F
CO_NESTED (C macro), 185 f-string, 342
CO_NEWLOCALS (C macro), 185 fatia, 352
CO_OPTIMIZED (C macro), 185 free (C function), 265
CO_VARARGS (C macro), 185 freefunc (C type), 318
CO_VARKEYWORDS (C macro), 185 freeze utility, 79
codificação da localidade, 347 frozenset
codificador de texto, 353 objeto, 175
coleta de lixo, 343 função, 343
Common Vulnerabilities and Exposures objeto, 177
CVE 2008-5983, 222 função chave, 346
compile função de corrotina, 341
função embutida, 77 função de retorno, 339
compreensão de conjunto, 352 função embutida
compreensão de dicionário, 341 __import__, 76
compreensão de lista, 347 abs, 112
contagem de referências, 351 ascii, 103
contexto, 340 bytes, 104
contexto atual, 341 classmethod, 282
contíguo, 122, 340 compile, 77
contíguo C, 122, 340 divmod, 111
contíguo Fortran, 122, 340 hash, 104, 297
copyright (in module sys), 222 int, 113
corrotina, 340 len, 105, 114, 116, 169, 173, 176
CPython, 341 ponto flutuante, 113
pow, 111, 113
D repr, 103, 296
decorador, 341 staticmethod, 282
descrgetfunc (C type), 319 tipo, 104
descritor, 341 tupla, 115, 170
descrsetfunc (C type), 319 função genérica, 344
desligamento do interpretador, 345
despacho único, 352 G
destructor (C type), 318 gancho de entrada de caminho, 350
382 Índice
The Python/C API, Release 3.13.7
gcvisitobjects_t (C type), 325 localizador, 343
gerador, 343, 344 localizador baseado no caminho, 350
gerador assíncrono, 338 localizador de entrada de caminho, 350
gerenciador de contexto, 340 localizador de metacaminho, 347
gerenciador de contexto assíncrono, 338 lock, interpreter, 223
getattrfunc (C type), 318 long integer
getattrofunc (C type), 318 objeto, 133
getbufferproc (C type), 319 LONG_MAX (C macro), 135
getiterfunc (C type), 319
getter (C type), 286 M
GIL, 344 mágico
método, 347
H main(), 220, 222, 250
hash malloc (C function), 265
função embutida, 104, 297 mapeamento, 347
hasheável, 344 objeto, 170
hashfunc (C type), 319 máquina virtual, 354
memoryview
I objeto, 199
IDLE, 345 metaclasse, 347
imortal, 345 METH_CLASS (C macro), 282
importação, 345 METH_COEXIST (C macro), 282
importador, 345 METH_FASTCALL (C macro), 281
imutável, 345 METH_KEYWORDS (C macro), 281
incr_item(), 11, 12 METH_METHOD (C macro), 281
initproc (C type), 318 METH_NOARGS (C macro), 282
inquiry (C type), 324 METH_O (C macro), 282
instancemethod METH_STATIC (C macro), 282
objeto, 180 METH_VARARGS (C macro), 281
instrução, 352 MethodType (em tipos de módulos), 177, 180
int método, 347
função embutida, 113 especial, 352
inteiro mágico, 347
objeto, 133 objeto, 180
interativo, 345 método especial, 352
interface de buffer método mágico, 347
(veja o protocolo de buffer), 118 modules (in module sys), 76, 217
interpretado, 345 ModuleType (in module types), 188
interpreter lock, 223 módulo, 347
iterador, 346 __main__, 12, 217, 232, 233
iterador assíncrono, 338 _thread, 226
iterador gerador, 344 builtins, 12, 217, 232, 233
iterador gerador assíncrono, 338 objeto, 188
iterável, 345 pesquisa caminho, 12, 217, 221
iterável assíncrono, 338 signal, 61
iternextfunc (C type), 319 sys, 12, 217, 232, 233
módulo de extensão, 342
K MRO, 348
KeyboardInterrupt (built-in exception), 61 mutável, 348
L N
lambda, 346 newfunc (C type), 318
LBYL, 346 nome qualificado, 351
len None
função embutida, 105, 114, 116, 169, 173, 176 objeto, 133
lenfunc (C type), 319 novas linhas universais, 354
lista, 346 numérico
objeto, 168 objeto, 133
Índice 383
The Python/C API, Release 3.13.7
número complexo, 340 objeto, 141
objeto, 142 porção, 350
pow
O função embutida, 111, 113
objeto, 349 Propostas de Melhorias do Python
arquivo, 186 PEP 1, 350
bytearray, 146 PEP 7, 3, 6
bytes, 144 PEP 238, 343
Cápsula, 201 PEP 278, 354
código, 181 PEP 302, 347
dicionário, 170 PEP 343, 340
frozenset, 175 PEP 353, 10
função, 177 PEP 362, 338, 349
instancemethod, 180 PEP 383, 155, 156
inteiro, 133 PEP 387, 15, 16
lista, 168 PEP 393, 147
long integer, 133 PEP 411, 350
mapeamento, 170 PEP 420, 348, 350
memoryview, 199 PEP 432, 263, 264
método, 180 PEP 442, 312
módulo, 188 PEP 443, 344
None, 133 PEP 451, 191
numérico, 133 PEP 456, 93
número complexo, 142 PEP 483, 344
ponto flutuante, 141 PEP 484, 337, 343, 344, 353, 354
sequência, 144 PEP 489, 192, 231
set, 175 PEP 492, 338, 340, 341
tipo, 7, 127 PEP 498, 342
tupla, 165 PEP 519, 350
objeto arquivo, 342 PEP 523, 205, 230
objeto arquivo ou similar, 342 PEP 525, 338
objeto buffer PEP 526, 337, 354
(veja o protocolo de buffer), 118 PEP 528, 216, 255
objeto bytes ou similar, 339 PEP 529, 156, 216
objeto caminho ou similar, 350 PEP 538, 261
objeto código, 181 PEP 539, 237
objobjargproc (C type), 319 PEP 540, 261
objobjproc (C type), 319 PEP 552, 252
operador morsa, 354 PEP 554, 233
ordem de resolução de métodos, 347 PEP 578, 75
OverflowError (built-in exception), 135, 136 PEP 585, 344
PEP 587, 243
P PEP 590, 106
PEP 623, 147
package variable
PEP 0626#out-of-process-debuggers-and-profilers,
__all__, 76
pacote, 349
182
PEP 634, 302
pacote de espaço de nomes, 348
PEP 667, 93, 204
pacote provisório, 350
PEP 0683, 49, 50, 345
pacote regular, 351
PEP 703, 343, 344
parâmetro, 349
PEP 3116, 354
PATH, 12, 13
PEP 3119, 104
path (no módulo sys), 12, 217, 221
PEP 3121, 189
PEP, 350
PEP 3147, 78
pesquisa
PEP 3151, 69
caminho, módulo, 12, 217, 221
PEP 3155, 351
platform (in module sys), 222
protocolo de buffer, 118
ponto flutuante
função embutida, 113
384 Índice
The Python/C API, Release 3.13.7
protocolo de gerenciamento de contexto, Py_CONSTANT_ZERO (C macro), 100
340 PY_CXX_CONST (C macro), 87
Py_ABS (C macro), 5 Py_DEBUG (C macro), 13
Py_AddPendingCall (C function), 234 Py_DebugFlag (C var), 214
Py_ALWAYS_INLINE (C macro), 5 Py_DecodeLocale (C function), 73
Py_ASNATIVEBYTES_ALLOW_INDEX (C macro), 139 Py_DECREF (C function), 50
Py_ASNATIVEBYTES_BIG_ENDIAN (C macro), 139 Py_DecRef (C function), 51
Py_ASNATIVEBYTES_DEFAULTS (C macro), 139 Py_DECREF (função C), 7
Py_ASNATIVEBYTES_LITTLE_ENDIAN (C macro), Py_DEPRECATED (C macro), 5
139 Py_DontWriteBytecodeFlag (C var), 215
Py_ASNATIVEBYTES_NATIVE_ENDIAN (C macro), Py_Ellipsis (C var), 199
139 Py_EncodeLocale (C function), 73
Py_ASNATIVEBYTES_REJECT_NEGATIVE (C macro), Py_END_ALLOW_THREADS (C macro), 224, 227
139 Py_END_CRITICAL_SECTION (C macro), 240
Py_ASNATIVEBYTES_UNSIGNED_BUFFER (C macro), Py_END_CRITICAL_SECTION2 (C macro), 241
139 Py_EndInterpreter (C function), 233
Py_AtExit (C function), 76 Py_EnterRecursiveCall (C function), 64
Py_AUDIT_READ (C macro), 284 Py_EQ (C macro), 305
Py_AuditHookFunction (C type), 75 Py_eval_input (C var), 46
Py_BEGIN_ALLOW_THREADS (C macro), 224, 227 Py_Exit (C function), 76
Py_BEGIN_CRITICAL_SECTION (C macro), 240 Py_ExitStatusException (C function), 245
Py_BEGIN_CRITICAL_SECTION2 (C macro), 241 Py_False (C var), 140
Py_BLOCK_THREADS (C macro), 228 Py_FatalError (C function), 76
Py_buffer (C type), 119 Py_FatalError(), 222
Py_buffer.buf (C member), 119 Py_FdIsInteractive (C function), 71
Py_buffer.format (C member), 120 Py_file_input (C var), 46
Py_buffer.internal (C member), 120 Py_Finalize (C function), 219
Py_buffer.itemsize (C member), 120 Py_FinalizeEx (C function), 76, 217, 218, 232, 233
Py_buffer.len (C member), 119 Py_FrozenFlag (C var), 215
Py_buffer.ndim (C member), 120 Py_GE (C macro), 305
Py_buffer.obj (C member), 119 Py_GenericAlias (C function), 211
Py_buffer.readonly (C member), 120 Py_GenericAliasType (C var), 212
Py_buffer.shape (C member), 120 Py_GetArgcArgv (C function), 263
Py_buffer.strides (C member), 120 Py_GetBuildInfo (C function), 222
Py_buffer.suboffsets (C member), 120 Py_GetCompiler (C function), 222
Py_BuildValue (C function), 88 Py_GetConstant (C function), 99
Py_BytesMain (C function), 219 Py_GetConstantBorrowed (C function), 100
Py_BytesWarningFlag (C var), 214 Py_GetCopyright (C function), 222
Py_CHARMASK (C macro), 5 Py_GETENV (C macro), 5
Py_CLEANUP_SUPPORTED (C macro), 85 Py_GetExecPrefix (C function), 221
Py_CLEAR (C function), 50 Py_GetExecPrefix (função C), 13
Py_CompileString (C function), 45 Py_GetPath (C function), 221
Py_CompileString (função C), 46 Py_GetPath (função C), 13
Py_CompileStringExFlags (C function), 46 Py_GetPath(), 220
Py_CompileStringFlags (C function), 45 Py_GetPlatform (C function), 222
Py_CompileStringObject (C function), 45 Py_GetPrefix (C function), 220
Py_complex (C type), 143 Py_GetPrefix (função C), 13
Py_complex.imag (C member), 143 Py_GetProgramFullPath (C function), 221
Py_complex.real (C member), 143 Py_GetProgramFullPath (função C), 13
Py_CONSTANT_ELLIPSIS (C macro), 100 Py_GetProgramName (C function), 220
Py_CONSTANT_EMPTY_BYTES (C macro), 100 Py_GetPythonHome (C function), 223
Py_CONSTANT_EMPTY_STR (C macro), 100 Py_GetVersion (C function), 221
Py_CONSTANT_EMPTY_TUPLE (C macro), 100 Py_GT (C macro), 305
Py_CONSTANT_FALSE (C macro), 100 Py_hash_t (C type), 92
Py_CONSTANT_NONE (C macro), 100 Py_HashPointer (C function), 93
Py_CONSTANT_NOT_IMPLEMENTED (C macro), 100 Py_HashRandomizationFlag (C var), 215
Py_CONSTANT_ONE (C macro), 100 Py_IgnoreEnvironmentFlag (C var), 215
Py_CONSTANT_TRUE (C macro), 100 Py_INCREF (C function), 49
Índice 385
The Python/C API, Release 3.13.7
Py_IncRef (C function), 51 PY_MONITORING_EVENT_PY_YIELD (C macro), 334
Py_INCREF (função C), 7 PY_MONITORING_EVENT_RAISE (C macro), 334
Py_Initialize (C function), 217 PY_MONITORING_EVENT_RERAISE (C macro), 334
Py_Initialize (função C), 12, 232 PY_MONITORING_EVENT_STOP_ITERATION (C ma-
Py_Initialize(), 220 cro), 334
Py_InitializeEx (C function), 218 PY_MONITORING_IS_INSTRUMENTED_EVENT (C
Py_InitializeFromConfig (C function), 218 function), 334
Py_InspectFlag (C var), 215 Py_NE (C macro), 305
Py_InteractiveFlag (C var), 215 Py_NewInterpreter (C function), 233
Py_Is (C function), 278 Py_NewInterpreterFromConfig (C function), 232
Py_IS_TYPE (C function), 279 Py_NewRef (C function), 50
Py_IsFalse (C function), 279 Py_NO_INLINE (C macro), 5
Py_IsFinalizing (C function), 218 Py_None (C var), 133
Py_IsInitialized (C function), 218 Py_NoSiteFlag (C var), 216
Py_IsInitialized (função C), 13 Py_NotImplemented (C var), 100
Py_IsNone (C function), 279 Py_NoUserSiteDirectory (C var), 216
Py_IsolatedFlag (C var), 216 Py_OpenCodeHookFunction (C type), 187
Py_IsTrue (C function), 279 Py_OptimizeFlag (C var), 217
Py_LE (C macro), 305 Py_PreInitialize (C function), 248
Py_LeaveRecursiveCall (C function), 64 Py_PreInitializeFromArgs (C function), 248
Py_LegacyWindowsFSEncodingFlag (C var), 216 Py_PreInitializeFromBytesArgs (C function),
Py_LegacyWindowsStdioFlag (C var), 216 248
Py_LIMITED_API (C macro), 16 Py_PRINT_RAW (C macro), 100
Py_LT (C macro), 305 Py_PRINT_RAW (macro C), 187
Py_Main (C function), 219 Py_QuietFlag (C var), 217
PY_MAJOR_VERSION (C macro), 327 Py_READONLY (C macro), 284
Py_MAX (C macro), 5 Py_REFCNT (C function), 49
Py_MEMBER_SIZE (C macro), 5 Py_RELATIVE_OFFSET (C macro), 284
PY_MICRO_VERSION (C macro), 327 PY_RELEASE_LEVEL (C macro), 327
Py_MIN (C macro), 5 PY_RELEASE_SERIAL (C macro), 327
PY_MINOR_VERSION (C macro), 327 Py_ReprEnter (C function), 64
Py_mod_create (C macro), 191 Py_ReprLeave (C function), 64
Py_mod_exec (C macro), 192 Py_RETURN_FALSE (C macro), 140
Py_mod_gil (C macro), 192 Py_RETURN_NONE (C macro), 133
Py_MOD_GIL_NOT_USED (C macro), 192 Py_RETURN_NOTIMPLEMENTED (C macro), 100
Py_MOD_GIL_USED (C macro), 192 Py_RETURN_RICHCOMPARE (C macro), 305
Py_mod_multiple_interpreters (C macro), 192 Py_RETURN_TRUE (C macro), 140
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED Py_RunMain (C function), 219
(C macro), 192 Py_SET_REFCNT (C function), 49
Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED (C Py_SET_SIZE (C function), 279
macro), 192 Py_SET_TYPE (C function), 279
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED (C Py_SetProgramName (C function), 220
macro), 192 Py_SetPythonHome (C function), 223
PY_MONITORING_EVENT_BRANCH (C macro), 334 Py_SETREF (C macro), 51
PY_MONITORING_EVENT_C_RAISE (C macro), 334 Py_single_input (C var), 46
PY_MONITORING_EVENT_C_RETURN (C macro), 334 Py_SIZE (C function), 279
PY_MONITORING_EVENT_CALL (C macro), 334 Py_ssize_t (C type), 10
PY_MONITORING_EVENT_EXCEPTION_HANDLED (C PY_SSIZE_T_MAX (C macro), 136
macro), 334 Py_STRINGIFY (C macro), 6
PY_MONITORING_EVENT_INSTRUCTION (C macro), Py_T_BOOL (C macro), 285
334 Py_T_BYTE (C macro), 285
PY_MONITORING_EVENT_JUMP (C macro), 334 Py_T_CHAR (C macro), 285
PY_MONITORING_EVENT_LINE (C macro), 334 Py_T_DOUBLE (C macro), 285
PY_MONITORING_EVENT_PY_RESUME (C macro), 334 Py_T_FLOAT (C macro), 285
PY_MONITORING_EVENT_PY_RETURN (C macro), 334 Py_T_INT (C macro), 285
PY_MONITORING_EVENT_PY_START (C macro), 334 Py_T_LONG (C macro), 285
PY_MONITORING_EVENT_PY_THROW (C macro), 334 Py_T_LONGLONG (C macro), 285
PY_MONITORING_EVENT_PY_UNWIND (C macro), 334 Py_T_OBJECT_EX (C macro), 285
386 Índice
The Python/C API, Release 3.13.7
Py_T_PYSSIZET (C macro), 285 Py_UNICODE_ISSPACE (C function), 150
Py_T_SHORT (C macro), 285 Py_UNICODE_ISTITLE (C function), 150
Py_T_STRING (C macro), 285 Py_UNICODE_ISUPPER (C function), 150
Py_T_STRING_INPLACE (C macro), 285 Py_UNICODE_JOIN_SURROGATES (C function), 151
Py_T_UBYTE (C macro), 285 Py_UNICODE_TODECIMAL (C function), 150
Py_T_UINT (C macro), 285 Py_UNICODE_TODIGIT (C function), 150
Py_T_ULONG (C macro), 285 Py_UNICODE_TOLOWER (C function), 150
Py_T_ULONGLONG (C macro), 285 Py_UNICODE_TONUMERIC (C function), 150
Py_T_USHORT (C macro), 285 Py_UNICODE_TOTITLE (C function), 150
Py_TPFLAGS_BASE_EXC_SUBCLASS (C macro), 301 Py_UNICODE_TOUPPER (C function), 150
Py_TPFLAGS_BASETYPE (C macro), 299 Py_UNREACHABLE (C macro), 6
Py_TPFLAGS_BYTES_SUBCLASS (C macro), 301 Py_UNUSED (C macro), 6
Py_TPFLAGS_DEFAULT (C macro), 299 Py_VaBuildValue (C function), 90
Py_TPFLAGS_DICT_SUBCLASS (C macro), 301 PY_VECTORCALL_ARGUMENTS_OFFSET (C macro),
Py_TPFLAGS_DISALLOW_INSTANTIATION (C macro), 107
301 Py_VerboseFlag (C var), 217
Py_TPFLAGS_HAVE_FINALIZE (C macro), 301 Py_Version (C var), 328
Py_TPFLAGS_HAVE_GC (C macro), 299 PY_VERSION_HEX (C macro), 327
Py_TPFLAGS_HAVE_VECTORCALL (C macro), 301 Py_VISIT (C macro), 324
Py_TPFLAGS_HEAPTYPE (C macro), 299 Py_XDECREF (C function), 50
Py_TPFLAGS_IMMUTABLETYPE (C macro), 301 Py_XDECREF (função C), 12
Py_TPFLAGS_ITEMS_AT_END (C macro), 300 Py_XINCREF (C function), 49
Py_TPFLAGS_LIST_SUBCLASS (C macro), 301 Py_XNewRef (C function), 50
Py_TPFLAGS_LONG_SUBCLASS (C macro), 300 Py_XSETREF (C macro), 51
Py_TPFLAGS_MANAGED_DICT (C macro), 300 PyAIter_Check (C function), 117
Py_TPFLAGS_MANAGED_WEAKREF (C macro), 300 PyAnySet_Check (C function), 176
Py_TPFLAGS_MAPPING (C macro), 302 PyAnySet_CheckExact (C function), 176
Py_TPFLAGS_METHOD_DESCRIPTOR (C macro), 300 PyArg_Parse (C function), 86
Py_TPFLAGS_READY (C macro), 299 PyArg_ParseTuple (C function), 86
Py_TPFLAGS_READYING (C macro), 299 PyArg_ParseTupleAndKeywords (C function), 86
Py_TPFLAGS_SEQUENCE (C macro), 302 PyArg_UnpackTuple (C function), 87
Py_TPFLAGS_TUPLE_SUBCLASS (C macro), 301 PyArg_ValidateKeywordArguments (C function),
Py_TPFLAGS_TYPE_SUBCLASS (C macro), 301 86
Py_TPFLAGS_UNICODE_SUBCLASS (C macro), 301 PyArg_VaParse (C function), 86
Py_TPFLAGS_VALID_VERSION_TAG (C macro), 302 PyArg_VaParseTupleAndKeywords (C function), 86
Py_tracefunc (C type), 235 PyASCIIObject (C type), 148
Py_True (C var), 140 PyAsyncMethods (C type), 317
Py_tss_NEEDS_INIT (C macro), 238 PyAsyncMethods.am_aiter (C member), 317
Py_tss_t (C type), 237 PyAsyncMethods.am_anext (C member), 318
Py_TYPE (C function), 279 PyAsyncMethods.am_await (C member), 317
Py_UCS1 (C type), 148 PyAsyncMethods.am_send (C member), 318
Py_UCS2 (C type), 148 PyBaseObject_Type (C var), 278
Py_UCS4 (C type), 148 PyBool_Check (C function), 140
Py_uhash_t (C type), 92 PyBool_FromLong (C function), 140
Py_UNBLOCK_THREADS (C macro), 228 PyBool_Type (C var), 140
Py_UnbufferedStdioFlag (C var), 217 PyBUF_ANY_CONTIGUOUS (C macro), 122
Py_UNICODE (C type), 148 PyBUF_C_CONTIGUOUS (C macro), 122
Py_UNICODE_IS_HIGH_SURROGATE (C function), 151 PyBUF_CONTIG (C macro), 123
Py_UNICODE_IS_LOW_SURROGATE (C function), 151 PyBUF_CONTIG_RO (C macro), 123
Py_UNICODE_IS_SURROGATE (C function), 150 PyBUF_F_CONTIGUOUS (C macro), 122
Py_UNICODE_ISALNUM (C function), 150 PyBUF_FORMAT (C macro), 121
Py_UNICODE_ISALPHA (C function), 150 PyBUF_FULL (C macro), 123
Py_UNICODE_ISDECIMAL (C function), 150 PyBUF_FULL_RO (C macro), 123
Py_UNICODE_ISDIGIT (C function), 150 PyBUF_INDIRECT (C macro), 122
Py_UNICODE_ISLINEBREAK (C function), 150 PyBUF_MAX_NDIM (C macro), 121
Py_UNICODE_ISLOWER (C function), 150 PyBUF_ND (C macro), 122
Py_UNICODE_ISNUMERIC (C function), 150 PyBUF_READ (C macro), 199
Py_UNICODE_ISPRINTABLE (C function), 150 PyBUF_RECORDS (C macro), 123
Índice 387
The Python/C API, Release 3.13.7
PyBUF_RECORDS_RO (C macro), 123 PyCapsule_GetContext (C function), 202
PyBUF_SIMPLE (C macro), 122 PyCapsule_GetDestructor (C function), 202
PyBUF_STRIDED (C macro), 123 PyCapsule_GetName (C function), 202
PyBUF_STRIDED_RO (C macro), 123 PyCapsule_GetPointer (C function), 201
PyBUF_STRIDES (C macro), 122 PyCapsule_Import (C function), 202
PyBUF_WRITABLE (C macro), 121 PyCapsule_IsValid (C function), 202
PyBUF_WRITE (C macro), 199 PyCapsule_New (C function), 201
PyBuffer_FillContiguousStrides (C function), PyCapsule_SetContext (C function), 202
125 PyCapsule_SetDestructor (C function), 203
PyBuffer_FillInfo (C function), 125 PyCapsule_SetName (C function), 203
PyBuffer_FromContiguous (C function), 125 PyCapsule_SetPointer (C function), 203
PyBuffer_GetPointer (C function), 125 PyCell_Check (C function), 181
PyBuffer_IsContiguous (C function), 125 PyCell_GET (C function), 181
PyBuffer_Release (C function), 124 PyCell_Get (C function), 181
PyBuffer_SizeFromFormat (C function), 125 PyCell_New (C function), 181
PyBuffer_ToContiguous (C function), 125 PyCell_SET (C function), 181
PyBufferProcs (C type), 316 PyCell_Set (C function), 181
PyBufferProcs (tipo C), 118 PyCell_Type (C var), 181
PyBufferProcs.bf_getbuffer (C member), 316 PyCellObject (C type), 180
PyBufferProcs.bf_releasebuffer (C member), PyCF_ALLOW_TOP_LEVEL_AWAIT (C macro), 47
317 PyCF_ONLY_AST (C macro), 47
PyByteArray_AS_STRING (C function), 147 PyCF_OPTIMIZED_AST (C macro), 47
PyByteArray_AsString (C function), 147 PyCF_TYPE_COMMENTS (C macro), 47
PyByteArray_Check (C function), 146 PyCFunction (C type), 280
PyByteArray_CheckExact (C function), 146 PyCFunction_New (C function), 282
PyByteArray_Concat (C function), 147 PyCFunction_NewEx (C function), 282
PyByteArray_FromObject (C function), 147 PyCFunctionFast (C type), 280
PyByteArray_FromStringAndSize (C function), PyCFunctionFastWithKeywords (C type), 280
147 PyCFunctionWithKeywords (C type), 280
PyByteArray_GET_SIZE (C function), 147 PyCMethod (C type), 280
PyByteArray_Resize (C function), 147 PyCMethod_New (C function), 282
PyByteArray_Size (C function), 147 PyCode_Addr2Line (C function), 182
PyByteArray_Type (C var), 146 PyCode_Addr2Location (C function), 182
PyByteArrayObject (C type), 146 PyCode_AddWatcher (C function), 183
PyBytes_AS_STRING (C function), 146 PyCode_Check (C function), 181
PyBytes_AsString (C function), 145 PyCode_ClearWatcher (C function), 183
PyBytes_AsStringAndSize (C function), 146 PyCode_GetCellvars (C function), 183
PyBytes_Check (C function), 144 PyCode_GetCode (C function), 183
PyBytes_CheckExact (C function), 144 PyCode_GetFreevars (C function), 183
PyBytes_Concat (C function), 146 PyCode_GetNumFree (C function), 181
PyBytes_ConcatAndDel (C function), 146 PyCode_GetVarnames (C function), 183
PyBytes_FromFormat (C function), 145 PyCode_New (função C), 182
PyBytes_FromFormatV (C function), 145 PyCode_NewEmpty (C function), 182
PyBytes_FromObject (C function), 145 PyCode_NewWithPosOnlyArgs (função C), 182
PyBytes_FromString (C function), 145 PyCode_Type (C var), 181
PyBytes_FromStringAndSize (C function), 145 PyCode_WatchCallback (C type), 183
PyBytes_GET_SIZE (C function), 145 PyCodec_BackslashReplaceErrors (C function),
PyBytes_Size (C function), 145 96
PyBytes_Type (C var), 144 PyCodec_Decode (C function), 94
PyBytesObject (C type), 144 PyCodec_Decoder (C function), 95
pyc baseado em hash, 344 PyCodec_Encode (C function), 94
PyCallable_Check (C function), 111 PyCodec_Encoder (C function), 95
PyCallIter_Check (C function), 196 PyCodec_IgnoreErrors (C function), 95
PyCallIter_New (C function), 197 PyCodec_IncrementalDecoder (C function), 95
PyCallIter_Type (C var), 196 PyCodec_IncrementalEncoder (C function), 95
PyCapsule (C type), 201 PyCodec_KnownEncoding (C function), 94
PyCapsule_CheckExact (C function), 201 PyCodec_LookupError (C function), 95
PyCapsule_Destructor (C type), 201 PyCodec_NameReplaceErrors (C function), 96
388 Índice
The Python/C API, Release 3.13.7
PyCodec_Register (C function), 94 PyConfig.install_signal_handlers (C mem-
PyCodec_RegisterError (C function), 95 ber), 254
PyCodec_ReplaceErrors (C function), 96 PyConfig.int_max_str_digits (C member), 254
PyCodec_StreamReader (C function), 95 PyConfig.interactive (C member), 254
PyCodec_StreamWriter (C function), 95 PyConfig.isolated (C member), 254
PyCodec_StrictErrors (C function), 95 PyConfig.legacy_windows_stdio (C member),
PyCodec_Unregister (C function), 94 254
PyCodec_XMLCharRefReplaceErrors (C function), PyConfig.malloc_stats (C member), 255
96 PyConfig.module_search_paths (C member), 255
PyCodeEvent (C type), 183 PyConfig.module_search_paths_set (C mem-
PyCodeObject (C type), 181 ber), 255
PyCompactUnicodeObject (C type), 148 PyConfig.optimization_level (C member), 255
PyCompilerFlags (C struct), 46 PyConfig.orig_argv (C member), 255
PyCompilerFlags.cf_feature_version (C mem- PyConfig.parse_argv (C member), 256
ber), 47 PyConfig.parser_debug (C member), 256
PyCompilerFlags.cf_flags (C member), 46 PyConfig.pathconfig_warnings (C member), 256
PyComplex_AsCComplex (C function), 144 PyConfig.perf_profiling (C member), 258
PyComplex_Check (C function), 143 PyConfig.platlibdir (C member), 255
PyComplex_CheckExact (C function), 143 PyConfig.prefix (C member), 256
PyComplex_FromCComplex (C function), 143 PyConfig.program_name (C member), 256
PyComplex_FromDoubles (C function), 143 PyConfig.pycache_prefix (C member), 256
PyComplex_ImagAsDouble (C function), 144 PyConfig.pythonpath_env (C member), 255
PyComplex_RealAsDouble (C function), 144 PyConfig.quiet (C member), 256
PyComplex_Type (C var), 143 PyConfig.run_command (C member), 257
PyComplexObject (C type), 143 PyConfig.run_filename (C member), 257
PyConfig (C type), 249 PyConfig.run_module (C member), 257
PyConfig_Clear (C function), 250 PyConfig.run_presite (C member), 257
PyConfig_InitIsolatedConfig (C function), 249 PyConfig.safe_path (C member), 250
PyConfig_InitPythonConfig (C function), 249 PyConfig.show_ref_count (C member), 257
PyConfig_Read (C function), 249 PyConfig.site_import (C member), 257
PyConfig_SetArgv (C function), 249 PyConfig.skip_source_first_line (C member),
PyConfig_SetBytesArgv (C function), 249 257
PyConfig_SetBytesString (C function), 249 PyConfig.stdio_encoding (C member), 258
PyConfig_SetString (C function), 249 PyConfig.stdio_errors (C member), 258
PyConfig_SetWideStringList (C function), 249 PyConfig.tracemalloc (C member), 258
PyConfig.argv (C member), 250 PyConfig.use_environment (C member), 258
PyConfig.base_exec_prefix (C member), 250 PyConfig.use_hash_seed (C member), 253
PyConfig.base_executable (C member), 250 PyConfig.user_site_directory (C member), 258
PyConfig.base_prefix (C member), 251 PyConfig.verbose (C member), 259
PyConfig.buffered_stdio (C member), 251 PyConfig.warn_default_encoding (C member),
PyConfig.bytes_warning (C member), 251 251
PyConfig.check_hash_pycs_mode (C member), PyConfig.warnoptions (C member), 259
251 PyConfig.write_bytecode (C member), 259
PyConfig.code_debug_ranges (C member), 251 PyConfig.xoptions (C member), 259
PyConfig.configure_c_stdio (C member), 252 PyContext (C type), 206
PyConfig.cpu_count (C member), 254 PyContext_CheckExact (C function), 207
PyConfig.dev_mode (C member), 252 PyContext_Copy (C function), 207
PyConfig.dump_refs (C member), 252 PyContext_CopyCurrent (C function), 207
PyConfig.exec_prefix (C member), 252 PyContext_Enter (C function), 207
PyConfig.executable (C member), 252 PyContext_Exit (C function), 207
PyConfig.faulthandler (C member), 252 PyContext_New (C function), 207
PyConfig.filesystem_encoding (C member), 252 PyContext_Type (C var), 206
PyConfig.filesystem_errors (C member), 253 PyContextToken (C type), 206
PyConfig.hash_seed (C member), 253 PyContextToken_CheckExact (C function), 207
PyConfig.home (C member), 253 PyContextToken_Type (C var), 207
PyConfig.import_time (C member), 253 PyContextVar (C type), 206
PyConfig.inspect (C member), 253 PyContextVar_CheckExact (C function), 207
PyContextVar_Get (C function), 207
Índice 389
The Python/C API, Release 3.13.7
PyContextVar_New (C function), 207 PyDict_AddWatcher (C function), 174
PyContextVar_Reset (C function), 208 PyDict_Check (C function), 170
PyContextVar_Set (C function), 207 PyDict_CheckExact (C function), 170
PyContextVar_Type (C var), 207 PyDict_Clear (C function), 171
PyCoro_CheckExact (C function), 206 PyDict_ClearWatcher (C function), 174
PyCoro_New (C function), 206 PyDict_Contains (C function), 171
PyCoro_Type (C var), 206 PyDict_ContainsString (C function), 171
PyCoroObject (C type), 206 PyDict_Copy (C function), 171
PyDate_Check (C function), 208 PyDict_DelItem (C function), 171
PyDate_CheckExact (C function), 208 PyDict_DelItemString (C function), 171
PyDate_FromDate (C function), 209 PyDict_GetItem (C function), 171
PyDate_FromTimestamp (C function), 211 PyDict_GetItemRef (C function), 171
PyDateTime_Check (C function), 209 PyDict_GetItemString (C function), 172
PyDateTime_CheckExact (C function), 209 PyDict_GetItemStringRef (C function), 172
PyDateTime_Date (C type), 208 PyDict_GetItemWithError (C function), 172
PyDateTime_DATE_GET_FOLD (C function), 210 PyDict_Items (C function), 173
PyDateTime_DATE_GET_HOUR (C function), 210 PyDict_Keys (C function), 173
PyDateTime_DATE_GET_MICROSECOND (C function), PyDict_Merge (C function), 174
210 PyDict_MergeFromSeq2 (C function), 174
PyDateTime_DATE_GET_MINUTE (C function), 210 PyDict_New (C function), 170
PyDateTime_DATE_GET_SECOND (C function), 210 PyDict_Next (C function), 173
PyDateTime_DATE_GET_TZINFO (C function), 210 PyDict_Pop (C function), 172
PyDateTime_DateTime (C type), 208 PyDict_PopString (C function), 173
PyDateTime_DateTimeType (C var), 208 PyDict_SetDefault (C function), 172
PyDateTime_DateType (C var), 208 PyDict_SetDefaultRef (C function), 172
PyDateTime_Delta (C type), 208 PyDict_SetItem (C function), 171
PyDateTime_DELTA_GET_DAYS (C function), 211 PyDict_SetItemString (C function), 171
PyDateTime_DELTA_GET_MICROSECONDS (C func- PyDict_Size (C function), 173
tion), 211 PyDict_Type (C var), 170
PyDateTime_DELTA_GET_SECONDS (C function), 211 PyDict_Unwatch (C function), 174
PyDateTime_DeltaType (C var), 208 PyDict_Update (C function), 174
PyDateTime_FromDateAndTime (C function), 209 PyDict_Values (C function), 173
PyDateTime_FromDateAndTimeAndFold (C func- PyDict_Watch (C function), 174
tion), 209 PyDict_WatchCallback (C type), 175
PyDateTime_FromTimestamp (C function), 211 PyDict_WatchEvent (C type), 175
PyDateTime_GET_DAY (C function), 210 PyDictObject (C type), 170
PyDateTime_GET_MONTH (C function), 210 PyDictProxy_New (C function), 171
PyDateTime_GET_YEAR (C function), 210 PyDoc_STR (C macro), 6
PyDateTime_Time (C type), 208 PyDoc_STRVAR (C macro), 6
PyDateTime_TIME_GET_FOLD (C function), 211 PyEllipsis_Type (C var), 199
PyDateTime_TIME_GET_HOUR (C function), 210 PyErr_BadArgument (C function), 55
PyDateTime_TIME_GET_MICROSECOND (C function), PyErr_BadInternalCall (C function), 56
210 PyErr_CheckSignals (C function), 61
PyDateTime_TIME_GET_MINUTE (C function), 210 PyErr_Clear (C function), 53
PyDateTime_TIME_GET_SECOND (C function), 210 PyErr_Clear (função C), 11, 12
PyDateTime_TIME_GET_TZINFO (C function), 211 PyErr_DisplayException (C function), 54
PyDateTime_TimeType (C var), 208 PyErr_ExceptionMatches (C function), 58
PyDateTime_TimeZone_UTC (C var), 208 PyErr_ExceptionMatches (função C), 12
PyDateTime_TZInfoType (C var), 208 PyErr_Fetch (C function), 58
PyDelta_Check (C function), 209 PyErr_Format (C function), 54
PyDelta_CheckExact (C function), 209 PyErr_FormatUnraisable (C function), 54
PyDelta_FromDSU (C function), 209 PyErr_FormatV (C function), 54
PyDescr_IsData (C function), 197 PyErr_GetExcInfo (C function), 60
PyDescr_NewClassMethod (C function), 197 PyErr_GetHandledException (C function), 59
PyDescr_NewGetSet (C function), 197 PyErr_GetRaisedException (C function), 58
PyDescr_NewMember (C function), 197 PyErr_GivenExceptionMatches (C function), 58
PyDescr_NewMethod (C function), 197 PyErr_NewException (C function), 62
PyDescr_NewWrapper (C function), 197 PyErr_NewExceptionWithDoc (C function), 62
390 Índice
The Python/C API, Release 3.13.7
PyErr_NoMemory (C function), 55 PyEval_GetLocals (C function), 93
PyErr_NormalizeException (C function), 59 PyEval_InitThreads (C function), 226
PyErr_Occurred (C function), 57 PyEval_InitThreads(), 217
PyErr_Occurred (função C), 10 PyEval_MergeCompilerFlags (C function), 46
PyErr_Print (C function), 54 PyEval_ReleaseThread (C function), 230
PyErr_PrintEx (C function), 53 PyEval_ReleaseThread(), 226
PyErr_ResourceWarning (C function), 57 PyEval_RestoreThread (C function), 224, 226
PyErr_Restore (C function), 59 PyEval_RestoreThread(), 226
PyErr_SetExcFromWindowsErr (C function), 55 PyEval_SaveThread (C function), 224, 226
PyErr_SetExcFromWindowsErrWithFilename (C PyEval_SaveThread(), 226
function), 56 PyEval_SetProfile (C function), 235
PyErr_SetExcFromWindowsErrWithFilenameObject PyEval_SetProfileAllThreads (C function), 236
(C function), 56 PyEval_SetTrace (C function), 236
PyErr_SetExcFromWindowsErrWithFilenameObjects PyEval_SetTraceAllThreads (C function), 236
(C function), 56 PyExc_ArithmeticError (C var), 65
PyErr_SetExcInfo (C function), 60 PyExc_AssertionError (C var), 65
PyErr_SetFromErrno (C function), 55 PyExc_AttributeError (C var), 65
PyErr_SetFromErrnoWithFilename (C function), PyExc_BaseException (C var), 65
55 PyExc_BaseExceptionGroup (C var), 65
PyErr_SetFromErrnoWithFilenameObject (C PyExc_BlockingIOError (C var), 65
function), 55 PyExc_BrokenPipeError (C var), 65
PyErr_SetFromErrnoWithFilenameObjects (C PyExc_BufferError (C var), 65
function), 55 PyExc_BytesWarning (C var), 70
PyErr_SetFromWindowsErr (C function), 55 PyExc_ChildProcessError (C var), 65
PyErr_SetFromWindowsErrWithFilename (C PyExc_ConnectionAbortedError (C var), 66
function), 55 PyExc_ConnectionError (C var), 66
PyErr_SetHandledException (C function), 60 PyExc_ConnectionRefusedError (C var), 66
PyErr_SetImportError (C function), 56 PyExc_ConnectionResetError (C var), 66
PyErr_SetImportErrorSubclass (C function), 56 PyExc_DeprecationWarning (C var), 70
PyErr_SetInterrupt (C function), 61 PyExc_EncodingWarning (C var), 70
PyErr_SetInterruptEx (C function), 61 PyExc_EnvironmentError (C var), 69
PyErr_SetNone (C function), 55 PyExc_EOFError (C var), 66
PyErr_SetObject (C function), 54 PyExc_Exception (C var), 65
PyErr_SetRaisedException (C function), 58 PyExc_FileExistsError (C var), 66
PyErr_SetString (C function), 54 PyExc_FileNotFoundError (C var), 66
PyErr_SetString (função C), 11 PyExc_FloatingPointError (C var), 66
PyErr_SyntaxLocation (C function), 56 PyExc_FutureWarning (C var), 70
PyErr_SyntaxLocationEx (C function), 56 PyExc_GeneratorExit (C var), 66
PyErr_SyntaxLocationObject (C function), 56 PyExc_ImportError (C var), 66
PyErr_WarnEx (C function), 57 PyExc_ImportWarning (C var), 70
PyErr_WarnExplicit (C function), 57 PyExc_IndentationError (C var), 66
PyErr_WarnExplicitObject (C function), 57 PyExc_IndexError (C var), 66
PyErr_WarnFormat (C function), 57 PyExc_InterruptedError (C var), 66
PyErr_WriteUnraisable (C function), 54 PyExc_IOError (C var), 69
PyEval_AcquireThread (C function), 230 PyExc_IsADirectoryError (C var), 67
PyEval_AcquireThread(), 226 PyExc_KeyboardInterrupt (C var), 67
PyEval_EvalCode (C function), 46 PyExc_KeyError (C var), 67
PyEval_EvalCodeEx (C function), 46 PyExc_LookupError (C var), 67
PyEval_EvalFrame (C function), 46 PyExc_MemoryError (C var), 67
PyEval_EvalFrameEx (C function), 46 PyExc_ModuleNotFoundError (C var), 67
PyEval_GetBuiltins (C function), 93 PyExc_NameError (C var), 67
PyEval_GetFrame (C function), 93 PyExc_NotADirectoryError (C var), 67
PyEval_GetFrameBuiltins (C function), 94 PyExc_NotImplementedError (C var), 67
PyEval_GetFrameGlobals (C function), 94 PyExc_OSError (C var), 67
PyEval_GetFrameLocals (C function), 94 PyExc_OverflowError (C var), 67
PyEval_GetFuncDesc (C function), 94 PyExc_PendingDeprecationWarning (C var), 70
PyEval_GetFuncName (C function), 94 PyExc_PermissionError (C var), 67
PyEval_GetGlobals (C function), 93 PyExc_ProcessLookupError (C var), 67
Índice 391
The Python/C API, Release 3.13.7
PyExc_PythonFinalizationError (C var), 67 PyFrame_Check (C function), 203
PyExc_RecursionError (C var), 68 PyFrame_GetBack (C function), 203
PyExc_ReferenceError (C var), 68 PyFrame_GetBuiltins (C function), 203
PyExc_ResourceWarning (C var), 70 PyFrame_GetCode (C function), 203
PyExc_RuntimeError (C var), 68 PyFrame_GetGenerator (C function), 204
PyExc_RuntimeWarning (C var), 70 PyFrame_GetGlobals (C function), 204
PyExc_StopAsyncIteration (C var), 68 PyFrame_GetLasti (C function), 204
PyExc_StopIteration (C var), 68 PyFrame_GetLineNumber (C function), 204
PyExc_SyntaxError (C var), 68 PyFrame_GetLocals (C function), 204
PyExc_SyntaxWarning (C var), 70 PyFrame_GetVar (C function), 204
PyExc_SystemError (C var), 68 PyFrame_GetVarString (C function), 204
PyExc_SystemExit (C var), 68 PyFrame_Type (C var), 203
PyExc_TabError (C var), 68 PyFrameLocalsProxy_Check (C function), 204
PyExc_TimeoutError (C var), 68 PyFrameLocalsProxy_Type (C var), 204
PyExc_TypeError (C var), 68 PyFrameObject (C type), 203
PyExc_UnboundLocalError (C var), 68 PyFrozenSet_Check (C function), 176
PyExc_UnicodeDecodeError (C var), 68 PyFrozenSet_CheckExact (C function), 176
PyExc_UnicodeEncodeError (C var), 69 PyFrozenSet_New (C function), 176
PyExc_UnicodeError (C var), 69 PyFrozenSet_Type (C var), 176
PyExc_UnicodeTranslateError (C var), 69 PyFunction_AddWatcher (C function), 178
PyExc_UnicodeWarning (C var), 70 PyFunction_Check (C function), 177
PyExc_UserWarning (C var), 70 PyFunction_ClearWatcher (C function), 179
PyExc_ValueError (C var), 69 PyFunction_GET_ANNOTATIONS (C function), 178
PyExc_Warning (C var), 70 PyFunction_GET_CLOSURE (C function), 178
PyExc_WindowsError (C var), 69 PyFunction_GET_CODE (C function), 178
PyExc_ZeroDivisionError (C var), 69 PyFunction_GET_DEFAULTS (C function), 178
PyException_GetArgs (C function), 62 PyFunction_GET_GLOBALS (C function), 178
PyException_GetCause (C function), 62 PyFunction_GET_KW_DEFAULTS (C function), 178
PyException_GetContext (C function), 62 PyFunction_GET_MODULE (C function), 178
PyException_GetTraceback (C function), 62 PyFunction_GetAnnotations (C function), 178
PyException_SetArgs (C function), 63 PyFunction_GetClosure (C function), 178
PyException_SetCause (C function), 62 PyFunction_GetCode (C function), 177
PyException_SetContext (C function), 62 PyFunction_GetDefaults (C function), 178
PyException_SetTraceback (C function), 62 PyFunction_GetGlobals (C function), 177
PyExceptionClass_Check (C function), 62 PyFunction_GetKwDefaults (C function), 178
PyExceptionClass_Name (C function), 62 PyFunction_GetModule (C function), 178
PyFile_FromFd (C function), 186 PyFunction_New (C function), 177
PyFile_GetLine (C function), 187 PyFunction_NewWithQualName (C function), 177
PyFile_SetOpenCodeHook (C function), 187 PyFunction_SetAnnotations (C function), 178
PyFile_WriteObject (C function), 187 PyFunction_SetClosure (C function), 178
PyFile_WriteString (C function), 187 PyFunction_SetDefaults (C function), 178
PyFloat_AS_DOUBLE (C function), 141 PyFunction_SetVectorcall (C function), 178
PyFloat_AsDouble (C function), 141 PyFunction_Type (C var), 177
PyFloat_Check (C function), 141 PyFunction_WatchCallback (C type), 179
PyFloat_CheckExact (C function), 141 PyFunction_WatchEvent (C type), 179
PyFloat_FromDouble (C function), 141 PyFunctionObject (C type), 177
PyFloat_FromString (C function), 141 PyGC_Collect (C function), 324
PyFloat_GetInfo (C function), 141 PyGC_Disable (C function), 324
PyFloat_GetMax (C function), 141 PyGC_Enable (C function), 324
PyFloat_GetMin (C function), 141 PyGC_IsEnabled (C function), 324
PyFloat_Pack2 (C function), 142 PyGen_Check (C function), 205
PyFloat_Pack4 (C function), 142 PyGen_CheckExact (C function), 205
PyFloat_Pack8 (C function), 142 PyGen_New (C function), 206
PyFloat_Type (C var), 141 PyGen_NewWithQualName (C function), 206
PyFloat_Unpack2 (C function), 142 PyGen_Type (C var), 205
PyFloat_Unpack4 (C function), 142 PyGenObject (C type), 205
PyFloat_Unpack8 (C function), 142 PyGetSetDef (C type), 286
PyFloatObject (C type), 141 PyGetSetDef.closure (C member), 286
392 Índice
The Python/C API, Release 3.13.7
PyGetSetDef.doc (C member), 286 PyInterpreterConfig_SHARED_GIL (C macro),
PyGetSetDef.get (C member), 286 232
PyGetSetDef.name (C member), 286 PyInterpreterConfig.allow_daemon_threads
PyGetSetDef.set (C member), 286 (C member), 231
PyGILState_Check (C function), 227 PyInterpreterConfig.allow_exec (C member),
PyGILState_Ensure (C function), 227 231
PyGILState_GetThisThreadState (C function), PyInterpreterConfig.allow_fork (C member),
227 231
PyGILState_Release (C function), 227 PyInterpreterConfig.allow_threads (C mem-
PyHASH_BITS (C macro), 92 ber), 231
PyHash_FuncDef (C type), 92 PyInterpreterConfig.check_multi_interp_extensions
PyHash_FuncDef.hash (C member), 92 (C member), 231
PyHash_FuncDef.hash_bits (C member), 92 PyInterpreterConfig.gil (C member), 231
PyHash_FuncDef.name (C member), 92 PyInterpreterConfig.use_main_obmalloc (C
PyHash_FuncDef.seed_bits (C member), 92 member), 231
PyHash_GetFuncDef (C function), 92 PyInterpreterState (C type), 225
PyHASH_IMAG (C macro), 92 PyInterpreterState_Clear (C function), 228
PyHASH_INF (C macro), 92 PyInterpreterState_Delete (C function), 228
PyHASH_MODULUS (C macro), 92 PyInterpreterState_Get (C function), 229
PyHASH_MULTIPLIER (C macro), 92 PyInterpreterState_GetDict (C function), 229
PyImport_AddModule (C function), 77 PyInterpreterState_GetID (C function), 229
PyImport_AddModuleObject (C function), 77 PyInterpreterState_Head (C function), 237
PyImport_AddModuleRef (C function), 77 PyInterpreterState_Main (C function), 237
PyImport_AppendInittab (C function), 79 PyInterpreterState_New (C function), 228
PyImport_ExecCodeModule (C function), 77 PyInterpreterState_Next (C function), 237
PyImport_ExecCodeModuleEx (C function), 78 PyInterpreterState_ThreadHead (C function),
PyImport_ExecCodeModuleObject (C function), 78 237
PyImport_ExecCodeModuleWithPathnames (C PyIter_Check (C function), 117
function), 78 PyIter_Next (C function), 117
PyImport_ExtendInittab (C function), 80 PyIter_Send (C function), 118
PyImport_FrozenModules (C var), 79 PyList_Append (C function), 170
PyImport_GetImporter (C function), 79 PyList_AsTuple (C function), 170
PyImport_GetMagicNumber (C function), 78 PyList_Check (C function), 168
PyImport_GetMagicTag (C function), 78 PyList_CheckExact (C function), 168
PyImport_GetModule (C function), 79 PyList_Clear (C function), 170
PyImport_GetModuleDict (C function), 78 PyList_Extend (C function), 170
PyImport_Import (C function), 77 PyList_GET_ITEM (C function), 169
PyImport_ImportFrozenModule (C function), 79 PyList_GET_SIZE (C function), 169
PyImport_ImportFrozenModuleObject (C func- PyList_GetItem (C function), 169
tion), 79 PyList_GetItem (função C), 9
PyImport_ImportModule (C function), 76 PyList_GetItemRef (C function), 169
PyImport_ImportModuleEx (C function), 76 PyList_GetSlice (C function), 170
PyImport_ImportModuleLevel (C function), 77 PyList_Insert (C function), 169
PyImport_ImportModuleLevelObject (C func- PyList_New (C function), 168
tion), 76 PyList_Reverse (C function), 170
PyImport_ImportModuleNoBlock (C function), 76 PyList_SET_ITEM (C function), 169
PyImport_ReloadModule (C function), 77 PyList_SetItem (C function), 169
PyIndex_Check (C function), 114 PyList_SetItem (função C), 8
PyInstanceMethod_Check (C function), 180 PyList_SetSlice (C function), 170
PyInstanceMethod_Function (C function), 180 PyList_Size (C function), 169
PyInstanceMethod_GET_FUNCTION (C function), PyList_Sort (C function), 170
180 PyList_Type (C var), 168
PyInstanceMethod_New (C function), 180 PyListObject (C type), 168
PyInstanceMethod_Type (C var), 180 PyLong_AS_LONG (C function), 135
PyInterpreterConfig (C type), 231 PyLong_AsDouble (C function), 137
PyInterpreterConfig_DEFAULT_GIL (C macro), PyLong_AsInt (C function), 135
232 PyLong_AsLong (C function), 135
PyInterpreterConfig_OWN_GIL (C macro), 232 PyLong_AsLongAndOverflow (C function), 135
Índice 393
The Python/C API, Release 3.13.7
PyLong_AsLongLong (C function), 135 PyMarshal_ReadObjectFromString (C function),
PyLong_AsLongLongAndOverflow (C function), 135 81
PyLong_AsNativeBytes (C function), 137 PyMarshal_ReadShortFromFile (C function), 80
PyLong_AsSize_t (C function), 136 PyMarshal_WriteLongToFile (C function), 80
PyLong_AsSsize_t (C function), 136 PyMarshal_WriteObjectToFile (C function), 80
PyLong_AsUnsignedLong (C function), 136 PyMarshal_WriteObjectToString (C function), 80
PyLong_AsUnsignedLongLong (C function), 136 PyMem_Calloc (C function), 268
PyLong_AsUnsignedLongLongMask (C function), PyMem_Del (C function), 268
136 PYMEM_DOMAIN_MEM (C macro), 271
PyLong_AsUnsignedLongMask (C function), 136 PYMEM_DOMAIN_OBJ (C macro), 271
PyLong_AsVoidPtr (C function), 137 PYMEM_DOMAIN_RAW (C macro), 270
PyLong_Check (C function), 133 PyMem_Free (C function), 268
PyLong_CheckExact (C function), 133 PyMem_GetAllocator (C function), 271
PyLong_FromDouble (C function), 134 PyMem_Malloc (C function), 267
PyLong_FromLong (C function), 133 PyMem_New (C macro), 268
PyLong_FromLongLong (C function), 134 PyMem_RawCalloc (C function), 267
PyLong_FromNativeBytes (C function), 134 PyMem_RawFree (C function), 267
PyLong_FromSize_t (C function), 134 PyMem_RawMalloc (C function), 267
PyLong_FromSsize_t (C function), 134 PyMem_RawRealloc (C function), 267
PyLong_FromString (C function), 134 PyMem_Realloc (C function), 268
PyLong_FromUnicodeObject (C function), 134 PyMem_Resize (C macro), 268
PyLong_FromUnsignedLong (C function), 134 PyMem_SetAllocator (C function), 271
PyLong_FromUnsignedLongLong (C function), 134 PyMem_SetupDebugHooks (C function), 271
PyLong_FromUnsignedNativeBytes (C function), PyMemAllocatorDomain (C type), 270
135 PyMemAllocatorEx (C type), 270
PyLong_FromVoidPtr (C function), 134 PyMember_GetOne (C function), 283
PyLong_GetInfo (C function), 139 PyMember_SetOne (C function), 283
PyLong_Type (C var), 133 PyMemberDef (C type), 283
PyLongObject (C type), 133 PyMemberDef.doc (C member), 283
PyMapping_Check (C function), 116 PyMemberDef.flags (C member), 283
PyMapping_DelItem (C function), 116 PyMemberDef.name (C member), 283
PyMapping_DelItemString (C function), 116 PyMemberDef.offset (C member), 283
PyMapping_GetItemString (C function), 116 PyMemberDef.type (C member), 283
PyMapping_GetOptionalItem (C function), 116 PyMemoryView_Check (C function), 199
PyMapping_GetOptionalItemString (C function), PyMemoryView_FromBuffer (C function), 199
116 PyMemoryView_FromMemory (C function), 199
PyMapping_HasKey (C function), 117 PyMemoryView_FromObject (C function), 199
PyMapping_HasKeyString (C function), 117 PyMemoryView_GET_BASE (C function), 199
PyMapping_HasKeyStringWithError (C function), PyMemoryView_GET_BUFFER (C function), 199
116 PyMemoryView_GetContiguous (C function), 199
PyMapping_HasKeyWithError (C function), 116 PyMethod_Check (C function), 180
PyMapping_Items (C function), 117 PyMethod_Function (C function), 180
PyMapping_Keys (C function), 117 PyMethod_GET_FUNCTION (C function), 180
PyMapping_Length (C function), 116 PyMethod_GET_SELF (C function), 180
PyMapping_SetItemString (C function), 116 PyMethod_New (C function), 180
PyMapping_Size (C function), 116 PyMethod_Self (C function), 180
PyMapping_Values (C function), 117 PyMethod_Type (C var), 180
PyMappingMethods (C type), 315 PyMethodDef (C type), 280
PyMappingMethods.mp_ass_subscript (C mem- PyMethodDef.ml_doc (C member), 281
ber), 315 PyMethodDef.ml_flags (C member), 281
PyMappingMethods.mp_length (C member), 315 PyMethodDef.ml_meth (C member), 281
PyMappingMethods.mp_subscript (C member), PyMethodDef.ml_name (C member), 280
315 PyMODINIT_FUNC (C macro), 4
PyMarshal_ReadLastObjectFromFile (C func- PyModule_Add (C function), 194
tion), 80 PyModule_AddFunctions (C function), 193
PyMarshal_ReadLongFromFile (C function), 80 PyModule_AddIntConstant (C function), 195
PyMarshal_ReadObjectFromFile (C function), 80 PyModule_AddIntMacro (C macro), 195
PyModule_AddObject (C function), 194
394 Índice
The Python/C API, Release 3.13.7
PyModule_AddObjectRef (C function), 193 PyMonitoring_FirePyYieldEvent (C function),
PyModule_AddStringConstant (C function), 195 331
PyModule_AddStringMacro (C macro), 195 PyMonitoring_FireRaiseEvent (C function), 332
PyModule_AddType (C function), 195 PyMonitoring_FireReraiseEvent (C function),
PyModule_Check (C function), 188 332
PyModule_CheckExact (C function), 188 PyMonitoring_FireStopIterationEvent (C
PyModule_Create (C function), 190 function), 332
PyModule_Create2 (C function), 190 PyMonitoringState (C type), 331
PyModule_ExecDef (C function), 193 PyMutex (C type), 239
PyModule_FromDefAndSpec (C function), 193 PyMutex_Lock (C function), 239
PyModule_FromDefAndSpec2 (C function), 193 PyMutex_Unlock (C function), 239
PyModule_GetDef (C function), 188 PyNumber_Absolute (C function), 112
PyModule_GetDict (C function), 188 PyNumber_Add (C function), 111
PyModule_GetFilename (C function), 189 PyNumber_And (C function), 112
PyModule_GetFilenameObject (C function), 188 PyNumber_AsSsize_t (C function), 114
PyModule_GetName (C function), 188 PyNumber_Check (C function), 111
PyModule_GetNameObject (C function), 188 PyNumber_Divmod (C function), 111
PyModule_GetState (C function), 188 PyNumber_Float (C function), 113
PyModule_New (C function), 188 PyNumber_FloorDivide (C function), 111
PyModule_NewObject (C function), 188 PyNumber_Index (C function), 113
PyModule_SetDocString (C function), 193 PyNumber_InPlaceAdd (C function), 112
PyModule_Type (C var), 188 PyNumber_InPlaceAnd (C function), 113
PyModuleDef (C type), 189 PyNumber_InPlaceFloorDivide (C function), 112
PyModuleDef_Init (C function), 191 PyNumber_InPlaceLshift (C function), 113
PyModuleDef_Slot (C type), 191 PyNumber_InPlaceMatrixMultiply (C function),
PyModuleDef_Slot.slot (C member), 191 112
PyModuleDef_Slot.value (C member), 191 PyNumber_InPlaceMultiply (C function), 112
PyModuleDef.m_base (C member), 189 PyNumber_InPlaceOr (C function), 113
PyModuleDef.m_clear (C member), 190 PyNumber_InPlacePower (C function), 113
PyModuleDef.m_doc (C member), 189 PyNumber_InPlaceRemainder (C function), 113
PyModuleDef.m_free (C member), 190 PyNumber_InPlaceRshift (C function), 113
PyModuleDef.m_methods (C member), 189 PyNumber_InPlaceSubtract (C function), 112
PyModuleDef.m_name (C member), 189 PyNumber_InPlaceTrueDivide (C function), 112
PyModuleDef.m_size (C member), 189 PyNumber_InPlaceXor (C function), 113
PyModuleDef.m_slots (C member), 189 PyNumber_Invert (C function), 112
PyModuleDef.m_slots.m_reload (C member), 189 PyNumber_Long (C function), 113
PyModuleDef.m_traverse (C member), 190 PyNumber_Lshift (C function), 112
PyMonitoring_EnterScope (C function), 332 PyNumber_MatrixMultiply (C function), 111
PyMonitoring_ExitScope (C function), 334 PyNumber_Multiply (C function), 111
PyMonitoring_FireBranchEvent (C function), 332 PyNumber_Negative (C function), 111
PyMonitoring_FireCallEvent (C function), 331 PyNumber_Or (C function), 112
PyMonitoring_FireCRaiseEvent (C function), 332 PyNumber_Positive (C function), 111
PyMonitoring_FireCReturnEvent (C function), PyNumber_Power (C function), 111
332 PyNumber_Remainder (C function), 111
PyMonitoring_FireExceptionHandledEvent (C PyNumber_Rshift (C function), 112
function), 332 PyNumber_Subtract (C function), 111
PyMonitoring_FireJumpEvent (C function), 332 PyNumber_ToBase (C function), 113
PyMonitoring_FireLineEvent (C function), 331 PyNumber_TrueDivide (C function), 111
PyMonitoring_FirePyResumeEvent (C function), PyNumber_Xor (C function), 112
331 PyNumberMethods (C type), 313
PyMonitoring_FirePyReturnEvent (C function), PyNumberMethods.nb_absolute (C member), 314
331 PyNumberMethods.nb_add (C member), 314
PyMonitoring_FirePyStartEvent (C function), PyNumberMethods.nb_and (C member), 314
331 PyNumberMethods.nb_bool (C member), 314
PyMonitoring_FirePyThrowEvent (C function), PyNumberMethods.nb_divmod (C member), 314
332 PyNumberMethods.nb_float (C member), 314
PyMonitoring_FirePyUnwindEvent (C function), PyNumberMethods.nb_floor_divide (C member),
332 315
Índice 395
The Python/C API, Release 3.13.7
PyNumberMethods.nb_index (C member), 315 PyObject_CallOneArg (C function), 109
PyNumberMethods.nb_inplace_add (C member), PyObject_CheckBuffer (C function), 124
314 PyObject_ClearManagedDict (C function), 106
PyNumberMethods.nb_inplace_and (C member), PyObject_ClearWeakRefs (C function), 200
315 PyObject_CopyData (C function), 125
PyNumberMethods.nb_inplace_floor_divide PyObject_Del (C function), 277
(C member), 315 PyObject_DelAttr (C function), 102
PyNumberMethods.nb_inplace_lshift (C mem- PyObject_DelAttrString (C function), 102
ber), 315 PyObject_DelItem (C function), 105
PyNumberMethods.nb_inplace_matrix_multiply PyObject_DelItemString (C function), 105
(C member), 315 PyObject_Dir (C function), 105
PyNumberMethods.nb_inplace_multiply (C PyObject_Format (C function), 103
member), 314 PyObject_Free (C function), 269
PyNumberMethods.nb_inplace_or (C member), PyObject_GC_Del (C function), 323
315 PyObject_GC_IsFinalized (C function), 323
PyNumberMethods.nb_inplace_power (C mem- PyObject_GC_IsTracked (C function), 323
ber), 315 PyObject_GC_New (C macro), 322
PyNumberMethods.nb_inplace_remainder (C PyObject_GC_NewVar (C macro), 322
member), 315 PyObject_GC_Resize (C macro), 323
PyNumberMethods.nb_inplace_rshift (C mem- PyObject_GC_Track (C function), 323
ber), 315 PyObject_GC_UnTrack (C function), 323
PyNumberMethods.nb_inplace_subtract (C PyObject_GenericGetAttr (C function), 102
member), 314 PyObject_GenericGetDict (C function), 102
PyNumberMethods.nb_inplace_true_divide (C PyObject_GenericHash (C function), 93
member), 315 PyObject_GenericSetAttr (C function), 102
PyNumberMethods.nb_inplace_xor (C member), PyObject_GenericSetDict (C function), 103
315 PyObject_GetAIter (C function), 105
PyNumberMethods.nb_int (C member), 314 PyObject_GetArenaAllocator (C function), 273
PyNumberMethods.nb_invert (C member), 314 PyObject_GetAttr (C function), 101
PyNumberMethods.nb_lshift (C member), 314 PyObject_GetAttrString (C function), 101
PyNumberMethods.nb_matrix_multiply (C mem- PyObject_GetBuffer (C function), 124
ber), 315 PyObject_GetItem (C function), 105
PyNumberMethods.nb_multiply (C member), 314 PyObject_GetItemData (C function), 106
PyNumberMethods.nb_negative (C member), 314 PyObject_GetIter (C function), 105
PyNumberMethods.nb_or (C member), 314 PyObject_GetOptionalAttr (C function), 101
PyNumberMethods.nb_positive (C member), 314 PyObject_GetOptionalAttrString (C function),
PyNumberMethods.nb_power (C member), 314 102
PyNumberMethods.nb_remainder (C member), 314 PyObject_GetTypeData (C function), 105
PyNumberMethods.nb_reserved (C member), 314 PyObject_HasAttr (C function), 101
PyNumberMethods.nb_rshift (C member), 314 PyObject_HasAttrString (C function), 101
PyNumberMethods.nb_subtract (C member), 314 PyObject_HasAttrStringWithError (C function),
PyNumberMethods.nb_true_divide (C member), 101
315 PyObject_HasAttrWithError (C function), 101
PyNumberMethods.nb_xor (C member), 314 PyObject_Hash (C function), 104
PyObject (C type), 278 PyObject_HashNotImplemented (C function), 104
PyObject_ASCII (C function), 103 PyObject_HEAD (C macro), 278
PyObject_AsFileDescriptor (C function), 187 PyObject_HEAD_INIT (C macro), 279
PyObject_Bytes (C function), 104 PyObject_Init (C function), 277
PyObject_Call (C function), 108 PyObject_InitVar (C function), 277
PyObject_CallFunction (C function), 109 PyObject_IS_GC (C function), 323
PyObject_CallFunctionObjArgs (C function), 109 PyObject_IsInstance (C function), 104
PyObject_CallMethod (C function), 109 PyObject_IsSubclass (C function), 104
PyObject_CallMethodNoArgs (C function), 110 PyObject_IsTrue (C function), 104
PyObject_CallMethodObjArgs (C function), 110 PyObject_Length (C function), 105
PyObject_CallMethodOneArg (C function), 110 PyObject_LengthHint (C function), 105
PyObject_CallNoArgs (C function), 109 PyObject_Malloc (C function), 269
PyObject_CallObject (C function), 109 PyObject_New (C macro), 277
PyObject_Calloc (C function), 269 PyObject_NewVar (C macro), 277
396 Índice
The Python/C API, Release 3.13.7
PyObject_Not (C function), 104 PyProperty_Type (C var), 197
PyObject_Print (C function), 100 PyRefTracer (C type), 236
PyObject_Realloc (C function), 269 PyRefTracer_CREATE (C var), 236
PyObject_Repr (C function), 103 PyRefTracer_DESTROY (C var), 236
PyObject_RichCompare (C function), 103 PyRefTracer_GetTracer (C function), 236
PyObject_RichCompareBool (C function), 103 PyRefTracer_SetTracer (C function), 236
PyObject_SelfIter (C function), 105 PyRun_AnyFile (C function), 43
PyObject_SetArenaAllocator (C function), 273 PyRun_AnyFileEx (C function), 43
PyObject_SetAttr (C function), 102 PyRun_AnyFileExFlags (C function), 43
PyObject_SetAttrString (C function), 102 PyRun_AnyFileFlags (C function), 43
PyObject_SetItem (C function), 105 PyRun_File (C function), 45
PyObject_Size (C function), 105 PyRun_FileEx (C function), 45
PyObject_Str (C function), 103 PyRun_FileExFlags (C function), 45
PyObject_Type (C function), 104 PyRun_FileFlags (C function), 45
PyObject_TypeCheck (C function), 104 PyRun_InteractiveLoop (C function), 44
PyObject_VAR_HEAD (C macro), 278 PyRun_InteractiveLoopFlags (C function), 44
PyObject_Vectorcall (C function), 110 PyRun_InteractiveOne (C function), 44
PyObject_VectorcallDict (C function), 110 PyRun_InteractiveOneFlags (C function), 44
PyObject_VectorcallMethod (C function), 110 PyRun_SimpleFile (C function), 44
PyObject_VisitManagedDict (C function), 106 PyRun_SimpleFileEx (C function), 44
PyObjectArenaAllocator (C type), 273 PyRun_SimpleFileExFlags (C function), 44
PyObject.ob_refcnt (C member), 292 PyRun_SimpleString (C function), 43
PyObject.ob_type (C member), 292 PyRun_SimpleStringFlags (C function), 43
PyOS_AfterFork (C function), 72 PyRun_String (C function), 45
PyOS_AfterFork_Child (C function), 72 PyRun_StringFlags (C function), 45
PyOS_AfterFork_Parent (C function), 71 PySendResult (C type), 118
PyOS_BeforeFork (C function), 71 PySeqIter_Check (C function), 196
PyOS_CheckStack (C function), 72 PySeqIter_New (C function), 196
PyOS_double_to_string (C function), 91 PySeqIter_Type (C var), 196
PyOS_FSPath (C function), 71 PySequence_Check (C function), 114
PyOS_getsig (C function), 72 PySequence_Concat (C function), 114
PyOS_InputHook (C var), 44 PySequence_Contains (C function), 115
PyOS_ReadlineFunctionPointer (C var), 44 PySequence_Count (C function), 115
PyOS_setsig (C function), 72 PySequence_DelItem (C function), 115
PyOS_sighandler_t (C type), 72 PySequence_DelSlice (C function), 115
PyOS_snprintf (C function), 90 PySequence_Fast (C function), 115
PyOS_stricmp (C function), 91 PySequence_Fast_GET_ITEM (C function), 115
PyOS_string_to_double (C function), 91 PySequence_Fast_GET_SIZE (C function), 115
PyOS_strnicmp (C function), 91 PySequence_Fast_ITEMS (C function), 115
PyOS_strtol (C function), 90 PySequence_GetItem (C function), 114
PyOS_strtoul (C function), 90 PySequence_GetItem (função C), 9
PyOS_vsnprintf (C function), 90 PySequence_GetSlice (C function), 114
PyPreConfig (C type), 246 PySequence_Index (C function), 115
PyPreConfig_InitIsolatedConfig (C function), PySequence_InPlaceConcat (C function), 114
246 PySequence_InPlaceRepeat (C function), 114
PyPreConfig_InitPythonConfig (C function), 246 PySequence_ITEM (C function), 116
PyPreConfig.allocator (C member), 246 PySequence_Length (C function), 114
PyPreConfig.coerce_c_locale (C member), 247 PySequence_List (C function), 115
PyPreConfig.coerce_c_locale_warn (C mem- PySequence_Repeat (C function), 114
ber), 247 PySequence_SetItem (C function), 114
PyPreConfig.configure_locale (C member), 246 PySequence_SetSlice (C function), 115
PyPreConfig.dev_mode (C member), 247 PySequence_Size (C function), 114
PyPreConfig.isolated (C member), 247 PySequence_Tuple (C function), 115
PyPreConfig.legacy_windows_fs_encoding (C PySequenceMethods (C type), 315
member), 247 PySequenceMethods.sq_ass_item (C member),
PyPreConfig.parse_argv (C member), 247 316
PyPreConfig.use_environment (C member), 247 PySequenceMethods.sq_concat (C member), 315
PyPreConfig.utf8_mode (C member), 247
Índice 397
The Python/C API, Release 3.13.7
PySequenceMethods.sq_contains (C member), PyStructSequence_SET_ITEM (C function), 168
316 PyStructSequence_SetItem (C function), 168
PySequenceMethods.sq_inplace_concat (C PyStructSequence_UnnamedField (C var), 168
member), 316 PySys_AddAuditHook (C function), 75
PySequenceMethods.sq_inplace_repeat (C PySys_Audit (C function), 74
member), 316 PySys_AuditTuple (C function), 75
PySequenceMethods.sq_item (C member), 316 PySys_FormatStderr (C function), 74
PySequenceMethods.sq_length (C member), 315 PySys_FormatStdout (C function), 74
PySequenceMethods.sq_repeat (C member), 315 PySys_GetObject (C function), 74
PySet_Add (C function), 176 PySys_GetXOptions (C function), 74
PySet_Check (C function), 176 PySys_ResetWarnOptions (C function), 74
PySet_CheckExact (C function), 176 PySys_SetArgv (C function), 223
PySet_Clear (C function), 177 PySys_SetArgvEx (C function), 222
PySet_Contains (C function), 176 PySys_SetObject (C function), 74
PySet_Discard (C function), 177 PySys_WriteStderr (C function), 74
PySet_GET_SIZE (C function), 176 PySys_WriteStdout (C function), 74
PySet_New (C function), 176 Python 3000, 350
PySet_Pop (C function), 177 PYTHON_CPU_COUNT, 254
PySet_Size (C function), 176 PYTHON_GIL, 344
PySet_Type (C var), 175 PYTHON_PERF_JIT_SUPPORT, 258
PySetObject (C type), 175 PYTHON_PRESITE, 257
PySignal_SetWakeupFd (C function), 61 PYTHONCOERCECLOCALE, 261
PySlice_AdjustIndices (C function), 198 PYTHONDEBUG, 215, 256
PySlice_Check (C function), 197 PYTHONDEVMODE, 252
PySlice_GetIndices (C function), 197 PYTHONDONTWRITEBYTECODE, 215, 259
PySlice_GetIndicesEx (C function), 198 PYTHONDUMPREFS, 252
PySlice_New (C function), 197 PYTHONEXECUTABLE, 256
PySlice_Type (C var), 197 PYTHONFAULTHANDLER, 252
PySlice_Unpack (C function), 198 PYTHONHASHSEED, 215, 253
PyState_AddModule (C function), 196 PYTHONHOME, 13, 215, 223, 253
PyState_FindModule (C function), 196 Pythônico, 350
PyState_RemoveModule (C function), 196 PYTHONINSPECT, 215, 253
PyStatus (C type), 244 PYTHONINTMAXSTRDIGITS, 254
PyStatus_Error (C function), 245 PYTHONIOENCODING, 258
PyStatus_Exception (C function), 245 PYTHONLEGACYWINDOWSFSENCODING, 216, 247
PyStatus_Exit (C function), 245 PYTHONLEGACYWINDOWSSTDIO, 216, 254
PyStatus_IsError (C function), 245 PYTHONMALLOC, 266, 270, 272, 273
PyStatus_IsExit (C function), 245 PYTHONMALLOCSTATS, 255, 266
PyStatus_NoMemory (C function), 245 PYTHONNODEBUGRANGES, 251
PyStatus_Ok (C function), 245 PYTHONNOUSERSITE, 217, 259
PyStatus.err_msg (C member), 245 PYTHONOPTIMIZE, 217, 255
PyStatus.exitcode (C member), 245 PYTHONPATH, 13, 215, 255
PyStatus.func (C member), 245 PYTHONPLATLIBDIR, 255
PyStructSequence_Desc (C type), 167 PYTHONPROFILEIMPORTTIME, 253
PyStructSequence_Desc.doc (C member), 167 PYTHONPYCACHEPREFIX, 256
PyStructSequence_Desc.fields (C member), 167 PYTHONSAFEPATH, 250
PyStructSequence_Desc.n_in_sequence (C PYTHONTRACEMALLOC, 258
member), 167 PYTHONUNBUFFERED, 217, 251
PyStructSequence_Desc.name (C member), 167 PYTHONUTF8, 247, 261
PyStructSequence_Field (C type), 167 PYTHONVERBOSE, 217, 259
PyStructSequence_Field.doc (C member), 168 PYTHONWARNINGS, 259
PyStructSequence_Field.name (C member), 167 PyThread_create_key (C function), 239
PyStructSequence_GET_ITEM (C function), 168 PyThread_delete_key (C function), 239
PyStructSequence_GetItem (C function), 168 PyThread_delete_key_value (C function), 239
PyStructSequence_InitType (C function), 167 PyThread_get_key_value (C function), 239
PyStructSequence_InitType2 (C function), 167 PyThread_ReInitTLS (C function), 239
PyStructSequence_New (C function), 168 PyThread_set_key_value (C function), 239
PyStructSequence_NewType (C function), 167 PyThread_tss_alloc (C function), 238
398 Índice
The Python/C API, Release 3.13.7
PyThread_tss_create (C function), 238 PyTuple_SetItem (C function), 166
PyThread_tss_delete (C function), 238 PyTuple_SetItem (função C), 8
PyThread_tss_free (C function), 238 PyTuple_Size (C function), 166
PyThread_tss_get (C function), 238 PyTuple_Type (C var), 165
PyThread_tss_is_created (C function), 238 PyTupleObject (C type), 165
PyThread_tss_set (C function), 238 PyType_AddWatcher (C function), 128
PyThreadState (C type), 223, 226 PyType_Check (C function), 127
PyThreadState_Clear (C function), 228 PyType_CheckExact (C function), 127
PyThreadState_Delete (C function), 228 PyType_ClearCache (C function), 127
PyThreadState_DeleteCurrent (C function), 228 PyType_ClearWatcher (C function), 128
PyThreadState_EnterTracing (C function), 229 PyType_FromMetaclass (C function), 130
PyThreadState_Get (C function), 226 PyType_FromModuleAndSpec (C function), 131
PyThreadState_GetDict (C function), 230 PyType_FromSpec (C function), 131
PyThreadState_GetFrame (C function), 228 PyType_FromSpecWithBases (C function), 131
PyThreadState_GetID (C function), 229 PyType_GenericAlloc (C function), 129
PyThreadState_GetInterpreter (C function), 229 PyType_GenericNew (C function), 129
PyThreadState_GetUnchecked (C function), 226 PyType_GetDict (C function), 128
PyThreadState_LeaveTracing (C function), 229 PyType_GetFlags (C function), 127
PyThreadState_New (C function), 228 PyType_GetFullyQualifiedName (C function), 129
PyThreadState_Next (C function), 237 PyType_GetModule (C function), 130
PyThreadState_SetAsyncExc (C function), 230 PyType_GetModuleByDef (C function), 130
PyThreadState_Swap (C function), 226 PyType_GetModuleName (C function), 129
PyThreadState.interp (C member), 226 PyType_GetModuleState (C function), 130
PyTime_AsSecondsDouble (C function), 97 PyType_GetName (C function), 129
PyTime_Check (C function), 209 PyType_GetQualName (C function), 129
PyTime_CheckExact (C function), 209 PyType_GetSlot (C function), 129
PyTime_FromTime (C function), 209 PyType_GetTypeDataSize (C function), 106
PyTime_FromTimeAndFold (C function), 209 PyType_HasFeature (C function), 128
PyTime_MAX (C var), 96 PyType_IS_GC (C function), 128
PyTime_MIN (C var), 96 PyType_IsSubtype (C function), 129
PyTime_Monotonic (C function), 96 PyType_Modified (C function), 128
PyTime_MonotonicRaw (C function), 97 PyType_Ready (C function), 129
PyTime_PerfCounter (C function), 97 PyType_Slot (C type), 132
PyTime_PerfCounterRaw (C function), 97 PyType_Slot.pfunc (C member), 133
PyTime_t (C type), 96 PyType_Slot.slot (C member), 132
PyTime_Time (C function), 97 PyType_Spec (C type), 131
PyTime_TimeRaw (C function), 97 PyType_Spec.basicsize (C member), 132
PyTimeZone_FromOffset (C function), 210 PyType_Spec.flags (C member), 132
PyTimeZone_FromOffsetAndName (C function), 210 PyType_Spec.itemsize (C member), 132
PyTrace_C_CALL (C var), 235 PyType_Spec.name (C member), 132
PyTrace_C_EXCEPTION (C var), 235 PyType_Spec.slots (C member), 132
PyTrace_C_RETURN (C var), 235 PyType_Type (C var), 127
PyTrace_CALL (C var), 235 PyType_Watch (C function), 128
PyTrace_EXCEPTION (C var), 235 PyType_WatchCallback (C type), 128
PyTrace_LINE (C var), 235 PyTypeObject (C type), 127
PyTrace_OPCODE (C var), 235 PyTypeObject.tp_alloc (C member), 309
PyTrace_RETURN (C var), 235 PyTypeObject.tp_as_async (C member), 296
PyTraceMalloc_Track (C function), 274 PyTypeObject.tp_as_buffer (C member), 298
PyTraceMalloc_Untrack (C function), 274 PyTypeObject.tp_as_mapping (C member), 297
PyTuple_Check (C function), 166 PyTypeObject.tp_as_number (C member), 296
PyTuple_CheckExact (C function), 166 PyTypeObject.tp_as_sequence (C member), 296
PyTuple_GET_ITEM (C function), 166 PyTypeObject.tp_base (C member), 307
PyTuple_GET_SIZE (C function), 166 PyTypeObject.tp_bases (C member), 310
PyTuple_GetItem (C function), 166 PyTypeObject.tp_basicsize (C member), 293
PyTuple_GetSlice (C function), 166 PyTypeObject.tp_cache (C member), 311
PyTuple_New (C function), 166 PyTypeObject.tp_call (C member), 297
PyTuple_Pack (C function), 166 PyTypeObject.tp_clear (C member), 304
PyTuple_SET_ITEM (C function), 166 PyTypeObject.tp_dealloc (C member), 294
Índice 399
The Python/C API, Release 3.13.7
PyTypeObject.tp_del (C member), 311 PyUnicode_AsUTF8AndSize (C function), 159
PyTypeObject.tp_descr_get (C member), 308 PyUnicode_AsUTF8String (C function), 159
PyTypeObject.tp_descr_set (C member), 308 PyUnicode_AsUTF16String (C function), 160
PyTypeObject.tp_dict (C member), 307 PyUnicode_AsUTF32String (C function), 160
PyTypeObject.tp_dictoffset (C member), 308 PyUnicode_AsWideChar (C function), 157
PyTypeObject.tp_doc (C member), 302 PyUnicode_AsWideCharString (C function), 158
PyTypeObject.tp_finalize (C member), 311 PyUnicode_BuildEncodingMap (C function), 154
PyTypeObject.tp_flags (C member), 298 PyUnicode_Check (C function), 148
PyTypeObject.tp_free (C member), 310 PyUnicode_CheckExact (C function), 148
PyTypeObject.tp_getattr (C member), 295 PyUnicode_Compare (C function), 164
PyTypeObject.tp_getattro (C member), 298 PyUnicode_CompareWithASCIIString (C func-
PyTypeObject.tp_getset (C member), 307 tion), 165
PyTypeObject.tp_hash (C member), 297 PyUnicode_Concat (C function), 163
PyTypeObject.tp_init (C member), 309 PyUnicode_Contains (C function), 165
PyTypeObject.tp_is_gc (C member), 310 PyUnicode_CopyCharacters (C function), 154
PyTypeObject.tp_itemsize (C member), 293 PyUnicode_Count (C function), 164
PyTypeObject.tp_iter (C member), 306 PyUnicode_DATA (C function), 149
PyTypeObject.tp_iternext (C member), 306 PyUnicode_Decode (C function), 158
PyTypeObject.tp_members (C member), 307 PyUnicode_DecodeASCII (C function), 161
PyTypeObject.tp_methods (C member), 306 PyUnicode_DecodeCharmap (C function), 162
PyTypeObject.tp_mro (C member), 311 PyUnicode_DecodeCodePageStateful (C func-
PyTypeObject.tp_name (C member), 293 tion), 163
PyTypeObject.tp_new (C member), 309 PyUnicode_DecodeFSDefault (C function), 157
PyTypeObject.tp_repr (C member), 296 PyUnicode_DecodeFSDefaultAndSize (C func-
PyTypeObject.tp_richcompare (C member), 305 tion), 157
PyTypeObject.tp_setattr (C member), 296 PyUnicode_DecodeLatin1 (C function), 161
PyTypeObject.tp_setattro (C member), 298 PyUnicode_DecodeLocale (C function), 156
PyTypeObject.tp_str (C member), 297 PyUnicode_DecodeLocaleAndSize (C function),
PyTypeObject.tp_subclasses (C member), 311 155
PyTypeObject.tp_traverse (C member), 303 PyUnicode_DecodeMBCS (C function), 162
PyTypeObject.tp_vectorcall (C member), 312 PyUnicode_DecodeMBCSStateful (C function), 162
PyTypeObject.tp_vectorcall_offset (C mem- PyUnicode_DecodeRawUnicodeEscape (C func-
ber), 295 tion), 161
PyTypeObject.tp_version_tag (C member), 311 PyUnicode_DecodeUnicodeEscape (C function),
PyTypeObject.tp_watched (C member), 312 161
PyTypeObject.tp_weaklist (C member), 311 PyUnicode_DecodeUTF7 (C function), 161
PyTypeObject.tp_weaklistoffset (C member), PyUnicode_DecodeUTF7Stateful (C function), 161
306 PyUnicode_DecodeUTF8 (C function), 158
PyTZInfo_Check (C function), 209 PyUnicode_DecodeUTF8Stateful (C function), 158
PyTZInfo_CheckExact (C function), 209 PyUnicode_DecodeUTF16 (C function), 160
PyUnicode_1BYTE_DATA (C function), 148 PyUnicode_DecodeUTF16Stateful (C function),
PyUnicode_1BYTE_KIND (C macro), 149 160
PyUnicode_2BYTE_DATA (C function), 148 PyUnicode_DecodeUTF32 (C function), 159
PyUnicode_2BYTE_KIND (C macro), 149 PyUnicode_DecodeUTF32Stateful (C function),
PyUnicode_4BYTE_DATA (C function), 148 160
PyUnicode_4BYTE_KIND (C macro), 149 PyUnicode_EncodeCodePage (C function), 163
PyUnicode_AsASCIIString (C function), 162 PyUnicode_EncodeFSDefault (C function), 157
PyUnicode_AsCharmapString (C function), 162 PyUnicode_EncodeLocale (C function), 156
PyUnicode_AsEncodedString (C function), 158 PyUnicode_EqualToUTF8 (C function), 164
PyUnicode_AsLatin1String (C function), 161 PyUnicode_EqualToUTF8AndSize (C function), 164
PyUnicode_AsMBCSString (C function), 163 PyUnicode_Fill (C function), 154
PyUnicode_AsRawUnicodeEscapeString (C func- PyUnicode_Find (C function), 164
tion), 161 PyUnicode_FindChar (C function), 164
PyUnicode_AsUCS4 (C function), 155 PyUnicode_Format (C function), 165
PyUnicode_AsUCS4Copy (C function), 155 PyUnicode_FromEncodedObject (C function), 154
PyUnicode_AsUnicodeEscapeString (C function), PyUnicode_FromFormat (C function), 151
161 PyUnicode_FromFormatV (C function), 154
PyUnicode_AsUTF8 (C function), 159 PyUnicode_FromKindAndData (C function), 151
400 Índice
The Python/C API, Release 3.13.7
PyUnicode_FromObject (C function), 154 PyUnicodeEncodeError_SetStart (C function), 63
PyUnicode_FromOrdinal (C function), 154 PyUnicodeIter_Type (C var), 148
PyUnicode_FromString (C function), 151 PyUnicodeObject (C type), 148
PyUnicode_FromStringAndSize (C function), 151 PyUnicodeTranslateError_GetEnd (C function),
PyUnicode_FromWideChar (C function), 157 63
PyUnicode_FSConverter (C function), 156 PyUnicodeTranslateError_GetObject (C func-
PyUnicode_FSDecoder (C function), 156 tion), 63
PyUnicode_GET_LENGTH (C function), 148 PyUnicodeTranslateError_GetReason (C func-
PyUnicode_GetDefaultEncoding (C function), 154 tion), 64
PyUnicode_GetLength (C function), 154 PyUnicodeTranslateError_GetStart (C func-
PyUnicode_InternFromString (C function), 165 tion), 63
PyUnicode_InternInPlace (C function), 165 PyUnicodeTranslateError_SetEnd (C function),
PyUnicode_IsIdentifier (C function), 149 63
PyUnicode_Join (C function), 164 PyUnicodeTranslateError_SetReason (C func-
PyUnicode_KIND (C function), 149 tion), 64
PyUnicode_MAX_CHAR_VALUE (C function), 149 PyUnicodeTranslateError_SetStart (C func-
PyUnicode_New (C function), 151 tion), 63
PyUnicode_Partition (C function), 163 PyUnstable, 15
PyUnicode_READ (C function), 149 PyUnstable_AtExit (C function), 220
PyUnicode_READ_CHAR (C function), 149 PyUnstable_Code_GetExtra (C function), 186
PyUnicode_ReadChar (C function), 155 PyUnstable_Code_GetFirstFree (C function), 181
PyUnicode_READY (C function), 148 PyUnstable_Code_New (C function), 181
PyUnicode_Replace (C function), 164 PyUnstable_Code_NewWithPosOnlyArgs (C func-
PyUnicode_RichCompare (C function), 165 tion), 182
PyUnicode_RPartition (C function), 163 PyUnstable_Code_SetExtra (C function), 186
PyUnicode_RSplit (C function), 163 PyUnstable_Eval_RequestCodeExtraIndex (C
PyUnicode_Split (C function), 163 function), 185
PyUnicode_Splitlines (C function), 163 PyUnstable_Exc_PrepReraiseStar (C function),
PyUnicode_Substring (C function), 155 63
PyUnicode_Tailmatch (C function), 164 PyUnstable_GC_VisitObjects (C function), 325
PyUnicode_Translate (C function), 162 PyUnstable_InterpreterFrame_GetCode (C
PyUnicode_Type (C var), 148 function), 205
PyUnicode_WRITE (C function), 149 PyUnstable_InterpreterFrame_GetLasti (C
PyUnicode_WriteChar (C function), 155 function), 205
PyUnicodeDecodeError_Create (C function), 63 PyUnstable_InterpreterFrame_GetLine (C
PyUnicodeDecodeError_GetEncoding (C func- function), 205
tion), 63 PyUnstable_InterpreterState_GetMainModule
PyUnicodeDecodeError_GetEnd (C function), 63 (C function), 229
PyUnicodeDecodeError_GetObject (C function), PyUnstable_Long_CompactValue (C function), 140
63 PyUnstable_Long_IsCompact (C function), 139
PyUnicodeDecodeError_GetReason (C function), PyUnstable_Module_SetGIL (C function), 195
64 PyUnstable_Object_ClearWeakRefsNoCallbacks
PyUnicodeDecodeError_GetStart (C function), 63 (C function), 201
PyUnicodeDecodeError_SetEnd (C function), 63 PyUnstable_Object_GC_NewWithExtraData (C
PyUnicodeDecodeError_SetReason (C function), function), 322
64 PyUnstable_PerfMapState_Fini (C function), 98
PyUnicodeDecodeError_SetStart (C function), 63 PyUnstable_PerfMapState_Init (C function), 97
PyUnicodeEncodeError_GetEncoding (C func- PyUnstable_Type_AssignVersionTag (C func-
tion), 63 tion), 130
PyUnicodeEncodeError_GetEnd (C function), 63 PyUnstable_WritePerfMapEntry (C function), 98
PyUnicodeEncodeError_GetObject (C function), PyVarObject (C type), 278
63 PyVarObject_HEAD_INIT (C macro), 279
PyUnicodeEncodeError_GetReason (C function), PyVarObject.ob_size (C member), 293
64 PyVectorcall_Call (C function), 108
PyUnicodeEncodeError_GetStart (C function), 63 PyVectorcall_Function (C function), 108
PyUnicodeEncodeError_SetEnd (C function), 63 PyVectorcall_NARGS (C function), 108
PyUnicodeEncodeError_SetReason (C function), PyWeakref_Check (C function), 200
64 PyWeakref_CheckProxy (C function), 200
Índice 401
The Python/C API, Release 3.13.7
PyWeakref_CheckRef (C function), 200 sys
PyWeakref_GET_OBJECT (C function), 200 módulo, 12, 217, 232, 233
PyWeakref_GetObject (C function), 200 SystemError (built-in exception), 188, 189
PyWeakref_GetRef (C function), 200
PyWeakref_NewProxy (C function), 200 T
PyWeakref_NewRef (C function), 200 T_BOOL (macro C), 286
PyWideStringList (C type), 244 T_BYTE (macro C), 286
PyWideStringList_Append (C function), 244 T_CHAR (macro C), 286
PyWideStringList_Insert (C function), 244 T_DOUBLE (macro C), 286
PyWideStringList.items (C member), 244 T_FLOAT (macro C), 286
PyWideStringList.length (C member), 244 T_INT (macro C), 286
PyWrapper_New (C function), 197 T_LONG (macro C), 286
T_LONGLONG (macro C), 286
R T_NONE (C macro), 286
READ_RESTRICTED (macro C), 284 T_OBJECT (C macro), 286
READONLY (macro C), 284 T_OBJECT_EX (macro C), 286
realloc (C function), 265 T_PYSSIZET (macro C), 286
referência emprestada, 339 T_SHORT (macro C), 286
referência forte, 352 T_STRING (macro C), 286
releasebufferproc (C type), 319 T_STRING_INPLACE (macro C), 286
REPL, 351 T_UBYTE (macro C), 286
repr T_UINT (macro C), 286
função embutida, 103, 296 T_ULONG (macro C), 286
reprfunc (C type), 318 T_ULONGULONG (macro C), 286
RESTRICTED (macro C), 284 T_USHORT (macro C), 286
richcmpfunc (C type), 319 ternaryfunc (C type), 319
threads livres, 343
S tipagem pato, 342
sendfunc (C type), 319 tipo, 353
sequência, 351 função embutida, 104
objeto, 144 objeto, 7, 127
set tipo genérico, 344
objeto, 175 token, 353
set_all(), 9 tratador de erros e codificação do
setattrfunc (C type), 318 sistema de arquivos, 342
setattrofunc (C type), 318 trava global do interpretador, 223, 344
setswitchinterval (in module sys), 223 traverseproc (C type), 324
setter (C type), 286 tupla
SIGINT (C macro), 61 função embutida, 115, 170
signal objeto, 165
módulo, 61 tupla nomeada, 348
SIZE_MAX (C macro), 136
spec de módulo, 348 U
ssizeargfunc (C type), 319 ULONG_MAX (C macro), 136
ssizeobjargproc (C type), 319 unaryfunc (C type), 319
staticmethod USE_STACKCHECK (C macro), 72
função embutida, 282
stderr (no módulo sys), 232, 233 V
stdin (no módulo sys), 232, 233 variável de ambiente
stdlib, 352 __PYVENV_LAUNCHER__, 251, 256
stdout (no módulo sys), 232, 233 PATH, 12, 13
strerror (C function), 55 PYTHON_CPU_COUNT, 254
string PYTHON_GIL, 344
PyObject_Str (C function), 103 PYTHON_PERF_JIT_SUPPORT, 258
structmember.h, 286 PYTHON_PRESITE, 257
suavemente descontinuado, 352 PYTHONCOERCECLOCALE, 261
sum_list(), 10 PYTHONDEBUG, 215, 256
sum_sequence(), 10, 11 PYTHONDEVMODE, 252
402 Índice
The Python/C API, Release 3.13.7
PYTHONDONTWRITEBYTECODE, 215, 259
PYTHONDUMPREFS, 252
PYTHONEXECUTABLE, 256
PYTHONFAULTHANDLER, 252
PYTHONHASHSEED, 215, 253
PYTHONHOME, 13, 215, 223, 253
PYTHONINSPECT, 215, 253
PYTHONINTMAXSTRDIGITS, 254
PYTHONIOENCODING, 258
PYTHONLEGACYWINDOWSFSENCODING, 216, 247
PYTHONLEGACYWINDOWSSTDIO, 216, 254
PYTHONMALLOC, 266, 270, 272, 273
PYTHONMALLOCSTATS, 255, 266
PYTHONNODEBUGRANGES, 251
PYTHONNOUSERSITE, 217, 259
PYTHONOPTIMIZE, 217, 255
PYTHONPATH, 13, 215, 255
PYTHONPLATLIBDIR, 255
PYTHONPROFILEIMPORTTIME, 253
PYTHONPYCACHEPREFIX, 256
PYTHONSAFEPATH, 250
PYTHONTRACEMALLOC, 258
PYTHONUNBUFFERED, 217, 251
PYTHONUTF8, 247, 261
PYTHONVERBOSE, 217, 259
PYTHONWARNINGS, 259
variável de classe, 339
variável de clausura, 340
variável de contexto, 340
variável livre, 343
vectorcallfunc (C type), 107
verificador de tipo estático, 352
version (in module sys), 221, 222
visão de dicionário, 341
visitproc (C type), 324
W
WRITE_RESTRICTED (macro C), 284
Z
Zen do Python, 354
Índice 403