0% acharam este documento útil (0 voto)
23 visualizações

C Api

Este documento descreve a interface C/C++ da API Python. Ele discute padrões de codificação, macros úteis, objetos, tipos, contagens de referências, exceções, incorporação de Python em C/C++ e outras funcionalidades da API.

Enviado por

tanaxot264
Direitos autorais
© © All Rights Reserved
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
0% acharam este documento útil (0 voto)
23 visualizações

C Api

Este documento descreve a interface C/C++ da API Python. Ele discute padrões de codificação, macros úteis, objetos, tipos, contagens de referências, exceções, incorporação de Python em C/C++ e outras funcionalidades da API.

Enviado por

tanaxot264
Direitos autorais
© © All Rights Reserved
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
Você está na página 1/ 326

The Python/C API

Release 3.10.6

Guido van Rossum


and the Python development team

setembro 05, 2022

Python Software Foundation


Email: [email protected]
Sumário

1 Introdução 3
1.1 Padrões de codificação . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Incluir arquivos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Macros úteis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Objetos, tipos e contagens de referências . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4.1 Contagens de referências . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4.2 Tipos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5 Exceções . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.6 Incorporando Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.7 Compilações de depuração . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2 C API Stability 13
2.1 Interface binária de aplicativo estável . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1.1 Limited API Scope and Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.1.2 Limited API Caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.2 Platform Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.3 Contents of Limited API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3 A camada de Mais Alto Nível 39

4 Contagem de Referências 45

5 Manipulando Exceções 47
5.1 Impressão e limpeza . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.2 Lançando exceções . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.3 Emitindo advertências . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.4 Consultando o indicador de erro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.5 Tratamento de sinal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.6 Classes de exceção . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.7 Objeto Exceção . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.8 Objetos de exceção Unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.9 Controle de recursão . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.10 Exceções Padrão . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.11 Categorias de aviso padrão . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

6 Utilitários 59
6.1 Utilitários do Sistema Operacional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
6.2 System Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6.3 Process Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
6.4 Importando módulos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
6.5 Suporte a marshalling de dados . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

i
6.6 Análise de argumentos e construção de valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.6.1 Análise de argumentos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.6.2 Construindo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.7 Conversão e formação de strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.8 Reflexão . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.9 Registro de codec e funções de suporte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.9.1 API de pesquisa de codec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.9.2 API de registro de tratamentos de erros de decodificação Unicode . . . . . . . . . . . . . 80

7 Camada de Objetos Abstratos 81


7.1 Protocolo de objeto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.2 Protocolo de chamada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.2.1 O protocolo tp_call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.2.2 O protocolo vectorcall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.2.3 Object Calling API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.2.4 Call Support API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.3 Protocolo de número . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.4 Protocolo de sequência . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
7.5 Protocolo de mapeamento . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
7.6 Protocolo Iterador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
7.7 Protocolo de Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
7.7.1 Estrutura de Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
7.7.2 Tipos de solicitação do buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
7.7.3 Vetores Complexos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
7.7.4 Buffer-related functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.8 Protocolo de Buffer Antigo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

8 Camada de Objetos Concretos 105


8.1 Objetos Fundamentais . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
8.1.1 Objetos tipo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
8.1.2 O Objeto None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.2 Objetos Numéricos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.2.1 Objetos Inteiros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.2.2 Objetos Booleanos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
8.2.3 Objetos de ponto flutuante . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
8.2.4 Objetos de números complexos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
8.3 Objetos Sequência . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
8.3.1 Objetos Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
8.3.2 Objetos Byte Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.3.3 Objetos Unicode e Codecs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
8.3.4 Objeto tupla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
8.3.5 Objetos sequência de estrutura . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
8.3.6 Objeto List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
8.4 Coleções . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
8.4.1 Objetos dicionários . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
8.4.2 Objeto Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
8.5 Objetos Função . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
8.5.1 Objetos Função . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
8.5.2 Objetos de Método de Instância . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
8.5.3 Objetos método . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
8.5.4 Objeto célula . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
8.5.5 Objetos código . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
8.6 Outros Objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
8.6.1 Objetos arquivos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
8.6.2 Objeto Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
8.6.3 Objetos Iteradores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
8.6.4 Objetos Descritores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
8.6.5 Objetos Slice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158

ii
8.6.6 Objeto Ellipsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
8.6.7 Objetos MemoryView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
8.6.8 Objetos de referência fraca . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
8.6.9 Capsules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
8.6.10 Objetos Geradores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
8.6.11 Objetos corrotina . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
8.6.12 Objetos de variáveis de contexto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
8.6.13 Objetos DateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
8.6.14 Objetos de indicação de tipos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

9 Inicialização, Finalização e Threads 169


9.1 Antes da Inicialização do Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
9.2 Variáveis de configuração global . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
9.3 Inicializando e encerrando o interpretador . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
9.4 Process-wide parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
9.5 Thread State and the Global Interpreter Lock . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
9.5.1 Releasing the GIL from extension code . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
9.5.2 Non-Python created threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
9.5.3 Cuidados com o uso de fork() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
9.5.4 High-level API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
9.5.5 Low-level API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
9.6 Sub-interpreter support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
9.6.1 Bugs and caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
9.7 Asynchronous Notifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
9.8 Profiling and Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
9.9 Advanced Debugger Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
9.10 Thread Local Storage Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
9.10.1 Thread Specific Storage (TSS) API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
9.10.2 Thread Local Storage (TLS) API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188

10 Configuração de Inicialização do Python 189


10.1 Exemplo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
10.2 PyWideStringList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
10.3 PyStatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
10.4 PyPreConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
10.5 Preinitialize Python with PyPreConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
10.6 PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
10.7 Initialization with PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
10.8 Isolated Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
10.9 Python Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
10.10 Python Path Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
10.11 Py_RunMain() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
10.12 Py_GetArgcArgv() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
10.13 Multi-Phase Initialization Private Provisional API . . . . . . . . . . . . . . . . . . . . . . . . . . 207

11 Gerenciamento de Memória 209


11.1 Visão Geral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
11.2 Allocator Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
11.3 Raw Memory Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
11.4 Interface da Memória . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
11.5 Object allocators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
11.6 Default Memory Allocators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
11.7 Customize Memory Allocators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
11.8 Debug hooks on the Python memory allocators . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
11.9 The pymalloc allocator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
11.9.1 Customize pymalloc Arena Allocator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
11.10 tracemalloc C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
11.11 Exemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

iii
12 Suporte a implementação de Objetos 219
12.1 Alocando Objetos na Pilha . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
12.2 Estruturas Comuns de Objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
12.2.1 Base object types and macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
12.2.2 Implementing functions and methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
12.2.3 Accessing attributes of extension types . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
12.3 Objetos tipo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
12.3.1 Referências rápidas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
12.3.2 PyTypeObject Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
12.3.3 PyObject Slots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
12.3.4 PyVarObject Slots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
12.3.5 PyTypeObject Slots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
12.3.6 Static Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
12.3.7 Heap Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
12.4 Number Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
12.5 Mapping Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
12.6 Sequence Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
12.7 Buffer Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
12.8 Async Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
12.9 Slot Type typedefs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
12.10 Exemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
12.11 Suporte a Coleta de Lixo Cíclica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
12.11.1 Controlling the Garbage Collector State . . . . . . . . . . . . . . . . . . . . . . . . . . . 260

13 API e Versionamento ABI 261

A Glossário 263

B Sobre esses documentos 277


B.1 Contribuidores da Documentação Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

C História e Licença 279


C.1 História do software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
C.2 Termos e condições para acessar ou usar Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
C.2.1 ACORDO DE LICENCIAMENTO DA PSF PARA PYTHON 3.10.6 . . . . . . . . . . 280
C.2.2 ACORDO DE LICENCIAMENTO DA BEOPEN.COM PARA PYTHON 2.0 . . . . . . 281
C.2.3 CONTRATO DE LICENÇA DA CNRI PARA O PYTHON 1.6.1 . . . . . . . . . . . . 282
C.2.4 ACORDO DE LICENÇA DA CWI PARA PYTHON 0.9.0 A 1.2 . . . . . . . . . . . . 283
C.2.5 LICENÇA BSD DE ZERO CLÁUSULA PARA CÓDIGO NA DOCUMENTAÇÃO DO
PYTHON 3.10.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
C.3 Licenças e Reconhecimentos para Software Incorporado . . . . . . . . . . . . . . . . . . . . . . . 284
C.3.1 Mersenne Twister . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
C.3.2 Soquetes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
C.3.3 Serviços de soquete assíncrono . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
C.3.4 Gerenciamento de cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
C.3.5 Rastreamento de execução . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
C.3.6 Funções UUencode e UUdecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
C.3.7 Chamadas de procedimento remoto XML . . . . . . . . . . . . . . . . . . . . . . . . . 287
C.3.8 test_epoll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
C.3.9 kqueue de seleção . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
C.3.10 SipHash24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
C.3.11 strtod e dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
C.3.18 Conjunto de testes C14N do W3C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294

iv
D Direitos autorais 297

Índice 299

v
vi
The Python/C API, Release 3.10.6

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

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.

3
The Python/C API, Release 3.10.6

1.2 Incluir arquivos

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

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

4 Capítulo 1. Introdução
The Python/C API, Release 3.10.6

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.
Novo na versão 3.7.
Py_ABS(x)
Retorna o valor absoluto de x.
Novo na versão 3.3.
Py_MIN(x, y)
Retorna o valor mínimo entre x e y.
Novo na versão 3.3.
Py_MAX(x, y)
Retorna o valor máximo entre x e y.
Novo na versão 3.3.
Py_STRINGIFY(x)
Converte x para uma string C. Por exemplo, Py_STRINGIFY(123) retorna "123".
Novo na versão 3.4.
Py_MEMBER_SIZE(type, member)
Retorna o tamanho do member de uma estrutura (type) em bytes.
Novo na versão 3.6.
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_GETENV(s)
Como getenv(s), mas retorna NULL se -E foi passada na linha de comando (isto é, se
Py_IgnoreEnvironmentFlag estiver definida).
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; }.
Novo na versão 3.4.
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.


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
especificado em PEP 7.
Exemplo:

1.3. Macros úteis 5


The Python/C API, Release 3.10.6

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

static PyMethodDef deque_methods[] = {


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

PyDoc_STR(str)
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:
static PyMethodDef pysqlite_row_methods[] = {
{"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
PyDoc_STR("Returns the keys of the row.")},
{NULL, NULL}
};

1.4 Objetos, tipos 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 PyOb-
ject*. 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 exem-
plo, 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ência é importante porque os computadores de hoje têm um tamanho de memória finito (e
geralmente muito limitado); Conta quantos lugares diferentes existem que têm uma referência a um objeto. Esse local
poderia ser outro objeto, uma variável C global (ou estática) ou uma variável local em alguma função C. Quando a
contagem de referência de um objeto se torna zero, o objeto é desalocado. Se contiver referências a outros objetos, sua
contagem de referência será diminuída. Esses outros objetos podem ser desalocados, por sua vez, se esse decremento
fizer com que sua contagem de referência se torne zero e assim por diante. (Há um problema óbvio com objetos que
fazem referência um ao outro aqui; por enquanto, a solução é “não faça isso”).
As contagens de referências são sempre manipuladas explicitamente. A maneira normal é usar a macro
Py_INCREF() para incrementar a contagem de referências de um objeto em um, e Py_DECREF() para diminuí-
la em um. A macro Py_DECREF() é consideravelmente mais complexa que a “incref”, uma vez que deve verificar
se a contagem de referências torna-se zero e então fazer com que o desalocador do objeto seja chamado. O desaloca-
dor é um ponteiro de função contido na estrutura de tipo do objeto. O desalocador específico do tipo se encarrega de
diminuir as contagens de referências para outros objetos contidos no objeto se este for um tipo de objeto composto,
como uma lista, bem como realizar qualquer finalização adicional necessária. Não há chance de que a contagem
de referências possa estourar; pelo menos tantos bits são usados para manter a contagem de referência quanto há
locais de memória distintos na memória virtual (assumindo sizeof(Py_ssize_t) >= sizeof(void*)).
Portanto, o incremento da contagem de referências é uma operação simples.

6 Capítulo 1. Introdução
The Python/C API, Release 3.10.6

Não é necessário incrementar a contagem de referências de um objeto 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 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 incrementar sua
contagem de referências. Alguma outra operação poderia remover o objeto da lista, diminuindo sua contagem de
referências e possivelmente 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 incrementam a contagem de refe-
rê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 Python/C é 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 decref nela cha-
mando 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
chamador, 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 assume 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("three"));

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

1.4. Objetos, tipos e contagens de referências 7


The Python/C API, Release 3.10.6

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, "three");


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

É muito mais comum usar PyObject_SetItem() e amigos com itens cujas referências você está apenas pe-
gando emprestado, como argumentos que foram passados para a função que você está escrevendo. Nesse caso, o
comportamento deles em relação às contagens de referência é muito mais são, já que você não precisa incrementar
uma contagem de referências para que possa dar uma referência (“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)
(continua na próxima página)

8 Capítulo 1. Introdução
The Python/C API, Release 3.10.6

(continuação da página anterior)


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

long
sum_sequence(PyObject *sequence)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
n = PySequence_Length(sequence);
if (n < 0)
return -1; /* Has no length */
for (i = 0; i < n; i++) {
item = PySequence_GetItem(sequence, i);
if (item == NULL)
return -1; /* Not a sequence, or other failure */
if (PyLong_Check(item)) {
value = PyLong_AsLong(item);
Py_DECREF(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
else {
Py_DECREF(item); /* Discard reference ownership */
}
}
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
Part of the Stable ABI. A signed integral type such that sizeof(Py_ssize_t) == sizeof(size_t).
C99 doesn’t define such a thing directly (size_t is an unsigned integral type). See PEP 353 for details.
PY_SSIZE_T_MAX is the largest positive value of type Py_ssize_t.

1.4. Objetos, tipos e contagens de referências 9


The Python/C API, Release 3.10.6

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 documentaçã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 booleano verda-
deiro/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 do 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 loop 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)
{
(continua na próxima página)

10 Capítulo 1. Introdução
The Python/C API, Release 3.10.6

(continuação da página anterior)


/* Objects all initialized to NULL for Py_XDECREF */
PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
int rv = -1; /* Return value initialized to -1 (failure) */

item = PyObject_GetItem(dict, key);


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

/* Clear the error and use zero: */


PyErr_Clear();
item = PyLong_FromLong(0L);
if (item == NULL)
goto error;
}
const_one = PyLong_FromLong(1L);
if (const_one == NULL)
goto error;

incremented_item = PyNumber_Add(item, const_one);


if (incremented_item == NULL)
goto error;

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


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

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

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


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

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


}

Este 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

1.6. Incorporando Python 11


The Python/C API, Release 3.10.6

para o código Python que será executado posteriormente, ela deve ser definida explicitamente com uma chamada
com PySys_SetArgvEx(argc, argv, updatepath) após a chamada de Py_Initialize().
Na maioria dos sistemas (em particular, no Unix e no Windows, embora os detalhes sejam ligeiramente diferentes),
Py_Initialize() calcula o caminho de pesquisa do módulo com base em sua melhor estimativa para a locali-
zação do executável do interpretador Python padrão, assumindo 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).
Por exemplo, se o executável Python for encontrado em /usr/local/bin/python, ele presumirá que as biblio-
tecas 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 subs-
tituir 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 chamando Py_SetProgramName(file) antes de cha-
mar Py_Initialize(). 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 (fa-
zer outra chamada para Py_Initialize()) ou a aplicação simplesmente termina com o uso de Python e
deseja liberar memó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.
A full list of the various types of debugging builds is in the file Misc/SpecialBuilds.txt in the Python source
distribution. Builds are available that support tracing of reference counts, debugging the memory allocator, or low-
level profiling of the main interpreter loop. Only the most frequently used builds will be described in the remainder
of this section.
Compilar o interpretador com a macro Py_DEBUG definida produz o que geralmente se entende por uma com-
pilação de depuração do Python. Py_DEBUG é habilitada na compilaçã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 compilaçã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 adicio-
nando dois campos extras a cada PyObject. As alocações totais também são rastreadas. Ao sair, todas as referên-
cias 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 detalha-
das.

12 Capítulo 1. Introdução
CAPÍTULO 2

C API Stability

Python’s C API is covered by the Backwards Compatibility Policy, PEP 387. While the C API will change with
every minor release (e.g. from 3.9 to 3.10), most changes will be source-compatible, typically by only adding new
API. Changing existing API or removing API is only done after a deprecation period or to fix serious issues.
CPython’s Application Binary Interface (ABI) is forward- and backwards-compatible across a minor release (if these
are compiled the same way; see Platform Considerations below). So, code compiled for Python 3.10.0 will work on
3.10.8 and vice versa, but will need to be compiled separately for 3.9.x and 3.10.x.
Names prefixed by an underscore, such as _Py_InternalState, are private API that can change without notice
even in patch releases.

2.1 Interface binária de aplicativo estável

Python 3.2 introduced the Limited API, a subset of Python’s C API. Extensions that only use the Limited API can be
compiled once and work with multiple versions of Python. Contents of the Limited API are listed below.
To enable this, Python provides a Stable ABI: a set of symbols that will remain compatible across Python 3.x versions.
The Stable ABI contains symbols exposed in the Limited API, but also other ones – for example, functions necessary
to support older versions of the Limited API.
(For simplicity, this document talks about extensions, but the Limited API and Stable ABI work the same way for all
uses of the API – for example, embedding Python.)
Py_LIMITED_API
Define this macro before including Python.h to opt in to only use the Limited API, and to select the Limited
API version.
Define Py_LIMITED_API to the value of PY_VERSION_HEX corresponding to the lowest Python version
your extension supports. The extension will work without recompilation with all Python 3 releases from the
specified one onward, and can use Limited API introduced up to that version.
Rather than using the PY_VERSION_HEX macro directly, hardcode a minimum minor version (e.g.
0x030A0000 for Python 3.10) for stability when compiling with future Python versions.
You can also define Py_LIMITED_API to 3. This works the same as 0x03020000 (Python 3.2, the version
that introduced Limited API).
On Windows, extensions that use the Stable ABI should be linked against python3.dll rather than a version-
specific library such as python39.dll.

13
The Python/C API, Release 3.10.6

On some platforms, Python will look for and load shared library files named with the abi3 tag (e.g. mymodule.
abi3.so). It does not check if such extensions conform to a Stable ABI. The user (or their packaging tools) need to
ensure that, for example, extensions built with the 3.10+ Limited API are not installed for lower versions of Python.
All functions in the Stable ABI are present as functions in Python’s shared library, not solely as macros. This makes
them usable from languages that don’t use the C preprocessor.

2.1.1 Limited API Scope and Performance

The goal for the Limited API is to allow everything that is possible with the full C API, but possibly with a performance
penalty.
For example, while PyList_GetItem() is available, its “unsafe” macro variant PyList_GET_ITEM() is not.
The macro can be faster because it can rely on version-specific implementation details of the list object.
Without Py_LIMITED_API defined, some C API functions are inlined or replaced by macros. Defining
Py_LIMITED_API disables this inlining, allowing stability as Python’s data structures are improved, but possi-
bly reducing performance.
By leaving out the Py_LIMITED_API definition, it is possible to compile a Limited API extension with a version-
specific ABI. This can improve performance for that Python version, but will limit compatibility. Compiling with
Py_LIMITED_API will then yield an extension that can be distributed where a version-specific one is not available
– for example, for prereleases of an upcoming Python version.

2.1.2 Limited API Caveats

Note that compiling with Py_LIMITED_API is not a complete guarantee that code conforms to the Limited API or
the Stable ABI. Py_LIMITED_API only covers definitions, but an API also includes other issues, such as expected
semantics.
One issue that Py_LIMITED_API does not guard against is calling a function with arguments that are invalid in
a lower Python version. For example, consider a function that starts accepting NULL for an argument. In Python
3.9, NULL now selects a default behavior, but in Python 3.8, the argument will be used directly, causing a NULL
dereference and crash. A similar argument works for fields of structs.
Another issue is that some struct fields are currently not hidden when Py_LIMITED_API is defined, even though
they’re part of the Limited API.
For these reasons, we recommend testing an extension with all minor Python versions it supports, and preferably to
build with the lowest such version.
We also recommend reviewing documentation of all used API to check if it is explicitly part of the Limited API.
Even with Py_LIMITED_API defined, a few private declarations are exposed for technical reasons (or even unin-
tentionally, as bugs).
Also note that the Limited API is not necessarily stable: compiling with Py_LIMITED_API with Python 3.8 means
that the extension will run with Python 3.12, but it will not necessarily compile with Python 3.12. In particular, parts
of the Limited API may be deprecated and removed, provided that the Stable ABI stays stable.

2.2 Platform Considerations

ABI stability depends not only on Python, but also on the compiler used, lower-level libraries and compiler options.
For the purposes of the Stable ABI, these details define a “platform”. They usually depend on the OS type and
processor architecture
It is the responsibility of each particular distributor of Python to ensure that all Python versions on a particular
platform are built in a way that does not break the Stable ABI. This is the case with Windows and macOS releases
from python.org and many third-party distributors.

14 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

2.3 Contents of Limited API

Currently, the Limited API includes the following items:


• PyAIter_Check()
• PyArg_Parse()
• PyArg_ParseTuple()
• PyArg_ParseTupleAndKeywords()
• PyArg_UnpackTuple()
• PyArg_VaParse()
• PyArg_VaParseTupleAndKeywords()
• PyArg_ValidateKeywordArguments()
• PyBaseObject_Type
• PyBool_FromLong()
• PyBool_Type
• PyByteArrayIter_Type
• PyByteArray_AsString()
• PyByteArray_Concat()
• PyByteArray_FromObject()
• PyByteArray_FromStringAndSize()
• PyByteArray_Resize()
• PyByteArray_Size()
• PyByteArray_Type
• PyBytesIter_Type
• PyBytes_AsString()
• PyBytes_AsStringAndSize()
• PyBytes_Concat()
• PyBytes_ConcatAndDel()
• PyBytes_DecodeEscape()
• PyBytes_FromFormat()
• PyBytes_FromFormatV()
• PyBytes_FromObject()
• PyBytes_FromString()
• PyBytes_FromStringAndSize()
• PyBytes_Repr()
• PyBytes_Size()
• PyBytes_Type
• PyCFunction
• PyCFunctionWithKeywords
• PyCFunction_Call()

2.3. Contents of Limited API 15


The Python/C API, Release 3.10.6

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

16 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

• 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_GetItemString()
• PyDict_GetItemWithError()
• PyDict_Items()
• PyDict_Keys()
• PyDict_Merge()
• PyDict_MergeFromSeq2()
• PyDict_New()
• PyDict_Next()
• PyDict_SetItem()
• PyDict_SetItemString()

2.3. Contents of Limited API 17


The Python/C API, Release 3.10.6

• PyDict_Size()
• PyDict_Type
• PyDict_Update()
• PyDict_Values()
• PyEllipsis_Type
• PyEnum_Type
• PyErr_BadArgument()
• PyErr_BadInternalCall()
• PyErr_CheckSignals()
• PyErr_Clear()
• PyErr_Display()
• PyErr_ExceptionMatches()
• PyErr_Fetch()
• PyErr_Format()
• PyErr_FormatV()
• PyErr_GetExcInfo()
• PyErr_GivenExceptionMatches()
• PyErr_NewException()
• PyErr_NewExceptionWithDoc()
• PyErr_NoMemory()
• PyErr_NormalizeException()
• PyErr_Occurred()
• PyErr_Print()
• PyErr_PrintEx()
• PyErr_ProgramText()
• PyErr_ResourceWarning()
• PyErr_Restore()
• PyErr_SetExcFromWindowsErr()
• PyErr_SetExcFromWindowsErrWithFilename()
• PyErr_SetExcFromWindowsErrWithFilenameObject()
• PyErr_SetExcFromWindowsErrWithFilenameObjects()
• PyErr_SetExcInfo()
• PyErr_SetFromErrno()
• PyErr_SetFromErrnoWithFilename()
• PyErr_SetFromErrnoWithFilenameObject()
• PyErr_SetFromErrnoWithFilenameObjects()
• PyErr_SetFromWindowsErr()
• PyErr_SetFromWindowsErrWithFilename()
• PyErr_SetImportError()

18 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

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

2.3. Contents of Limited API 19


The Python/C API, Release 3.10.6

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

20 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

• 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_GetCause()
• PyException_GetContext()
• PyException_GetTraceback()
• PyException_SetCause()
• PyException_SetContext()
• PyException_SetTraceback()
• PyFile_FromFd()
• PyFile_GetLine()
• PyFile_WriteObject()
• PyFile_WriteString()
• PyFilter_Type
• PyFloat_AsDouble()
• PyFloat_FromDouble()
• PyFloat_FromString()
• PyFloat_GetInfo()

2.3. Contents of Limited API 21


The Python/C API, Release 3.10.6

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

22 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

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

2.3. Contents of Limited API 23


The Python/C API, Release 3.10.6

• PyLong_FromLong()
• PyLong_FromLongLong()
• PyLong_FromSize_t()
• PyLong_FromSsize_t()
• PyLong_FromString()
• PyLong_FromUnsignedLong()
• PyLong_FromUnsignedLongLong()
• PyLong_FromVoidPtr()
• PyLong_GetInfo()
• PyLong_Type
• PyMap_Type
• PyMapping_Check()
• PyMapping_GetItemString()
• PyMapping_HasKey()
• PyMapping_HasKeyString()
• PyMapping_Items()
• PyMapping_Keys()
• PyMapping_Length()
• PyMapping_SetItemString()
• PyMapping_Size()
• PyMapping_Values()
• PyMem_Calloc()
• PyMem_Free()
• PyMem_Malloc()
• PyMem_Realloc()
• PyMemberDef
• PyMemberDescr_Type
• PyMemoryView_FromMemory()
• PyMemoryView_FromObject()
• PyMemoryView_GetContiguous()
• PyMemoryView_Type
• PyMethodDef
• PyMethodDescr_Type
• PyModuleDef
• PyModuleDef_Base
• PyModuleDef_Init()
• PyModuleDef_Type
• PyModule_AddFunctions()
• PyModule_AddIntConstant()

24 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

• PyModule_AddObject()
• PyModule_AddObjectRef()
• PyModule_AddStringConstant()
• PyModule_AddType()
• PyModule_Create2()
• PyModule_ExecDef()
• PyModule_FromDefAndSpec2()
• PyModule_GetDef()
• PyModule_GetDict()
• PyModule_GetFilename()
• PyModule_GetFilenameObject()
• PyModule_GetName()
• PyModule_GetNameObject()
• PyModule_GetState()
• PyModule_New()
• PyModule_NewObject()
• PyModule_SetDocString()
• PyModule_Type
• PyNumber_Absolute()
• PyNumber_Add()
• PyNumber_And()
• PyNumber_AsSsize_t()
• PyNumber_Check()
• PyNumber_Divmod()
• PyNumber_Float()
• PyNumber_FloorDivide()
• PyNumber_InPlaceAdd()
• PyNumber_InPlaceAnd()
• PyNumber_InPlaceFloorDivide()
• PyNumber_InPlaceLshift()
• PyNumber_InPlaceMatrixMultiply()
• PyNumber_InPlaceMultiply()
• PyNumber_InPlaceOr()
• PyNumber_InPlacePower()
• PyNumber_InPlaceRemainder()
• PyNumber_InPlaceRshift()
• PyNumber_InPlaceSubtract()
• PyNumber_InPlaceTrueDivide()
• PyNumber_InPlaceXor()

2.3. Contents of Limited API 25


The Python/C API, Release 3.10.6

• PyNumber_Index()
• PyNumber_Invert()
• PyNumber_Long()
• PyNumber_Lshift()
• PyNumber_MatrixMultiply()
• PyNumber_Multiply()
• PyNumber_Negative()
• PyNumber_Or()
• PyNumber_Positive()
• PyNumber_Power()
• PyNumber_Remainder()
• PyNumber_Rshift()
• PyNumber_Subtract()
• PyNumber_ToBase()
• PyNumber_TrueDivide()
• PyNumber_Xor()
• PyOS_AfterFork()
• PyOS_AfterFork_Child()
• PyOS_AfterFork_Parent()
• PyOS_BeforeFork()
• PyOS_CheckStack()
• PyOS_FSPath()
• PyOS_InputHook
• PyOS_InterruptOccurred()
• PyOS_double_to_string()
• PyOS_getsig()
• PyOS_mystricmp()
• PyOS_mystrnicmp()
• PyOS_setsig()
• PyOS_sighandler_t
• PyOS_snprintf()
• PyOS_string_to_double()
• PyOS_strtol()
• PyOS_strtoul()
• PyOS_vsnprintf()
• PyObject
• PyObject.ob_refcnt
• PyObject.ob_type
• PyObject_ASCII()

26 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

• PyObject_AsCharBuffer()
• PyObject_AsFileDescriptor()
• PyObject_AsReadBuffer()
• PyObject_AsWriteBuffer()
• PyObject_Bytes()
• PyObject_Call()
• PyObject_CallFunction()
• PyObject_CallFunctionObjArgs()
• PyObject_CallMethod()
• PyObject_CallMethodObjArgs()
• PyObject_CallNoArgs()
• PyObject_CallObject()
• PyObject_Calloc()
• PyObject_CheckReadBuffer()
• PyObject_ClearWeakRefs()
• PyObject_DelItem()
• PyObject_DelItemString()
• PyObject_Dir()
• PyObject_Format()
• PyObject_Free()
• PyObject_GC_Del()
• PyObject_GC_IsFinalized()
• PyObject_GC_IsTracked()
• PyObject_GC_Track()
• PyObject_GC_UnTrack()
• PyObject_GenericGetAttr()
• PyObject_GenericGetDict()
• PyObject_GenericSetAttr()
• PyObject_GenericSetDict()
• PyObject_GetAIter()
• PyObject_GetAttr()
• PyObject_GetAttrString()
• PyObject_GetItem()
• PyObject_GetIter()
• PyObject_HasAttr()
• PyObject_HasAttrString()
• PyObject_Hash()
• PyObject_HashNotImplemented()
• PyObject_Init()

2.3. Contents of Limited API 27


The Python/C API, Release 3.10.6

• PyObject_InitVar()
• PyObject_IsInstance()
• PyObject_IsSubclass()
• PyObject_IsTrue()
• PyObject_Length()
• PyObject_Malloc()
• PyObject_Not()
• PyObject_Realloc()
• PyObject_Repr()
• PyObject_RichCompare()
• PyObject_RichCompareBool()
• PyObject_SelfIter()
• PyObject_SetAttr()
• PyObject_SetAttrString()
• PyObject_SetItem()
• PyObject_Size()
• PyObject_Str()
• PyObject_Type()
• 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()

28 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

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

2.3. Contents of Limited API 29


The Python/C API, Release 3.10.6

• PySys_SetArgv()
• PySys_SetArgvEx()
• PySys_SetObject()
• PySys_SetPath()
• PySys_WriteStderr()
• PySys_WriteStdout()
• PyThreadState
• PyThreadState_Clear()
• PyThreadState_Delete()
• PyThreadState_Get()
• PyThreadState_GetDict()
• PyThreadState_GetFrame()
• PyThreadState_GetID()
• PyThreadState_GetInterpreter()
• PyThreadState_New()
• PyThreadState_SetAsyncExc()
• PyThreadState_Swap()
• PyThread_GetInfo()
• PyThread_ReInitTLS()
• PyThread_acquire_lock()
• PyThread_acquire_lock_timed()
• PyThread_allocate_lock()
• PyThread_create_key()
• PyThread_delete_key()
• PyThread_delete_key_value()
• 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()

30 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

• PyThread_tss_free()
• PyThread_tss_get()
• PyThread_tss_is_created()
• PyThread_tss_set()
• PyTraceBack_Here()
• PyTraceBack_Print()
• PyTraceBack_Type
• PyTupleIter_Type
• PyTuple_GetItem()
• PyTuple_GetSlice()
• PyTuple_New()
• PyTuple_Pack()
• PyTuple_SetItem()
• PyTuple_Size()
• PyTuple_Type
• PyTypeObject
• PyType_ClearCache()
• PyType_FromModuleAndSpec()
• PyType_FromSpec()
• PyType_FromSpecWithBases()
• PyType_GenericAlloc()
• PyType_GenericNew()
• PyType_GetFlags()
• PyType_GetModule()
• PyType_GetModuleState()
• PyType_GetSlot()
• 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()

2.3. Contents of Limited API 31


The Python/C API, Release 3.10.6

• PyUnicodeDecodeError_SetReason()
• PyUnicodeDecodeError_SetStart()
• PyUnicodeEncodeError_GetEncoding()
• PyUnicodeEncodeError_GetEnd()
• PyUnicodeEncodeError_GetObject()
• PyUnicodeEncodeError_GetReason()
• PyUnicodeEncodeError_GetStart()
• PyUnicodeEncodeError_SetEnd()
• PyUnicodeEncodeError_SetReason()
• PyUnicodeEncodeError_SetStart()
• PyUnicodeIter_Type
• PyUnicodeTranslateError_GetEnd()
• PyUnicodeTranslateError_GetObject()
• PyUnicodeTranslateError_GetReason()
• PyUnicodeTranslateError_GetStart()
• PyUnicodeTranslateError_SetEnd()
• PyUnicodeTranslateError_SetReason()
• PyUnicodeTranslateError_SetStart()
• PyUnicode_Append()
• PyUnicode_AppendAndDel()
• PyUnicode_AsASCIIString()
• PyUnicode_AsCharmapString()
• PyUnicode_AsDecodedObject()
• PyUnicode_AsDecodedUnicode()
• PyUnicode_AsEncodedObject()
• PyUnicode_AsEncodedString()
• PyUnicode_AsEncodedUnicode()
• PyUnicode_AsLatin1String()
• PyUnicode_AsMBCSString()
• PyUnicode_AsRawUnicodeEscapeString()
• PyUnicode_AsUCS4()
• PyUnicode_AsUCS4Copy()
• PyUnicode_AsUTF16String()
• PyUnicode_AsUTF32String()
• PyUnicode_AsUTF8AndSize()
• PyUnicode_AsUTF8String()
• PyUnicode_AsUnicodeEscapeString()
• PyUnicode_AsWideChar()
• PyUnicode_AsWideCharString()

32 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

• PyUnicode_BuildEncodingMap()
• PyUnicode_Compare()
• PyUnicode_CompareWithASCIIString()
• PyUnicode_Concat()
• PyUnicode_Contains()
• PyUnicode_Count()
• PyUnicode_Decode()
• PyUnicode_DecodeASCII()
• PyUnicode_DecodeCharmap()
• PyUnicode_DecodeCodePageStateful()
• PyUnicode_DecodeFSDefault()
• PyUnicode_DecodeFSDefaultAndSize()
• PyUnicode_DecodeLatin1()
• PyUnicode_DecodeLocale()
• PyUnicode_DecodeLocaleAndSize()
• PyUnicode_DecodeMBCS()
• PyUnicode_DecodeMBCSStateful()
• PyUnicode_DecodeRawUnicodeEscape()
• PyUnicode_DecodeUTF16()
• PyUnicode_DecodeUTF16Stateful()
• PyUnicode_DecodeUTF32()
• PyUnicode_DecodeUTF32Stateful()
• PyUnicode_DecodeUTF7()
• PyUnicode_DecodeUTF7Stateful()
• PyUnicode_DecodeUTF8()
• PyUnicode_DecodeUTF8Stateful()
• PyUnicode_DecodeUnicodeEscape()
• PyUnicode_EncodeCodePage()
• PyUnicode_EncodeFSDefault()
• PyUnicode_EncodeLocale()
• PyUnicode_FSConverter()
• PyUnicode_FSDecoder()
• PyUnicode_Find()
• PyUnicode_FindChar()
• PyUnicode_Format()
• PyUnicode_FromEncodedObject()
• PyUnicode_FromFormat()
• PyUnicode_FromFormatV()
• PyUnicode_FromObject()

2.3. Contents of Limited API 33


The Python/C API, Release 3.10.6

• PyUnicode_FromOrdinal()
• PyUnicode_FromString()
• PyUnicode_FromStringAndSize()
• PyUnicode_FromWideChar()
• PyUnicode_GetDefaultEncoding()
• PyUnicode_GetLength()
• PyUnicode_GetSize()
• PyUnicode_InternFromString()
• PyUnicode_InternImmortal()
• 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
• PyWeakReference
• PyWeakref_GetObject()
• PyWeakref_NewProxy()
• PyWeakref_NewRef()
• PyWrapperDescr_Type
• PyWrapper_New()
• PyZip_Type
• Py_AddPendingCall()
• Py_AtExit()
• Py_BEGIN_ALLOW_THREADS

34 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

• Py_BLOCK_THREADS
• Py_BuildValue()
• Py_BytesMain()
• Py_CompileString()
• Py_DecRef()
• Py_DecodeLocale()
• Py_END_ALLOW_THREADS
• Py_EncodeLocale()
• Py_EndInterpreter()
• Py_EnterRecursiveCall()
• Py_Exit()
• Py_FatalError()
• Py_FileSystemDefaultEncodeErrors
• Py_FileSystemDefaultEncoding
• Py_Finalize()
• Py_FinalizeEx()
• Py_GenericAlias()
• Py_GenericAliasType
• Py_GetBuildInfo()
• Py_GetCompiler()
• Py_GetCopyright()
• Py_GetExecPrefix()
• Py_GetPath()
• Py_GetPlatform()
• Py_GetPrefix()
• Py_GetProgramFullPath()
• Py_GetProgramName()
• Py_GetPythonHome()
• Py_GetRecursionLimit()
• Py_GetVersion()
• Py_HasFileSystemDefaultEncoding
• Py_IncRef()
• Py_Initialize()
• Py_InitializeEx()
• Py_Is()
• Py_IsFalse()
• Py_IsInitialized()
• Py_IsNone()
• Py_IsTrue()

2.3. Contents of Limited API 35


The Python/C API, Release 3.10.6

• Py_LeaveRecursiveCall()
• Py_Main()
• Py_MakePendingCalls()
• Py_NewInterpreter()
• Py_NewRef()
• Py_ReprEnter()
• Py_ReprLeave()
• Py_SetPath()
• Py_SetProgramName()
• Py_SetPythonHome()
• Py_SetRecursionLimit()
• Py_UCS4
• Py_UNBLOCK_THREADS
• Py_UTF8Mode
• Py_VaBuildValue()
• Py_XNewRef()
• Py_intptr_t
• Py_ssize_t
• Py_uintptr_t
• allocfunc
• binaryfunc
• descrgetfunc
• descrsetfunc
• destructor
• getattrfunc
• getattrofunc
• getiterfunc
• getter
• hashfunc
• initproc
• inquiry
• iternextfunc
• lenfunc
• newfunc
• objobjargproc
• objobjproc
• reprfunc
• richcmpfunc
• setattrfunc

36 Capítulo 2. C API Stability


The Python/C API, Release 3.10.6

• setattrofunc
• setter
• ssizeargfunc
• ssizeobjargproc
• ssizessizeargfunc
• ssizessizeobjargproc
• symtable
• ternaryfunc
• traverseproc
• unaryfunc
• visitproc

2.3. Contents of Limited API 37


The Python/C API, Release 3.10.6

38 Capítulo 2. C API Stability


CAPÍTULO 3

A camada de Mais Alto Nível

The functions in this chapter will let you execute Python source code given in a file or a buffer, but they will not let
you interact in a more detailed way with the interpreter.
Several of these functions accept a start symbol from the grammar as a parameter. The available start symbols are
Py_eval_input, Py_file_input, and Py_single_input. These are described following the functions
which accept them as parameters.
Note also that several of these functions take FILE* parameters. One particular issue which needs to be handled
carefully is that the FILE structure for different C libraries can be different and incompatible. Under Windows (at
least), it is possible for dynamically linked extensions to actually use different libraries, so care should be taken that
FILE* parameters are only passed to these functions if it is certain that they were created by the same library that
the Python runtime is using.
int Py_Main(int argc, wchar_t **argv)
Part of the Stable ABI. The main program for the standard interpreter. This is made available for programs
which embed Python. The argc and argv parameters should be prepared exactly as those which are passed to
a C program’s main() function (converted to wchar_t according to the user’s locale). It is important to note
that the argument list may be modified (but the contents of the strings pointed to by the argument list are not).
The return value will be 0 if the interpreter exits normally (i.e., without an exception), 1 if the interpreter exits
due to an exception, or 2 if the parameter list does not represent a valid Python command line.
Note that if an otherwise unhandled SystemExit is raised, this function will not return 1, but exit the
process, as long as Py_InspectFlag is not set.
int Py_BytesMain(int argc, char **argv)
Part of the Stable ABI since version 3.8. Similar to Py_Main() but argv is an array of bytes strings.
Novo na versão 3.8.
int PyRun_AnyFile(FILE *fp, const char *filename)
This is a simplified interface to PyRun_AnyFileExFlags() below, leaving closeit set to 0 and flags set
to NULL.
int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
This is a simplified interface to PyRun_AnyFileExFlags() below, leaving the closeit argument set to 0.
int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)
This is a simplified interface to PyRun_AnyFileExFlags() below, leaving the flags argument set to
NULL.

39
The Python/C API, Release 3.10.6

int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)
If fp refers to a file associated with an interactive device (console or terminal input or Unix
pseudo-terminal), return the value of PyRun_InteractiveLoop(), otherwise return the re-
sult of PyRun_SimpleFile(). filename is decoded from the filesystem encoding (sys.
getfilesystemencoding()). If filename is NULL, this function uses "???" as the filename. If closeit
is true, the file is closed before PyRun_SimpleFileExFlags() returns.
int PyRun_SimpleString(const char *command)
This is a simplified interface to PyRun_SimpleStringFlags() below, leaving the
PyCompilerFlags* argument set to NULL.
int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Executes the Python source code from command in the __main__ module according to the flags argument.
If __main__ does not already exist, it is created. Returns 0 on success or -1 if an exception was raised. If
there was an error, there is no way to get the exception information. For the meaning of flags, see below.
Note that if an otherwise unhandled SystemExit is raised, this function will not return -1, but exit the
process, as long as Py_InspectFlag is not set.
int PyRun_SimpleFile(FILE *fp, const char *filename)
This is a simplified interface to PyRun_SimpleFileExFlags() below, leaving closeit set to 0 and flags
set to NULL.
int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)
This is a simplified interface to PyRun_SimpleFileExFlags() below, leaving flags set to NULL.
int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags
*flags)
Similar to PyRun_SimpleStringFlags(), but the Python source code is read from fp instead of an
in-memory string. filename should be the name of the file, it is decoded from filesystem encoding and error
handler. If closeit is true, the file is closed before PyRun_SimpleFileExFlags() returns.

Nota: On Windows, fp should be opened as binary mode (e.g. fopen(filename, "rb")). Otherwise,
Python may not handle script file with LF line ending correctly.

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


This is a simplified interface to PyRun_InteractiveOneFlags() below, leaving flags set to NULL.
int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Read and execute a single statement from a file associated with an interactive device according to the flags
argument. The user will be prompted using sys.ps1 and sys.ps2. filename is decoded from the filesystem
encoding and error handler.
Returns 0 when the input was executed successfully, -1 if there was an exception, or an error code from the
errcode.h include file distributed as part of Python if there was a parse error. (Note that errcode.h is
not included by Python.h, so must be included specifically if needed.)
int PyRun_InteractiveLoop(FILE *fp, const char *filename)
This is a simplified interface to PyRun_InteractiveLoopFlags() below, leaving flags set to NULL.
int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Read and execute statements from a file associated with an interactive device until EOF is reached. The user
will be prompted using sys.ps1 and sys.ps2. filename is decoded from the filesystem encoding and error
handler. Returns 0 at EOF or a negative number upon failure.
int (*PyOS_InputHook)(void)
Part of the Stable ABI. Can be set to point to a function with the prototype int func(void). The function
will be called when Python’s interpreter prompt is about to become idle and wait for user input from the
terminal. The return value is ignored. Overriding this hook can be used to integrate the interpreter’s prompt
with other event loops, as done in the Modules/_tkinter.c in the Python source code.
char *(*PyOS_ReadlineFunctionPointer)(FILE*, FILE*, const char*)
Can be set to point to a function with the prototype char *func(FILE *stdin, FILE *stdout,

40 Capítulo 3. A camada de Mais Alto Nível


The Python/C API, Release 3.10.6

char *prompt), overriding the default function used to read a single line of input at the interpreter’s
prompt. The function is expected to output the string prompt if it’s not NULL, and then read a line of input
from the provided standard input file, returning the resulting string. For example, The readline module
sets this hook to provide line-editing and tab-completion features.
The result must be a string allocated by PyMem_RawMalloc() or PyMem_RawRealloc(), or NULL if
an error occurred.
Alterado na versão 3.4: The result must be allocated by PyMem_RawMalloc() or
PyMem_RawRealloc(), instead of being allocated by PyMem_Malloc() or PyMem_Realloc().
PyObject *PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Return value: New reference. This is a simplified interface to PyRun_StringFlags() below, leaving flags
set to NULL.
PyObject *PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCom-
pilerFlags *flags)
Return value: New reference. Execute Python source code from str in the context specified by the objects
globals and locals with the compiler flags specified by flags. globals must be a dictionary; locals can be any
object that implements the mapping protocol. The parameter start specifies the start token that should be used
to parse the source code.
Returns the result of executing the code as a Python object, or NULL if an exception was raised.
PyObject *PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)
Return value: New reference. This is a simplified interface to PyRun_FileExFlags() below, leaving
closeit set to 0 and flags set to NULL.
PyObject *PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
int closeit)
Return value: New reference. This is a simplified interface to PyRun_FileExFlags() below, leaving flags
set to NULL.
PyObject *PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject
*locals, PyCompilerFlags *flags)
Return value: New reference. This is a simplified interface to PyRun_FileExFlags() below, leaving
closeit set to 0.
PyObject *PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject
*locals, int closeit, PyCompilerFlags *flags)
Return value: New reference. Similar to PyRun_StringFlags(), but the Python source code is read from
fp instead of an in-memory string. filename should be the name of the file, it is decoded from the filesystem
encoding and error handler. If closeit is true, the file is closed before PyRun_FileExFlags() returns.
PyObject *Py_CompileString(const char *str, const char *filename, int start)
Return value: New reference. Part of the Stable ABI. This is a simplified interface to
Py_CompileStringFlags() below, leaving flags set to NULL.
PyObject *Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompiler-
Flags *flags)
Return value: New reference. This is a simplified interface to Py_CompileStringExFlags() below,
with optimize set to -1.
PyObject *Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompiler-
Flags *flags, int optimize)
Return value: New reference. Parse and compile the Python source code in str, returning the resulting code
object. The start token is given by start; this can be used to constrain the code which can be compiled and should
be Py_eval_input, Py_file_input, or Py_single_input. The filename specified by filename is
used to construct the code object and may appear in tracebacks or SyntaxError exception messages. This
returns NULL if the code cannot be parsed or compiled.
The integer optimize specifies the optimization level of the compiler; a value of -1 selects the optimization
level of the interpreter as given by -O options. Explicit levels are 0 (no optimization; __debug__ is true), 1
(asserts are removed, __debug__ is false) or 2 (docstrings are removed too).
Novo na versão 3.4.

41
The Python/C API, Release 3.10.6

PyObject *Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompi-
lerFlags *flags, int optimize)
Return value: New reference. Like Py_CompileStringObject(), but filename is a byte string decoded
from the filesystem encoding and error handler.
Novo na versão 3.2.
PyObject *PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Return value: New reference. Part of the Stable ABI. This is a simplified interface to
PyEval_EvalCodeEx(), with just the code object, and global and local variables. The other ar-
guments are set to NULL.
PyObject *PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const
*args, int argcount, PyObject *const *kws, int kwcount, PyObject
*const *defs, int defcount, PyObject *kwdefs, PyObject *closure)
Return value: New reference. Part of the Stable ABI. Evaluate a precompiled code object, given a particular
environment for its evaluation. This environment consists of a dictionary of global variables, a mapping object
of local variables, arrays of arguments, keywords and defaults, a dictionary of default values for keyword-only
arguments and a closure tuple of cells.
type PyFrameObject
Part of the Limited API (as an opaque struct). The C structure of the objects used to describe frame objects.
The fields of this type are subject to change at any time.
PyObject *PyEval_EvalFrame(PyFrameObject *f)
Return value: New reference. Part of the Stable ABI. Evaluate an execution frame. This is a simplified interface
to PyEval_EvalFrameEx(), for backward compatibility.
PyObject *PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Return value: New reference. Part of the Stable ABI. This is the main, unvarnished function of Python in-
terpretation. The code object associated with the execution frame f is executed, interpreting bytecode and
executing calls as needed. The additional throwflag parameter can mostly be ignored - if true, then it causes
an exception to immediately be thrown; this is used for the throw() methods of generator objects.
Alterado na versão 3.4: This function now includes a debug assertion to help ensure that it does not silently
discard an active exception.
int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
This function changes the flags of the current evaluation frame, and returns true on success, false on failure.
int Py_eval_input
The start symbol from the Python grammar for isolated expressions; for use with Py_CompileString().
int Py_file_input
The start symbol from the Python grammar for sequences of statements as read from a file or other source; for
use with Py_CompileString(). This is the symbol to use when compiling arbitrarily long Python source
code.
int Py_single_input
The start symbol from the Python grammar for a single statement; for use with Py_CompileString().
This is the symbol used for the interactive interpreter loop.
struct PyCompilerFlags
This is the structure used to hold compiler flags. In cases where code is only being compiled, it is passed as
int flags, and in cases where code is being executed, it is passed as PyCompilerFlags *flags. In
this case, from __future__ import can modify flags.
Whenever PyCompilerFlags *flags is NULL, cf_flags is treated as equal to 0, and any modifica-
tion due to from __future__ import is discarded.
int cf_flags
Compiler flags.
int cf_feature_version
cf_feature_version is the minor Python version. It should be initialized to PY_MINOR_VERSION.

42 Capítulo 3. A camada de Mais Alto Nível


The Python/C API, Release 3.10.6

The field is ignored by default, it is used if and only if PyCF_ONLY_AST flag is set in cf_flags.
Alterado na versão 3.8: Added cf_feature_version field.
int CO_FUTURE_DIVISION
This bit can be set in flags to cause division operator / to be interpreted as “true division” according to PEP
238.

43
The Python/C API, Release 3.10.6

44 Capítulo 3. A camada de Mais Alto Nível


CAPÍTULO 4

Contagem de Referências

As macros nesta seção são usadas para gerenciar contagens de referências de objetos Python.
void Py_INCREF(PyObject *o)
Increment the reference count for object o.
This function is usually used to convert a borrowed reference to a strong reference in-place. The
Py_NewRef() function can be used to create a new strong reference.
The object must not be NULL; if you aren’t sure that it isn’t NULL, use Py_XINCREF().
void Py_XINCREF(PyObject *o)
Aumenta a contagem de referências para o objeto o. O objeto pode ser NULL, caso em que a macro não tem
efeito.
See also Py_XNewRef().
PyObject *Py_NewRef(PyObject *o)
Part of the Stable ABI since version 3.10. Create a new strong reference to an object: increment the reference
count of the object o and return the object o.
When the strong reference is no longer needed, Py_DECREF() should be called on it to decrement the object
reference count.
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().


Novo na versão 3.10.
PyObject *Py_XNewRef(PyObject *o)
Part of the Stable ABI since version 3.10. Similar to Py_NewRef(), but the object o can be NULL.
If the object o is NULL, the function just returns NULL.
Novo na versão 3.10.

45
The Python/C API, Release 3.10.6

void Py_DECREF(PyObject *o)


Decrement the reference count for object o.
If the reference count reaches zero, the object’s type’s deallocation 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().

Aviso: A função de desalocação pode fazer com que o código Python arbitrário seja invocado (por exem-
plo, quando uma instância de classe com um método __del__() é desalocada). Embora as exceções
em tal código não sejam propagadas, o código executado tem acesso livre a todas as variáveis globais do
Python. Isso significa que qualquer objeto que é alcançável de uma variável global deve estar em um estado
consistente antes de Py_DECREF() ser invocado. Por exemplo, o código para excluir um objeto de uma
lista deve copiar uma referência ao objeto excluído em uma variável temporária, atualizar a estrutura de
dados da lista e então chamar Py_DECREF() para a variável temporária.

void Py_XDECREF(PyObject *o)


Diminui a contagem de referências para o objeto o. O objeto pode ser NULL, caso em que a macro não tem
efeito; caso contrário, o efeito é o mesmo de Py_DECREF(), e o mesmo aviso se aplica.
void Py_CLEAR(PyObject *o)
Diminui a contagem de referências para o objeto o. O objeto pode ser NULL, caso em que a macro não tem
efeito; caso contrário, o efeito é o mesmo de Py_DECREF(), exceto que o argumento também é definido
como NULL. O aviso para Py_DECREF() não se aplica em relação ao objeto passado porque a macro usa
cuidadosamente uma variável temporária e define o argumento como NULL antes de diminuir sua contagem
de referências.
É uma boa ideia usar essa macro sempre que diminuir a contagem de referências de um objeto que pode ser
percorrido durante a coleta de lixo.
void Py_IncRef(PyObject *o)
Part of the Stable ABI. Increment the reference count for object o. A function version of Py_XINCREF().
It can be used for runtime dynamic embedding of Python.
void Py_DecRef(PyObject *o)
Part of the Stable ABI. Decrement the reference count for object o. A function version of Py_XDECREF().
It can be used for runtime dynamic embedding of Python.
As seguintes funções ou macros são apenas para uso dentro do núcleo do interpretador: _Py_Dealloc(),
_Py_ForgetReference(), _Py_NewReference(), bem como a variável global _Py_RefTotal.

46 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, or -1 se retornarem um número inteiro (exceção: as funções PyArg_*
retornam 1 em caso de sucesso e 0 em caso de 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: The error indicator is not the result of sys.exc_info(). The former corresponds to an exception that
is not yet caught (and is therefore still propagating), while the latter returns an exception after it is caught (and has
therefore stopped propagating).

5.1 Impressão e limpeza

void PyErr_Clear()
Part of the Stable ABI. 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)
Part of the Stable ABI. Print a standard traceback to sys.stderr and clear the error indicator. Unless the
error is a SystemExit, in that case no traceback is printed and the Python process will exit with the error
code specified by the SystemExit instance.
Chame esta função apenas quando o indicador de erro estiver definido. Caso contrário, causará um erro fatal!

47
The Python/C API, Release 3.10.6

If set_sys_last_vars is nonzero, the variables sys.last_type, sys.last_value and sys.


last_traceback will be set to the type, value and traceback of the printed exception, respectively.
void PyErr_Print()
Part of the Stable ABI. Alias para“PyErr_PrintEx(1)“.
void PyErr_WriteUnraisable(PyObject *obj)
Part of the Stable ABI. Chame 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
impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs
in an __del__() method.
The function is called with a single argument obj that identifies the context in which the unraisable exception
occurred. If possible, the repr of obj will be printed in the warning message.
Uma exceção deve ser definida ao chamar essa função.

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)
Part of the Stable ABI. This is the most common way to set the error indicator. The first argument specifies
the exception type; it is normally one of the standard exceptions, e.g. PyExc_RuntimeError. You need
not increment its reference count. The second argument is an error message; it is decoded from 'utf-8'.
void PyErr_SetObject(PyObject *type, PyObject *value)
Part of the Stable ABI. 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, ...)
Return value: Always NULL. Part of the Stable ABI. 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.
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Return value: Always NULL. Part of the Stable ABI since version 3.5. Igual a PyErr_Format(), mas usando
o argumento va_list em vez de um número variável de argumentos.
Novo na versão 3.5.
void PyErr_SetNone(PyObject *type)
Part of the Stable ABI. Isso é uma abreviação para PyErr_SetObject(type, Py_None).
int PyErr_BadArgument()
Part of the Stable ABI. 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()
Return value: Always NULL. Part of the Stable ABI. 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)
Return value: Always NULL. Part of the Stable ABI. This is a convenience function to raise an exception when
a C library function has returned an error and set the C variable errno. It constructs a tuple object whose
first item is the integer errno value and whose second item is the corresponding error message (gotten from
strerror()), and then calls PyErr_SetObject(type, object). On Unix, when the errno value
is EINTR, indicating an interrupted system call, this calls PyErr_CheckSignals(), and if that set the

48 Capítulo 5. Manipulando Exceções


The Python/C API, Release 3.10.6

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 *filenameOb-
ject)
Return value: Always NULL. Part of the Stable ABI. Similar to PyErr_SetFromErrno(), with the addi-
tional behavior that if filenameObject is not NULL, it is passed to the constructor of type as a third parameter.
In the case of OSError exception, this is used to define the filename attribute of the exception instance.
PyObject *PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameOb-
ject, PyObject *filenameObject2)
Return value: Always NULL. Part of the Stable ABI since version 3.7. Similar to
PyErr_SetFromErrnoWithFilenameObject(), but takes a second filename object, for rai-
sing errors when a function that takes two filenames fails.
Novo na versão 3.4.
PyObject *PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)
Return value: Always NULL. Part of the Stable ABI. Similar to
PyErr_SetFromErrnoWithFilenameObject(), but the filename is given as a C string. file-
name is decoded from the filesystem encoding and error handler.
PyObject *PyErr_SetFromWindowsErr(int ierr)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. This is a convenience func-
tion to raise WindowsError. If called with ierr of 0, the error code returned by a call to GetLastError()
is used instead. It calls the Win32 function FormatMessage() to retrieve the Windows description of error
code given by ierr or GetLastError(), then it constructs a tuple object whose first item is the ierr value
and whose second item is the corresponding error message (gotten from FormatMessage()), and then calls
PyErr_SetObject(PyExc_WindowsError, object). This function always returns NULL.
Disponibilidade: Windows.
PyObject *PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar to
PyErr_SetFromWindowsErr(), with an additional parameter specifying the exception type to be raised.
Disponibilidade: Windows.
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar à
PyErr_SetFromWindowsErrWithFilenameObject(), mas o nome do arquivo é dados como uma
String C. O nome do arquivo é decodificado a partir do sistema de arquivos (os.fsdecode()).
Disponibilidade: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr,
PyObject *filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar to
PyErr_SetFromWindowsErrWithFilenameObject(), with an additional parameter specifying
the exception type to be raised.
Disponibilidade: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr,
PyObject *filename, PyOb-
ject *filename2)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar à
PyErr_SetExcFromWindowsErrWithFilenameObject(), mas aceita um segundo caminho do
objeto.
Disponibilidade: Windows.
Novo na versão 3.4.
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char
*filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar à

5.2. Lançando exceções 49


The Python/C API, Release 3.10.6

PyErr_SetFromWindowsErrWithFilename(), com um parâmetro adicional especificando o tipo


de exceção a ser gerado.
Disponibilidade: Windows.
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 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.
Novo na versão 3.3.
PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name,
PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.6. Muito parecido com
PyErr_SetImportError() mas a função permite especificar uma subclasse de ImportError para
levantar uma exceção.
Novo 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.
Novo na versão 3.4.
void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Part of the Stable ABI since version 3.7. Like PyErr_SyntaxLocationObject(), but filename is a
byte string decoded from the filesystem encoding and error handler.
Novo na versão 3.2.
void PyErr_SyntaxLocation(const char *filename, int lineno)
Part of the Stable ABI. Like PyErr_SyntaxLocationEx(), but the col_offset parameter is omitted.
void PyErr_BadInternalCall()
Part of the Stable ABI. 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 invo-
ked with an illegal 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)
Part of the Stable ABI. 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
warning categories are available as global variables whose names are enumerated at Categorias de aviso padrão.
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.

50 Capítulo 5. Manipulando Exceções


The Python/C API, Release 3.10.6

int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int li-


neno, 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.
Novo na versão 3.4.
int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno,
const char *module, PyObject *registry)
Part of the Stable ABI. Similar 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, ...)
Part of the Stable ABI. Function similar to PyErr_WarnEx(), but use PyUnicode_FromFormat() to
format the warning message. format is an ASCII-encoded string.
Novo na versão 3.2.
int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI since version 3.6. Function similar to PyErr_WarnFormat(), but category is
ResourceWarning and it passes source to warnings.WarningMessage().
Novo na versão 3.6.

5.4 Consultando o indicador de erro

PyObject *PyErr_Occurred()
Return value: Borrowed reference. Part of the Stable ABI. 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.
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)


Part of the Stable ABI. 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)
Part of the Stable ABI. 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.
void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)
Part of the Stable ABI. 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.

Nota: Esta função, normalmente, é usada apenas pelo código que precisa capturar exceções ou pelo código
que precisa salvar e restaurar temporariamente o indicador de erro. Por exemplo:

{
PyObject *type, *value, *traceback;
(continua na próxima página)

5.4. Consultando o indicador de erro 51


The Python/C API, Release 3.10.6

(continuação da página anterior)


PyErr_Fetch(&type, &value, &traceback);

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

PyErr_Restore(type, value, traceback);


}

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


Part of the Stable ABI. Set the error indicator from the three objects. If the error indicator is already set, it is
cleared first. 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 code that needs to save and restore the error indicator tempo-
rarily. Use PyErr_Fetch() to save the current error indicator.

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


Part of the Stable ABI. 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);
}

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


Part of the Stable ABI since version 3.7. Retrieve 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. Returns new
references for the three objects, any of which may be NULL. Does not modify the exception info state.

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.

Novo na versão 3.3.


void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)
Part of the Stable ABI since version 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. For general
rules about the three arguments, see PyErr_Restore().

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.

Novo na versão 3.3.

52 Capítulo 5. Manipulando Exceções


The Python/C API, Release 3.10.6

5.5 Tratamento de sinal

int PyErr_CheckSignals()
Part of the Stable ABI. This function interacts with Python’s signal handling.
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()
Part of the Stable ABI. 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)


Part of the Stable ABI since version 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 cal-
led.
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.

Novo 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.
Alterado na versão 3.5: No Windows, a função agora também suporta manipuladores de socket.

5.5. Tratamento de sinal 53


The Python/C API, Release 3.10.6

5.6 Classes de exceção

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


Return value: New reference. Part of the Stable ABI. This utility function creates and returns a new excep-
tion 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 (accessible 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)
Return value: New reference. Part of the Stable ABI. 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.
Novo na versão 3.2.

5.7 Objeto Exceção

PyObject *PyException_GetTraceback(PyObject *ex)


Return value: New reference. Part of the Stable ABI. Return the traceback associated with the exception as a
new reference, as accessible from Python through __traceback__. If there is no traceback associated, this
returns NULL.
int PyException_SetTraceback(PyObject *ex, PyObject *tb)
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. Return the context (another exception instance during
whose handling ex was raised) associated with the exception as a new reference, as accessible from Python
through __context__. If there is no context associated, this returns NULL.
void PyException_SetContext(PyObject *ex, PyObject *ctx)
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. Return the cause (either an exception instance, or None,
set by raise ... from ...) associated with the exception as a new reference, as accessible from Python
through __cause__.
void PyException_SetCause(PyObject *ex, PyObject *cause)
Part of the Stable ABI. Set the cause associated with the exception to cause. Use NULL to clear it. There is no
type check to make sure that cause is either an exception instance or None. This steals a reference to cause.
__suppress_context__ para essa função é definido True , implicitamente.

54 Capítulo 5. Manipulando Exceções


The Python/C API, Release 3.10.6

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 *re-
ason)
Return value: New reference. Part of the Stable ABI. Create a UnicodeDecodeError object with the
attributes encoding, object, length, start, end and reason. encoding and reason are UTF-8 encoded strings.
PyObject *PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *ob-
ject, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end,
const char *reason)
Return value: New reference. Create a UnicodeEncodeError object with the attributes encoding, object,
length, start, end and reason. encoding and reason are UTF-8 encoded strings.
Obsoleto desde a versão 3.3: 3.11
Py_UNICODE is deprecated since Python 3.3. Please migrate to
PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns", ...).
PyObject *PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length,
Py_ssize_t start, Py_ssize_t end, const char *re-
ason)
Return value: New reference. Create a UnicodeTranslateError object with the attributes object, length,
start, end and reason. reason is a UTF-8 encoded string.
Obsoleto desde a versão 3.3: 3.11
Py_UNICODE is deprecated since Python 3.3. Please migrate to
PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns", ...).
PyObject *PyUnicodeDecodeError_GetEncoding(PyObject *exc)
PyObject *PyUnicodeEncodeError_GetEncoding(PyObject *exc)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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.
int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)

5.8. Objetos de exceção Unicode 55


The Python/C API, Release 3.10.6

int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)


Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI since version 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(). In 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)
Part of the Stable ABI since version 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 protec-
ting 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)
Part of the Stable ABI. 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.
void Py_ReprLeave(PyObject *object)
Part of the Stable ABI. Termina a Py_ReprEnter(). Deve ser chamado uma vez para cada chamada de
Py_ReprEnter() que retorna zero.

56 Capítulo 5. Manipulando Exceções


The Python/C API, Release 3.10.6

5.10 Exceções Padrão

All standard Python exceptions 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:

Nome C Nome Python Notas


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

5.10. Exceções Padrão 57


The Python/C API, Release 3.10.6

Tabela 1 – continuação da página anterior


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

Novo 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 and PyExc_TimeoutError were introduced following PEP 3151.
Novo na versão 3.5: PyExc_StopAsyncIteration and PyExc_RecursionError.
Novo na versão 3.6: PyExc_ModuleNotFoundError.
Esses são os aliases de compatibilidade para PyExc_OSError:

Nome C Notas
PyExc_EnvironmentError
PyExc_IOError
2
PyExc_WindowsError

Alterado na versão 3.3: Esses aliases costumavam ser tipos de exceção separados.
Notas:

5.11 Categorias de aviso padrão

All standard Python 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:

Nome C Nome Python Notas


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

Novo na versão 3.2: PyExc_ResourceWarning.


Notas:

1 Esta é uma classe base para outras exceções padrão.


2 Defina apenas no Windows; proteja o código que usa isso testando se a macro do pré-processador MS_WINDOWS está definida.
3 Esta é uma classe base para outras categorias de aviso padrão.

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


Return value: New reference. Part of the Stable ABI since version 3.6. Return the file system representation for
path. If the object is a str or bytes object, then its reference count is incremented. If the object implements
the os.PathLike interface, then __fspath__() is returned as long as it is a str or bytes object.
Otherwise TypeError is raised and NULL is returned.
Novo na versão 3.6.
int Py_FdIsInteractive(FILE *fp, const char *filename)
Return true (nonzero) if the standard I/O file fp with name filename is deemed interactive. This is the case
for files for which isatty(fileno(fp)) is true. If the global flag Py_InteractiveFlag is true,
this function also returns true if the filename pointer is NULL or if the name is equal to one of the strings
'<stdin>' or '???'.
void PyOS_BeforeFork()
Part of the Stable ABI on platforms with fork() since version 3.7. Function to prepare some internal state before
a process fork. This should be called before calling fork() or any similar function that clones the current
process. Only available on systems where fork() is defined.

Aviso: The C fork() call should only be made from the “main” thread (of the “main” interpreter). The
same is true for PyOS_BeforeFork().

Novo na versão 3.7.


void PyOS_AfterFork_Parent()
Part of the Stable ABI on platforms with fork() since version 3.7. Function to update some internal state after a
process fork. This should be called from the parent process after calling fork() or any similar function that
clones the current process, regardless of whether process cloning was successful. Only available on systems
where fork() is defined.

59
The Python/C API, Release 3.10.6

Aviso: The C fork() call should only be made from the “main” thread (of the “main” interpreter). The
same is true for PyOS_AfterFork_Parent().

Novo na versão 3.7.


void PyOS_AfterFork_Child()
Part of the Stable ABI on platforms with fork() since version 3.7. Function to update internal interpreter state
after a process fork. This must be called from the child process after calling fork(), or any similar function
that clones the current process, if there is any chance the process will call back into the Python interpreter.
Only available on systems where fork() is defined.

Aviso: The C fork() call should only be made from the “main” thread (of the “main” interpreter). The
same is true for PyOS_AfterFork_Child().

Novo na versão 3.7.


Ver também:
os.register_at_fork() allows registering custom Python functions to be called by
PyOS_BeforeFork(), PyOS_AfterFork_Parent() and PyOS_AfterFork_Child().
void PyOS_AfterFork()
Part of the Stable ABI on platforms with fork(). Função para atualizar algum estado interno após uma bifurcação
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.
Obsoleto desde a versão 3.7: This function is superseded by PyOS_AfterFork_Child().
int PyOS_CheckStack()
Part of the Stable ABI on platforms with USE_STACKCHECK since version 3.7. Retorna verdadeiro quando
o interpretador ficar sem espaço de pilha. Esta é uma verificação confiável, mas só está disponível quando
USE_STACKCHECK está definido (atualmente no Windows usando o compilador Microsoft Visual C++).
USE_STACKCHECK será definido automaticamente; você nunca deve mudar a definição em seu próprio có-
digo.
PyOS_sighandler_t PyOS_getsig(int i)
Part of the Stable ABI. Retorna o manipulador de sinal atual para o sinal i. Este é um invólucro fino em torno
de sigaction() ou signal(). Não ligue para essas funções diretamente! PyOS_sighandler_t é
um alias de typedef para void (*)int.
PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)
Part of the Stable ABI. Defina o manipulador de sinal para que o sinal i seja h; Devolva o antigo manipulador
de sinal. Este é um invólucro fino em torno de sigaction() ou signal(). Não ligue para essas funções
diretamente! PyOS_sighandler_t é um alias de typedef para void (*)int.
wchar_t *Py_DecodeLocale(const char *arg, size_t *size)
Part of the Stable ABI since version 3.7.

Aviso: This function should not be called directly: use the PyConfig API with the
PyConfig_SetBytesString() function which ensures that Python is preinitialized.
This function must not be called before Python is preinitialized and so that the LC_CTYPE locale is properly
configured: see the Py_PreInitialize() function.

Decode a byte string from the filesystem encoding and error handler. If the error handler is surrogateescape
error handler, undecodable bytes are decoded as characters in range U+DC80..U+DCFF; and if a byte sequence
can be decoded as a surrogate character, the bytes are escaped using the surrogateescape error handler instead
of decoding them.

60 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

Return a pointer to a newly allocated wide character string, use PyMem_RawFree() to free the memory. If
size is not NULL, write the number of wide characters excluding the null character into *size
Return NULL on decoding error or memory allocation error. If size is not NULL, *size is set to
(size_t)-1 on memory error or set to (size_t)-2 on decoding error.
The filesystem encoding and error handler are selected by PyConfig_Read(): see
filesystem_encoding and filesystem_errors members of PyConfig.
Decoding errors should never happen, unless there is a bug in the C library.
Use the Py_EncodeLocale() function to encode the character string back to a byte string.
Ver também:
The PyUnicode_DecodeFSDefaultAndSize() and PyUnicode_DecodeLocaleAndSize()
functions.
Novo na versão 3.5.
Alterado na versão 3.7: The function now uses the UTF-8 encoding in the Python UTF-8 Mode.
Alterado na versão 3.8: The function now uses the UTF-8 encoding on Windows if
Py_LegacyWindowsFSEncodingFlag is zero;
char *Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
Part of the Stable ABI since version 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.
The filesystem encoding and error handler are selected by PyConfig_Read(): see
filesystem_encoding and filesystem_errors members of PyConfig.
Use the Py_DecodeLocale() function to decode the bytes string back to a wide character string.

Aviso: This function must not be called before Python is preinitialized and so that the LC_CTYPE locale
is properly configured: see the Py_PreInitialize() function.

Ver também:
The PyUnicode_EncodeFSDefault() and PyUnicode_EncodeLocale() functions.
Novo na versão 3.5.
Alterado na versão 3.7: The function now uses the UTF-8 encoding in the Python UTF-8 Mode.
Alterado na versão 3.8: The function now uses the UTF-8 encoding on Windows if
Py_LegacyWindowsFSEncodingFlag is zero.

6.1. Utilitários do Sistema Operacional 61


The Python/C API, Release 3.10.6

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)
Return value: Borrowed reference. Part of the Stable ABI. 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)
Part of the Stable ABI. 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()
Part of the Stable ABI. Reset sys.warnoptions to an empty list. This function may be called prior to
Py_Initialize().
void PySys_AddWarnOption(const wchar_t *s)
Part of the Stable ABI. Append s to sys.warnoptions. This function must be called prior to
Py_Initialize() in order to affect the warnings filter list.
void PySys_AddWarnOptionUnicode(PyObject *unicode)
Part of the Stable ABI. Append unicode to sys.warnoptions.
Note: this function is not currently usable from outside the CPython implementation, as it must be called prior
to the implicit import of warnings in Py_Initialize() to be effective, but can’t be called until enough
of the runtime has been initialized to permit the creation of Unicode objects.
void PySys_SetPath(const wchar_t *path)
Part of the Stable ABI. Set sys.path to a list object of paths found in path which should be a list of paths
separated with the platform’s search path delimiter (: on Unix, ; on Windows).
void PySys_WriteStdout(const char *format, ...)
Part of the Stable ABI. 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, ...)
Part of the Stable ABI. As PySys_WriteStdout(), but write to sys.stderr or stderr instead.
void PySys_FormatStdout(const char *format, ...)
Part of the Stable ABI. Function similar to PySys_WriteStdout() but format the message using
PyUnicode_FromFormatV() and don’t truncate the message to an arbitrary length.
Novo na versão 3.2.
void PySys_FormatStderr(const char *format, ...)
Part of the Stable ABI. As PySys_FormatStdout(), but write to sys.stderr or stderr instead.
Novo na versão 3.2.
void PySys_AddXOption(const wchar_t *s)
Part of the Stable ABI since version 3.7. Parse s as a set of -X options and add them to the current options map-
ping as returned by PySys_GetXOptions(). This function may be called prior to Py_Initialize().
Novo na versão 3.2.

62 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

PyObject *PySys_GetXOptions()
Return value: Borrowed reference. Part of the Stable ABI since version 3.7. Return the current dictionary of
-X options, similarly to sys._xoptions. On error, NULL is returned and an exception is set.
Novo na versão 3.2.
int PySys_Audit(const char *event, const char *format, ...)
Raise an auditing event with any active hooks. Return zero for success and non-zero with an exception set on
failure.
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 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.
Novo na versão 3.8.
Alterado na versão 3.8.2: Require Py_ssize_t for # format characters. Previously, an unavoidable depre-
cation warning was raised.
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 of type int (*)const char *event, PyObject *args, void *userData, where args is gua-
ranteed to be a PyTupleObject. 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 a 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.
Novo na versão 3.8.

6.3 Process Control

void Py_FatalError(const char *message)


Part of the Stable ABI. Print a fatal error message and kill the process. No cleanup is performed. This function
should only be invoked when a condition is detected that would make it dangerous to continue using the Python
interpreter; e.g., when the object administration appears to be corrupted. On Unix, the standard C library
function abort() is called which will attempt to produce a core file.
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.

6.3. Process Control 63


The Python/C API, Release 3.10.6

void Py_Exit(int status)


Part of the Stable ABI. 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))
Part of the Stable ABI. 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.

6.4 Importando módulos

PyObject *PyImport_ImportModule(const char *name)


Return value: New reference. Part of the Stable ABI. Esta é uma interface simplificada para
PyImport_ImportModuleEx() abaixo, deixando os argumentos globals e locals definidos como NULL
e level definido como 0. Quando o argumento name contém um caractere de ponto (quando especifica um
submódulo de um pacote), o argumento fromlist é definido para a lista ['*'] de modo que o valor de retorno
é o módulo nomeado em vez do pacote de nível superior que o contém como faria caso contrário, seja o caso.
(Infelizmente, isso tem um efeito colateral adicional quando name de fato especifica um subpacote em vez de
um submódulo: os submódulos especificados na variável __all__ do pacote são carregados.) Retorna uma
nova referência ao módulo importado, ou NULL com uma exceção definida em caso de falha. Uma importação
com falha de um módulo não deixa o módulo em sys.modules.
Esta função sempre usa importações absolutas.
PyObject *PyImport_ImportModuleNoBlock(const char *name)
Return value: New reference. Part of the Stable ABI. Esta função é um alias descontinuado de
PyImport_ImportModule().
Alterado na versão 3.3: Essa função falhava em alguns casos, quando o bloqueio de importação era mantido
por outra thread. No Python 3.3, no entanto, o esquema de bloqueio mudou passando a ser por módulo na
maior parte, dessa forma, o comportamento especial dessa função não é mais necessário.
PyObject *PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals,
PyObject *fromlist)
Return value: New reference. 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().
PyObject *PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject
*locals, PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI since version 3.7. Importa um módulo. Isso é melhor des-
crito 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.
Novo na versão 3.3.

64 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

PyObject *PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,


PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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_AddModuleObject(PyObject *name)
Return value: Borrowed reference. Part of the Stable ABI since version 3.7. Retorna o objeto módulo corres-
pondente a um nome de módulo. O argumento name pode ter a forma package.module. Primeiro verifica
o dicionário de módulos se houver algum, caso contrário, cria um novo e insere-o no dicionário de módulos.
Retorna NULL com uma exceção definida em caso de falha.

Nota: Esta função não carrega ou importa o módulo; se o módulo não foi carregado, você receberá um
objeto de módulo vazio. Use PyImport_ImportModule() ou uma de suas variações para importar um
módulo. Estruturas de pacotes implícitos por um nome pontilhado para a name não são criados se não estiverem
presentes.

Novo na versão 3.3.


PyObject *PyImport_AddModule(const char *name)
Return value: Borrowed reference. Part of the Stable ABI. Semelhante para
PyImport_AddModuleObject(), mas o nome é uma string codifica em UTF-8 em vez de um
objeto Unicode.
PyObject *PyImport_ExecCodeModule(const char *name, PyObject *co)
Return value: New reference. Part of the Stable ABI. Dado um nome de módulo (possivelmente na forma
package.module) e um objeto código lido de um arquivo de bytecode Python ou obtido da função embutida
compile(), carrega o módulo. Retorna uma nova referência ao objeto do módulo, ou NULL com uma
exceção definida se ocorrer um erro. name é removido de sys.modules em casos de erro, mesmo se
name já estivesse em sys.modules na entrada para PyImport_ExecCodeModule(). Deixar módulos
incompletamente inicializados em sys.modules é perigoso, pois as importações de tais módulos não têm
como saber se o objeto módulo é um estado desconhecido (e provavelmente danificado em relação às intenções
do autor do módulo).
O __spec__ e o __loader__ do módulo serão definidos, se não estiverem, com os valores apropriados. O
carregador do spec será definido para o __loader__ do módulo (se definido) e para uma instância da classe
SourceFileLoader em caso contrário.
O atributo __file__ do módulo será definido para o co_filename do objeto código. Se aplicável,
__cached__ também será definido.
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().

6.4. Importando módulos 65


The Python/C API, Release 3.10.6

PyObject *PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *path-


name)
Return value: New reference. Part of the Stable ABI. Como PyImport_ExecCodeModule(), mas o
atributo __file__ do objeto módulo é definido como pathname se não for NULL.
Veja também PyImport_ExecCodeModuleWithPathnames().
PyObject *PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
PyObject *cpathname)
Return value: New reference. Part of the Stable ABI since version 3.7. Como
PyImport_ExecCodeModuleEx(), mas o atributo __cached__ do objeto módulo é definido
como cpathname se não for NULL. Das três funções, esta é a preferida para usar.
Novo na versão 3.3.
PyObject *PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
const char *pathname, const char
*cpathname)
Return value: New reference. Part of the Stable ABI. Como PyImport_ExecCodeModuleObject(),
mas name, pathname e cpathname são strings codificadas em UTF-8. Também são feitas tentativas para des-
cobrir qual valor para pathname deve ser de cpathname se o primeiro estiver definido como NULL.
Novo na versão 3.2.
Alterado na versão 3.3: Usa imp.source_from_cache() no cálculo do caminho de origem se apenas o
caminho do bytecode for fornecido.
long PyImport_GetMagicNumber()
Part of the Stable ABI. 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()
Part of the Stable ABI. 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.
Novo na versão 3.2.
PyObject *PyImport_GetModuleDict()
Return value: Borrowed reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI since version 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.
Novo na versão 3.7.
PyObject *PyImport_GetImporter(PyObject *path)
Return value: New reference. Part of the Stable ABI. Retorna um objeto localizador para o item path de
sys.path/pkg.__path__, possivelmente obtendo-o do dicionário sys.path_importer_cache.
Se ainda não foi armazenado em cache, atravessa sys.path_hooks até que um gancho seja encontrado que
possa lidar com o item de caminho. Retorna None se nenhum gancho puder; isso diz ao nosso chamador que o
localizador baseado no caminho não conseguiu encontrar um localizador para este item de caminho. Armazena
o resultado em sys.path_importer_cache. Retorna uma nova referência ao objeto localizador.
int PyImport_ImportFrozenModuleObject(PyObject *name)
Return value: New reference. Part of the Stable ABI since version 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 defi-
nida 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.)

66 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

Novo 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)
Part of the Stable ABI. 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 uti-
litá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;
};

const struct _frozen *PyImport_FrozenModules


Este ponteiro é inicializado para apontar para um vetor de registros de struct_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
Part of the Stable ABI. 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
Estrutura que descreve uma única entrada na lista de módulos embutidos. Cada uma dessas estruturas fornece o
nome e a função de inicialização para um módulo embutido ao interpretador. O nome é uma string codificada
em ASCII. Os programas que embutem Python podem usar um vetor dessas estruturas em conjunto com
PyImport_ExtendInittab() para fornecer módulos embutidos adicionais. A estrutura é definida em
Include/import.h como:

struct _inittab {
const char *name; /* ASCII encoded string */
PyObject* (*initfunc)(void);
};

int PyImport_ExtendInittab(struct _inittab *newtab)


Adiciona uma coleção de módulos à tabela de módulos embutidos. O vetor newtab deve terminar com uma
entrada sentinela que contém NULL para o campo name; a falha em fornecer o valor sentinela pode resultar
em uma falha de memória. Retorna 0 em caso de sucesso ou -1 se memória insuficiente puder ser alocada
para estender a tabela interna. Em caso de falha, nenhum módulo é adicionado à tabela interna. Deve ser
chamado antes de Py_Initialize().
Se Python é inicializado várias vezes, PyImport_AppendInittab() ou
PyImport_ExtendInittab() devem ser chamados antes de cada inicialização do Python.

6.4. Importando módulos 67


The Python/C API, Release 3.10.6

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 possui suporte a duas versões do formato de dados: a versão 0 é a versão histórica, a versão 1 compartilha
sequências de caracteres 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.
void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)
Aplica marshalling em um objeto Python, value, para file. version indica o formato do arquivo.
PyObject *PyMarshal_WriteObjectToString(PyObject *value, int version)
Return value: New reference. 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)
Return value: New reference. 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.
PyObject *PyMarshal_ReadLastObjectFromFile(FILE *file)
Return value: New reference. 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 ele 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)
Return value: New reference. 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.

68 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

6.6 Análise de argumentos e construção de valores

Essas funções são úteis ao criar funções e métodos das suas extensões. 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 and buffers

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.
Em geral, quando um formato define um ponteiro para um buffer, o buffer é gerenciado pelo objeto Python corres-
pondente e o buffer compartilha o tempo de vida desse objeto. Você não terá que liberar nenhuma memória por
conta própria. As únicas exceções são es, es#, et e et#.
No entanto, quando uma estrutura de Py_buffer é preenchida, o buffer subjacente é bloqueado para que
o chamador possa posteriormente usar o buffer mesmo dentro de um bloco Py_BEGIN_ALLOW_THREADS
sem o risco de dados mutáveis serem redimensionados ou destruídos. Como resultado, você precisa chamar
PyBuffer_Release() depois de ter concluído o processamento dos dados (ou em algum caso de interrupção
precoce).
Salvo indicação em contrário, os buffers não são terminados em NUL.
Alguns formatos requerem um objeto byte ou similar somente leitura e definem um ponteiro em vez de uma estrutura
de buffer. Eles trabalham verificando se o campo PyBufferProcs.bf_releasebuffer do objeto é NULL,
o que não permite objetos mutáveis, como bytearray.

Nota: Para todas as variantes de formatos # (s#, y#, etc.), a macro PY_SSIZE_T_CLEAN deve ser definida antes
de incluir Python.h. No Python 3.9 e mais antigo, o tipo do argumento de comprimento é Py_ssize_t se a
macro PY_SSIZE_T_CLEAN é definida, ou int caso contrário.

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 em 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 byte ou similar. Se você quer aceitar caminhos de arquivos do sistema
e convertê-los para strings 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.

6.6. Análise de argumentos e construção de valores 69


The Python/C API, Release 3.10.6

s* (str ou objeto byte ou similar) [Py_buffer] Esse formato aceita tanto objetos Unicode quanto objetos byte ou
similar. 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 byte ou similar somente leitura) [const char *, Py_ssize_t] Como s*, exceto que não aceita
objetos mutáveis. 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 byte 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 byte ou similar somente leitura ou None) [const char *, Py_ssize_t] Como s#, mas o ob-
jeto Python também pode ser None, nesse caso o ponteiro C é definido como NULL.
y (objeto byte ou similar somente leitura) [const char *] Este formato converte um objeto byte ou similar para um
ponteiro C para uma string de caracteres; 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 byte ou similar) [Py_buffer] Esta variante em s* não aceita objetos unicode, apenas objetos byte ou
similar. Esta é a maneira recomendada para aceitar dados binários.
y# (objeto byte ou similar somente leitura) [const char *, Py_ssize_t] Esta variação de s# não aceita objetos
Unicode, apenas objetos byte ou similar.
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) [const Py_UNICODE *] Converte um objeto Python Unicode para um ponteiro C para um buffer de
caracteres Unicode terminado em NUL. Você deve passar o endereço de uma variável ponteiro Py_UNICODE,
que será preenchida com um ponteiro para um buffer Unicode existente. Por favor, note que o comprimento de
um caractere Py_UNICODE depende das opções de compilação (está entre 16 ou 32 bits). A string Python não
deve conter pontos de código nulos incorporados, 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.
Deprecated since version 3.3, will be removed in version 3.12: Parte do estilo antigo Py_UNICODE API; por
favor migre o uso para PyUnicode_AsWideCharString().
u# (str) [const Py_UNICODE *, Py_ssize_t] Esta variante de u armazena em duas variáveis C, a primeira
um ponteiro para um buffer Unicode de dados, a segunda para seu comprimento. Esta variante permite pon-
teiros para nulos.
Deprecated since version 3.3, will be removed in version 3.12: Parte do estilo antigo Py_UNICODE API; por
favor migre o uso para PyUnicode_AsWideCharString().
Z (str ou None) [const Py_UNICODE *] Como u, mas o objeto Python também pode ser None, nesse caso o
ponteiro Py_UNICODE é definido como NULL.
Deprecated since version 3.3, will be removed in version 3.12: Parte do estilo antigo Py_UNICODE API; por
favor migre o uso para PyUnicode_AsWideCharString().
Z# (str ou None) [const Py_UNICODE *, Py_ssize_t] Como u#, mas o objeto Python também pode ser
None, nesse caso o ponteiro Py_UNICODE é definido como NULL

70 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

Deprecated since version 3.3, will be removed in version 3.12: Parte do estilo antigo Py_UNICODE API; por
favor migre o uso para PyUnicode_AsWideCharString().
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 byte 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 a 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 ob-
jetos de cadeia de bytes são passados sem os recodificar. Em vez disso, a implementação assume que o objeto
de cadeia 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 a 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 de cadeia de bytes são passados sem que sejam recodificados. Em vez
disso, a implementação assume que o objeto de cadeia de bytes usa a codificação passada como parâmetro.

6.6. Análise de argumentos e construção de valores 71


The Python/C API, Release 3.10.6

Números

b (int) [unsigned char] Converte um inteiro Python não negativo em um inteiro pequeno não assinado (unsigned
tiny int), armazenado em um unsigned char do C
B (int) [unsigned char] Converte um inteiro Python para um pequeno inteiro (tiny int) 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 compri-
mento 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

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. A contagem de referências do objeto 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 primeiro é 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, anything] 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

72 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

alocado. Nesta segunda chamada, o parâmetro object será NULL; address terá o mesmo valor que na chamada
original.
Alterado na versão 3.1: 109 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.
Novo 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.
É possível passar inteiros “long” (inteiros em que o valor excede a constante da plataforma LONG_MAX) contudo
nenhuma checagem de intervalo é propriamente feita — os bits mais significativos são silenciosamente truncados
quando o campo de recebimento é muito pequeno para receber o valor (na verdade, a semântica é herdada de down-
casts no C — seu raio de ação pode variar).
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 correspondentes
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 correspondente(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.
Novo 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).
; 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
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.

6.6. Análise de argumentos e construção de valores 73


The Python/C API, Release 3.10.6

Funções da API

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


Part of the Stable ABI. 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)
Part of the Stable ABI. 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
*keywords[], ...)
Part of the Stable ABI. Analisa os parâmetros de uma função que recebe ambos parâmetros posicionais e de
palavra reservada em variáveis locais. O argumento keywords é um vetor terminado por NULL de nomes de
parâmetros de palavra reservada. Nomes vazios denotam positional-only parameters. Retorna verdadeiro em
caso de sucesso; em caso de falha, retorna falso e levanta a exceção apropriada.
Alterado na versão 3.6: Adicionado suporte para positional-only parameters.
int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char
*keywords[], va_list vargs)
Part of the Stable ABI. Idêntico a PyArg_ParseTupleAndKeywords(), exceto que aceita uma va_list
ao invés de um número variável de argumentos.
int PyArg_ValidateKeywordArguments(PyObject*)
Part of the Stable ABI. 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
checagem.
Novo na versão 3.2.
int PyArg_Parse(PyObject *args, const char *format, ...)
Part of the Stable ABI. Função usada para desconstruir as listas de argumento de funções “old-style” — estas
são funções que usam o método de análise de parâmetro METH_OLDARGS, que foi removido no Python
3. Isso não é recomendado para uso de análise de parâmetro em código novo, e a maior parte do código
no interpretador padrão foi modificada para não usar mais isso para esse propósito. Ela continua um modo
conveniente de decompor outras tuplas, contudo, e pode continuar a ser usada para esse propósito.
int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
Part of the Stable ABI. Uma forma mais simples de recuperação de parâmetro que não usa uma string de for-
mato 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âme-
tros 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);
(continua na próxima página)

74 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

(continuação da página anterior)


}
return result;
}

A chamada à PyArg_UnpackTuple() neste exemplo é inteiramente equivalente à chamada para


PyArg_ParseTuple():

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

6.6.2 Construindo valores

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


Return value: New reference. Part of the Stable ABI. Cria um novo valor baseado em uma string de formataçã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 for-
mataçã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 re-
ferenciados 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 compri-
mento é 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#.

6.6. Análise de argumentos e construção de valores 75


The Python/C API, Release 3.10.6

i (int) [int] Converte um simples int do C em um objeto inteiro do Python.


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 (exceto por sua contagem de referências, que é
incrementada por um). Se o objeto passado é um ponteiro NULL, assume-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 incrementa a contagem de referências do objeto.
Ú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.
[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, respec-
tivamente.
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)
Return value: New reference. Part of the Stable ABI. Idêntico a Py_BuildValue(), exceto que aceita uma
va_list ao invés de um número variável de argumentos.

76 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

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, ...)
Part of the Stable ABI. 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)
Part of the Stable ABI. Saída não superior a size bytes para str de acordo com o formato string 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 bibli-
oteca Standard 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.
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.
double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)
Part of the Stable ABI. 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 defina *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 retorne -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; levantar essa exceção e retornar
-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.
Novo na versão 3.1.
char *PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)
Part of the Stable ABI. Converte um double val 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, al-
ternados por operador lógico OU:

6.7. Conversão e formação de strings 77


The Python/C API, Release 3.10.6

• 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 es-
pecificador '#' 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().
Novo 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 o caso.
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 o caso.

6.8 Reflexão

PyObject *PyEval_GetBuiltins(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna um dicionário dos componentes internos
no quadro de execução atual ou o interpretador do estado do encadeamento, se nenhum quadro estiver em
execução no momento.
PyObject *PyEval_GetLocals(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna um dicionário das variáveis locais no quadro
de execução atual ou NULL se nenhum quadro estiver sendo executado no momento.
PyObject *PyEval_GetGlobals(void)
Return value: Borrowed reference. Part of the Stable ABI. 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)
Return value: Borrowed reference. Part of the Stable ABI. Retorna o quadro do estado atual da thread, que é
NULL se nenhum quadro estiver em execução no momento.
Veja também PyThreadState_GetFrame().
PyFrameObject *PyFrame_GetBack(PyFrameObject *frame)
Obtém o frame próximo ao quadro externo.
Retorna uma referência forte ou NULL se frame não tiver quadro externo.
frame não deve ser NULL.
Novo na versão 3.9.
PyCodeObject *PyFrame_GetCode(PyFrameObject *frame)
Part of the Stable ABI since version 3.10. Obtém o código de frame.
Retorna uma referência forte.
frame não deve ser NULL. O resultado (código do quadro) não pode ser NULL.
Novo na versão 3.9.
int PyFrame_GetLineNumber(PyFrameObject *frame)
Part of the Stable ABI since version 3.10. Retorna o número da linha do frame atualmente em execução.

78 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6

frame não deve ser NULL.


const char *PyEval_GetFuncName(PyObject *func)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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, “construtor”, “instância” e “objeto”. Concatenado com
o resultado de PyEval_GetFuncName(), o resultado será uma descrição de func.

6.9 Registro de codec e funções de suporte

int PyCodec_Register(PyObject *search_function)


Part of the Stable ABI. 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)
Part of the Stable ABI since version 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.
Novo na versão 3.10.
int PyCodec_KnownEncoding(const char *encoding)
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyCodec_Decode(PyObject *object, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. 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 en-
coding, 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.9.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)
Return value: New reference. Part of the Stable ABI. Obtém uma função de codificação para o encoding dado.
PyObject *PyCodec_Decoder(const char *encoding)
Return value: New reference. Part of the Stable ABI. Obtém uma função de decodificação para o encoding
dado.
PyObject *PyCodec_IncrementalEncoder(const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtém um objeto IncrementalEncoder para o
encoding dado.

6.9. Registro de codec e funções de suporte 79


The Python/C API, Release 3.10.6

PyObject *PyCodec_IncrementalDecoder(const char *encoding, const char *errors)


Return value: New reference. Part of the Stable ABI. Obtém um objeto IncrementalDecoder para o
encoding dado.
PyObject *PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtém uma função de fábrica StreamReader para o
encoding dado.
PyObject *PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtém uma função de fábrica StreamWriter para o
encoding dado.

6.9.2 API de registro de tratamentos de erros de decodificação Unicode

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


Part of the Stable ABI. 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
problemática de caracteres ou bytes e seu deslocamento na string original (consulte Objetos de exceção Uni-
code para funções que extraem essa informação). A função de retorno de chamada deve levantar a exceção
dada, ou retornar 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)
Return value: New reference. Part of the Stable ABI. 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)
Return value: Always NULL. Part of the Stable ABI. Levanta exc como uma exceção.
PyObject *PyCodec_IgnoreErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Ignora o erro de unicode, ignorando a entrada que causou
o erro.
PyObject *PyCodec_ReplaceErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Substitui o erro de unicode por ? ou U+FFFD.
PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Substitui o erro de unicode por caracteres da referência
XML.
PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI. Substitui o erro de unicode com escapes de barra invertida
(\x, \u e \U).
PyObject *PyCodec_NameReplaceErrors(PyObject *exc)
Return value: New reference. Part of the Stable ABI since version 3.7. Substitui os erros de codificação unicode
com escapes \N{...}.
Novo na versão 3.5.

80 Capítulo 6. Utilitários
CAPÍTULO 7

Camada de Objetos Abstratos

As funções neste capítulo interagem com os objetos do Python independentemente do tipo deles ou com classes
amplas dos tipos de objetos (por exemplo, todos os tipos numéricos ou todos os tipos de sequência). Quando usado
nos tipos de objetos pros quais eles não se aplicam eles criarão uma exceção no Python.
Não é possível usar estas funções em objetos que não estão apropriadamente inicializados, tal como uma objeto de
lista que foi criado por PyList_New(), mas cujos itens não foram definidos como algum valor não NULL ainda.

7.1 Protocolo de objeto

PyObject *Py_NotImplemented
O singleton NotImplemented, usado para sinalizar que uma operação não foi implementada para a com-
binação de tipo fornecida.
Py_RETURN_NOTIMPLEMENTED
Trata corretamente o retorno de Py_NotImplemented de dentro de uma função C (ou seja, incrementa a
contagem de referências de NotImplemented e retorna-a).
int PyObject_Print(PyObject *o, FILE *fp, int flags)
Print an object o, on file fp. Returns -1 on error. The flags argument is used to enable certain printing options.
The only option currently supported is Py_PRINT_RAW; if given, the str() of the object is written instead
of the repr().
int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
Part of the Stable ABI. Returns 1 if o has the attribute attr_name, and 0 otherwise. This is equivalent to the
Python expression hasattr(o, attr_name). This function always succeeds.
Note that exceptions which occur while calling __getattr__() and __getattribute__() methods
will get suppressed. To get error reporting use PyObject_GetAttr() instead.
int PyObject_HasAttrString(PyObject *o, const char *attr_name)
Part of the Stable ABI. Returns 1 if o has the attribute attr_name, and 0 otherwise. This is equivalent to the
Python expression hasattr(o, attr_name). This function always succeeds.
Note that exceptions which occur while calling __getattr__() and __getattribute__()
methods and creating a temporary string object will get suppressed. To get error reporting use
PyObject_GetAttrString() instead.
PyObject *PyObject_GetAttr(PyObject *o, PyObject *attr_name)
Return value: New reference. Part of the Stable ABI. Retrieve an attribute named attr_name from object o.

81
The Python/C API, Release 3.10.6

Returns the attribute value on success, or NULL on failure. This is the equivalent of the Python expression
o.attr_name.
PyObject *PyObject_GetAttrString(PyObject *o, const char *attr_name)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyObject_GenericGetAttr(PyObject *o, PyObject *name)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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, but this feature is deprecated in favour of using
PyObject_DelAttrString().
int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)
Part of the Stable ABI. 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)
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)
Delete attribute named attr_name, for object o. Returns -1 on failure. This is the equivalent of the Python
statement del o.attr_name.
PyObject *PyObject_GenericGetDict(PyObject *o, void *context)
Return value: New reference. Part of the Stable ABI since version 3.10. A generic implementation for the getter
of a __dict__ descriptor. It creates the dictionary if necessary.
Novo na versão 3.3.
int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
Part of the Stable ABI since version 3.7. A generic implementation for the setter of a __dict__ descriptor.
This implementation does not allow the dictionary to be deleted.
Novo na versão 3.3.
PyObject *PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)
Return value: New reference. Part of the Stable ABI. Compare the values of o1 and o2 using the operation
specified by opid, which must be one of Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, or Py_GE, corresponding
to <, <=, ==, !=, >, or >= respectively. This is the equivalent of the Python expression o1 op o2, where
op is the operator corresponding to opid. Returns the value of the comparison on success, or NULL on failure.
int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)
Part of the Stable ABI. Compare the values of o1 and o2 using the operation specified by opid, which must

82 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

be one of Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, or Py_GE, corresponding to <, <=, ==, !=, >, or >=
respectively. Returns -1 on error, 0 if the result is false, 1 otherwise. This is the equivalent of the Python
expression o1 op o2, where op is the operator corresponding to opid.

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_Repr(PyObject *o)


Return value: New reference. Part of the Stable ABI. 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: This function now includes a debug assertion to help ensure that it does not silently
discard an active exception.
PyObject *PyObject_ASCII(PyObject *o)
Return value: New reference. Part of the Stable ABI. As PyObject_Repr(), compute a string represen-
tation 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)
Return value: New reference. Part of the Stable ABI. 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.
Alterado na versão 3.4: This function now includes a debug assertion to help ensure that it does not silently
discard an active exception.
PyObject *PyObject_Bytes(PyObject *o)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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).

7.1. Protocolo de objeto 83


The Python/C API, Release 3.10.6

Py_hash_t PyObject_Hash(PyObject *o)


Part of the Stable ABI. 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)
Part of the Stable ABI. Set a TypeError indicating that type(o) is not hashable and return -1. This
function receives special treatment when stored in a tp_hash slot, allowing a type to explicitly indicate to the
interpreter that it is not hashable.
int PyObject_IsTrue(PyObject *o)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. When o is non-NULL, returns a type object corresponding
to the object type of object o. On failure, raises SystemError and returns NULL. This is equivalent to
the Python expression type(o). This function increments the reference count of 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 the incremented reference count is needed.
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)
Part of the Stable ABI. 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).
Novo na versão 3.4.
PyObject *PyObject_GetItem(PyObject *o, PyObject *key)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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].
PyObject *PyObject_Dir(PyObject *o)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. This is equivalent to the Python expression iter(o).

84 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

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_GetAIter(PyObject *o)
Return value: New reference. Part of the Stable ABI since version 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.
Novo na versão 3.10.

7.2 Protocolo de chamada

O CPython permite dois protocolos de chamada: tp_call e vectorcall.

7.2.1 O protocolo tp_call

Instances of classes that set tp_call are callable. The signature of the slot is:

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

A call is made using a tuple for the positional arguments and a dict for the keyword arguments, similarly to
callable(*args, **kwargs) in Python code. args must be non-NULL (use an empty tuple if there are
no arguments) but kwargs may be NULL if there are no keyword arguments.
This convention is not only used by tp_call: tp_new and tp_init also pass arguments this way.
To call an object, use PyObject_Call() or another call API.

7.2.2 O protocolo vectorcall

Novo na versão 3.9.


The vectorcall protocol was introduced in PEP 590 as an additional protocol for making calls more efficient.
As rule of thumb, CPython will prefer the vectorcall for internal calls if the callable supports it. However, this is not
a hard rule. Additionally, some third-party extensions use tp_call directly (rather than using PyObject_Call()).
Therefore, a class supporting vectorcall must also implement tp_call. Moreover, the callable must behave the
same regardless of which protocol is used. The recommended way to achieve this is by setting tp_call to
PyVectorcall_Call(). This bears repeating:

Aviso: A class supporting vectorcall must also implement tp_call with the same semantics.

A class should not implement vectorcall if that would be slower than tp_call. For example, if the callee needs to
convert the arguments to an args tuple and kwargs dict anyway, then there is no point in implementing vectorcall.
Classes can implement the vectorcall protocol by enabling the Py_TPFLAGS_HAVE_VECTORCALL flag and setting
tp_vectorcall_offset to the offset inside the object structure where a vectorcallfunc appears. This is a pointer
to a function with the following signature:
typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf,
PyObject *kwnames)
• callable is the object being called.
• args is a C array consisting of the positional arguments followed by the values of the keyword argu-
ments. This can be NULL if there are no arguments.

7.2. Protocolo de chamada 85


The Python/C API, Release 3.10.6

• nargsf is the number of positional arguments plus possibly the PY_VECTORCALL_ARGUMENTS_OFFSET


flag. To get the actual number of positional arguments from nargsf, use PyVectorcall_NARGS().
• kwnames is a tuple containing the names of the keyword arguments; in other words, the keys of the
kwargs dict. These names must be strings (instances of str or a subclass) and they must be unique.
If there are no keyword arguments, then kwnames can instead be NULL.
PY_VECTORCALL_ARGUMENTS_OFFSET
If this flag is set in a vectorcall nargsf argument, the callee is allowed to temporarily change args[-1]. In
other words, args points to argument 1 (not 0) in the allocated vector. The callee must restore the value of
args[-1] before returning.
For PyObject_VectorcallMethod(), this flag means instead that args[0] may be changed.
Whenever they can do so cheaply (without additional allocation), callers are encouraged to use
PY_VECTORCALL_ARGUMENTS_OFFSET. Doing so will allow callables such as bound methods to make
their onward calls (which include a prepended self argument) very efficiently.
To call an object that implements vectorcall, use a call API function as with any other callable.
PyObject_Vectorcall() will usually be most efficient.

Nota: No CPython 3.8, a API vectorcall e funções relacionadas estavam disponíveis provisoriamente sob
nomes com um sublinhado inicial: _PyObject_Vectorcall, _Py_TPFLAGS_HAVE_VECTORCALL,
_PyObject_VectorcallMethod, _PyVectorcall_Function, _PyObject_CallOneArg,
_PyObject_CallMethodNoArgs, _PyObject_CallMethodOneArg. Além disso,
PyObject_VectorcallDict estava disponível como _PyObject_FastCallDict. Os nomes anti-
gos ainda estão definidos como apelidos para os novos nomes sem o sublinhado.

Controle de recursão

When using tp_call, callees do not need to worry about recursion: CPython uses Py_EnterRecursiveCall()
and Py_LeaveRecursiveCall() for calls made using tp_call.
For efficiency, this is not the case for calls done using vectorcall: the callee should use Py_EnterRecursiveCall and
Py_LeaveRecursiveCall if needed.

Vectorcall Support API

Py_ssize_t PyVectorcall_NARGS(size_t nargsf)


Given a vectorcall nargsf argument, return the actual number of arguments. Currently equivalent to:

(Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)

However, the function PyVectorcall_NARGS should be used to allow for future extensions.
Novo na versão 3.8.
vectorcallfunc PyVectorcall_Function(PyObject *op)
If op does not support the vectorcall protocol (either because the type does not or because the specific instance
does not), return NULL. Otherwise, return the vectorcall function pointer stored in op. This function never
raises an exception.
This is mostly useful to check whether or not op supports vectorcall, which can be done by checking
PyVectorcall_Function(op) != NULL.
Novo na versão 3.8.
PyObject *PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict)
Call callable’s vectorcallfunc with positional and keyword arguments given in a tuple and dict, respec-
tively.

86 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

This is a specialized function, intended to be put in the tp_call slot or be used in an implementation of
tp_call. It does not check the Py_TPFLAGS_HAVE_VECTORCALL flag and it does not fall back to
tp_call.
Novo na versão 3.8.

7.2.3 Object Calling API

Various functions are available for calling a Python object. Each converts its arguments to a convention supported by
the called object – either tp_call or vectorcall. In order to do as little conversion as possible, pick one that best fits the
format of data you have available.
The following table summarizes the available functions; please see individual documentation for details.

Função callable args kwargs


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

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


Return value: New reference. Part of the Stable ABI. Call a callable Python object callable, with arguments
given by the tuple args, and named arguments given by the dictionary kwargs.
args must not be NULL; use an empty tuple if no arguments are needed. If no named arguments are needed,
kwargs can be NULL.
Return the result of the call on success, or raise an exception and return NULL on failure.
This is the equivalent of the Python expression: callable(*args, **kwargs).
PyObject *PyObject_CallNoArgs(PyObject *callable)
Part of the Stable ABI since version 3.10. Call a callable Python object callable without any arguments. It is
the most efficient way to call a callable Python object without any argument.
Return the result of the call on success, or raise an exception and return NULL on failure.
Novo na versão 3.9.
PyObject *PyObject_CallOneArg(PyObject *callable, PyObject *arg)
Call a callable Python object callable with exactly 1 positional argument arg and no keyword arguments.
Return the result of the call on success, or raise an exception and return NULL on failure.
Novo na versão 3.9.
PyObject *PyObject_CallObject(PyObject *callable, PyObject *args)
Return value: New reference. Part of the Stable ABI. Call a callable Python object callable, with arguments
given by the tuple args. If no arguments are needed, then args can be NULL.
Return the result of the call on success, or raise an exception and return NULL on failure.
This is the equivalent of the Python expression: callable(*args).

7.2. Protocolo de chamada 87


The Python/C API, Release 3.10.6

PyObject *PyObject_CallFunction(PyObject *callable, const char *format, ...)


Return value: New reference. Part of the Stable ABI. Call a callable Python object callable, with a variable
number of C arguments. The C arguments are described using a Py_BuildValue() style format string.
The format can be NULL, indicating that no arguments are provided.
Return the result of the call on success, or raise an exception and return NULL on failure.
This is the equivalent of the Python expression: callable(*args).
Note that if you only pass PyObject* args, PyObject_CallFunctionObjArgs() is a faster alternative.
Alterado na versão 3.4: The type of format was changed from char *.
PyObject *PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
Return value: New reference. Part of the Stable ABI. Call the method named name of object obj with a variable
number of C arguments. The C arguments are described by a Py_BuildValue() format string that should
produce a tuple.
The format can be NULL, indicating that no arguments are provided.
Return the result of the call on success, or raise an exception and return NULL on failure.
This is the equivalent of the Python expression: obj.name(arg1, arg2, ...).
Note that if you only pass PyObject* args, PyObject_CallMethodObjArgs() is a faster alternative.
Alterado na versão 3.4: The types of name and format were changed from char *.
PyObject *PyObject_CallFunctionObjArgs(PyObject *callable, ...)
Return value: New reference. Part of the Stable ABI. Call a callable Python object callable, with a variable
number of PyObject* arguments. The arguments are provided as a variable number of parameters followed by
NULL.
Return the result of the call on success, or raise an exception and return NULL on failure.
This is the equivalent of the Python expression: callable(arg1, arg2, ...).
PyObject *PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ...)
Return value: New reference. Part of the Stable ABI. Call a method of the Python object obj, where the name
of the method is given as a Python string object in name. It is called with a variable number of PyObject*
arguments. The arguments are provided as a variable number of parameters followed by NULL.
Return the result of the call on success, or raise an exception and return NULL on failure.
PyObject *PyObject_CallMethodNoArgs(PyObject *obj, PyObject *name)
Call a method of the Python object obj without arguments, where the name of the method is given as a Python
string object in name.
Return the result of the call on success, or raise an exception and return NULL on failure.
Novo na versão 3.9.
PyObject *PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObject *arg)
Call a method of the Python object obj with a single positional argument arg, where the name of the method
is given as a Python string object in name.
Return the result of the call on success, or raise an exception and return NULL on failure.
Novo na versão 3.9.
PyObject *PyObject_Vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Call a callable Python object callable. The arguments are the same as for vectorcallfunc. If callable
supports vectorcall, this directly calls the vectorcall function stored in callable.
Return the result of the call on success, or raise an exception and return NULL on failure.
Novo na versão 3.9.

88 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

PyObject *PyObject_VectorcallDict(PyObject *callable, PyObject *const *args, size_t nargsf,


PyObject *kwdict)
Call callable with positional arguments passed exactly as in the vectorcall protocol, but with keyword arguments
passed as a dictionary kwdict. The args array contains only the positional arguments.
Regardless of which protocol is used internally, a conversion of arguments needs to be done. Therefore, this
function should only be used if the caller already has a dictionary ready to use for the keyword arguments, but
not a tuple for the positional arguments.
Novo na versão 3.9.
PyObject *PyObject_VectorcallMethod(PyObject *name, PyObject *const *args, size_t nargsf,
PyObject *kwnames)
Call a method using the vectorcall calling convention. The name of the method is given as a Python string
name. The object whose method is called is args[0], and the args array starting at args[1] represents the
arguments of the call. There must be at least one positional argument. nargsf is the number of positional
arguments including args[0], plus PY_VECTORCALL_ARGUMENTS_OFFSET if the value of args[0]
may temporarily be changed. Keyword arguments can be passed just like in PyObject_Vectorcall().
If the object has the Py_TPFLAGS_METHOD_DESCRIPTOR feature, this will call the unbound method
object with the full args vector as arguments.
Return the result of the call on success, or raise an exception and return NULL on failure.
Novo na versão 3.9.

7.2.4 Call Support API

int PyCallable_Check(PyObject *o)


Part of the Stable ABI. 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)


Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI since version 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.
Novo na versão 3.5.
PyObject *PyNumber_FloorDivide(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Return the floor of o1 divided by o2, or NULL on failure.
This is the equivalent of the Python expression o1 // o2.

7.3. Protocolo de número 89


The Python/C API, Release 3.10.6

PyObject *PyNumber_TrueDivide(PyObject *o1, PyObject *o2)


Return value: New reference. Part of the Stable ABI. Return a reasonable approximation for the mathematical
value of o1 divided by o2, or NULL on failure. The return value is “approximate” because binary floating point
numbers are approximate; it is not possible to represent all real numbers in base two. This function can return
a floating point value when passed two integers. This is the equivalent of the Python expression o1 / o2.
PyObject *PyNumber_Remainder(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the remainder of dividing o1 by o2, or NULL on
failure. This is the equivalent of the Python expression o1 % o2.
PyObject *PyNumber_Divmod(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. See the built-in function divmod(). Returns NULL on
failure. This is the equivalent of the Python expression divmod(o1, o2).
PyObject *PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3)
Return value: New reference. Part of the Stable ABI. See the built-in function pow(). Returns NULL on
failure. This is the equivalent of the Python expression pow(o1, o2, o3), where o3 is optional. If o3 is
to be ignored, pass Py_None in its place (passing NULL for o3 would cause an illegal memory access).
PyObject *PyNumber_Negative(PyObject *o)
Return value: New reference. Part of the Stable ABI. Returns the negation of o on success, or NULL on failure.
This is the equivalent of the Python expression -o.
PyObject *PyNumber_Positive(PyObject *o)
Return value: New reference. Part of the Stable ABI. Returns o on success, or NULL on failure. This is the
equivalent of the Python expression +o.
PyObject *PyNumber_Absolute(PyObject *o)
Return value: New reference. Part of the Stable ABI. Returns the absolute value of o, or NULL on failure. This
is the equivalent of the Python expression abs(o).
PyObject *PyNumber_Invert(PyObject *o)
Return value: New reference. Part of the Stable ABI. Returns the bitwise negation of o on success, or NULL
on failure. This is the equivalent of the Python expression ~o.
PyObject *PyNumber_Lshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the result of left shifting o1 by o2 on success, or
NULL on failure. This is the equivalent of the Python expression o1 << o2.
PyObject *PyNumber_Rshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the result of right shifting o1 by o2 on success,
or NULL on failure. This is the equivalent of the Python expression o1 >> o2.
PyObject *PyNumber_And(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the “bitwise and” of o1 and o2 on success and
NULL on failure. This is the equivalent of the Python expression o1 & o2.
PyObject *PyNumber_Xor(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the “bitwise exclusive or” of o1 by o2 on success,
or NULL on failure. This is the equivalent of the Python expression o1 ^ o2.
PyObject *PyNumber_Or(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the “bitwise or” of o1 and o2 on success, or
NULL on failure. This is the equivalent of the Python expression o1 | o2.
PyObject *PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the result of adding o1 and o2, or NULL on
failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1
+= o2.
PyObject *PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the result of subtracting o2 from o1, or NULL on
failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1
-= o2.

90 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

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


Return value: New reference. Part of the Stable ABI. Returns the result of multiplying o1 and o2, or NULL on
failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1
*= o2.
PyObject *PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI since version 3.7. Returns the result of matrix multiplication
on o1 and o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent
of the Python statement o1 @= o2.
Novo na versão 3.5.
PyObject *PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the mathematical floor of dividing o1 by o2, or
NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python
statement o1 //= o2.
PyObject *PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Return a reasonable approximation for the mathematical
value of o1 divided by o2, or NULL on failure. The return value is “approximate” because binary floating point
numbers are approximate; it is not possible to represent all real numbers in base two. This function can return
a floating point value when passed two integers. The operation is done in-place when o1 supports it. This is
the equivalent of the Python statement o1 /= o2.
PyObject *PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the remainder of dividing o1 by o2, or NULL on
failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1
%= o2.
PyObject *PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3)
Return value: New reference. Part of the Stable ABI. See the built-in function pow(). Returns NULL on
failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement
o1 **= o2 when o3 is Py_None, or an in-place variant of pow(o1, o2, o3) otherwise. If o3 is to be
ignored, pass Py_None in its place (passing NULL for o3 would cause an illegal memory access).
PyObject *PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the result of left shifting o1 by o2 on success,
or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python
statement o1 <<= o2.
PyObject *PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the result of right shifting o1 by o2 on success,
or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python
statement o1 >>= o2.
PyObject *PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the “bitwise and” of o1 and o2 on success and
NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python
statement o1 &= o2.
PyObject *PyNumber_InPlaceXor(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the “bitwise exclusive or” of o1 by o2 on success,
or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python
statement o1 ^= o2.
PyObject *PyNumber_InPlaceOr(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the “bitwise or” of o1 and o2 on success, or NULL
on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement
o1 |= o2.
PyObject *PyNumber_Long(PyObject *o)
Return value: New reference. Part of the Stable ABI. Returns the o converted to an integer object on success,
or NULL on failure. This is the equivalent of the Python expression int(o).

7.3. Protocolo de número 91


The Python/C API, Release 3.10.6

PyObject *PyNumber_Float(PyObject *o)


Return value: New reference. Part of the Stable ABI. Returns the o converted to a float object on success, or
NULL on failure. This is the equivalent of the Python expression float(o).
PyObject *PyNumber_Index(PyObject *o)
Return value: New reference. Part of the Stable ABI. Returns the o converted to a Python int on success or
NULL with a TypeError exception raised on failure.
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.
PyObject *PyNumber_ToBase(PyObject *n, int base)
Return value: New reference. Part of the Stable ABI. Returns the integer n converted to base base as a string.
The base argument must be one of 2, 8, 10, or 16. For base 2, 8, or 16, the returned string is prefixed
with a base marker of '0b', '0o', or '0x', respectively. If n is not a Python int, it is converted with
PyNumber_Index() first.
Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc)
Part of the Stable ABI. Returns o converted to a Py_ssize_t value if o can be interpreted as an integer. If
the call fails, an exception is raised and -1 is returned.
If o can be converted to a Python int but the attempt to convert to a Py_ssize_t value would raise an
OverflowError, then the exc argument is the type of exception that will be raised (usually IndexError
or OverflowError). If exc is NULL, then the exception is cleared and the value is clipped to
PY_SSIZE_T_MIN for a negative integer or PY_SSIZE_T_MAX for a positive integer.
int PyIndex_Check(PyObject *o)
Part of the Stable ABI since version 3.8. Returns 1 if o is an index integer (has the nb_index slot of the
tp_as_number structure filled in), and 0 otherwise. This function always succeeds.

7.4 Protocolo de sequência

int PySequence_Check(PyObject *o)


Part of the Stable ABI. Return 1 if the object provides the sequence protocol, and 0 otherwise. Note that
it returns 1 for Python classes with a __getitem__() method, unless they are dict subclasses, since in
general it is impossible to determine what type of keys the class supports. This function always succeeds.
Py_ssize_t PySequence_Size(PyObject *o)
Py_ssize_t PySequence_Length(PyObject *o)
Part of the Stable ABI. Retorna o número de objetos em sequência o em caso de sucesso e -1 em caso de
falha. Isso é equivalente à expressão Python len(o).
PyObject *PySequence_Concat(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna a concatenação de o1 e o2 em caso de sucesso,
e NULL em caso de falha. Este é o equivalente da expressão Python o1 + o2.
PyObject *PySequence_Repeat(PyObject *o, Py_ssize_t count)
Return value: New reference. Part of the Stable ABI. Retorna o resultado da repetição do objeto sequência o
count vezes ou NULL em caso de falha. Este é o equivalente da expressão Python o * count.
PyObject *PySequence_InPlaceConcat(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna a concatenação de o1 e o2 em caso de sucesso,
e NULL em caso de falha. A operação é feita no local quando o1 suportar. Este é o equivalente da expressão
Python o1 += o2.
PyObject *PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Return value: New reference. Part of the Stable ABI. Retorna o resultado da repetição do objeto sequência o
count vezes ou NULL em caso de falha. A operação é feita localmente quando o suportar. Este é o equivalente
da expressão Python o *= count.

92 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

PyObject *PySequence_GetItem(PyObject *o, Py_ssize_t i)


Return value: New reference. Part of the Stable ABI. Retorna o elemento i de o ou NULL em caso de falha.
Este é o equivalente da expressão Python o[i].
PyObject *PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
Return value: New reference. Part of the Stable ABI. Retorna a fatia do objeto sequência o entre i1 e i2, ou
NULL em caso de falha. Este é o equivalente da expressão Python o[i1:i2].
int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v)
Part of the Stable ABI. 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. Isso é equivalente à instrução Python o[i]=v. Esta função não rouba
uma referência a v.
If v is NULL, the element is deleted, but this feature is deprecated in favour of using
PySequence_DelItem().
int PySequence_DelItem(PyObject *o, Py_ssize_t i)
Part of the Stable ABI. Exclui o elemento i do objeto o. Retorna -1 em caso de falha. Isso é equivalente à
instrução Python del o[i].
int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v)
Part of the Stable ABI. Atribui o objeto sequência v à fatia no objeto sequência o de i1 a i2. Isso é equivalente
à instrução Python o[i1:i2] = v.
int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)
Part of the Stable ABI. Exclui a fatia no objeto sequência o de i1 a i2. Retorna -1 em caso de falha. Isso é
equivalente à instrução Python del o[i1:i2].
Py_ssize_t PySequence_Count(PyObject *o, PyObject *value)
Part of the Stable ABI. Return the number of occurrences of value in o, that is, return the number of keys
for which o[key] == value. On failure, return -1. This is equivalent to the Python expression o.
count(value).
int PySequence_Contains(PyObject *o, PyObject *value)
Part of the Stable ABI. Determine if o contains value. If an item in o is equal to value, return 1, otherwise
return 0. On error, return -1. This is equivalent to the Python expression value in o.
Py_ssize_t PySequence_Index(PyObject *o, PyObject *value)
Part of the Stable ABI. Return the first index i for which o[i] == value. On error, return -1. This is
equivalent to the Python expression o.index(value).
PyObject *PySequence_List(PyObject *o)
Return value: New reference. Part of the Stable ABI. Return a list object with the same contents as the sequence
or iterable o, or NULL on failure. The returned list is guaranteed to be new. This is equivalent to the Python
expression list(o).
PyObject *PySequence_Tuple(PyObject *o)
Return value: New reference. Part of the Stable ABI. Return a tuple object with the same contents as the
sequence or iterable o, or NULL on failure. If o is a tuple, a new reference will be returned, otherwise a tuple
will be constructed with the appropriate contents. This is equivalent to the Python expression tuple(o).
PyObject *PySequence_Fast(PyObject *o, const char *m)
Return value: New reference. Part of the Stable ABI. Return the sequence or iterable o as an object usable
by the other PySequence_Fast* family of functions. If the object is not a sequence or iterable, raises
TypeError with m as the message text. Returns NULL on failure.
The PySequence_Fast* functions are thus named because they assume o is a PyTupleObject or a
PyListObject and access the data fields of o directly.
As a CPython implementation detail, if o is already a sequence or list, it will be returned.
Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o)
Returns the length of o, assuming that o was returned by PySequence_Fast() and that
o is not NULL. The size can also be retrieved by calling PySequence_Size() on o, but
PySequence_Fast_GET_SIZE() is faster because it can assume o is a list or tuple.

7.4. Protocolo de sequência 93


The Python/C API, Release 3.10.6

PyObject *PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i)


Return value: Borrowed reference. Return the ith element of o, assuming that o was returned by
PySequence_Fast(), o is not NULL, and that i is within bounds.
PyObject **PySequence_Fast_ITEMS(PyObject *o)
Return the underlying array of PyObject pointers. Assumes that o was returned by PySequence_Fast()
and o is not NULL.
Note, if a list gets resized, the reallocation may relocate the items array. So, only use the underlying array
pointer in contexts where the sequence cannot change.
PyObject *PySequence_ITEM(PyObject *o, Py_ssize_t i)
Return value: New reference. Return the ith element of o or NULL on failure. Faster form of
PySequence_GetItem() but without checking that PySequence_Check() on o is true and without
adjustment for negative indices.

7.5 Protocolo de mapeamento

Veja também PyObject_GetItem(), PyObject_SetItem() e PyObject_DelItem().


int PyMapping_Check(PyObject *o)
Part of the Stable ABI. Return 1 if the object provides the mapping protocol or supports slicing, and 0
otherwise. Note that it returns 1 for Python classes with a __getitem__() method, since in general it
is impossible to determine what type of keys the class supports. This function always succeeds.
Py_ssize_t PyMapping_Size(PyObject *o)
Py_ssize_t PyMapping_Length(PyObject *o)
Part of the Stable ABI. Retorna 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)
Return value: New reference. Part of the Stable ABI. Retorna o elemento de o correspondente à string
key ou NULL em caso de falha. Este é o equivalente da expressão Python o[key]. Veja também
PyObject_GetItem().
int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *v)
Part of the Stable ABI. Mapeia a string key para o valor v no objeto o. Retorna -1 em caso de falha. Este é o
equivalente da instrução Python o[key] = v. Veja também PyObject_SetItem(). Esta função não
rouba uma referência a v.
int PyMapping_DelItem(PyObject *o, PyObject *key)
Remove o mapeamento para o objeto key do objeto o. Retorna -1 em caso de falha. Isso é equivalente à
instrução Python del o[key]. Este é um alias de PyObject_DelItem().
int PyMapping_DelItemString(PyObject *o, const char *key)
Remove o mapeamento para a string key do objeto o. Retorna -1 em caso de falha. Isso é equivalente à
instrução Python del o[key].
int PyMapping_HasKey(PyObject *o, PyObject *key)
Part of the Stable ABI. 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.
Observe que as exceções que ocorrem ao chamar o método __getitem__() serão suprimidas. Para obter
relatórios de erros, use PyObject_GetItem().
int PyMapping_HasKeyString(PyObject *o, const char *key)
Part of the Stable ABI. 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.
Observe que as exceções que ocorrem ao chamar o método __getitem__() e criar um objeto string tem-
porário serão suprimidas. Para obter relatórios de erros, use PyMapping_GetItemString().

94 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

PyObject *PyMapping_Keys(PyObject *o)


Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI since version 3.8. Return non-zero if the object o can be safely passed to
PyIter_Next(), and 0 otherwise. This function always succeeds.
int PyAIter_Check(PyObject *o)
Part of the Stable ABI since version 3.10. Return non-zero if the object o provides the AsyncIterator
protocol, and 0 otherwise. This function always succeeds.
Novo na versão 3.10.
PyObject *PyIter_Next(PyObject *o)
Return value: New reference. Part of the Stable ABI. Return the next value from the iterator o. The object must
be an iterator according to PyIter_Check() (it is up to the caller to check this). If there are no remaining
values, returns NULL with no exception set. If an error occurs while retrieving the item, returns NULL and
passes along the exception.
Para escrever um loop que itere sobre um iterador, o código C deve ser algo como isto

PyObject *iterator = PyObject_GetIter(obj);


PyObject *item;

if (iterator == NULL) {
/* propagate error */
}

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


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

Py_DECREF(iterator);

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

7.6. Protocolo Iterador 95


The Python/C API, Release 3.10.6

type PySendResult
The enum value used to represent different results of PyIter_Send().
Novo na versão 3.10.
PySendResult PyIter_Send(PyObject *iter, PyObject *arg, PyObject **presult)
Part of the Stable ABI since version 3.10. Sends the arg value into the iterator iter. Returns:
• PYGEN_RETURN if iterator returns. Return value is returned via presult.
• PYGEN_NEXT if iterator yields. Yielded value is returned via presult.
• PYGEN_ERROR if iterator has raised and exception. presult is set to NULL.
Novo na versão 3.10.

7.7 Protocolo de Buffer

Certos objetos disponíveis em 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 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;
• 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).
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 consumidor da interface de buffer é o método write() de objetos arquivo: qualquer objeto que pode
exportar uma série de bytes através da interface de buffer pode ser gravado em um arquivo. Enquanto write() só
precisa de acesso somente leitura aos conteúdos internos do objeto passado, outros métodos, tais como readinto()
precisam de acesso de gravação ao conteúdo de seu argumento. A interface de buffer permite aos objetos permitir
ou rejeitar seletivamente a exportação de buffers de leitura e escrita e de somente leitura.
Existem duas maneiras para um usuário da interface de buffer adquirir um buffer em um objeto alvo:
• chamada PyObject_GetBuffer() com os parâmetros certos;
• chamada PyArg_ParseTuple() (ou um dos seus irmãos) com um dos y*, w* ou s* format codes.
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.

96 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

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

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.
void *obj
Uma nova referência ao objeto exportador. A referência é possuída pelo consumidor e automaticamente
decrementada e definida para NULL por PyBuffer_Release(). O campo é o equivalente ao valor
de retorno de qualquer função 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 me-
mó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.
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 assumir itemsize == 1.
const char *format
Uma string terminada por NUL no estilo de sintaxe de módulo struct descrevendo os conteúdos de
um único item. Se isso é NULL, "B" (unsigned bytes) é assumido.
Este campo é controlado pelo sinalizador PyBUF_FORMAT.

7.7. Protocolo de Buffer 97


The Python/C API, Release 3.10.6

int ndim
O número de dimensões que a memória representa como um vetor n-dimensional. Se é 0, buf aponta
para um único item representando um escalar. Neste caso, shape, strides e suboffsets DEVEM
ser NULL.
A macro PyBUF_MAX_NDIM limita o número máximo de dimensões a 64. Os exportadores DEVEM
respeitar esse limite, os consumidores de buffers multidimensionais DEVEM ser capazes de lidar com
dimensões PyBUF_MAX_NDIM.
Py_ssize_t *shape
Uma matriz de Py_ssize_t do comprimento ndim indicando a forma da memória como uma ma-
triz 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
especial. 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 ar-
mazenados 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.
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.

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 drasti-
camente, o consumidor usa o argumento flags para especificar o tipo de buffer exato que pode manipular.
Todos Py_buffer são inequivocamente definidos pelo tipo de solicitação.

98 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

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 reportar falha. Caso contrário, o exportador pode fornecer um buffer de somente leitura
ou gravável, mas a escolha DEVE ser consistente para todos os consumidores.
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
solicitar um buffer simples gravável.
PyBUF_FORMAT pode ser |’d para qualquer um dos sinalizadores, exceto PyBUF_SIMPLE. O último já implica o
formato B (bytes não assinados).

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.

Solicitação Forma Avanços suboffsets


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

7.7. Protocolo de Buffer 99


The Python/C API, Release 3.10.6

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.

Solicitação Forma Avanços suboffsets contig readonly formato


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


"""Verify that the parameters represent a valid array within
the bounds of the allocated memory:
char *mem: start of the physical memory block
memlen: length of the physical memory block
offset: (char *)buf - mem
"""
if offset % itemsize:
return False
(continua na próxima página)

100 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

(continuação da página anterior)


if offset < 0 or offset+itemsize > memlen:
return False
if any(v % itemsize for v in strides):
return False

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

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


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

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

Estilo-PIL: forma, 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
representaçã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.
Here is a function that returns a pointer to the element in an N-D array pointed to by an N-dimensional index when
there are both non-NULL strides and suboffsets:

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 Buffer-related functions

int PyObject_CheckBuffer(PyObject *obj)


Return 1 if obj supports the buffer interface otherwise 0. When 1 is returned, it doesn’t guarantee that
PyObject_GetBuffer() will succeed. This function always succeeds.
int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags)
Send a request to exporter to fill in view as specified by flags. If the exporter cannot provide a buffer of the
exact type, it MUST raise PyExc_BufferError, set view->obj to NULL and return -1.
On success, fill in view, set view->obj to a new reference to exporter and return 0. In the case of chained
buffer providers that redirect requests to a single object, view->obj MAY refer to this object instead of
exporter (See Buffer Object Structures).
Successful calls to PyObject_GetBuffer() must be paired with calls to PyBuffer_Release(),
similar to malloc() and free(). Thus, after the consumer is done with the buffer,
PyBuffer_Release() must be called exactly once.

7.7. Protocolo de Buffer 101


The Python/C API, Release 3.10.6

void PyBuffer_Release(Py_buffer *view)


Release the buffer view and decrement the reference count for view->obj. This function MUST be called
when the buffer is no longer being used, otherwise reference leaks may occur.
It is an error to call this function on a buffer that was not obtained via PyObject_GetBuffer().
Py_ssize_t PyBuffer_SizeFromFormat(const char *format)
Return the implied itemsize from format. On error, raise an exception and return -1.
Novo na versão 3.9.
int PyBuffer_IsContiguous(Py_buffer *view, char order)
Return 1 if the memory defined by the view is C-style (order is 'C') or Fortran-style (order is 'F') contiguous
or either one (order is 'A'). Return 0 otherwise. This function always succeeds.
void *PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
Get the memory area pointed to by the indices inside the given view. indices must point to an array of
view->ndim indices.
int PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
Copy contiguous len bytes from buf to view. fort can be 'C' or 'F' (for C-style or Fortran-style ordering).
0 is returned on success, -1 on error.
int PyBuffer_ToContiguous(void *buf, Py_buffer *src, Py_ssize_t len, char order)
Copy len bytes from src to its contiguous representation in buf. order can be 'C' or 'F' or 'A' (for C-style
or Fortran-style ordering or either one). 0 is returned on success, -1 on error.
This function fails if len != src->len.
void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int item-
size, char order)
Fill the strides array with byte-strides of a contiguous (C-style if order is 'C' or Fortran-style if order is 'F')
array of the given shape with the given number of bytes per element.
int PyBuffer_FillInfo(Py_buffer *view, PyObject *exporter, void *buf, Py_ssize_t len, int readonly, int
flags)
Handle buffer requests for an exporter that wants to expose buf of size len with writability set according to
readonly. buf is interpreted as a sequence of unsigned bytes.
The flags argument indicates the request type. This function always fills in view as specified by flags, unless
buf has been designated as read-only and PyBUF_WRITABLE is set in flags.
On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise
PyExc_BufferError, set view->obj to NULL and return -1;
If this function is used as part of a getbufferproc, exporter MUST be set to the exporting object and flags must
be passed unmodified. Otherwise, exporter MUST be NULL.

7.8 Protocolo de Buffer Antigo

Obsoleto desde a versão 3.0.


Essas funções faziam parte da API do “protocolo de buffer antigo” no Python 2. No Python 3, esse protocolo não
existe mais, mas as funções ainda estão expostas para facilitar a portabilidade do código 2.x. Eles atuam como um
wrapper de compatibilidade em torno do novo protocolo de buffer, mas não oferecem controle sobre a vida útil dos
recursos adquiridos quando um buffer é exportado.
Portanto, é recomendável que você chame PyObject_GetBuffer() (ou os códigos de formatação y* ou
w* com o família de funções de PyArg_ParseTuple()) para obter uma visão de buffer sobre um objeto e
PyBuffer_Release() quando a visão de buffer puder ser liberada.
int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len)
Part of the Stable ABI. Retorna um ponteiro para um local de memória somente leitura utilizável como entrada
baseada em caracteres. O argumento obj deve ter suporte a interface do buffer de caracteres de segmento

102 Capítulo 7. Camada de Objetos Abstratos


The Python/C API, Release 3.10.6

único. Em caso de sucesso, retorna 0, define buffer com o local da memória e buffer_len com o comprimento
do buffer. Retorna -1 e define a TypeError em caso de erro.
int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
Part of the Stable ABI. Retorna um ponteiro para um local de memória somente leitura que contém dados
arbitrários. O argumento obj deve ter suporte a interface de buffer legível de segmento único. Em caso de
sucesso, retorna 0, define buffer com o local da memória e buffer_len com o comprimento do buffer. Retorna
-1 e define a TypeError em caso de erro.
int PyObject_CheckReadBuffer(PyObject *o)
Part of the Stable ABI. Retorna 1 se o tiver suporte a interface de buffer legível de segmento único. Caso
contrário, retorna 0. Esta função sempre tem sucesso.
Observe que esta função tenta obter e liberar um buffer, e as exceções que ocorrem ao chamar as funções
correspondentes serão suprimidas. Para obter o relatório de erros, use PyObject_GetBuffer() em vez
disso.
int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len)
Part of the Stable ABI. Retorna um ponteiro para um local de memória gravável. O argumento obj deve ter
suporte a interface de buffer de caracteres de segmento único. Em caso de sucesso, retorna 0, define buffer
com o local da memória e buffer_len com o comprimento do buffer. Retorna -1 e define a TypeError em
caso de erro.

7.8. Protocolo de Buffer Antigo 103


The Python/C API, Release 3.10.6

104 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
Part of the Limited API (as an opaque struct). A estrutura C dos objetos usados para descrever tipos embutidos.
PyTypeObject PyType_Type
Part of the Stable ABI. 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()
Part of the Stable ABI. Limpa o cache de pesquisa interno. Retorna a marcação de versão atual.

105
The Python/C API, Release 3.10.6

unsigned long PyType_GetFlags(PyTypeObject *type)


Part of the Stable ABI. Retorna o membro tp_flags de type. Esta função deve ser usada principalmente
com Py_LIMITED_API; os bits sinalizadores individuais têm garantia de estabilidade em todas as versões do
Python, mas o acesso a tp_flags não faz parte da API limitada.
Novo na versão 3.2.
Alterado na versão 3.4: O tipo de retorno é agora um unsigned long em vez de um long.
void PyType_Modified(PyTypeObject *type)
Part of the Stable ABI. 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_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.
int PyType_IS_GC(PyTypeObject *o)
Retorna verdadeiro se o objeto tipo incluir suporte para o detector de ciclo; isso testa o sinalizador de tipo
Py_TPFLAGS_HAVE_GC.
int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
Part of the Stable ABI. Retorna verdadeiro se a for um subtipo de b.
Esta função só verifica pelos subtipos, o que significa que __subclasscheck__() não é chamado em b.
Chame PyObject_IsSubclass() para fazer a mesma verificação que issubclass() faria.
PyObject *PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI. 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.

void *PyType_GetSlot(PyTypeObject *type, int slot)


Part of the Stable ABI since version 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.
Novo 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)
Part of the Stable ABI since version 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.

106 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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.
Novo na versão 3.9.
void *PyType_GetModuleState(PyTypeObject *type)
Part of the Stable ABI since version 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.
Novo na versão 3.9.

Creating Heap-Allocated Types

The following functions and structs are used to create heap types.
PyObject *PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
Return value: New reference. Part of the Stable ABI since version 3.10. Creates and returns a heap type from
the spec (Py_TPFLAGS_HEAPTYPE).
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.
Novo 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.
PyObject *PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Return value: New reference. Part of the Stable ABI since version 3.3. Equivalent to
PyType_FromModuleAndSpec(NULL, spec, bases).
Novo na versão 3.3.
PyObject *PyType_FromSpec(PyType_Spec *spec)
Return value: New reference. Part of the Stable ABI. Equivalent to
PyType_FromSpecWithBases(spec, NULL).
type PyType_Spec
Part of the Stable ABI (including all members). Structure defining a type’s behavior.
const char *PyType_Spec.name
Name of the type, used to set PyTypeObject.tp_name.
int PyType_Spec.basicsize
int PyType_Spec.itemsize
Size of the instance in bytes, used to set PyTypeObject.tp_basicsize and PyTypeObject.
tp_itemsize.
int PyType_Spec.flags
Type flags, used to set PyTypeObject.tp_flags.

8.1. Objetos Fundamentais 107


The Python/C API, Release 3.10.6

If the Py_TPFLAGS_HEAPTYPE flag is not set, PyType_FromSpecWithBases() sets it auto-


matically.
PyType_Slot *PyType_Spec.slots
Array of PyType_Slot structures. Terminated by the special slot value {0, NULL}.
type PyType_Slot
Part of the Stable ABI (including all members). Structure defining optional functionality of a type, containing
a slot ID and a value pointer.
int PyType_Slot.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 fields cannot be set at all using PyType_Spec and PyType_Slot:
• tp_dict
• tp_mro
• tp_cache
• tp_subclasses
• tp_weaklist
• tp_vectorcall
• tp_weaklistoffset (see PyMemberDef)
• tp_dictoffset (see PyMemberDef)
• tp_vectorcall_offset (see PyMemberDef)
The following fields cannot be set using PyType_Spec and PyType_Slot under the limited
API:
• bf_getbuffer
• bf_releasebuffer
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.
void *PyType_Slot.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.

108 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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, denota falta de valor. Este objeto não tem métodos. O mesmo precisa ser tratado
como qualquer outro objeto com relação à contagem de referência.
Py_RETURN_NONE
Manipular devidamente o retorno Py_None de dentro de uma função C (ou seja, incrementar a contagem de
referência de None e devolvê-la.)

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 distin-
guido de um número. Use PyErr_Occurred() para desambiguar.
type PyLongObject
Part of the Limited API (as an opaque struct). Este subtipo de PyObject representa um objeto inteiro Python.
PyTypeObject PyLong_Type
Part of the Stable ABI. 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.
PyObject *PyLong_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Retorna um novo objeto PyLongObject de v ou NULL
em caso de falha.
The current implementation keeps an array of integer objects for all integers between -5 and 256. When you
create an int in that range you actually just get back a reference to the existing object.
PyObject *PyLong_FromUnsignedLong(unsigned long v)
Return value: New reference. Part of the Stable ABI. Retorna um novo objeto PyLongObject de um un-
signed long C ou NULL em caso de falha.
PyObject *PyLong_FromSsize_t(Py_ssize_t v)
Return value: New reference. Part of the Stable ABI. Retorna um novo objeto PyLongObject de um
Py_ssize_t C ou NULL em caso de falha.
PyObject *PyLong_FromSize_t(size_t v)
Return value: New reference. Part of the Stable ABI. Retorna um novo objeto PyLongObject de um
size_t C ou NULL em caso de falha.
PyObject *PyLong_FromLongLong(long long v)
Return value: New reference. Part of the Stable ABI. Retorna um novo objeto PyLongObject de um long
long C ou NULL em caso de falha.

8.2. Objetos Numéricos 109


The Python/C API, Release 3.10.6

PyObject *PyLong_FromUnsignedLongLong(unsigned long long v)


Return value: New reference. Part of the Stable ABI. Retorna um novo objeto PyLongObject de um un-
signed long long C ou NULL em caso de falha.
PyObject *PyLong_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. Retorna um novo PyLongObject com base no valor
da string em str, que é interpretado de acordo com a raiz em base. Se pend não for NULL, *pend apontará
para o primeiro caractere em str que segue a representação do número. 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 iniciais e sublinhados
simples após um especificador de base e entre dígitos são ignorados. Se não houver dígitos, ValueError
será levantada.
PyObject *PyLong_FromUnicodeObject(PyObject *u, int base)
Return value: New reference. Converte uma sequência de dígitos Unicode na string u para um valor inteiro
Python.
Novo na versão 3.3.
PyObject *PyLong_FromVoidPtr(void *p)
Return value: New reference. Part of the Stable ABI. Cria um inteiro Python a partir do ponteiro p. O valor do
ponteiro pode ser recuperado do valor resultante usando PyLong_AsVoidPtr().
long PyLong_AsLong(PyObject *obj)
Part of the Stable ABI. Return a C long representation of obj. If obj is not an instance of PyLongObject,
first call its __index__() method (if present) to convert it to a PyLongObject.
Levanta OverflowError se o valor de obj estiver fora do intervalo de um 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_AsLongAndOverflow(PyObject *obj, int *overflow)
Part of the Stable ABI. Return a C long representation of obj. If obj is not an instance of PyLongObject,
first call its __index__() method (if present) to convert it to a PyLongObject.
Se o valor de obj for maior que LONG_MAX ou menor que LONG_MIN, define *overflow para 1 ou -1,
respectivamente, e retorna -1; caso contrário, define *overflow para 0. Se qualquer outra exceção ocorrer,
define *overflow para 0 e retorne -1 como de costume.
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)
Part of the Stable ABI. Return a C long long representation of obj. If obj is not an instance of PyLongObject,
first call its __index__() method (if present) to convert it to a PyLongObject.
Levanta OverflowError se o valor de obj estiver fora do intervalo de um 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__().
long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)
Part of the Stable ABI. Return a C long long representation of obj. If obj is not an instance of PyLongObject,
first call its __index__() method (if present) to convert it to a PyLongObject.

110 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

Se o valor de obj for maior que LLONG_MAX ou menor que LLONG_MIN, define *overflow para 1 ou -1,
respectivamente, e retorna -1; caso contrário, define *overflow para 0. Se qualquer outra exceção ocorrer,
define *overflow para 0 e retorne -1 como de costume.
Retorna -1 no caso de erro. Use PyErr_Occurred() para desambiguar.
Novo 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. Retorna uma representação de unsigned long C de pylong. pylong deve ser uma instância
de PyLongObject.
Levanta OverflowError se o valor de pylong estiver fora do intervalo de um unsigned long.
Retorna (unsigned long)-1 no caso de erro. Use PyErr_Occurred() para desambiguar.
size_t PyLong_AsSize_t(PyObject *pylong)
Part of the Stable ABI. 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)
Part of the Stable ABI. Retorna uma representação de unsigned long long C de pylong. pylong deve ser uma
instância de PyLongObject.
Levanta OverflowError se o valor de pylong estiver fora do intervalo de um 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)
Part of the Stable ABI. Return a C unsigned long representation of obj. If obj is not an instance of
PyLongObject, first call its __index__() method (if present) to convert it to a PyLongObject.
Se o valor de obj estiver fora do intervalo para um unsigned long, retorna a redução desse módulo de valor
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)
Part of the Stable ABI. Return a C unsigned long long representation of obj. If obj is not an instance of
PyLongObject, first call its __index__() method (if present) to convert it to a PyLongObject.
Se o valor de obj estiver fora do intervalo para um unsigned long long, retorna a redução desse módulo de valor
ULLONG_MAX + 1.
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__().

8.2. Objetos Numéricos 111


The Python/C API, Release 3.10.6

double PyLong_AsDouble(PyObject *pylong)


Part of the Stable ABI. Retorna uma representação de double C de pylong. pylong deve ser uma instância de
PyLongObject.
Levanta OverflowError se o valor de pylong estiver fora do intervalo de um double.
Retorna -1.0 no caso de erro. Use PyErr_Occurred() para desambiguar.
void *PyLong_AsVoidPtr(PyObject *pylong)
Part of the Stable ABI. Converte um inteiro Python pylong em um ponteiro void C. Se pylong não puder ser
convertido, uma OverflowError será levantada. Isso só é garantido para produzir um ponteiro utilizável
void para valores criados com PyLong_FromVoidPtr().
Retorna NULL no caso de erro. Use PyErr_Occurred() para desambiguar.

8.2.2 Objetos Booleanos

Booleano em Python é implementado como uma subclasse de inteiros. Existem apenas dois tipos de booleanos
Py_False e Py_True. Como tal, as funções normais de criação e exclusão não se aplicam a booleanos. No
entanto, as seguintes macros estão disponíveis.
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 possui métodos. Ele precisa ser tratado como qualquer outro objeto
em relação às contagens de referência.
PyObject *Py_True
O objeto Python True. Este objeto não possui métodos. Ele precisa ser tratado como qualquer outro objeto
em relação às contagens de referência.
Py_RETURN_FALSE
Retornar Py_False de uma função, incrementando adequadamente sua contagem de referência.
Py_RETURN_TRUE
Retorna Py_True de uma função, incrementando adequadamente sua contagem de referência.
PyObject *PyBool_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Retorna uma nova referência para Py_True ou
Py_False dependendo do valor de verdade de v.

8.2.3 Objetos de ponto flutuante

type PyFloatObject
Este subtipo de PyObject representa um objeto de ponto flutuante do Python.
PyTypeObject PyFloat_Type
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. Cria um objeto PyFloatObject baseado em uma
string de valor “str” ou NULL em falha.

112 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

PyObject *PyFloat_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. Cria um objeto PyFloatObject de v ou NULL em
falha.
double PyFloat_AsDouble(PyObject *pyfloat)
Part of the Stable ABI. 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á cha-
mado primeiro para converter pyfloat em um ponto flutuante. Se __float__() não estiver definido,
ele voltará a __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)
Return value: New reference. Part of the Stable ABI. Retorna uma instância de structseq que contém informa-
ções sobre a precisão, os valores mínimo e máximo de um ponto flutuante. É um wrapper fino em torno do
arquivo de cabeçalho float.h.
double PyFloat_GetMax()
Part of the Stable ABI. Retorna o ponto flutuante finito máximo representável DBL_MAX como double do C.
double PyFloat_GetMin()
Part of the Stable ABI. Retorna o ponto flutuante positivo mínimo normalizado DBL_MIN como double do C.

8.2.4 Objetos de números complexos

Os objetos de 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.

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

8.2. Objetos Numéricos 113


The Python/C API, Release 3.10.6

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
Part of the Stable ABI. 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)
Return value: New reference. Cria um novo objeto de número complexo Python a partir de um valor C
Py_complex.
PyObject *PyComplex_FromDoubles(double real, double imag)
Return value: New reference. Part of the Stable ABI. Retorna um novo objeto PyComplexObject de real
e imag.
double PyComplex_RealAsDouble(PyObject *op)
Part of the Stable ABI. Retorna a parte real de op como um double C.
double PyComplex_ImagAsDouble(PyObject *op)
Part of the Stable ABI. Retorna a parte imaginária de op como um double C.
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 -1.0 como um valor real.
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.

114 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

8.3.1 Objetos Bytes

These functions raise TypeError when expecting a bytes parameter and called with a non-bytes parameter.
type PyBytesObject
Esta é uma instância de PyObject representando o objeto bytes do Python.
PyTypeObject PyBytes_Type
Part of the Stable ABI. 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.
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)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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, ...)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. Idêntico a PyBytes_FromFormat() exceto que é
preciso exatamente dois argumentos.
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 115


The Python/C API, Release 3.10.6

PyObject *PyBytes_FromObject(PyObject *o)


Return value: New reference. Part of the Stable ABI. Retorna a representação de bytes do objeto o que imple-
menta o protocolo de buffer.
Py_ssize_t PyBytes_Size(PyObject *o)
Part of the Stable ABI. Retorna o comprimento dos bytes em objeto bytes o.
Py_ssize_t PyBytes_GET_SIZE(PyObject *o)
Forma macro de PyBytes_Size(), mas sem verificação de erro.
char *PyBytes_AsString(PyObject *o)
Part of the Stable ABI. 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)
Forma de macro de PyBytes_AsString(), mas sem verificação de erro.
int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
Part of the Stable ABI. Retorna os conteúdos terminados nulos do objeto obj através das variáveis de saída
buffer e length.
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 eleva 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. Cria um novo objeto bytes em *bytes contendo o conteúdo de newpart anexado a bytes.
Esta versão diminui a contagem de referências de newpart.
int _PyBytes_Resize(PyObject **bytes, Py_ssize_t newsize)
Uma maneira de redimensionar um objeto de bytes, mesmo que seja “imutável”. Use isso apenas para construir
um novo objeto de bytes; não use isso se os bytes já puderem ser conhecidos em outras partes do código. É
um erro invocar essa função se o refcount no objeto de bytes de entrada não for um. 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.

116 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

8.3.2 Objetos Byte Array

type PyByteArrayObject
Esse subtipo de PyObject representa um objeto Python bytearray.
PyTypeObject PyByteArray_Type
Part of the Stable ABI. 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.
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 byte-
array. Esta função sempre tem sucesso.

Funções diretas da API

PyObject *PyByteArray_FromObject(PyObject *o)


Return value: New reference. Part of the Stable ABI. Retorna um novo objeto bytearray, o, que implementa o
protocolo de buffer.
PyObject *PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Cria um novo objeto bytearray a partir de string e seu
comprimento, len. Em caso de falha, NULL é retornado.
PyObject *PyByteArray_Concat(PyObject *a, PyObject *b)
Return value: New reference. Part of the Stable ABI. Concatena os bytearrays a e b e retorna um novo bytearray
com o resultado.
Py_ssize_t PyByteArray_Size(PyObject *bytearray)
Part of the Stable ABI. Retorna o tamanho de bytearray após verificar se há um ponteiro NULL.
char *PyByteArray_AsString(PyObject *bytearray)
Part of the Stable ABI. Retorna o conteúdo de bytearray como uma matriz de caracteres após verificar um
ponteiro NULL. A matriz retornada sempre tem um byte nulo extra acrescentado.
int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len)
Part of the Stable ABI. 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)
Versão macro de PyByteArray_AsString().
Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray)
Versão macro de PyByteArray_Size().

8.3. Objetos Sequência 117


The Python/C API, Release 3.10.6

8.3.3 Objetos Unicode e Codecs

Unicode Objects

Since the implementation of PEP 393 in Python 3.3, Unicode objects internally use a variety of representations, in
order to allow handling the complete range of Unicode characters while staying memory efficient. There are special
cases for strings where all code points are below 128, 256, or 65536; otherwise, code points must be below 1114112
(which is the full Unicode range).
Py_UNICODE* and UTF-8 representations are created on demand and cached in the Unicode object. The
Py_UNICODE* representation is deprecated and inefficient.
Due to the transition between the old APIs and the new APIs, Unicode objects can internally be in two states depending
on how they were created:
• “canonical” Unicode objects are all objects created by a non-deprecated Unicode API. They use the most
efficient representation allowed by the implementation.
• “legacy” Unicode objects have been created through one of the deprecated APIs (typically
PyUnicode_FromUnicode()) and only bear the Py_UNICODE* representation; you will have to
call PyUnicode_READY() on them before calling any other API.

Nota: The “legacy” Unicode object will be removed in Python 3.12 with deprecated APIs. All Unicode objects will
be “canonical” since then. See PEP 623 for more information.

Unicode Type

These are the basic Unicode object types used for the Unicode implementation in Python:
type Py_UCS4
type Py_UCS2
type Py_UCS1
Part of the Stable ABI. These types are typedefs for unsigned integer types wide enough to contain characters
of 32 bits, 16 bits and 8 bits, respectively. When dealing with single Unicode characters, use Py_UCS4.
Novo na versão 3.3.
type Py_UNICODE
This is a typedef of wchar_t, which is a 16-bit type or 32-bit type depending on the platform.
Alterado na versão 3.3: In previous versions, this was a 16-bit type or a 32-bit type depending on whether you
selected a “narrow” or “wide” Unicode version of Python at build time.
type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject
These subtypes of PyObject represent a Python Unicode object. In almost all cases, they shouldn’t be used
directly, since all API functions that deal with Unicode objects take and return PyObject pointers.
Novo na versão 3.3.
PyTypeObject PyUnicode_Type
Part of the Stable ABI. This instance of PyTypeObject represents the Python Unicode type. It is exposed
to Python code as str.
The following APIs are really C macros and can be used to do fast checks and to access internal read-only data of
Unicode objects:
int PyUnicode_Check(PyObject *o)
Return true if the object o is a Unicode object or an instance of a Unicode subtype. This function always
succeeds.

118 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

int PyUnicode_CheckExact(PyObject *o)


Return true if the object o is a Unicode object, but not an instance of a subtype. This function always succeeds.
int PyUnicode_READY(PyObject *o)
Ensure the string object o is in the “canonical” representation. This is required before using any of the access
macros described below.
Returns 0 on success and -1 with an exception set on failure, which in particular happens if memory allocation
fails.
Novo na versão 3.3.
Deprecated since version 3.10, will be removed in version 3.12: This API will be removed with
PyUnicode_FromUnicode().
Py_ssize_t PyUnicode_GET_LENGTH(PyObject *o)
Return the length of the Unicode string, in code points. o has to be a Unicode object in the “canonical”
representation (not checked).
Novo na versão 3.3.
Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *o)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *o)
Py_UCS4 *PyUnicode_4BYTE_DATA(PyObject *o)
Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 integer types for direct cha-
racter access. No checks are performed if the canonical representation has the correct character size; use
PyUnicode_KIND() to select the right macro. Make sure PyUnicode_READY() has been called be-
fore accessing this.
Novo na versão 3.3.
PyUnicode_WCHAR_KIND
PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND
Return values of the PyUnicode_KIND() macro.
Novo na versão 3.3.
Deprecated since version 3.10, will be removed in version 3.12: PyUnicode_WCHAR_KIND is deprecated.
unsigned int PyUnicode_KIND(PyObject *o)
Return one of the PyUnicode kind constants (see above) that indicate how many bytes per character this Uni-
code object uses to store its data. o has to be a Unicode object in the “canonical” representation (not checked).
Novo na versão 3.3.
void *PyUnicode_DATA(PyObject *o)
Return a void pointer to the raw Unicode buffer. o has to be a Unicode object in the “canonical” representation
(not checked).
Novo na versão 3.3.
void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, Py_UCS4 value)
Write into a canonical representation data (as obtained with PyUnicode_DATA()). This macro does not
do any sanity checks and is intended for usage in loops. The caller should cache the kind value and data pointer
as obtained from other macro calls. index is the index in the string (starts at 0) and value is the new code point
value which should be written to that location.
Novo na versão 3.3.
Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index)
Read a code point from a canonical representation data (as obtained with PyUnicode_DATA()). No checks
or ready calls are performed.
Novo na versão 3.3.

8.3. Objetos Sequência 119


The Python/C API, Release 3.10.6

Py_UCS4 PyUnicode_READ_CHAR(PyObject *o, Py_ssize_t index)


Read a character from a Unicode object o, which must be in the “canonical” representation. This is less efficient
than PyUnicode_READ() if you do multiple consecutive reads.
Novo na versão 3.3.
PyUnicode_MAX_CHAR_VALUE(o)
Return the maximum code point that is suitable for creating another string based on o, which must be in the
“canonical” representation. This is always an approximation but more efficient than iterating over the string.
Novo na versão 3.3.
Py_ssize_t PyUnicode_GET_SIZE(PyObject *o)
Return the size of the deprecated Py_UNICODE representation, in code units (this includes surrogate pairs as
2 units). o has to be a Unicode object (not checked).
Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please
migrate to using PyUnicode_GET_LENGTH().
Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o)
Return the size of the deprecated Py_UNICODE representation in bytes. o has to be a Unicode object (not
checked).
Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please
migrate to using PyUnicode_GET_LENGTH().
Py_UNICODE *PyUnicode_AS_UNICODE(PyObject *o)
const char *PyUnicode_AS_DATA(PyObject *o)
Return a pointer to a Py_UNICODE representation of the object. The returned buffer is always terminated
with an extra null code point. It may also contain embedded null code points, which would cause the string to
be truncated when used in most C functions. The AS_DATA form casts the pointer to const char*. The o
argument has to be a Unicode object (not checked).
Alterado na versão 3.3: This macro is now inefficient – because in many cases the Py_UNICODE repre-
sentation does not exist and needs to be created – and can fail (return NULL with an exception set). Try to
port the code to use the new PyUnicode_nBYTE_DATA() macros or use PyUnicode_WRITE() or
PyUnicode_READ().
Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please
migrate to using the PyUnicode_nBYTE_DATA() family of macros.
int PyUnicode_IsIdentifier(PyObject *o)
Part of the Stable ABI. Return 1 if the string is a valid identifier according to the language definition, section
identifiers. Return 0 otherwise.
Alterado na versão 3.9: The function does not call Py_FatalError() anymore if the string is not ready.

Unicode Character Properties

Unicode provides many different character properties. The most often needed ones are available through these macros
which are mapped to C functions depending on the Python configuration.
int Py_UNICODE_ISSPACE(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a whitespace character.
int Py_UNICODE_ISLOWER(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a lowercase character.
int Py_UNICODE_ISUPPER(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is an uppercase character.
int Py_UNICODE_ISTITLE(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a titlecase character.

120 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)


Return 1 or 0 depending on whether ch is a linebreak character.
int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a decimal character.
int Py_UNICODE_ISDIGIT(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a digit character.
int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a numeric character.
int Py_UNICODE_ISALPHA(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is an alphabetic character.
int Py_UNICODE_ISALNUM(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is an alphanumeric character.
int Py_UNICODE_ISPRINTABLE(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a printable character. Nonprintable characters are those characters
defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which
is considered printable. (Note that printable characters in this context are those which should not be escaped
when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout
or sys.stderr.)
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.
Obsoleto desde a versão 3.3: This function uses simple case mappings.
Py_UCS4 Py_UNICODE_TOUPPER(Py_UCS4 ch)
Return the character ch converted to upper case.
Obsoleto desde a versão 3.3: This function uses simple case mappings.
Py_UCS4 Py_UNICODE_TOTITLE(Py_UCS4 ch)
Return the character ch converted to title case.
Obsoleto desde a versão 3.3: This function uses simple case mappings.
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 macro
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 macro 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 macro does not raise
exceptions.
These APIs can be used to work with surrogates:
Py_UNICODE_IS_SURROGATE(ch)
Check if ch is a surrogate (0xD800 <= ch <= 0xDFFF).
Py_UNICODE_IS_HIGH_SURROGATE(ch)
Check if ch is a high surrogate (0xD800 <= ch <= 0xDBFF).
Py_UNICODE_IS_LOW_SURROGATE(ch)
Check if ch is a low surrogate (0xDC00 <= ch <= 0xDFFF).
Py_UNICODE_JOIN_SURROGATES(high, low)
Join two surrogate characters and return a single Py_UCS4 value. high and low are respectively the leading
and trailing surrogates in a surrogate pair.

8.3. Objetos Sequência 121


The Python/C API, Release 3.10.6

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)
Return value: New reference. 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.
Novo na versão 3.3.
PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
Return value: New reference. Create a new Unicode object with the given kind (possible values are
PyUnicode_1BYTE_KIND etc., as returned by PyUnicode_KIND()). The buffer must point to an
array of size units of 1, 2 or 4 bytes per character, as given by the kind.
Novo na versão 3.3.
PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from the char buffer u. The
bytes will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. If the buffer is not
NULL, the return value might be a shared object, i.e. modification of the data is not allowed.
If u is NULL, this function behaves like PyUnicode_FromUnicode() with the buffer set to NULL. This
usage is deprecated in favor of PyUnicode_New(), and will be removed in Python 3.12.
PyObject *PyUnicode_FromString(const char *u)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from a UTF-8 encoded null-
terminated char buffer u.
PyObject *PyUnicode_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI. Take a C printf()-style format string and a variable
number of arguments, calculate the size of the resulting Python Unicode string and return a string with the
values formatted into it. The variable arguments must be C types and must correspond exactly to the format
characters in the format ASCII-encoded string. The following format characters are allowed:

122 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

Caracteres Formatados Tipo Comentário


%% n/d O caractere literal %.
%c int A single character, represented as a C int.
%d int Equivalente a printf("%d").1
%u unsigned int Equivalente a printf("%u").1
%ld long Equivalente a printf("%ld").1
%li long Equivalent to printf("%li").1
%lu unsigned long Equivalente a printf("%lu").1
%lld long long Equivalent to printf("%lld").1
%lli long long Equivalent to printf("%lli").1
%llu unsigned long long Equivalent to printf("%llu").1
%zd Py_ssize_t Equivalente a printf("%zd").1
%zi Py_ssize_t Equivalent to printf("%zi").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.
%A PyObject* The result of calling ascii().
%U PyObject* A Unicode object.
%V PyObject*, const char* A Unicode object (which may be NULL) and a
null-terminated C character array as a second
parameter (which will be used, if the first
parameter is NULL).
%S PyObject* The result of calling PyObject_Str().
%R PyObject* The result of calling PyObject_Repr().

An unrecognized format character causes all the rest of the format string to be copied as-is to the result string,
and any extra arguments discarded.

Nota: The width formatter unit is number of characters rather than bytes. The precision formatter unit is
number of bytes 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).

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"
added.
PyObject *PyUnicode_FromFormatV(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Identical to PyUnicode_FromFormat() except that
it takes exactly two arguments.
PyObject *PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char
*errors)
Return value: New reference. Part of the Stable ABI. 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).
1 For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi, zu, i, x): the 0-conversion flag has effect even when a precision is given.

8.3. Objetos Sequência 123


The Python/C API, Release 3.10.6

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.
Py_ssize_t PyUnicode_GetLength(PyObject *unicode)
Part of the Stable ABI since version 3.7. Return the length of the Unicode object, in code points.
Novo 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.
Novo na versão 3.3.
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.
Novo na versão 3.3.
int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 character)
Part of the Stable ABI since version 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).
Novo na versão 3.3.
Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
Part of the Stable ABI since version 3.7. Read a character from a string. This function checks that
unicode is a Unicode object and the index is not out of bounds, in contrast to the macro version
PyUnicode_READ_CHAR().
Novo na versão 3.3.
PyObject *PyUnicode_Substring(PyObject *str, Py_ssize_t start, Py_ssize_t end)
Return value: New reference. Part of the Stable ABI since version 3.7. Return a substring of str, from character
index start (included) to character index end (excluded). Negative indices are not supported.
Novo na versão 3.3.
Py_UCS4 *PyUnicode_AsUCS4(PyObject *u, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)
Part of the Stable ABI since version 3.7. Copy the string u 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 u). buffer is returned on success.
Novo na versão 3.3.
Py_UCS4 *PyUnicode_AsUCS4Copy(PyObject *u)
Part of the Stable ABI since version 3.7. Copy the string u 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.
Novo na versão 3.3.

124 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

Deprecated Py_UNICODE APIs

Deprecated since version 3.3, will be removed in version 3.12.


These API functions are deprecated with the implementation of PEP 393. Extension modules can continue using
them, as they will not be removed in Python 3.x, but need to be aware that their use can now cause performance and
memory hits.
PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Return value: New reference. Create a Unicode object from the Py_UNICODE buffer u of the given size. u
may be NULL which causes the contents to be undefined. It is the user’s responsibility to fill in the needed data.
The buffer is copied into the new object.
If the buffer is not NULL, the return value might be a shared object. Therefore, modification of the resulting
Unicode object is only allowed when u is NULL.
If the buffer is NULL, PyUnicode_READY() must be called once the string content has been filled before
using any of the access macros such as PyUnicode_KIND().
Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API,
please migrate to using PyUnicode_FromKindAndData(), PyUnicode_FromWideChar(), or
PyUnicode_New().
Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
Return a read-only pointer to the Unicode object’s internal Py_UNICODE buffer, or NULL on error. This will
create the Py_UNICODE* representation of the object if it is not yet available. The buffer is always terminated
with an extra null code point. Note that the resulting Py_UNICODE string may also contain embedded null
code points, which would cause the string to be truncated when used in most C functions.
Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please mi-
grate to using PyUnicode_AsUCS4(), PyUnicode_AsWideChar(), PyUnicode_ReadChar()
or similar new APIs.
PyObject *PyUnicode_TransformDecimalToASCII(Py_UNICODE *s, Py_ssize_t size)
Return value: New reference. Create a Unicode object by replacing all decimal digits in Py_UNICODE buffer
of the given size by ASCII digits 0–9 according to their decimal value. Return NULL if an exception occurs.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using Py_UNICODE_TODECIMAL().
Py_UNICODE *PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
Like PyUnicode_AsUnicode(), but also saves the Py_UNICODE() array length (excluding the extra
null terminator) in size. Note that the resulting Py_UNICODE* string may contain embedded null code points,
which would cause the string to be truncated when used in most C functions.
Novo na versão 3.3.
Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please mi-
grate to using PyUnicode_AsUCS4(), PyUnicode_AsWideChar(), PyUnicode_ReadChar()
or similar new APIs.
Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
Part of the Stable ABI. Return the size of the deprecated Py_UNICODE representation, in code units (this
includes surrogate pairs as 2 units).
Deprecated since version 3.3, will be removed in version 3.12: Part of the old-style Unicode API, please
migrate to using PyUnicode_GET_LENGTH().
PyObject *PyUnicode_FromObject(PyObject *obj)
Return value: New reference. Part of the Stable ABI. Copy an instance of a Unicode subtype to a new true
Unicode object if necessary. If obj is already a true Unicode object (not a subtype), return the reference with
incremented refcount.
Objects other than Unicode or its subtypes will cause a TypeError.

8.3. Objetos Sequência 125


The Python/C API, Release 3.10.6

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 len, const char *er-
rors)
Return value: New reference. Part of the Stable ABI since version 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
Py_FileSystemDefaultEncoding (the locale encoding read at Python startup).
This function ignores the Python UTF-8 Mode.
Ver também:
The Py_DecodeLocale() function.
Novo 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)
Return value: New reference. Part of the Stable ABI since version 3.7. Similar to
PyUnicode_DecodeLocaleAndSize(), but compute the string length using strlen().
Novo na versão 3.3.
PyObject *PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI since version 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 Py_FileSystemDefaultEncoding
(the locale encoding read at Python startup).
This function ignores the Python UTF-8 Mode.
Ver também:
The Py_EncodeLocale() function.
Novo 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

To encode and decode file names and other environment strings, Py_FileSystemDefaultEncoding should
be used as the encoding, and Py_FileSystemDefaultEncodeErrors should be used as the error handler
(PEP 383 and PEP 529). To encode file names to bytes during argument parsing, the "O&" converter should be
used, passing PyUnicode_FSConverter() as the conversion function:
int PyUnicode_FSConverter(PyObject *obj, void *result)
Part of the Stable ABI. ParseTuple converter: encode str objects – obtained directly or through the os.
PathLike interface – to bytes using PyUnicode_EncodeFSDefault(); bytes objects are output
as-is. result must be a PyBytesObject* which must be released when it is no longer used.
Novo na versão 3.1.

126 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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:
int PyUnicode_FSDecoder(PyObject *obj, void *result)
Part of the Stable ABI. ParseTuple converter: decode bytes objects – obtained either directly or indirectly
through the os.PathLike interface – to str using PyUnicode_DecodeFSDefaultAndSize();
str objects are output as-is. result must be a PyUnicodeObject* which must be released when it is no longer
used.
Novo na versão 3.2.
Alterado na versão 3.6: Aceita um objeto caminho ou similar.
PyObject *PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Decode a string from the filesystem encoding and error
handler.
If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding.
Py_FileSystemDefaultEncoding is initialized at startup from the locale encoding and can-
not be modified later. 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: Use Py_FileSystemDefaultEncodeErrors error handler.
PyObject *PyUnicode_DecodeFSDefault(const char *s)
Return value: New reference. Part of the Stable ABI. Decode a null-terminated string from the filesystem
encoding and error handler.
If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding.
Use PyUnicode_DecodeFSDefaultAndSize() if you know the string length.
Alterado na versão 3.6: Use Py_FileSystemDefaultEncodeErrors error handler.
PyObject *PyUnicode_EncodeFSDefault(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Encode a Unicode object to
Py_FileSystemDefaultEncoding with the Py_FileSystemDefaultEncodeErrors
error handler, and return bytes. Note that the resulting bytes object may contain null bytes.
If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding.
Py_FileSystemDefaultEncoding is initialized at startup from the locale encoding and can-
not be modified later. If you need to encode a string to the current locale encoding, use
PyUnicode_EncodeLocale().
Ver também:
The Py_EncodeLocale() function.
Novo na versão 3.2.
Alterado na versão 3.6: Use Py_FileSystemDefaultEncodeErrors error handler.

8.3. Objetos Sequência 127


The Python/C API, Release 3.10.6

wchar_t Support

wchar_t support for platforms which support it:


PyObject *PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from the wchar_t buffer w 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 *w, Py_ssize_t size)
Part of the Stable ABI. Copy the Unicode object contents into the wchar_t buffer w. At most size
wchar_t characters are copied (excluding a possibly trailing null termination character). Return the num-
ber of wchar_t characters copied or -1 in case of an error. Note that the resulting wchar_t* string may
or may not be null-terminated. It is the responsibility of the caller to make sure that the wchar_t* string is
null-terminated in case this is required by the application. Also, note that the wchar_t* string might contain
null characters, which would cause the string to be truncated when used with most C functions.
wchar_t *PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)
Part of the Stable ABI since version 3.7. Convert the Unicode object to a wide character string. The output
string always ends with a null character. If size is not NULL, write the number of wide characters (excluding
the trailing null termination character) into *size. Note that the resulting wchar_t string might contain null
characters, which would cause the string to be truncated when used with most C functions. If size is NULL and
the wchar_t* string contains null characters a ValueError is raised.
Returns a buffer allocated by PyMem_Alloc() (use PyMem_Free() to free it) on success. On error,
returns NULL and *size is undefined. Raises a MemoryError if memory allocation is failed.
Novo 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 sys-
tem calls should use PyUnicode_FSConverter() for encoding file names. This uses the variable
Py_FileSystemDefaultEncoding internally. This variable should be treated as read-only: on some sys-
tems, it will be a pointer to a static string, on others, it will change at run-time (such as when the application invokes
setlocale).
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 *s, Py_ssize_t size, const char *encoding, const char
*errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
encoded string s. 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.

128 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

PyObject *PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char


*errors)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding,
const char *errors)
Return value: New reference. Encode the Py_UNICODE buffer s of the given size and return a Python by-
tes 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.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using PyUnicode_AsEncodedString().

UTF-8 Codecs

These are the UTF-8 codec APIs:


PyObject *PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
UTF-8 encoded string s. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors,
Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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.
const char *PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)
Part of the Stable ABI since version 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.
In the case of an error, NULL is returned with an exception set and no size is stored.
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.
Novo 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.
Novo na versão 3.3.
Alterado na versão 3.7: The return type is now const char * rather of char *.
PyObject *PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
Return value: New reference. Encode the Py_UNICODE buffer s of the given size using UTF-8 and return a
Python bytes object. Return NULL if an exception was raised by the codec.

8.3. Objetos Sequência 129


The Python/C API, Release 3.10.6

Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE
API; please migrate to using PyUnicode_AsUTF8String(), PyUnicode_AsUTF8AndSize() or
PyUnicode_AsEncodedString().

UTF-32 Codecs

These are the UTF-32 codec APIs:


PyObject *PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteor-
der)
Return value: New reference. Part of the Stable ABI. 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

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 *s, Py_ssize_t size, const char *errors,
int *byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. If consumed is NULL,
behave like PyUnicode_DecodeUTF32(). If consumed is not NULL,
PyUnicode_DecodeUTF32Stateful() will not treat trailing incomplete UTF-32 byte sequen-
ces (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)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors,
int byteorder)
Return value: New reference. Return a Python bytes object holding the UTF-32 encoded value of the Unicode
data in s. Output is written according to the following byte order:

byteorder == -1: little endian


byteorder == 0: native byte order (writes a BOM mark)
byteorder == 1: big endian

If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two
modes, no BOM mark is prepended.
If Py_UNICODE_WIDE is not defined, surrogate pairs will be output as a single code point.
Return NULL if an exception was raised by the codec.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using PyUnicode_AsUTF32String() or PyUnicode_AsEncodedString().

130 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

UTF-16 Codecs

These are the UTF-16 codec APIs:


PyObject *PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteor-
der)
Return value: New reference. Part of the Stable ABI. 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 *s, Py_ssize_t size, const char *errors,
int *byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. If consumed is NULL,
behave like PyUnicode_DecodeUTF16(). If consumed is not NULL,
PyUnicode_DecodeUTF16Stateful() will not treat trailing incomplete UTF-16 byte sequen-
ces (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)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors,
int byteorder)
Return value: New reference. Return a Python bytes object holding the UTF-16 encoded value of the Unicode
data in s. Output is written according to the following byte order:

byteorder == -1: little endian


byteorder == 0: native byte order (writes a BOM mark)
byteorder == 1: big endian

If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two
modes, no BOM mark is prepended.
If Py_UNICODE_WIDE is defined, a single Py_UNICODE value may get represented as a surrogate pair. If
it is not defined, each Py_UNICODE values is interpreted as a UCS-2 character.
Return NULL if an exception was raised by the codec.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using PyUnicode_AsUTF16String() or PyUnicode_AsEncodedString().

8.3. Objetos Sequência 131


The Python/C API, Release 3.10.6

UTF-7 Codecs

These are the UTF-7 codec APIs:


PyObject *PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
UTF-7 encoded string s. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors,
Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int
base64WhiteSpace, const char *errors)
Return value: New reference. Encode the Py_UNICODE buffer of the given size using UTF-7 and return a
Python bytes object. Return NULL if an exception was raised by the codec.
If base64SetO is nonzero, “Set O” (punctuation that has no otherwise special meaning) will be encoded in
base-64. If base64WhiteSpace is nonzero, whitespace will be encoded in base-64. Both are set to zero for the
Python “utf-7” codec.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using PyUnicode_AsEncodedString().

Unicode-Escape Codecs

These are the “Unicode Escape” codec APIs:


PyObject *PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *er-
rors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
Unicode-Escape encoded string s. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
Return value: New reference. Encode the Py_UNICODE buffer of the given size using Unicode-Escape and
return a bytes object. Return NULL if an exception was raised by the codec.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using PyUnicode_AsUnicodeEscapeString().

Raw-Unicode-Escape Codecs

These are the “Raw Unicode Escape” codec APIs:


PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char
*errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
Raw-Unicode-Escape encoded string s. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. 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.

132 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)


Return value: New reference. Encode the Py_UNICODE buffer of the given size using Raw-Unicode-Escape
and return a bytes object. Return NULL if an exception was raised by the codec.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style
Py_UNICODE API; please migrate to using PyUnicode_AsRawUnicodeEscapeString() or
PyUnicode_AsEncodedString().

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 *s, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
Latin-1 encoded string s. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
Return value: New reference. Encode the Py_UNICODE buffer of the given size using Latin-1 and return a
Python bytes object. Return NULL if an exception was raised by the codec.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using PyUnicode_AsLatin1String() or PyUnicode_AsEncodedString().

ASCII Codecs

These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors.
PyObject *PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
ASCII encoded string s. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
Return value: New reference. Encode the Py_UNICODE buffer of the given size using ASCII and return a
Python bytes object. Return NULL if an exception was raised by the codec.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using PyUnicode_AsASCIIString() or PyUnicode_AsEncodedString().

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 *data, Py_ssize_t size, PyObject *mapping,
const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
encoded string s using the given mapping object. Return NULL if an exception was raised by the codec.

8.3. Objetos Sequência 133


The Python/C API, Release 3.10.6

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)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping,
const char *errors)
Return value: New reference. Encode the Py_UNICODE buffer of the given size using the given mapping object
and return the result as a bytes object. Return NULL if an exception was raised by the codec.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using PyUnicode_AsCharmapString() or PyUnicode_AsEncodedString().
The following codec API is special in that maps Unicode to Unicode.
PyObject *PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)
Return value: New reference. Part of the Stable ABI. 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.
Unmapped 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.
PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject
*mapping, const char *errors)
Return value: New reference. Translate a Py_UNICODE buffer of the given size by applying a character
mapping table to it and return the resulting Unicode object. Return NULL when an exception was raised by the
codec.
Deprecated since version 3.3, will be removed in version 3.11: Part of the old-style Py_UNICODE API; please
migrate to using PyUnicode_Translate(). or generic codec based API

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 *s, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Create a Unicode object
by decoding size bytes of the MBCS encoded string s. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeMBCSStateful(const char *s, Py_ssize_t size, const char *errors,
Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. 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_AsMBCSString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Encode a Unicode object

134 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Encode the Unicode object
using the specified code page and return a Python bytes object. Return NULL if an exception was raised by the
codec. Use CP_ACP code page to get the MBCS encoder.
Novo na versão 3.3.
PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors)
Return value: New reference. Encode the Py_UNICODE buffer of the given size using MBCS and return a
Python bytes object. Return NULL if an exception was raised by the codec.
Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE
API; please migrate to using PyUnicode_AsMBCSString(), PyUnicode_EncodeCodePage() or
PyUnicode_AsEncodedString().

Methods & Slots

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)
Return value: New reference. Part of the Stable ABI. Concat two strings giving a new Unicode string.
PyObject *PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyUnicode_Splitlines(PyObject *s, int keepend)
Return value: New reference. Part of the Stable ABI. Split a Unicode string at line breaks, returning a list of
Unicode strings. CRLF is considered to be one line break. If keepend is 0, the line break characters are not
included in the resulting strings.
PyObject *PyUnicode_Join(PyObject *separator, PyObject *seq)
Return value: New reference. Part of the Stable ABI. Join a sequence of strings using the given separator and
return the resulting Unicode string.
Py_ssize_t PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
Part of the Stable ABI. Return 1 if substr matches str[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 *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direc-
tion)
Part of the Stable ABI. Return the first position of substr in str[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 *str, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direc-
tion)
Part of the Stable ABI since version 3.7. Return the first position of the character ch in str[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.
Novo na versão 3.3.

8.3. Objetos Sequência 135


The Python/C API, Release 3.10.6

Alterado na versão 3.7: start and end are now adjusted to behave like str[start:end].
Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
Part of the Stable ABI. Return the number of non-overlapping occurrences of substr in str[start:end].
Return -1 if an error occurred.
PyObject *PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t max-
count)
Return value: New reference. Part of the Stable ABI. Replace at most maxcount occurrences of substr in str
with replstr and return the resulting Unicode object. maxcount == -1 means replace all occurrences.
int PyUnicode_Compare(PyObject *left, PyObject *right)
Part of the Stable ABI. 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_CompareWithASCIIString(PyObject *uni, const char *string)
Part of the Stable ABI. Compare a Unicode object, uni, 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)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. Return a new string object from format and args; this is
analogous to format % args.
int PyUnicode_Contains(PyObject *container, PyObject *element)
Part of the Stable ABI. Check whether element is contained in container and return true or false accordingly.
element has to coerce to a one element Unicode string. -1 is returned if there was an error.
void PyUnicode_InternInPlace(PyObject **string)
Part of the Stable ABI. Intern the argument *string 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
*string, it sets *string to it (decrementing the reference count of the old string object and incrementing the
reference count of the interned string object), otherwise it leaves *string alone and interns it (incrementing its
reference count). (Clarification: even though there is a lot of talk about reference counts, think of this function
as reference-count-neutral; you own the object after the call if and only if you owned it before the call.)
PyObject *PyUnicode_InternFromString(const char *v)
Return value: New reference. Part of the Stable ABI. A combination of PyUnicode_FromString() and
PyUnicode_InternInPlace(), returning either a new Unicode string object that has been interned, or
a new (“owned”) reference to an earlier interned string object with the same value.

136 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

8.3.4 Objeto tupla

type PyTupleObject
Este subtipo de PyObject representa um objeto tupla em Python.
PyTypeObject PyTuple_Type
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. Retorna um novo objeto tupla de tamanho len, ou NULL
em caso de falha.
PyObject *PyTuple_Pack(Py_ssize_t n, ...)
Return value: New reference. Part of the Stable ABI. Retorna um novo objeto tupla de tamanho n, ou NULL
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)
Part of the Stable ABI. Pega um ponteiro para um objeto tupla e retorna o tamanho dessa tupla.
Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
Retorna o tamanho da tupla p, que deve ser diferente de NULL e apontar para uma tupla; nenhuma verificação
de erro é executada.
PyObject *PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Part of the Stable ABI. 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.
PyObject *PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Como PyTuple_GetItem(), mas faz nenhuma verificação de seus
argumentos.
PyObject *PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)
Return value: New reference. Part of the Stable ABI. Retorna a fatia da tupla apontada por p entre low (baixo)
e high (alto), ou NULL em caso de falha. Este é o equivalente da expressão Python p[low:high]. A
indexação do final da lista não é suportada.
int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Part of the Stable ABI. 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.

Nota: Esta macro “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.

8.3. Objetos Sequência 137


The Python/C API, Release 3.10.6

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 assumir 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)
Return value: New reference. Part of the Stable ABI. 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().
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)
O mesmo que PyStructSequence_InitType, mas retorna 0 em caso de sucesso e -1 em caso de falha.
Novo na versão 3.4.
type PyStructSequence_Desc
Part of the Stable ABI (including all members). Contém as metainformações de um tipo de sequência de
estrutura a ser criado.

Campo Tipo em C Significado


name const char * nome do tipo sequência de estrutura
doc const char * ponteiro para docstring para o tipo ou NULL para omitir
fields PyStructSequence_Field
ponteiro para um vetor terminado em NULL com nomes de
* campos do novo tipo
n_in_sequence
int número de campos visíveis para o lado Python (se usado
como tupla)

type PyStructSequence_Field
Part of the Stable ABI (including all members). 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.

CampoTipo em Significado
C
name const nome do campo ou NULL para terminar a lista de campos nomeados; definida para
char * PyStructSequence_UnnamedField para deixar sem nome
doc const campo docstring ou NULL para omitir
char *

const char *const PyStructSequence_UnnamedField


Valor especial para um nome de campo para deixá-lo sem nome.
Alterado na versão 3.9: O tipo foi alterado de char *.

138 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

PyObject *PyStructSequence_New(PyTypeObject *type)


Return value: New reference. Part of the Stable ABI. Cria um instância de type, que deve ser criada com
PyStructSequence_NewType().
PyObject *PyStructSequence_GetItem(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Part of the Stable ABI. Retorna o objeto na posição pos na sequência de
estrutura apontada por p. Nenhuma verificação de limites é executada.
PyObject *PyStructSequence_GET_ITEM(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Macro equivalente de PyStructSequence_GetItem().
void PyStructSequence_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Part of the Stable ABI. 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.

Nota: Esta função “rouba” uma referência a o.

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


Macro equivalente de PyStructSequence_SetItem().

Nota: Esta função “rouba” uma referência a o.

8.3.6 Objeto List

type PyListObject
Este subtipo de PyObject representa um objeto de lista Python.
PyTypeObject PyList_Type
Part of the Stable ABI. 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.
PyObject *PyList_New(Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. 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 de lista retornado 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().

Py_ssize_t PyList_Size(PyObject *list)


Part of the Stable ABI. 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)
Forma macro de PyList_Size() sem verificação de erros.
PyObject *PyList_GetItem(PyObject *list, Py_ssize_t index)
Return value: Borrowed reference. Part of the Stable ABI. 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 (<o ou >=len(list)), retorna NULL e levanta uma exceção IndexError.

8.3. Objetos Sequência 139


The Python/C API, Release 3.10.6

PyObject *PyList_GET_ITEM(PyObject *list, Py_ssize_t i)


Return value: Borrowed reference. Forma macro de PyList_GetItem() sem verificação de erros.
int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)
Part of the Stable ABI. 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
preencher novas listas onde não há conteúdo anterior.

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)


Part of the Stable ABI. 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).
int PyList_Append(PyObject *list, PyObject *item)
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI. 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 (ex-
clusã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_Sort(PyObject *list)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. Retorna um novo objeto tupla contendo os conteúdos de
list; equivale a“tuple(list)“.

140 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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
Part of the Stable ABI. 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.
PyObject *PyDict_New()
Return value: New reference. Part of the Stable ABI. Retorna um novo dicionário vazio ou NULL em caso de
falha.
PyObject *PyDictProxy_New(PyObject *mapping)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI. Esvazia um dicionário existente de todos os pares chave-valor.
int PyDict_Contains(PyObject *p, PyObject *key)
Part of the Stable ABI. 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.
PyObject *PyDict_Copy(PyObject *p)
Return value: New reference. Part of the Stable ABI. Retorna um novo dicionário que contém o mesmo chave-
valor como p.
int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
Part of the Stable ABI. 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)
Part of the Stable ABI. Insere val no dicionário p usando key como uma chave. key deve ser a const char*.
O objeto chave é criado usando PyUnicode_FromString(key). 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_DelItem(PyObject *p, PyObject *key)
Part of the Stable ABI. 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)
Part of the Stable ABI. Remove a entrada no dicionário p que tem uma chave especificada pela string key. Se
key não estiver no dicionário, KeyError é levantada. Retorna 0 em caso de sucesso ou -1 em caso de falha.
PyObject *PyDict_GetItem(PyObject *p, PyObject *key)
Return value: Borrowed reference. Part of the Stable ABI. Retorna 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.
Observe que as exceções que ocorrem ao chamar os métodos __hash__() e __eq__() serão suprimidas.
Para obter o relatório de erros, use PyDict_GetItemWithError().

8.4. Coleções 141


The Python/C API, Release 3.10.6

Alterado na versão 3.10: Chamar esta API sem GIL retido foi permitido por motivos históricos. Não é mais
permitido.
PyObject *PyDict_GetItemWithError(PyObject *p, PyObject *key)
Return value: Borrowed reference. Part of the Stable ABI. Variante de PyDict_GetItem() que não su-
prime 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)
Return value: Borrowed reference. Part of the Stable ABI. É o mesmo que PyDict_GetItem(), mas key
é especificada como um const char*, em vez de um PyObject*.
Observe que as exceções que ocorrem ao chamar os métodos __hash__() e __eq__() e criar um objeto
string temporário serão suprimidas. Para obter o relatório de erros, use PyDict_GetItemWithError().
PyObject *PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)
Return value: Borrowed reference. 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.
Novo na versão 3.4.
PyObject *PyDict_Items(PyObject *p)
Return value: New reference. Part of the Stable ABI. Retorna um PyListObject contendo todos os itens
do dicionário.
PyObject *PyDict_Keys(PyObject *p)
Return value: New reference. Part of the Stable ABI. Retorna um PyListObject contendo todas as chaves
do dicionário.
PyObject *PyDict_Values(PyObject *p)
Return value: New reference. Part of the Stable ABI. Retorna um PyListObject contendo todos os valores
do dicionário p.
Py_ssize_t PyDict_Size(PyObject *p)
Part of the Stable ABI. Retorna o número de itens no dicionário. Isso é equivalente a len(p) em um dicio-
nário.
int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Part of the Stable ABI. 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)) {


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

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;

(continua na próxima página)

142 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

(continuação da página anterior)


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

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


Part of the Stable ABI. Itera sobre 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 encontrada 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)
Part of the Stable ABI. É 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)
Part of the Stable ABI. 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

8.4.2 Objeto Set

This section details the public API for set and frozenset objects. Any functiona-
lity not listed below is best accessed using either the abstract object protocol (including
PyObject_CallMethod(), PyObject_RichCompareBool(), PyObject_Hash(),
PyObject_Repr(), PyObject_IsTrue(), PyObject_Print(), and PyObject_GetIter()) or
the abstract number protocol (including PyNumber_And(), PyNumber_Subtract(), PyNumber_Or(),
PyNumber_Xor(), PyNumber_InPlaceAnd(), PyNumber_InPlaceSubtract(),
PyNumber_InPlaceOr(), and PyNumber_InPlaceXor()).
type PySetObject
This subtype of PyObject is used to hold the internal data for both set and frozenset objects. It is like
a PyDictObject in that it is a fixed size for small sets (much like tuple storage) and will point to a separate,
variable sized block of memory for medium and large sized sets (much like list storage). None of the fields of
this structure should be considered public and all are subject to change. All access should be done through the
documented API rather than by manipulating the values in the structure.
PyTypeObject PySet_Type
Part of the Stable ABI. Essa é uma instância de PyTypeObject representando o tipo Python set

8.4. Coleções 143


The Python/C API, Release 3.10.6

PyTypeObject PyFrozenSet_Type
Part of the Stable ABI. 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.
Novo 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)
Return value: New reference. Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. Retorna uma nova frozenset contendo objetos re-
tornados 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 sub-
tipos.
Py_ssize_t PySet_Size(PyObject *anyset)
Part of the Stable ABI. Retorna o comprimento de um objeto set ou frozenset. Equivalente a
len(anyset). Levanta um PyExc_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)
Part of the Stable ABI. 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 conjun-
tos não hasheáveis em frozensets temporários. Levanta um TypeError se a key não for hasheável. Levanta
PyExc_SystemError se anyset não é um set, frozenset, ou uma instância de um subtipo.
int PySet_Add(PyObject *set, PyObject *key)
Part of the Stable ABI. Add key to a set instance. Also works with frozenset instances (like
PyTuple_SetItem() it can be used to fill in the values of brand new frozensets before they are expo-
sed to other code). Return 0 on success or -1 on failure. Raise a TypeError if the key is unhashable. Raise
a MemoryError if there is no room to grow. Raise a SystemError if set is not an instance of set or its
subtype.

144 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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)
Part of the Stable ABI. 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 PyExc_SystemError se set não é uma
instância de set ou seu subtipo.
PyObject *PySet_Pop(PyObject *set)
Return value: New reference. Part of the Stable ABI. 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)
Part of the Stable ABI. Limpa todos os elementos de um conjunto existente

8.5 Objetos Função

8.5.1 Objetos Função

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á exposto aos programa-
dores Python como types.FunctionType.
int PyFunction_Check(PyObject *o)
Retorna verdadeiro se o é um objeto de função (tem tipo PyFunction_Type). O parâmetro não deve ser
NULL. Esta função sempre tem sucesso.
PyObject *PyFunction_New(PyObject *code, PyObject *globals)
Return value: New reference. Retorna um novo objeto função associado ao código objeto code. globals deve
ser um dicionário com as variáveis globais acessíveis à função.
A docstring e o nome da função são recuperados do objeto de código. __module__ * é recuperado de *glo-
bals. Os padrões de argumento, as anotações e o encerramento são definidos como NULL. __qualname__ está
definido para o mesmo valor que o nome da função.
PyObject *PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)
Return value: New reference. Como PyFunction_New(), mas também permite configurar o atributo
__qualname__ do objeto da função. qualname deve ser um objeto unicode ou NULL; Se NULL, o atributo
__qualname__ é definido como o mesmo valor que o atributo __name__.
Novo na versão 3.3.
PyObject *PyFunction_GetCode(PyObject *op)
Return value: Borrowed reference. Retorna o objeto de código associado ao objeto função op.
PyObject *PyFunction_GetGlobals(PyObject *op)
Return value: Borrowed reference. Retorna o dicionário global associado ao objeto função op.
PyObject *PyFunction_GetModule(PyObject *op)
Return value: Borrowed reference. Retorna uma referência emprestada para o atributo __module__ do objeto
função op. Pode ser NULL.
Esta é normalmente uma string contendo o nome do módulo, mas pode ser configurada para qualquer outro
objeto pelo código Python.

8.5. Objetos Função 145


The Python/C API, Release 3.10.6

PyObject *PyFunction_GetDefaults(PyObject *op)


Return value: Borrowed reference. Retorna o argumento os valores padrão do objeto função op. Isso pode ser
uma tupla de argumentos ou NULL.
int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
Define o argumento valores padrão para o objeto função op. defaults deve ser Py_None ou uma tupla.
Levanta SystemError e retorna -1 em falha.
PyObject *PyFunction_GetClosure(PyObject *op)
Return value: Borrowed reference. Retorna o fechamento associado ao objeto função op. Isso pode ser NULL
ou uma tupla de objetos de 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 falha.
PyObject *PyFunction_GetAnnotations(PyObject *op)
Return value: Borrowed reference. 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 falha.

8.5.2 Objetos de Método de Instância

Um método de instância é um wrapper para um PyCFunction e a nova maneira de vincular um PyCFunction


a um objeto de 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 progra-
mas 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)
Return value: New reference. Return a new instance method object, with func being any callable object. func
is the function that will be called when the instance method is called.
PyObject *PyInstanceMethod_Function(PyObject *im)
Return value: Borrowed reference. Retorna o objeto função associado ao método de instância im.
PyObject *PyInstanceMethod_GET_FUNCTION(PyObject *im)
Return value: Borrowed reference. 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.

146 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

PyObject *PyMethod_New(PyObject *func, PyObject *self)


Return value: New reference. 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)
Return value: Borrowed reference. Retorna o objeto função associado ao método meth.
PyObject *PyMethod_GET_FUNCTION(PyObject *meth)
Return value: Borrowed reference. Versão macro de PyMethod_Function() que evita a verificação de
erros.
PyObject *PyMethod_Self(PyObject *meth)
Return value: Borrowed reference. Retorna a instância associada com o método meth.
PyObject *PyMethod_GET_SELF(PyObject *meth)
Return value: Borrowed reference. 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.
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(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)
Return value: New reference. Cria e retorna um novo objeto célula contendo o valor ob. O parâmetro pode ser
NULL.
PyObject *PyCell_Get(PyObject *cell)
Return value: New reference. Retorna o conteúdo da célula cell.
PyObject *PyCell_GET(PyObject *cell)
Return value: Borrowed reference. 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; se não for um objeto célula, -1 será retornado. Em caso
de sucesso, 0 será retornado.
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. Objetos Função 147


The Python/C API, Release 3.10.6

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 tipo Python code.
int PyCode_Check(PyObject *co)
Retorna verdadeiro se co for um objeto code. Esta função sempre tem sucesso.
int PyCode_GetNumFree(PyCodeObject *co)
Retorna o número de variáveis livres em co.
PyCodeObject *PyCode_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, int firs-
tlineno, PyObject *lnotab)
Return value: New reference. Retorna um novo objeto código. Se você precisa de um objeto código fictício
para criar um quadro, use PyCode_NewEmpty() no caso. Chamar PyCode_New() diretamente pode
vinculá-lo a uma versão precisa do Python, uma vez que a definição do bytecode muda frequentemente.
PyCodeObject *PyCode_NewWithPosOnlyArgs(int argcount, int posonlyargcount, int kwonlyargcount,
int nlocals, int stacksize, int flags, PyObject *code,
PyObject *consts, PyObject *names, PyObject *varna-
mes, PyObject *freevars, PyObject *cellvars, PyObject
*filename, PyObject *name, int firstlineno, PyObject
*lnotab)
Return value: New reference. Semelhante a PyCode_New(), mas com um “posonlyargcount” extra para
argumentos apenas posicionais.
Novo na versão 3.8.
PyCodeObject *PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
Return value: New reference. Retorna um novo objeto código vazio com o nome do arquivo especificado,
o nome da função e o número da primeira linha. É ilegal executar exec() ou eval() no objeto código
resultante.
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 de forma eficiente os números de linha em um objeto código, use a API descrita no PEP 626.

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 wrappers C de conveniência 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.
PyObject *PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char
*encoding, const char *errors, const char *newline, int closefd)
Return value: New reference. Part of the Stable ABI. 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

148 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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)
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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 manipu-
lador fornecido.
O manipulador é uma função do tipo 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 com nenhum argumento.
Novo na versão 3.8.
int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
Part of the Stable ABI. 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.
int PyFile_WriteString(const char *s, PyObject *p)
Part of the Stable ABI. 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. Outros Objetos 149


The Python/C API, Release 3.10.6

8.6.2 Objeto Module

PyTypeObject PyModule_Type
Part of the Stable ABI. This instance of PyTypeObject represents the Python module type. This is exposed
to Python programs as types.ModuleType.
int PyModule_Check(PyObject *p)
Return true if p is a module object, or a subtype of a module object. This function always succeeds.
int PyModule_CheckExact(PyObject *p)
Return true if p is a module object, but not a subtype of PyModule_Type. This function always succeeds.
PyObject *PyModule_NewObject(PyObject *name)
Return value: New reference. Part of the Stable ABI since version 3.7. Return a new module object
with the __name__ attribute set to name. The module’s __name__, __doc__, __package__, and
__loader__ attributes are filled in (all but __name__ are set to None); the caller is responsible for pro-
viding a __file__ attribute.
Novo na versão 3.3.
Alterado na versão 3.4: __package__ and __loader__ are set to None.
PyObject *PyModule_New(const char *name)
Return value: New reference. Part of the Stable ABI. Similar to PyModule_NewObject(), but the name
is a UTF-8 encoded string instead of a Unicode object.
PyObject *PyModule_GetDict(PyObject *module)
Return value: Borrowed reference. Part of the Stable ABI. Return the dictionary object that implements mo-
dule’s namespace; this object is the same as the __dict__ attribute of the module object. If module is not a
module object (or a subtype of a module object), SystemError is raised and NULL is returned.
It is recommended extensions use other PyModule_* and PyObject_* functions rather than directly manipulate
a module’s __dict__.
PyObject *PyModule_GetNameObject(PyObject *module)
Return value: New reference. Part of the Stable ABI since version 3.7. Return module’s __name__ value. If
the module does not provide one, or if it is not a string, SystemError is raised and NULL is returned.
Novo na versão 3.3.
const char *PyModule_GetName(PyObject *module)
Part of the Stable ABI. Similar to PyModule_GetNameObject() but return the name encoded to
'utf-8'.
void *PyModule_GetState(PyObject *module)
Part of the Stable ABI. Return the “state” of the module, that is, a pointer to the block of memory allocated at
module creation time, or NULL. See PyModuleDef.m_size.
PyModuleDef *PyModule_GetDef(PyObject *module)
Part of the Stable ABI. Return a pointer to the PyModuleDef struct from which the module was created, or
NULL if the module wasn’t created from a definition.
PyObject *PyModule_GetFilenameObject(PyObject *module)
Return value: New reference. Part of the Stable ABI. Return the name of the file from which module was loaded
using module’s __file__ attribute. If this is not defined, or if it is not a unicode string, raise SystemError
and return NULL; otherwise return a reference to a Unicode object.
Novo na versão 3.2.
const char *PyModule_GetFilename(PyObject *module)
Part of the Stable ABI. Similar to PyModule_GetFilenameObject() but return the filename encoded
to ‘utf-8’.
Obsoleto desde a versão 3.2: PyModule_GetFilename() raises UnicodeEncodeError on unenco-
dable filenames, use PyModule_GetFilenameObject() instead.

150 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

Initializing C modules

Modules objects are usually created from extension modules (shared libraries which export an initialization function),
or compiled-in modules (where the initialization function is added using PyImport_AppendInittab()). See
building or extending-with-embedding for details.
The initialization function can either pass a module definition instance to PyModule_Create(), and return the
resulting module object, or request “multi-phase initialization” by returning the definition struct itself.
type PyModuleDef
Part of the Stable ABI (including all members). The module definition struct, which holds all information
needed to create a module object. There is usually only one statically initialized variable of this type for each
module.
PyModuleDef_Base m_base
Always initialize this member to PyModuleDef_HEAD_INIT.
const char *m_name
Name for the new module.
const char *m_doc
Docstring for the module; usually a docstring variable created with PyDoc_STRVAR is used.
Py_ssize_t m_size
Module state may be kept in a per-module memory area that can be retrieved with
PyModule_GetState(), rather than in static globals. This makes modules safe for use in
multiple sub-interpreters.
This memory area is allocated based on m_size on module creation, and freed when the module object is
deallocated, after the m_free function has been called, if present.
Setting m_size to -1 means that the module does not support sub-interpreters, because it has global
state.
Setting it to a non-negative value means that the module can be re-initialized and specifies the additional
amount of memory it requires for its state. Non-negative m_size is required for multi-phase initializa-
tion.
See PEP 3121 for more details.
PyMethodDef *m_methods
A pointer to a table of module-level functions, described by PyMethodDef values. Can be NULL if no
functions are present.
PyModuleDef_Slot *m_slots
An array of slot definitions for multi-phase initialization, terminated by a {0, NULL} entry. When
using single-phase initialization, m_slots must be NULL.
Alterado na versão 3.5: Prior to version 3.5, this member was always set to NULL, and was defined as:

inquiry m_reload
traverseproc m_traverse
A traversal function to call during GC traversal of the module object, or NULL if not needed.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Alterado na versão 3.9: No longer called before the module state is allocated.
inquiry m_clear
A clear function to call during GC clearing of the module object, or NULL if not needed.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).

8.6. Outros Objetos 151


The Python/C API, Release 3.10.6

More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Like PyTypeObject.tp_clear, this function is not always called before a module 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 and m_free is called directly.
Alterado na versão 3.9: No longer called before the module state is allocated.
freefunc m_free
A function to call during deallocation of the module object, or NULL if not needed.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Alterado na versão 3.9: No longer called before the module state is allocated.

Single-phase initialization

The module initialization function may create and return the module object directly. This is referred to as “single-
phase initialization”, and uses one of the following two module creation functions:
PyObject *PyModule_Create(PyModuleDef *def)
Return value: New reference. Create a new module object, given the definition in def. This behaves like
PyModule_Create2() with module_api_version set to PYTHON_API_VERSION.
PyObject *PyModule_Create2(PyModuleDef *def, int module_api_version)
Return value: New reference. Part of the Stable ABI. 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.

Nota: Most uses of this function should be using PyModule_Create() instead; only use this if you are
sure you need it.

Before it is returned from in the initialization function, the resulting module object is typically populated using func-
tions like PyModule_AddObjectRef().

Multi-phase initialization

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 cre-
ated, and the execution phase, when it is populated. The distinction is similar to the __new__() and __init__()
methods of classes.
Unlike modules created using single-phase initialization, these modules are not singletons: if the sys.modules entry
is removed and the module is re-imported, a new module object is created, and the old module is subject to normal
garbage collection – as with Python modules. By default, multiple modules created from the same definition should
be independent: changes to one should not affect the others. This means that all state should be specific to the module
object (using e.g. using PyModule_GetState()), or its contents (such as the module’s __dict__ or individual
classes created with PyType_FromSpec()).
All modules created using multi-phase initialization are expected to support sub-interpreters. Making sure multiple
modules are independent is typically enough to achieve this.
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:

152 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

PyObject *PyModuleDef_Init(PyModuleDef *def)


Return value: Borrowed reference. Part of the Stable ABI since version 3.5. Ensures a module definition is a
properly initialized Python object that correctly reports its type and reference count.
Returns def cast to PyObject*, or NULL if an error occurred.
Novo 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
A slot ID, chosen from the available values explained below.
void *value
Value of the slot, whose meaning depends on the slot ID.
Novo na versão 3.5.
The m_slots array must be terminated by a slot with id 0.
The available slot types are:
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.
Multiple Py_mod_create slots may not be specified in one module definition.
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 dynami-
cally 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)
If multiple Py_mod_exec slots are specified, they are processed in the order they appear in the m_slots array.
See PEP 489 for more details on multi-phase initialization.

8.6. Outros Objetos 153


The Python/C API, Release 3.10.6

Low-level module creation functions

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)
Return value: New reference. Create a new module object, given the definition in module and the Mo-
duleSpec spec. This behaves like PyModule_FromDefAndSpec2() with module_api_version set to
PYTHON_API_VERSION.
Novo na versão 3.5.
PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int mo-
dule_api_version)
Return value: New reference. Part of the Stable ABI since version 3.7. Create a new module object, given the
definition in module and the ModuleSpec spec, assuming the API version module_api_version. If that version
does not match the version of the running interpreter, a RuntimeWarning is emitted.

Nota: Most uses of this function should be using PyModule_FromDefAndSpec() instead; only use this
if you are sure you need it.

Novo na versão 3.5.


int PyModule_ExecDef(PyObject *module, PyModuleDef *def)
Part of the Stable ABI since version 3.7. Process any execution slots (Py_mod_exec) given in def.
Novo na versão 3.5.
int PyModule_SetDocString(PyObject *module, const char *docstring)
Part of the Stable ABI since version 3.7. Set the docstring for module to docstring. This function is cal-
led automatically when creating a module from PyModuleDef, using either PyModule_Create or
PyModule_FromDefAndSpec.
Novo na versão 3.5.
int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)
Part of the Stable ABI since version 3.7. Add the functions from the NULL terminated functions array
to module. 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 parameter, 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.
Novo 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)
Part of the Stable ABI since version 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.
Return NULL if value is NULL. It must be called with an exception raised in this case.
Exemplo de uso:

154 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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

The example can also be written without checking explicitly if obj is 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.
Novo na versão 3.10.
int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
Part of the Stable ABI. Similar to PyModule_AddObjectRef(), but steals a reference to value on success
(if it returns 0).
The new PyModule_AddObjectRef() function is 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 decrements the refe-
rence count of value on success.
This means that its return value must be checked, and calling code must Py_DECREF() value manually on
error.

Exemplo de uso:

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

The example can also be written without checking explicitly if obj is NULL:

8.6. Outros Objetos 155


The Python/C API, Release 3.10.6

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

Note that Py_XDECREF() should be used instead of Py_DECREF() in this case, since obj can be NULL.
int PyModule_AddIntConstant(PyObject *module, const char *name, long value)
Part of the Stable ABI. Add an integer constant to module as name. This convenience function can be used
from the module’s initialization function. Return -1 on error, 0 on success.
int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
Part of the Stable ABI. 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 on error, 0 on
success.
int PyModule_AddIntMacro(PyObject *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 on error, 0 on success.
int PyModule_AddStringMacro(PyObject *module, macro)
Add a string constant to module.
int PyModule_AddType(PyObject *module, PyTypeObject *type)
Part of the Stable ABI since version 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 on error, 0 on success.
Novo na versão 3.9.

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)
Return value: Borrowed reference. Part of the Stable ABI. 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)
Part of the Stable ABI since version 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

156 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

import 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.
Return 0 on success or -1 on failure.
Novo na versão 3.3.
int PyState_RemoveModule(PyModuleDef *def)
Part of the Stable ABI since version 3.3. Removes the module object created from def from the interpreter
state. Return 0 on success or -1 on failure.
The caller must hold the GIL.
Novo 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
Part of the Stable ABI. 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(op)
Retorna true se o tipo de op for PySeqIter_Type. Esta função sempre é bem-sucedida.
PyObject *PySeqIter_New(PyObject *seq)
Return value: New reference. Part of the Stable ABI. 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 assi-
natura.
PyTypeObject PyCallIter_Type
Part of the Stable ABI. Objeto de tipo para objetos iteradores retornados por PyCallIter_New() e a forma
de dois argumentos da função embutida iter().
int PyCallIter_Check(op)
Retorna true se o tipo de op for PyCallIter_Type. Esta função sempre é bem-sucedida.
PyObject *PyCallIter_New(PyObject *callable, PyObject *sentinel)
Return value: New reference. Part of the Stable ABI. 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
Part of the Stable ABI. O tipo de objeto para os tipos de descritores embutidos.
PyObject *PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
Return value: New reference. Part of the Stable ABI.

8.6. Outros Objetos 157


The Python/C API, Release 3.10.6

PyObject *PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)


Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrap-
ped)
Return value: New reference.
PyObject *PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
Return value: New reference. Part of the Stable ABI.
int PyDescr_IsData(PyObject *descr)
Retorna 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*)
Return value: New reference. Part of the Stable ABI.

8.6.5 Objetos Slice

PyTypeObject PySlice_Type
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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 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)
Part of the Stable ABI. 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).
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)
Part of the Stable ABI. 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 arma-
zena o comprimento da fatia em slicelength. Índices 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 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) {

// return error
}

substituído por

158 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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


// return error
}
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 é im-
plementado como uma macro usando !PySlice_Unpack e !PySlice_AdjustIndices. Os argumentos start, stop e
step são avaliados mais de uma vez.
Obsoleto 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)
Part of the Stable ABI since version 3.7. Extrai os membros de dados de início, parada e inter-
mediá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 me-
nores que PY_SSIZE_T_MIN para PY_SSIZE_T_MIN, e silenciosamente aumenta os valores de interme-
diário menores que -PY_SSIZE_T_MAX para -PY_SSIZE_T_MAX.
Retorna -1 em caso de erro, 0 em caso de sucesso.
Novo 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)
Part of the Stable ABI since version 3.7. Ajusta os índices de fatias inicial/final presumindo uma sequência do
comprimento especificado. Índices 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.
Novo na versão 3.6.1.

8.6.6 Objeto Ellipsis

PyObject *Py_Ellipsis
O objeto Python Ellipsis. Este objeto não possui métodos. Ele precisa ser tratado como qualquer outro
objeto no que diz respeito às contagens de referências. Como Py_None, é um objeto singleton.

8.6.7 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)
Return value: New reference. Part of the Stable ABI. 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.
PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
Return value: New reference. Part of the Stable ABI since version 3.7. Cria um objeto memoryview usando
mem como o buffer subjacente. flags pode ser um dos seguintes PyBUF_READ ou PyBUF_WRITE.
Novo na versão 3.3.

8.6. Outros Objetos 159


The Python/C API, Release 3.10.6

PyObject *PyMemoryView_FromBuffer(Py_buffer *view)


Return value: New reference. 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)
Return value: New reference. Part of the Stable ABI. 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.
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.
Py_buffer *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.8 Objetos de 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(ob)
Retorna verdadeiro se ob for um objeto referência ou um objeto intermediário. Esta função sempre tem sucesso.
int PyWeakref_CheckRef(ob)
Retorna verdadeiro se ob for um objeto referência. Esta função sempre tem sucesso.
int PyWeakref_CheckProxy(ob)
Retorna verdadeiro se ob for um objeto intermediário. Esta função sempre tem sucesso.
PyObject *PyWeakref_NewRef(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference object for the object ob. This
will always return a new reference, but is not guaranteed to create a new object; an existing reference object
may be returned. The second parameter, callback, can be a callable object that receives notification when ob is
garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback
may also be None or NULL. If ob is not a weakly referencable object, or if callback is not callable, None, or
NULL, this will return NULL and raise TypeError.
PyObject *PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference proxy object for the object ob.
This will always return a new reference, but is not guaranteed to create a new object; an existing proxy object
may be returned. The second parameter, callback, can be a callable object that receives notification when ob is
garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback
may also be None or NULL. If ob is not a weakly referencable object, or if callback is not callable, None, or
NULL, this will return NULL and raise TypeError.
PyObject *PyWeakref_GetObject(PyObject *ref)
Return value: Borrowed reference. Part of the Stable ABI. Retorna o objeto referenciado de uma referência
fraca, ref. Se o referente não estiver mais em tempo real, retorna Py_None.

Nota: This function returns a borrowed reference to the referenced object. This means that you should always
call Py_INCREF() on the object except when it cannot be destroyed before the last usage of the borrowed
reference.

160 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

PyObject *PyWeakref_GET_OBJECT(PyObject *ref)


Return value: Borrowed reference. Semelhante a PyWeakref_GetObject(), mas implementado como
uma macro que não verifica erros.

8.6.9 Capsules

Consulte using-capsules para obter mais informações sobre o uso desses objetos.
Novo 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
Part of the Stable ABI. 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)
Return value: New reference. Part of the Stable ABI. 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().
void *PyCapsule_GetPointer(PyObject *capsule, const char *name)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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.

8.6. Outros Objetos 161


The Python/C API, Release 3.10.6

const char *PyCapsule_GetName(PyObject *capsule)


Part of the Stable ABI. 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)
Part of the Stable ABI. Importa um ponteiro para um objeto C de um atributo capsule em um módulo. O
parâmetro name deve especificar o nome completo do atributo, como em module.attribute. O nome
armazenado na cápsula deve corresponder exatamente a essa sequência. Se no_block for verdadeiro, importa o
módulo sem bloquear (usando PyImport_ImportModuleNoBlock()). Se no_block for falso, importa
o módulo convencionalmente (usando PyImport_ImportModule()).
Retorna o ponteiro interno pointer da cápsula com sucesso. Em caso de falha, define uma exceção e retorna
NULL.
int PyCapsule_IsValid(PyObject *capsule, const char *name)
Part of the Stable ABI. 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á.
int PyCapsule_SetContext(PyObject *capsule, void *context)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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.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.

162 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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)
Return value: New reference. 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)
Return value: New reference. 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

Novo 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)
Return value: New reference. 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

Nota: Alterado na versão 3.7.1: 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:

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

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

Veja bpo-34762 para mais detalhes.

Novo na versão 3.7.


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
PyTypeObject PyContext_Type
O objeto de tipo que representa o tipo de contexto.

8.6. Outros Objetos 163


The Python/C API, Release 3.10.6

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)
Return value: New reference. Cria um novo objeto de contexto vazio. Retorna NULL se um erro ocorreu.
PyObject *PyContext_Copy(PyObject *ctx)
Return value: New reference. Cria uma cópia rasa do objeto de contexto ctx passado. Retorna NULL se um
erro ocorreu.
PyObject *PyContext_CopyCurrent(void)
Return value: New reference. 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)
Return value: New reference. 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.
PyObject *PyContextVar_Set(PyObject *var, PyObject *value)
Return value: New reference. 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
retornou o token foi chamado. Esta função retorna 0 em caso de sucesso e -1 em caso de erro.

164 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

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.
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.
Novo na versão 3.7.
Macros de verificação de tipo:
int PyDate_Check(PyObject *ob)
Retorna true 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.
int PyDate_CheckExact(PyObject *ob)
Retorna true 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 true 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 true 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 true 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 true 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 true se ob é do tipo PyDateTime_DeltaType ou um subtipo de PyDateTime_DeltaType.
ob não deve ser NULL. Esta função sempre tem sucesso.
int PyDelta_CheckExact(PyObject *ob)
Retorna true 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 true se ob é do tipo PyDateTime_TZInfoType ou um subtipo de
PyDateTime_TZInfoType. ob não deve ser NULL. Esta função sempre tem sucesso.
int PyTZInfo_CheckExact(PyObject *ob)
Retorna true 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)
Return value: New reference. 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)
Return value: New reference. Retorna um objeto datetime.datetime com o ano, mês, dia, hora, minuto,
segundo, microssegundo especificados.

8.6. Outros Objetos 165


The Python/C API, Release 3.10.6

PyObject *PyDateTime_FromDateAndTimeAndFold(int year, int month, int day, int hour, int minute,
int second, int usecond, int fold)
Return value: New reference. Retorna um objeto datetime.datetime com o ano, mês, dia, hora, minuto,
segundo, microssegundo e a dobra especificados.
Novo na versão 3.6.
PyObject *PyTime_FromTime(int hour, int minute, int second, int usecond)
Return value: New reference. 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)
Return value: New reference. Retorna um objeto datetime.time com a hora, minuto, segundo, micros-
segundo e a dobra especificados.
Novo na versão 3.6.
PyObject *PyDelta_FromDSU(int days, int seconds, int useconds)
Return value: New reference. 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(PyDateTime_DeltaType *offset)
Return value: New reference. Retorna um objeto datetime.timezone com um deslocamento fixo sem
nome representado pelo argumento offset.
Novo na versão 3.7.
PyObject *PyTimeZone_FromOffsetAndName(PyDateTime_DeltaType *offset, PyUnicode *name)
Return value: New reference. Retorna um objeto datetime.timezone com um deslocamento fixo repre-
sentado pelo argumento offset e com tzname name.
Novo na versão 3.7.
Macros para extrair campos de objetos de data. O argumento deve ser uma instância de PyDateTime_Date, in-
cluindo subclasses (como PyDateTime_DateTime). O argumento não deve ser NULL e o tipo não está marcado:

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 de data e hora. O argumento deve ser uma instância de
PyDateTime_DateTime, incluindo 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)
Return the fold, as an int from 0 through 1.
Novo na versão 3.6.
PyObject *PyDateTime_DATE_GET_TZINFO(PyDateTime_DateTime *o)
Retorna o tzinfo (que pode ser None).

166 Capítulo 8. Camada de Objetos Concretos


The Python/C API, Release 3.10.6

Novo na versão 3.10.


Macros para extrair campos de objetos de tempo. O argumento deve ser uma instância de PyDateTime_Time,
incluindo 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.
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)
Return the fold, as an int from 0 through 1.
Novo na versão 3.6.
PyObject *PyDateTime_TIME_GET_TZINFO(PyDateTime_Time *o)
Retorna o tzinfo (que pode ser None).
Novo na versão 3.10.
Macros para extrair campos de objetos time delta. O argumento deve ser uma instância de PyDateTime_Delta,
incluindo subclasses. O argumento não deve ser NULL, e o tipo não é checado:
int PyDateTime_DELTA_GET_DAYS(PyDateTime_Delta *o)
Retorna o número de dias, como um inteiro de -999999999 a 999999999.
Novo 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.
Novo 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.
Novo na versão 3.3.
Macros para a conveniência de módulos implementando a API de DB:
PyObject *PyDateTime_FromTimestamp(PyObject *args)
Return value: New reference. Cria e retorna um novo objeto datetime.datetime, com uma tupla de
argumentos adequada para passar para datetime.datetime.fromtimestamp().
PyObject *PyDate_FromTimestamp(PyObject *args)
Return value: New reference. Cria e retorna um novo objeto datetime.date, com uma tupla de argumentos
adequada para passar para 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)
Part of the Stable ABI since version 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 automati-
camente e __args__ é definido como (args,). A verificação mínima é feita para os argumentos, então a

8.6. Outros Objetos 167


The Python/C API, Release 3.10.6

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[] = {
// Other methods.
...
{"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS,
,→"See PEP 585"}

...
}

Ver também:
O método de modelo de dados __class_getitem__().
Novo na versão 3.9.
PyTypeObject Py_GenericAliasType
Part of the Stable ABI since version 3.9. O tipo C do objeto retornado por Py_GenericAlias(). Equi-
valente a types.GenericAlias no Python.
Novo na versão 3.9.

168 Capítulo 8. Camada de Objetos Concretos


CAPÍTULO 9

Inicialização, Finalização e Threads

Consulte também Configuração de Inicialização do Python.

9.1 Antes da Inicialização do Python

In an application embedding Python, the Py_Initialize() function must be called before using any other
Python/C API functions; with the exception of a few functions and the global configuration variables.
As seguintes funções podem ser seguramente chamadas antes da inicialização do Python.
• Funções de Configuração
– PyImport_AppendInittab()
– PyImport_ExtendInittab()
– PyInitFrozenExtensions()
– PyMem_SetAllocator()
– PyMem_SetupDebugHooks()
– PyObject_SetArenaAllocator()
– Py_SetPath()
– Py_SetProgramName()
– Py_SetPythonHome()
– Py_SetStandardStreamEncoding()
– PySys_AddWarnOption()
– PySys_AddXOption()
– PySys_ResetWarnOptions()
• Funções Informativas:
– Py_IsInitialized()
– PyMem_GetAllocator()
– PyObject_GetArenaAllocator()

169
The Python/C API, Release 3.10.6

– Py_GetBuildInfo()
– Py_GetCompiler()
– Py_GetCopyright()
– Py_GetPlatform()
– Py_GetVersion()
• Utilitários:
– Py_DecodeLocale()
• Alocadores de memória:
– PyMem_RawMalloc()
– PyMem_RawRealloc()
– PyMem_RawCalloc()
– PyMem_RawFree()

Nota: As seguintes funções não devem ser chamadas antes Py_Initialize(): Py_EncodeLocale(),
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), Py_GetProgramFullPath(),
Py_GetPythonHome(), Py_GetProgramName() e PyEval_InitThreads().

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
Issue a warning when comparing bytes or bytearray with str or bytes with int. Issue an error if
greater or equal to 2.
Defina pela opção -b.
int Py_DebugFlag
Ative a saída de depuração do analisador sintático, (somente para especialistas, dependendo das opções de
compilação).
Configure com a opção -d e a variável de ambiente PYTHONDEBUG.
int Py_DontWriteBytecodeFlag
If set to non-zero, Python won’t try to write .pyc files on the import of source modules.
Set by the -B option and the PYTHONDONTWRITEBYTECODE environment variable.
int Py_FrozenFlag
Suppress error messages when calculating the module search path in Py_GetPath().
Sinalizador privado usado pelos programas _freeze_importlib e frozenmain.
int Py_HashRandomizationFlag
Set to 1 if the PYTHONHASHSEED environment variable is set to a non-empty string.
If the flag is non-zero, read the PYTHONHASHSEED environment variable to initialize the secret hash seed.
int Py_IgnoreEnvironmentFlag
Ignora todas as variáveis de ambiente PYTHON*, por exemplo PYTHONPATH e PYTHONHOME, que pode ser
definido.

170 Capítulo 9. Inicialização, Finalização e Threads


The Python/C API, Release 3.10.6

Defina pelas opções -E e -I.


int Py_InspectFlag
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.
Set by the -i option and the PYTHONINSPECT environment variable.
int Py_InteractiveFlag
Defina pela opção -i.
int Py_IsolatedFlag
Run Python in isolated mode. In isolated mode sys.path contains neither the script’s directory nor the
user’s site-packages directory.
Defina pela opção -I.
Novo na versão 3.4.
int Py_LegacyWindowsFSEncodingFlag
If the flag is non-zero, use the mbcs encoding with replace error handler, instead of the UTF-8 encoding
with surrogatepass error handler, for the filesystem encoding and error handler.
Set to 1 if the PYTHONLEGACYWINDOWSFSENCODING environment variable is set to a non-empty string.
Veja PEP 529 para mais detalhes.
Disponibilidade: Windows.
int Py_LegacyWindowsStdioFlag
If the flag is non-zero, use io.FileIO instead of WindowsConsoleIO for sys standard streams.
Set to 1 if the PYTHONLEGACYWINDOWSSTDIO environment variable is set to a non-empty string.
Veja PEP 528 para mais detalhes.
Disponibilidade: Windows.
int Py_NoSiteFlag
Desabilita a importação do módulo site e as manipulações dependentes do site de sys.path que isso
acarreta. Também desabilita essas manipulações se site for explicitamente importado mais tarde (chame
site.main() se você quiser que eles sejam acionados).
Defina pela opção -S.
int Py_NoUserSiteDirectory
Não adiciona o diretório site-packages de usuário a sys.path.
Set by the -s and -I options, and the PYTHONNOUSERSITE environment variable.
int Py_OptimizeFlag
Set by the -O option and the PYTHONOPTIMIZE environment variable.
int Py_QuietFlag
Não exibe as mensagens de copyright e de versão nem mesmo no modo interativo.
Defina pela opção -q.
Novo na versão 3.2.
int Py_UnbufferedStdioFlag
Force os fluxos stdout e stderr a não serem armazenados em buffer.
Set by the -u option and the PYTHONUNBUFFERED environment variable.
int Py_VerboseFlag
Print a message each time a module is initialized, showing the place (filename or built-in module) from which
it is loaded. If greater 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.
Set by the -v option and the PYTHONVERBOSE environment variable.

9.2. Variáveis de configuração global 171


The Python/C API, Release 3.10.6

9.3 Inicializando e encerrando o interpretador

void Py_Initialize()
Part of the Stable ABI. 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 Before Python Initialization 1 para
algumas exceções.
This initializes the table of loaded modules (sys.modules), and creates the fundamental modules
builtins, __main__ and sys. It also initializes the module search path (sys.path). It does not
set sys.argv; use PySys_SetArgvEx() for that. This is a no-op when called for a second time (without
calling Py_FinalizeEx() first). There is no return value; it is a fatal error if the initialization fails.

Nota: On Windows, changes the console mode from O_TEXT to O_BINARY, which will also affect non-
Python uses of the console using the C Runtime.

void Py_InitializeEx(int initsigs)


Part of the Stable ABI. This function works like Py_Initialize() if initsigs is 1. If initsigs is 0, it skips
initialization registration of signal handlers, which might be useful when Python is embedded.
int Py_IsInitialized()
Part of the Stable ABI. Return true (nonzero) when the Python interpreter has been initialized, false (zero) if
not. After Py_FinalizeEx() is called, this returns false until Py_Initialize() is called again.
int Py_FinalizeEx()
Part of the Stable ABI since version 3.6. Undo all initializations made by Py_Initialize() and sub-
sequent 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 memory allocated by the Python interpreter. This is a no-op when called for a second time (without calling
Py_Initialize() again first). Normally the return value is 0. If there were errors during finalization
(flushing buffered data), -1 is returned.
This function is provided for a number of reasons. An embedding application might want to restart Python
without having to restart the application itself. An application that has loaded the Python interpreter from a
dynamically loadable library (or DLL) might want to free all memory allocated by Python before unloading the
DLL. During a hunt for memory leaks in an application a developer might want to free all memory allocated
by Python before exiting from the application.
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 mo-
dules. Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory
allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in
circular references between objects is not freed. Some memory allocated by extension modules may not be
freed. Some extensions may not work properly if their initialization routine is called more than once; this can
happen if an application calls Py_Initialize() and Py_FinalizeEx() more than once.
Raises an auditing event cpython._PySys_ClearAuditHooks with no arguments.
Novo na versão 3.6.
void Py_Finalize()
Part of the Stable ABI. This is a backwards-compatible version of Py_FinalizeEx() that disregards the
return value.

172 Capítulo 9. Inicialização, Finalização e Threads


The Python/C API, Release 3.10.6

9.4 Process-wide parameters

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


This function should be called before Py_Initialize(), if it is called at all. It specifies which encoding
and error handling to use with standard IO, with the same meanings as in str.encode().
It overrides PYTHONIOENCODING values, and allows embedding code to control IO encoding when the
environment variable does not work.
encoding and/or errors may be NULL to use PYTHONIOENCODING and/or default values (depending on other
settings).
Note that sys.stderr always uses the “backslashreplace” error handler, regardless of this (or any other)
setting.
If Py_FinalizeEx() is called, this function will need to be called again in order to affect subsequent calls
to Py_Initialize().
Returns 0 if successful, a nonzero value on error (e.g. calling after the interpreter has already been initialized).
Novo na versão 3.4.
void Py_SetProgramName(const wchar_t *name)
Part of the Stable ABI. Esta função deve ser chamada antes de Py_Initialize() ser chamada pela pri-
meira 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.
Utiliza Py_DecodeLocale() para decodificar uma string de bytes para obter uma string tipo wchar_*.
wchar *Py_GetProgramName()
Part of the Stable ABI. Return the program name set with Py_SetProgramName(), 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().
wchar_t *Py_GetPrefix()
Part of the Stable ABI. Return the prefix for installed platform-independent files. This is derived through a
number of complicated rules from the program name set with Py_SetProgramName() and some environ-
ment variables; for example, if the program name is '/usr/local/bin/python', the prefix is '/usr/
local'. The returned string points into static storage; the caller should not modify its value. This corresponds
to the prefix variable in the top-level Makefile and the --prefix argument to the configure script
at build time. The value is available to Python code as sys.prefix. It is only useful on Unix. See also the
next function.
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().
wchar_t *Py_GetExecPrefix()
Part of the Stable ABI. Return the exec-prefix for installed platform-dependent files. This is derived through
a number of complicated rules from the program name set with Py_SetProgramName() and some envi-
ronment variables; for example, if the program name is '/usr/local/bin/python', the exec-prefix is
'/usr/local'. The returned string points into static storage; the caller should not modify its value. This
corresponds to the exec_prefix variable in the top-level Makefile and the --exec-prefix argu-
ment to the configure script at build time. The value is available to Python code as sys.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

9.4. Process-wide parameters 173


The Python/C API, Release 3.10.6

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().
wchar_t *Py_GetProgramFullPath()
Part of the Stable ABI. Return the full program name of the Python executable; this is computed as a side-
effect of deriving the default module search path from the program name (set by Py_SetProgramName()
above). 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().
wchar_t *Py_GetPath()
Part of the Stable ABI. Return the default module search path; this is computed from the program name (set by
Py_SetProgramName() above) 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().
void Py_SetPath(const wchar_t*)
Part of the Stable ABI since version 3.7. Set the default module search path. If this function is called before
Py_Initialize(), then Py_GetPath() won’t attempt to compute a default search path but uses the one
provided instead. This is useful if Python is embedded by an application that has full knowledge of the location
of all modules. The path components should be separated by the platform dependent delimiter character, which
is ':' on Unix and macOS, ';' on Windows.
This also causes sys.executable to be set to the program full path (see
Py_GetProgramFullPath()) and for sys.prefix and sys.exec_prefix to be empty. It
is up to the caller to modify these if required after calling Py_Initialize().
Utiliza Py_DecodeLocale() para decodificar uma string de bytes para obter uma string tipo wchar_*.
O argumento caminho é copiado internamente, então o chamador pode liberá-lo depois da finalização da cha-
mada.
Alterado na versão 3.8: O caminho completo do programa agora é utilizado para sys.executable, em
vez do nome do programa.
const char *Py_GetVersion()
Part of the Stable ABI. 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]"

174 Capítulo 9. Inicialização, Finalização e Threads


The Python/C API, Release 3.10.6

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.
const char *Py_GetPlatform()
Part of the Stable ABI. 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()
Part of the Stable ABI. 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()
Part of the Stable ABI. 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()
Part of the Stable ABI. 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)
Part of the Stable ABI. 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 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. 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 (".").
Utiliza Py_DecodeLocale() para decodificar uma string de bytes para obter uma string tipo wchar_*.

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:
PyRun_SimpleString("import sys; sys.path.pop(0)\n");

Novo na versão 3.1.3.

9.4. Process-wide parameters 175


The Python/C API, Release 3.10.6

void PySys_SetArgv(int argc, wchar_t **argv)


Part of the Stable ABI. This function works like PySys_SetArgvEx() with updatepath set to 1 unless the
python interpreter was started with the -I.
Utiliza Py_DecodeLocale() para decodificar uma string de bytes para obter uma string tipo wchar_*.
Alterado na versão 3.4: The updatepath value depends on -I.
void Py_SetPythonHome(const wchar_t *home)
Part of the Stable ABI. 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.
Utiliza Py_DecodeLocale() para decodificar uma string de bytes para obter uma string tipo wchar_*.
w_char *Py_GetPythonHome()
Part of the Stable ABI. Return the default “home”, that is, the value set by a previous call to
Py_SetPythonHome(), 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().

9.5 Thread State and the Global Interpreter Lock

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.
Therefore, the rule exists that only the thread that has acquired the GIL may operate on Python objects or call Python/C
API functions. In order to emulate concurrency of execution, the interpreter regularly tries to switch threads (see
sys.setswitchinterval()). The lock is also released around potentially blocking I/O operations like reading
or writing a file, so that other Python threads can run in the meantime.
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 retri-
eved using PyThreadState_Get().

9.5.1 Releasing the GIL from extension code

A maioria dos códigos de extensão que manipulam o 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.

This is so common that a pair of macros exists to simplify it:

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

The Py_BEGIN_ALLOW_THREADS macro opens a new block and declares a hidden local variable; the
Py_END_ALLOW_THREADS macro closes the block.

176 Capítulo 9. Inicialização, Finalização e Threads


The Python/C API, Release 3.10.6

The block above expands to the following code:

PyThreadState *_save;

_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
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 cryptographic
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();

/* 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 auto-
matically 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. Thread State and the Global Interpreter Lock 177


The Python/C API, Release 3.10.6

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 inter-
preter 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 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
Part of the Limited API (as an opaque struct). This data structure represents the state shared by a number 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
Part of the Limited API (as an opaque struct). Esta estrutura de dados representa o estado de uma tarefa. O
único membro de dados público é interp (PyInterpreterState*), que aponta para o estado do interpretador
desta tarefa.
void PyEval_InitThreads()
Part of the Stable ABI. Deprecated function which does nothing.
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 necessi-
dade de você chamá-la.
Alterado na versão 3.2: Esta função não pode mais ser chamada antes de Py_Initialize().
Deprecated since version 3.9, will be removed in version 3.11.
int PyEval_ThreadsInitialized()
Part of the Stable ABI. Returns a non-zero value if PyEval_InitThreads() has been called. This func-
tion can be called without holding the GIL, and therefore can be used to avoid calls to the locking API when
running single-threaded.
Alterado na versão 3.7: The GIL is now initialized by Py_Initialize().
Deprecated since version 3.9, will be removed in version 3.11.

178 Capítulo 9. Inicialização, Finalização e Threads


The Python/C API, Release 3.10.6

PyThreadState *PyEval_SaveThread()
Part of the Stable ABI. 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)
Part of the Stable ABI. 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 terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing()
to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termi-
nation.

PyThreadState *PyThreadState_Get()
Part of the Stable ABI. 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).
PyThreadState *PyThreadState_Swap(PyThreadState *tstate)
Part of the Stable ABI. Swap the current thread state with the thread state given by the argument tstate, which
may be NULL. The global interpreter lock must be held and is not released.
The following functions use thread-local storage, and are not compatible with sub-interpreters:
PyGILState_STATE PyGILState_Ensure()
Part of the Stable ABI. Ensure that the current thread is ready to call the Python C API regardless of the
current state of Python, or of the global interpreter lock. This may be called as many times as desired by a
thread as long as each call is matched with a call to PyGILState_Release(). In general, other thread-
related APIs may be used between PyGILState_Ensure() and PyGILState_Release() calls as
long as the thread state is restored to its previous state before the Release(). For example, normal usage of the
Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros is acceptable.
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 terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing()
to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termi-
nation.

void PyGILState_Release(PyGILState_STATE)
Part of the Stable ABI. 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()
Part of the Stable ABI. 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

9.5. Thread State and the Global Interpreter Lock 179


The Python/C API, Release 3.10.6

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.
Novo 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
Part of the Stable ABI. This macro expands to { PyThreadState *_save; _save =
PyEval_SaveThread();. Note that it contains an opening brace; it must be matched with a fol-
lowing Py_END_ALLOW_THREADS macro. See above for further discussion of this macro.
Py_END_ALLOW_THREADS
Part of the Stable ABI. This macro expands to PyEval_RestoreThread(_save); }. Note that it
contains a closing brace; it must be matched with an earlier Py_BEGIN_ALLOW_THREADS macro. See
above for further discussion of this macro.
Py_BLOCK_THREADS
Part of the Stable ABI. This macro expands to PyEval_RestoreThread(_save);: it is equivalent to
Py_END_ALLOW_THREADS without the closing brace.
Py_UNBLOCK_THREADS
Part of the Stable ABI. This macro expands to _save = PyEval_SaveThread();: it is equivalent to
Py_BEGIN_ALLOW_THREADS without the opening brace and variable declaration.

9.5.5 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()
Part of the Stable ABI. 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.
Raises an auditing event cpython.PyInterpreterState_New with no arguments.
void PyInterpreterState_Clear(PyInterpreterState *interp)
Part of the Stable ABI. Reset all information in an interpreter state object. The global interpreter lock must be
held.
Raises an auditing event cpython.PyInterpreterState_Clear with no arguments.
void PyInterpreterState_Delete(PyInterpreterState *interp)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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().
void PyThreadState_Delete(PyThreadState *tstate)
Part of the Stable ABI. 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().

180 Capítulo 9. Inicialização, Finalização e Threads


The Python/C API, Release 3.10.6

void PyThreadState_DeleteCurrent(void)
Destroy the current thread state and release the global interpreter lock. Like PyThreadState_Delete(),
the global interpreter lock need not be held. The thread state must have been reset with a previous call to
PyThreadState_Clear().
PyFrameObject *PyThreadState_GetFrame(PyThreadState *tstate)
Part of the Stable ABI since version 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.
Novo na versão 3.9.
uint64_t PyThreadState_GetID(PyThreadState *tstate)
Part of the Stable ABI since version 3.10. Get the unique thread state identifier of the Python thread state tstate.
tstate must not be NULL.
Novo na versão 3.9.
PyInterpreterState *PyThreadState_GetInterpreter(PyThreadState *tstate)
Part of the Stable ABI since version 3.10. Get the interpreter of the Python thread state tstate.
tstate must not be NULL.
Novo na versão 3.9.
PyInterpreterState *PyInterpreterState_Get(void)
Part of the Stable ABI since version 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.
Novo na versão 3.9.
int64_t PyInterpreterState_GetID(PyInterpreterState *interp)
Part of the Stable ABI since version 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.
Novo na versão 3.7.
PyObject *PyInterpreterState_GetDict(PyInterpreterState *interp)
Part of the Stable ABI since version 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.
Novo na versão 3.8.
typedef PyObject *(*_PyFrameEvalFunction)(PyThreadState *tstate, PyFrameObject *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
exception.
Alterado na versão 3.9: The function now takes a tstate parameter.
_PyFrameEvalFunction _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
Get the frame evaluation function.
See the PEP 523 “Adding a frame evaluation API to CPython”.
Novo na versão 3.9.

9.5. Thread State and the Global Interpreter Lock 181


The Python/C API, Release 3.10.6

void _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp, _PyFrameEvalFunc-


tion eval_frame)
Set the frame evaluation function.
See the PEP 523 “Adding a frame evaluation API to CPython”.
Novo na versão 3.9.
PyObject *PyThreadState_GetDict()
Return value: Borrowed reference. Part of the Stable ABI. 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)
Part of the Stable ABI. Asynchronously raise an exception in a thread. The id argument is the thread id of
the target thread; exc is the exception object to be raised. This function does not steal any references to exc.
To prevent naive misuse, you must write your own C extension to call this. Must be called with the GIL held.
Returns the number of thread states modified; this is normally one, but will be zero if the thread id isn’t found.
If exc is NULL, the pending exception (if any) for the thread is cleared. This raises no exceptions.
Alterado na versão 3.7: The type of the id parameter changed from long to unsigned long.
void PyEval_AcquireThread(PyThreadState *tstate)
Part of the Stable ABI. 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 terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing()
to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termi-
nation.

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 called while the interpreter is finalizing.
PyEval_RestoreThread() is a higher-level function which is always available (even when threads have
not been initialized).
void PyEval_ReleaseThread(PyThreadState *tstate)
Part of the Stable ABI. 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).
void PyEval_AcquireLock()
Part of the Stable ABI. Acquire the global interpreter lock. The lock must have been created earlier. If this
thread already has the lock, a deadlock ensues.
Obsoleto desde a versão 3.2: This function does not update the current thread state. Please use
PyEval_RestoreThread() or PyEval_AcquireThread() instead.

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

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 called while the interpreter is finalizing.

182 Capítulo 9. Inicialização, Finalização e Threads


The Python/C API, Release 3.10.6

void PyEval_ReleaseLock()
Part of the Stable ABI. Release the global interpreter lock. The lock must have been created earlier.
Obsoleto desde a versão 3.2: This function does not update the current thread state. Please use
PyEval_SaveThread() or PyEval_ReleaseThread() instead.

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 des-
troy them using the following functions:
PyThreadState *Py_NewInterpreter()
Part of the Stable ABI. 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 return value points 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, NULL is returned; 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;
however, unlike most other Python/C API functions, there needn’t be a current thread state on entry.)
Extension modules are shared between (sub-)interpreters as follows:
• For modules using multi-phase initialization, e.g. PyModule_FromDefAndSpec(), a separate mo-
dule 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
extension is imported, it is initialized normally, and a (shallow) copy of its module’s dictionary is squirre-
led 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.
void Py_EndInterpreter(PyThreadState *tstate)
Part of the Stable ABI. Destroy the (sub-)interpreter represented by the given thread state. The given thread
state must be the current thread state. See the discussion of thread states below. When the call returns, the
current thread state is NULL. All thread states associated with this interpreter are destroyed. (The global inter-
preter lock must be held before calling this function and is still held when it returns.) Py_FinalizeEx()
will destroy all sub-interpreters that haven’t been explicitly destroyed at that point.

9.6. Sub-interpreter support 183


The Python/C API, Release 3.10.6

9.6.1 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
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 bijec-
tion 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 cal-
ling of Python code from non-Python created threads will probably be broken when using sub-interpreters.

9.7 Asynchronous Notifications

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 Part of the Stable ABI. 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.

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.
Novo na versão 3.1.

184 Capítulo 9. Inicialização, Finalização e Threads


The Python/C API, Release 3.10.6

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
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 object to which the
event pertains, what is one of the constants PyTrace_CALL, PyTrace_EXCEPTION, PyTrace_LINE,
PyTrace_RETURN, PyTrace_C_CALL, PyTrace_C_EXCEPTION, PyTrace_C_RETURN, or
PyTrace_OPCODE, and arg depends on the value of what:

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
opcode is about to be executed. This event is not emitted by default: it must be explicitly requested by setting
f_trace_opcodes to 1 on the frame.

9.8. Profiling and Tracing 185


The Python/C API, Release 3.10.6

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.
The caller must hold the GIL.
void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
Set the tracing function to func. This is similar to PyEval_SetProfile(), except the tracing func-
tion 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 para-
meter.
The caller must hold the GIL.

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

186 Capítulo 9. Inicialização, Finalização e Threads


The Python/C API, Release 3.10.6

9.10.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.
Novo na versão 3.7.
Ver também:
“A New C-API for Thread-Local Storage in CPython” (PEP 539)
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.
When Py_LIMITED_API is not defined, static allocation of this type by Py_tss_NEEDS_INIT is allowed.
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.

Dynamic Allocation

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()
Part of the Stable ABI since version 3.7. Return a value which is the same state as a value initialized with
Py_tss_NEEDS_INIT, or NULL in the case of dynamic allocation failure.
void PyThread_tss_free(Py_tss_t *key)
Part of the Stable ABI since version 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)
Part of the Stable ABI since version 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)
Part of the Stable ABI since version 3.7. Return a zero value on successful initialization of a TSS key. The
behavior is undefined if the value pointed to by the key argument is not initialized by Py_tss_NEEDS_INIT.
This function can be called repeatedly on the same key – calling it on an already initialized key is a no-op and
immediately returns success.
void PyThread_tss_delete(Py_tss_t *key)
Part of the Stable ABI since version 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.

9.10. Thread Local Storage Support 187


The Python/C API, Release 3.10.6

int PyThread_tss_set(Py_tss_t *key, void *value)


Part of the Stable ABI since version 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)
Part of the Stable ABI since version 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.

9.10.2 Thread Local Storage (TLS) API

Obsoleto 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()
Part of the Stable ABI.
void PyThread_delete_key(int key)
Part of the Stable ABI.
int PyThread_set_key_value(int key, void *value)
Part of the Stable ABI.
void *PyThread_get_key_value(int key)
Part of the Stable ABI.
void PyThread_delete_key_value(int key)
Part of the Stable ABI.
void PyThread_ReInitTLS()
Part of the Stable ABI.

188 Capítulo 9. Inicialização, Finalização e Threads


CAPÍTULO 10

Configuração de Inicialização do Python

Novo na versão 3.8.


Python can be initialized with Py_InitializeFromConfig() and the PyConfig structure. It can be prei-
nitialized with Py_PreInitialize() and the PyPreConfig structure.
There are two kinds of configuration:
• The Python Configuration can be used to build a customized Python which behaves as the regular Python. For
example, environment variables and command line arguments are used to configure Python.
• The Isolated Configuration can be used to embed Python into an application. It isolates Python from the system.
For example, environment variables are ignored, the LC_CTYPE locale is left unchanged and no signal handler
is registered.
The Py_RunMain() function can be used to write a customized Python program.
Veja também Inicialização, Finalização e Threads.
Ver também:
PEP 587 “Configuração da inicialização do Python”.

10.1 Exemplo

Example of customized Python always running in isolated mode:

int main(int argc, char **argv)


{
PyStatus status;

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

/* Decode command line arguments.


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

189
The Python/C API, Release 3.10.6

(continuação da página anterior)


}

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

return Py_RunMain();

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

10.2 PyWideStringList
type PyWideStringList
Lista de 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.

190 Capítulo 10. Configuração de Inicialização do Python


The Python/C API, Release 3.10.6

10.3 PyStatus
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 must not be 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();
}
return PyStatus_Ok();
}

(continua na próxima página)

10.3. PyStatus 191


The Python/C API, Release 3.10.6

(continuação da página anterior)


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
Structure used to preinitialize 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
Name of the Python memory allocators:
• PYMEM_ALLOCATOR_NOT_SET (0): don’t change memory allocators (use defaults).
• PYMEM_ALLOCATOR_DEFAULT (1): default memory allocators.
• PYMEM_ALLOCATOR_DEBUG (2): default memory allocators with debug hooks.
• PYMEM_ALLOCATOR_MALLOC (3): use malloc() of the C library.
• PYMEM_ALLOCATOR_MALLOC_DEBUG (4): force usage of malloc() with debug hooks.
• PYMEM_ALLOCATOR_PYMALLOC (5): Python pymalloc memory allocator.
• PYMEM_ALLOCATOR_PYMALLOC_DEBUG (6): Python pymalloc memory allocator with debug
hooks.
PYMEM_ALLOCATOR_PYMALLOC and PYMEM_ALLOCATOR_PYMALLOC_DEBUG are not suppor-
ted if Python is configured using --without-pymalloc.
Veja Gerenciamento de memória.
Default: PYMEM_ALLOCATOR_NOT_SET.
int configure_locale
Set the LC_CTYPE locale to the user preferred locale?
If equals to 0, set coerce_c_locale and coerce_c_locale_warn members to 0.
See the locale encoding.
Default: 1 in Python config, 0 in isolated config.
int coerce_c_locale
If equals to 2, coerce the C locale.
If equals to 1, read the LC_CTYPE locale to decide if it should be coerced.
See the locale encoding.

192 Capítulo 10. Configuração de Inicialização do Python


The Python/C API, Release 3.10.6

Default: -1 in Python config, 0 in isolated config.


int coerce_c_locale_warn
Se diferente de zero, emite um aviso se a localidade C for forçada.
Default: -1 in Python config, 0 in isolated config.
int dev_mode
If non-zero, enables the Python Development Mode: see PyConfig.dev_mode.
Default: -1 in Python mode, 0 in isolated mode.
int isolated
Isolated mode: see PyConfig.isolated.
Default: 0 in Python mode, 1 in isolated mode.
int legacy_windows_fs_encoding
If non-zero:
• Set PyPreConfig.utf8_mode to 0,
• Set PyConfig.filesystem_encoding to "mbcs",
• Set PyConfig.filesystem_errors to "replace".
Initialized the from PYTHONLEGACYWINDOWSFSENCODING environment variable value.
Disponível apenas no Windows. A macro #ifdef MS_WINDOWS pode ser usada para código especí-
fico do Windows.
Default: 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: vej Argumentos de linha de comando.
Default: 1 in Python config, 0 in isolated config.
int use_environment
Use environment variables? See PyConfig.use_environment.
Default: 1 in Python config and 0 in isolated config.
int utf8_mode
If non-zero, enable the Python UTF-8 Mode.
Set by the -X utf8 command line option and the PYTHONUTF8 environment variable.
Default: -1 in Python config and 0 in isolated config.

10.5 Preinitialize Python with PyPreConfig

The preinitialization of Python:


• Set the Python memory allocators (PyPreConfig.allocator)
• Configure the LC_CTYPE locale (locale encoding)
• Set the Python UTF-8 Mode (PyPreConfig.utf8_mode)
The current preconfiguration (PyPreConfig type) is stored in _PyRuntime.preconfig.
Functions to preinitialize Python:
PyStatus Py_PreInitialize(const PyPreConfig *preconfig)
Preinitialize Python from preconfig preconfiguration.
preconfig must not be NULL.

10.5. Preinitialize Python with PyPreConfig 193


The Python/C API, Release 3.10.6

PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char


*const *argv)
Preinitialize Python from preconfig preconfiguration.
Parse argv command line arguments (bytes strings) if parse_argv of preconfig is non-zero.
preconfig must not be NULL.
PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t *const
*argv)
Preinitialize Python from preconfig preconfiguration.
Parse argv command line arguments (wide strings) if parse_argv of preconfig is non-zero.
preconfig must not be NULL.
The caller is responsible to handle exceptions (error or exit) using PyStatus_Exception() and
Py_ExitStatusException().
For Python Configuration (PyPreConfig_InitPythonConfig()), if Python is initialized with command line
arguments, the command line arguments must also be passed to preinitialize Python, since they have an effect on the
pre-configuration like encodings. For example, the -X utf8 command line option enables the Python UTF-8 Mode.
PyMem_SetAllocator() can be called after Py_PreInitialize() and before
Py_InitializeFromConfig() to install a custom memory allocator. It can be called before
Py_PreInitialize() if PyPreConfig.allocator is set to PYMEM_ALLOCATOR_NOT_SET.
Python memory allocation functions like PyMem_RawMalloc() must not be used before the Python preinitializa-
tion, whereas calling directly malloc() and free() is always safe. Py_DecodeLocale() must not be called
before the Python preinitialization.
Example using the preinitialization to enable the Python UTF-8 Mode:

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

preconfig.utf8_mode = 1;

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

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

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

10.6 PyConfig
type PyConfig
Structure containing most parameters to configure Python.
When done, the PyConfig_Clear() function must be used to release the configuration memory.
Structure methods:
void PyConfig_InitPythonConfig(PyConfig *config)
Initialize configuration with the Python Configuration.
void PyConfig_InitIsolatedConfig(PyConfig *config)
Initialize configuration with the Isolated Configuration.

194 Capítulo 10. Configuração de Inicialização do Python


The Python/C API, Release 3.10.6

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.
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 strippped 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.
void PyConfig_Clear(PyConfig *config)
Release configuration memory.
Most PyConfig methods preinitialize Python if needed. In that case, the Python preinitialization confi-
guration (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
called 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
Command line arguments: sys.argv.

10.6. PyConfig 195


The Python/C API, Release 3.10.6

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.
Default: NULL.
See also the orig_argv member.
wchar_t *base_exec_prefix
sys.base_exec_prefix.
Default: NULL.
Part of the Python Path Configuration output.
wchar_t *base_executable
Python base executable: sys._base_executable.
Set by the __PYVENV_LAUNCHER__ environment variable.
Set from PyConfig.executable if NULL.
Default: NULL.
Part of the Python Path Configuration output.
wchar_t *base_prefix
sys.base_prefix.
Default: NULL.
Part of the Python Path Configuration output.
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.
Default: 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.
Default: 0.
int warn_default_encoding
If non-zero, emit a EncodingWarning warning when io.TextIOWrapper uses its default enco-
ding. See io-encoding-warning for details.
Default: 0.
Novo na versão 3.10.
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.
Valid values:
• 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.
• L"default": The ‘check_source’ flag in hash-based pycs determines invalidation.

196 Capítulo 10. Configuração de Inicialização do Python


The Python/C API, Release 3.10.6

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 Win-
dows).
Default: 1 in Python config, 0 in isolated config.
int dev_mode
If non-zero, enable the Python Development Mode.
Default: -1 in Python mode, 0 in isolated mode.
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.
Need a special build of Python with the Py_TRACE_REFS macro defined: see the configure
--with-trace-refs option.
Default: 0.
wchar_t *exec_prefix
The site-specific directory prefix where the platform-dependent Python files are installed: sys.
exec_prefix.
Default: NULL.
Part of the Python Path Configuration output.
wchar_t *executable
The absolute path of the executable binary for the Python interpreter: sys.executable.
Default: NULL.
Part of the Python Path Configuration output.
int faulthandler
Enable faulthandler?
If non-zero, call faulthandler.enable() at startup.
Set to 1 by -X faulthandler and the PYTHONFAULTHANDLER environment variable.
Default: -1 in Python mode, 0 in isolated mode.
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.
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,
whereas the mbstowcs() function decodes from a different encoding (usually Latin1).
• "utf-8" if nl_langinfo(CODESET) returns an empty string.

10.6. PyConfig 197


The Python/C API, Release 3.10.6

• 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
Python home directory.
If Py_SetPythonHome() has been called, use its argument if it is not NULL.
Set by the PYTHONHOME environment variable.
Default: 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.
Default: 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.
Default: 0.
int install_signal_handlers
Install Python signal handlers?
Default: 1 in Python mode, 0 in isolated mode.

198 Capítulo 10. Configuração de Inicialização do Python


The Python/C API, Release 3.10.6

int interactive
If greater than 0, enable the interactive mode (REPL).
Incremented by the -i command line option.
Default: 0.
int isolated
If greater than 0, enable isolated mode:
• sys.path contains neither the script’s directory (computed from argv[0] or the current direc-
tory) nor the user’s site-packages directory.
• Python REPL doesn’t import readline nor enable default readline configuration on interactive
prompts.
• Set use_environment and user_site_directory to 0.
Default: 0 in Python mode, 1 in isolated mode.
See also PyPreConfig.isolated.
int legacy_windows_stdio
If non-zero, use io.FileIO instead of io.WindowsConsoleIO for sys.stdin, sys.stdout
and sys.stderr.
Set to 1 if the PYTHONLEGACYWINDOWSSTDIO environment variable is set to a non-empty string.
Disponível apenas no Windows. A macro #ifdef MS_WINDOWS pode ser usada para código especí-
fico do Windows.
Default: 0.
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.
Default: 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").
Part of the Python Path Configuration input.
Novo na versão 3.9.
wchar_t *pythonpath_env
Module search paths (sys.path) as a string separated by DELIM (os.path.pathsep).
Set by the PYTHONPATH environment variable.
Default: 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, the function calculating the Python Path Configuration
overrides the module_search_paths and sets module_search_paths_set to 1.

10.6. PyConfig 199


The Python/C API, Release 3.10.6

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.
Default: 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.
Default: empty list.
Novo na versão 3.10.
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 strippped 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.
Default: 0.
int pathconfig_warnings
On Unix, if non-zero, calculating the Python Path Configuration can log warnings into stderr. If equals
to 0, suppress these warnings.
It has no effect on Windows.
Default: 1 in Python mode, 0 in isolated mode.
Part of the Python Path Configuration input.
wchar_t *prefix
The site-specific directory prefix where the platform independent Python files are installed: sys.
prefix.
Default: NULL.
Part of the Python Path Configuration output.

200 Capítulo 10. Configuração de Inicialização do Python


The Python/C API, Release 3.10.6

wchar_t *program_name
Program name used to initialize executable and in early error messages during Python initialization.
• If Py_SetProgramName() has been called, use its argument.
• On macOS, use PYTHONEXECUTABLE environment variable if set.
• If the WITH_NEXT_FRAMEWORK macro is defined, use __PYVENV_LAUNCHER__ environment
variable if set.
• Use argv[0] of argv if available and non-empty.
• Otherwise, use L"python" on Windows, or L"python3" on other platforms.
Default: 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
environment variable.
If NULL, sys.pycache_prefix is set to None.
Default: NULL.
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.
Default: 0.
wchar_t *run_command
Value of the -c command line option.
Used by Py_RunMain().
Default: NULL.
wchar_t *run_filename
Filename passed on the command line: trailing command line argument without -c or -m.
For example, it is set to script.py by the python3 script.py arg command.
Used by Py_RunMain().
Default: NULL.
wchar_t *run_module
Value of the -m command line option.
Used by Py_RunMain().
Default: NULL.
int show_ref_count
Show total reference count at exit?
Set to 1 by -X showrefcount command line option.
Need a debug build of Python (the Py_REF_DEBUG macro must be defined).
Default: 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.

10.6. PyConfig 201


The Python/C API, Release 3.10.6

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.
Default: 1.
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.
Default: 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).
If Py_SetStandardStreamEncoding() has been called, use its error and errors arguments if
they are not NULL.
Use the PYTHONIOENCODING environment variable if it is non-empty.
Default encoding:
• "UTF-8" if PyPreConfig.utf8_mode is non-zero.
• Otherwise, use the locale encoding.
Default error handler:
• On Windows: use "surrogateescape".
• "surrogateescape" if PyPreConfig.utf8_mode is non-zero, or if the LC_CTYPE lo-
cale is “C” or “POSIX”.
• "strict" otherwise.
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
variable.
Default: -1 in Python mode, 0 in isolated mode.
int use_environment
Use environment variables?
If equals to zero, ignore the environment variables.
Default: 1 in Python config and 0 in isolated config.
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.

202 Capítulo 10. Configuração de Inicialização do Python


The Python/C API, Release 3.10.6

If greater 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 to the PYTHONVERBOSE environment variable value.
Default: 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 (,).
Default: empty list.
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 varia-
ble.
sys.dont_write_bytecode is initialized to the inverted value of write_bytecode.
Default: 1.
PyWideStringList xoptions
Values of the -X command line options: sys._xoptions.
Default: empty list.
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

Function to initialize Python:


PyStatus Py_InitializeFromConfig(const PyConfig *config)
Initialize Python from config configuration.
The caller is responsible to handle exceptions (error or exit) using PyStatus_Exception() and
Py_ExitStatusException().
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 initialized 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:

10.7. Initialization with PyConfig 203


The Python/C API, Release 3.10.6

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:
PyStatus init_python(const char *program_name)
{
PyStatus status;

PyConfig config;
PyConfig_InitPythonConfig(&config);

/* Set the program name before reading the configuration


(decode byte string from the locale encoding).

Implicitly preinitialize Python. */


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

/* Read all configuration at once */


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

/* Append our custom search path to sys.path */


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");
(continua na próxima página)

204 Capítulo 10. Configuração de Inicialização do Python


The Python/C API, Release 3.10.6

(continuação da página anterior)


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 configuration 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. Set the Python Path Configuration (“output fields”) to ignore
these configuration files and avoid the function computing the default path configuration.

10.9 Python Configuration

PyPreConfig_InitPythonConfig() and PyConfig_InitPythonConfig() functions create a con-


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

10.8. Isolated Configuration 205


The Python/C API, Release 3.10.6

• 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, path
configuration input fields are ignored as well.
Set pathconfig_warnings to 0 to suppress warnings when calculating the path configuration (Unix only, Win-
dows 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.
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
• python._pth (Windows only)
• pybuilddir.txt (Unix only)
The __PYVENV_LAUNCHER__ environment variable is used to set PyConfig.base_executable

206 Capítulo 10. Configuração de Inicialização do Python


The Python/C API, Release 3.10.6

10.11 Py_RunMain()

int Py_RunMain(void)
Execute 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.
By default and when if -i option is used, run the REPL.
Finally, finalizes Python and returns an exit status that can be passed to the exit() function.
See Python Configuration for an example of customized Python always running in isolated mode using
Py_RunMain().

10.12 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.13 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” initializa-
tion phase.
• PyConfig._isolated_interpreter: if non-zero, disallow threads, subprocesses and fork.
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 Configu-
ration 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.

10.11. Py_RunMain() 207


The Python/C API, Release 3.10.6

It may become possible to calculatin 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);
}
}

208 Capítulo 10. Configuração de Inicialização do Python


CAPÍTULO 11

Gerenciamento de Memória

11.1 Visão Geral

Memory management in Python involves a private heap containing all Python objects and data structures. The ma-
nagement of this private heap is ensured internally by the Python memory manager. The Python memory manager
has different components which deal with various dynamic storage management aspects, like sharing, segmentation,
preallocation or caching.
At the lowest level, a raw memory allocator ensures that there is enough room in the private heap for storing all
Python-related data by interacting with the memory manager of the operating system. On top of the raw memory
allocator, several object-specific allocators operate on the same heap and implement distinct memory management
policies adapted to the peculiarities of every object type. For example, integer objects are managed differently within
the heap than strings, tuples or dictionaries because integers imply different storage requirements and speed/space
tradeoffs. The Python memory manager thus delegates some of the work to the object-specific allocators, but ensures
that the latter operate within the bounds of the private heap.
It is important to understand that the management of the Python heap is performed by the interpreter itself and that
the user has no control over it, even if they regularly manipulate object pointers to memory blocks inside that heap.
The allocation of heap space for Python objects and other internal buffers is performed on demand by the Python
memory manager through the Python/C API functions listed in this document.
To avoid memory corruption, extension writers should never try to operate on Python objects with the functions
exported by the C library: malloc(), calloc(), realloc() and free(). This will result in mixed calls
between the C allocator and the Python memory manager with fatal consequences, because they implement different
algorithms and operate on different heaps. However, one may safely allocate and release memory blocks with the C
library allocator for individual purposes, as shown in the following example:

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);
free(buf); /* malloc'ed */
return res;

In this example, the memory request for the I/O buffer is handled by the C library allocator. The Python memory
manager is involved only in the allocation of the bytes object returned as a result.

209
The Python/C API, Release 3.10.6

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:
The PYTHONMALLOC environment variable can be used to configure the memory allocators used by Python.
The PYTHONMALLOCSTATS environment variable can be used to print statistics of the pymalloc memory allocator
every time a new pymalloc object arena is created, and on shutdown.

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. There is no hard requirement to use the memory
returned by the allocation functions belonging to a given domain for only the purposes hinted by that domain (although
this is the recommended practice). For example, one could use the memory returned by PyMem_RawMalloc()
for allocating Python objects or the memory returned by PyObject_Malloc() for allocating memory for buffers.
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
to the system.
• “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.
• Object domain: intended for allocating memory belonging to Python objects. The memory is taken from the
Python private heap.
When freeing memory previously allocated by the allocating functions belonging to a given domain,the matching
specific deallocating functions must be used. For example, PyMem_Free() must be used to free memory allocated
using PyMem_Malloc().

11.3 Raw Memory Interface

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.
Novo na versão 3.4.
void *PyMem_RawMalloc(size_t n)
Allocates n bytes and returns a pointer of type void* to the allocated memory, or NULL if the request fails.
Requesting zero bytes returns a distinct non-NULL pointer if possible, as if PyMem_RawMalloc(1) had
been called instead. The memory will not have been initialized in any way.

210 Capítulo 11. Gerenciamento de Memória


The Python/C API, Release 3.10.6

void *PyMem_RawCalloc(size_t nelem, size_t elsize)


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.
Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if
PyMem_RawCalloc(1, 1) had been called instead.
Novo na versão 3.5.
void *PyMem_RawRealloc(void *p, size_t n)
Resizes the memory block pointed to by p to n bytes. The contents will be unchanged to the minimum of the
old and the new sizes.
If p is NULL, the call is equivalent to PyMem_RawMalloc(n); else if n is equal to zero, the memory block
is resized but is not freed, and the returned pointer is non-NULL.
Unless p is NULL, it must have been returned by a previous call to PyMem_RawMalloc(),
PyMem_RawRealloc() or PyMem_RawCalloc().
If the request fails, PyMem_RawRealloc() returns NULL and p remains a valid pointer to the previous
memory area.
void PyMem_RawFree(void *p)
Frees the memory block pointed to by p, which must have been returned by a previous call to
PyMem_RawMalloc(), PyMem_RawRealloc() or PyMem_RawCalloc(). Otherwise, or if
PyMem_RawFree(p) has been called before, undefined behavior occurs.
If p is NULL, no operation is performed.

11.4 Interface da Memória

The following function sets, modeled after the ANSI C standard, but specifying behavior when requesting zero bytes,
are available for allocating and releasing memory from the Python heap.
The default memory allocator uses the pymalloc memory allocator.

Aviso: The GIL must be held when using these functions.

Alterado na versão 3.6: The default allocator is now pymalloc instead of system malloc().
void *PyMem_Malloc(size_t n)
Part of the Stable ABI. Allocates n bytes and returns a pointer of type void* to the allocated memory, or NULL
if the request fails.
Requesting zero bytes returns a distinct non-NULL pointer if possible, as if PyMem_Malloc(1) had been
called instead. The memory will not have been initialized in any way.
void *PyMem_Calloc(size_t nelem, size_t elsize)
Part of the Stable ABI since version 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.
Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if
PyMem_Calloc(1, 1) had been called instead.
Novo na versão 3.5.
void *PyMem_Realloc(void *p, size_t n)
Part of the Stable ABI. Resizes the memory block pointed to by p to n bytes. The contents will be unchanged
to the minimum of the old and the new sizes.
If p is NULL, the call is equivalent to PyMem_Malloc(n); else if n is equal to zero, the memory block is
resized but is not freed, and the returned pointer is non-NULL.

11.4. Interface da Memória 211


The Python/C API, Release 3.10.6

Unless p is NULL, it must have been returned by a previous call to PyMem_Malloc(), PyMem_Realloc()
or PyMem_Calloc().
If the request fails, PyMem_Realloc() returns NULL and p remains a valid pointer to the previous memory
area.
void PyMem_Free(void *p)
Part of the Stable ABI. Frees the memory block pointed to by p, which must have been returned by a
previous call to PyMem_Malloc(), PyMem_Realloc() or PyMem_Calloc(). Otherwise, or if
PyMem_Free(p) has been called before, undefined behavior occurs.
If p is NULL, no operation is performed.
The following type-oriented macros are provided for convenience. Note that TYPE refers to any C type.
TYPE *PyMem_New(TYPE, size_t 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.
TYPE *PyMem_Resize(void *p, TYPE, size_t 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.
This is a C preprocessor macro; p is always reassigned. Save the original value of p to avoid losing memory
when handling errors.
void PyMem_Del(void *p)
Same as PyMem_Free().
In addition, the following macro sets are provided for calling the Python memory allocator directly, without involving
the C API functions listed above. However, note that their use does not preserve binary compatibility across Python
versions and is therefore deprecated in extension modules.
• PyMem_MALLOC(size)
• PyMem_NEW(type, size)
• PyMem_REALLOC(ptr, size)
• PyMem_RESIZE(ptr, type, size)
• PyMem_FREE(ptr)
• PyMem_DEL(ptr)

11.5 Object allocators

The following function sets, modeled after the ANSI C standard, but specifying behavior when requesting zero bytes,
are available for allocating and releasing memory from the Python heap.

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.

The default object allocator uses the pymalloc memory allocator.

Aviso: The GIL must be held when using these functions.

void *PyObject_Malloc(size_t n)
Part of the Stable ABI. Allocates n bytes and returns a pointer of type void* to the allocated memory, or NULL
if the request fails.

212 Capítulo 11. Gerenciamento de Memória


The Python/C API, Release 3.10.6

Requesting zero bytes returns a distinct non-NULL pointer if possible, as if PyObject_Malloc(1) had
been called instead. The memory will not have been initialized in any way.
void *PyObject_Calloc(size_t nelem, size_t elsize)
Part of the Stable ABI since version 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.
Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if
PyObject_Calloc(1, 1) had been called instead.
Novo na versão 3.5.
void *PyObject_Realloc(void *p, size_t n)
Part of the Stable ABI. Resizes the memory block pointed to by p to n bytes. The contents will be unchanged
to the minimum of the old and the new sizes.
If p is NULL, the call is equivalent to PyObject_Malloc(n); else if n is equal to zero, the memory block
is resized but is not freed, and the returned pointer is non-NULL.
Unless p is NULL, it must have been returned by a previous call to PyObject_Malloc(),
PyObject_Realloc() or PyObject_Calloc().
If the request fails, PyObject_Realloc() returns NULL and p remains a valid pointer to the previous
memory area.
void PyObject_Free(void *p)
Part of the Stable ABI. Frees the memory block pointed to by p, which must have been returned by a previous
call to PyObject_Malloc(), PyObject_Realloc() or PyObject_Calloc(). Otherwise, or if
PyObject_Free(p) has been called before, undefined behavior occurs.
If p is NULL, no operation is performed.

11.6 Default Memory Allocators

Default memory allocators:

Configuração Nome Py- PyMem_Malloc PyOb-


Mem_RawMalloc ject_Malloc
Release build "pymalloc" malloc pymalloc pymalloc
Debug build "pymalloc_debug"malloc + debug pymalloc + pymalloc +
debug debug
Release build, without py- "malloc" malloc malloc malloc
malloc
Debug build, without py- "malloc_debug" malloc + debug malloc + de- malloc + de-
malloc bug bug

Legend:
• 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.
• “+ debug”: with debug hooks on the Python memory allocators.
• “Debug build”: Python build in debug mode.

11.6. Default Memory Allocators 213


The Python/C API, Release 3.10.6

11.7 Customize Memory Allocators

Novo na versão 3.4.


type PyMemAllocatorEx
Structure used to describe a memory block allocator. The structure has the following fields:

Campo Significado
void *ctx user context passed as first argument
void* malloc(void *ctx, size_t size) allocate a memory block
void* calloc(void *ctx, size_t nelem, allocate a memory block initialized
size_t elsize) with zeros
void* realloc(void *ctx, void *ptr, size_t allocate or resize a memory block
new_size)
void free(void *ctx, void *ptr) free a memory block

Alterado na versão 3.5: The PyMemAllocator structure was renamed to PyMemAllocatorEx and a
new calloc field was added.
type PyMemAllocatorDomain
Enum used to identify an allocator domain. Domains:
PYMEM_DOMAIN_RAW
Funções:
• PyMem_RawMalloc()
• PyMem_RawRealloc()
• 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)
Get the memory block allocator of the specified domain.
void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Set the memory block allocator of the specified domain.
The new allocator must return a distinct non-NULL pointer when requesting zero bytes.
For the PYMEM_DOMAIN_RAW domain, the allocator must be thread-safe: the GIL is not held when the
allocator is called.
If the new allocator is not a hook (does not call the previous allocator), the PyMem_SetupDebugHooks()
function must be called to reinstall the debug hooks on top on the new allocator.

214 Capítulo 11. Gerenciamento de Memória


The Python/C API, Release 3.10.6

void PyMem_SetupDebugHooks(void)
Setup debug hooks in the Python memory allocators to detect memory errors.

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 preini-
tialization 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.
On error, the debug hooks use the tracemalloc module to get the traceback where a memory block was allocated.
The traceback is only displayed if tracemalloc is tracing Python memory allocations and the memory block was
traced.
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 uniniti-
alized 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
PYMEM_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,
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.

11.8. Debug hooks on the Python memory allocators 215


The Python/C API, Release 3.10.6

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
release mode. On error, the debug hooks now use tracemalloc to get the traceback where a memory block
was allocated. The debug hooks now also check if the GIL is held when functions of PYMEM_DOMAIN_OBJ and
PYMEM_DOMAIN_MEM domains are called.
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 Win-
dows CRT debug malloc() and free().

11.9 The pymalloc allocator

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 256 KiB. 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.
The arena allocator uses the following functions:
• VirtualAlloc() e VirtualFree() no Windows,
• mmap() e munmap() se disponível,
• 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).

11.9.1 Customize pymalloc Arena Allocator

Novo na versão 3.4.


type PyObjectArenaAllocator
Structure used to describe an arena allocator. The structure has three fields:

Campo Significado
void *ctx user context passed as first argument
void* alloc(void *ctx, size_t size) allocate an arena of size bytes
void free(void *ctx, void *ptr, size_t free an arena
size)

void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)


Get the arena allocator.
void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
Set the arena allocator.

216 Capítulo 11. Gerenciamento de Memória


The Python/C API, Release 3.10.6

11.10 tracemalloc C API

Novo na versão 3.7.


int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size)
Track an allocated memory block in the tracemalloc module.
Return 0 on success, return -1 on error (failed to allocate memory to store the trace). Return -2 if tracemalloc
is disabled.
If memory block is already tracked, update the existing trace.
int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)
Untrack an allocated memory block in the tracemalloc module. Do nothing if the block was not tracked.
Return -2 if tracemalloc is disabled, otherwise return 0.

11.11 Exemplos

Here is the example from section Visão Geral, rewritten so that the I/O buffer is allocated from the Python heap by
using the first function set:

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;

The same code using the type-oriented function set:

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;

Note that in the two examples above, the buffer is always manipulated via functions belonging to the same set. Indeed,
it is required to use the same memory API family for a given memory block, so that the risk of mixing different
allocators is reduced to a minimum. The following code sequence contains two errors, one of which is labeled as
fatal because it mixes two different allocators operating on different heaps.

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().
These will be explained in the next chapter on defining and implementing new object types in C.

11.10. tracemalloc C API 217


The Python/C API, Release 3.10.6

218 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 Pilha

PyObject *_PyObject_New(PyTypeObject *type)


Return value: New reference.
PyVarObject *_PyObject_NewVar(PyTypeObject *type, Py_ssize_t size)
Return value: New reference.
PyObject *PyObject_Init(PyObject *op, PyTypeObject *type)
Return value: Borrowed reference. Part of the Stable ABI. Initialize a newly allocated object op with its type
and initial reference. Returns the initialized object. If type indicates that the object participates in the cyclic
garbage detector, it is added to the detector’s set of observed objects. Other fields of the object are not affected.
PyVarObject *PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size)
Return value: Borrowed reference. Part of the Stable ABI. Isto faz tudo que o PyObject_Init() faz e
também inicializa a informação de comprimento para um objeto de tamanho variável.
TYPE *PyObject_New(TYPE, PyTypeObject *type)
Return value: New reference. Aloca um novo objeto Python usando o tipo de estrutura do C TYPE e o ob-
jeto Python do tipo type. Campos não definidos pelo cabeçalho do objeto Python não são inicializados; a
contagem de referências do objeto será um. O tamanho da alocação de memória é determinado do campo
tp_basicsize do objeto tipo.
TYPE *PyObject_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size)
Return value: New reference. Aloca um novo objeto Python usando o tipo de estrutura do C TYPE e o objeto
Python do tipo type. Campos não definidos pelo cabeçalho do objeto Python não são inicializados. A memória
alocada permite a estrutura TYPE e os campos size do tamanho dado pelo campo tp_itemsize do tipo type.
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.
void PyObject_Del(void *op)
Libera memória alocada a um objeto usando PyObject_New() ou PyObject_NewVar(). Isto é nor-
malmente chamado pelo tp_dealloc manipulador 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.

219
The Python/C API, Release 3.10.6

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:
PyModule_Create() Para alocar e criar módulos de extensão.

12.2 Estruturas Comuns de Objetos

There are a large number of structures which are used in the definition of object types for Python. This section
describes these structures and how they are used.

12.2.1 Base object types and macros

All Python objects ultimately share a small number of fields at the beginning of the object’s representation in memory.
These are represented by the PyObject and PyVarObject types, which are defined, in turn, by the expansions
of some macros also used, whether directly or indirectly, in the definition of all other Python objects.
type PyObject
Part of the Limited API. (Only some members are part of the stable ABI.) All object types are extensions of this
type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In
a normal “release” build, it contains only the object’s reference count and a pointer to the corresponding type
object. Nothing is actually declared to be a PyObject, but every pointer to a Python object can be cast to a
PyObject*. Access to the members must be done by using the macros Py_REFCNT and Py_TYPE.
type PyVarObject
Part of the Limited API. (Only some members are part of the stable ABI.) This is an extension of PyObject
that adds the ob_size field. This is only used for objects that have some notion of length. This type does not
often appear in the Python/C API. Access to the members must be done by using the macros Py_REFCNT,
Py_TYPE, and Py_SIZE.
PyObject_HEAD
This is a macro used when declaring new types which represent objects without a varying length. The PyOb-
ject_HEAD macro expands to:
PyObject ob_base;

See documentation of PyObject above.


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;

See documentation of PyVarObject above.


int Py_Is(const PyObject *x, const PyObject *y)
Part of the Stable ABI since version 3.10. Test if the x object is the y object, the same as x is y in Python.
Novo na versão 3.10.
int Py_IsNone(const PyObject *x)
Part of the Stable ABI since version 3.10. Test if an object is the None singleton, the same as x is None
in Python.
Novo na versão 3.10.
int Py_IsTrue(const PyObject *x)
Part of the Stable ABI since version 3.10. Test if an object is the True singleton, the same as x is True
in Python.

220 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

Novo na versão 3.10.


int Py_IsFalse(const PyObject *x)
Part of the Stable ABI since version 3.10. Test if an object is the False singleton, the same as x is False
in Python.
Novo na versão 3.10.
PyTypeObject *Py_TYPE(const PyObject *o)
Get the type of the Python object o.
Return a borrowed reference.
The Py_SET_TYPE() function must be used to set an object type.
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.
Novo na versão 3.9.
void Py_SET_TYPE(PyObject *o, PyTypeObject *type)
Set the object o type to type.
Novo na versão 3.9.
Py_ssize_t Py_REFCNT(const PyObject *o)
Get the reference count of the Python object o.
Alterado na versão 3.10: Py_REFCNT() is changed to the inline static function. Use Py_SET_REFCNT()
to set an object reference count.
void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)
Set the object o reference counter to refcnt.
Novo na versão 3.9.
Py_ssize_t Py_SIZE(const PyVarObject *o)
Get the size of the Python object o.
The Py_SET_SIZE() function must be used to set an object size.
void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size)
Set the object o size to size.
Novo 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:

_PyObject_EXTRA_INIT
1, type, size,

12.2. Estruturas Comuns de Objetos 221


The Python/C API, Release 3.10.6

12.2.2 Implementing functions and methods

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

PyObject *PyCFunction(PyObject *self,


PyObject *args);

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

PyObject *PyCFunctionWithKeywords(PyObject *self,


PyObject *args,
PyObject *kwargs);

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

PyObject *_PyCFunctionFast(PyObject *self,


PyObject *const *args,
Py_ssize_t nargs);

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

PyObject *_PyCFunctionFastWithKeywords(PyObject *self,


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

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

PyObject *PyCMethod(PyObject *self,


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

Novo na versão 3.9.


type PyMethodDef
Part of the Stable ABI (including all members). Structure used to describe a method of an extension type. This
structure has four fields:

Campo Tipo em C Significado


ml_name const char * name of the method
ml_meth PyCFunction pointer to the C implementation
ml_flags int flag bits indicating how the call should be constructed
ml_doc const char * points to the contents of the docstring

222 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

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_VARARGS | METH_KEYWORDS
Methods with these flags must be of type PyCFunctionWithKeywords. The function expects
three parameters: 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).
Novo 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.
Novo na versão 3.7.
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.
Novo 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.
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 pa-
rameter, 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.

12.2. Estruturas Comuns de Objetos 223


The Python/C API, Release 3.10.6

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.

12.2.3 Accessing attributes of extension types

type PyMemberDef
Part of the Stable ABI (including all members). Structure which describes an attribute of a type which corres-
ponds to a C struct member. Its fields are:

Campo Tipo em C Significado


name const char * name of the member
type int the type of the member in the C struct
offset Py_ssize_t the offset in bytes that the member is located on the type’s object struct
flags int flag bits indicating if the field should be read-only or writable
doc const char * points to the contents of the docstring

type can be one of many T_ macros corresponding to various C types. When the member is accessed in
Python, it will be converted to the equivalent Python type.

Macro name C type


T_SHORT short
T_INT int
T_LONG long
T_FLOAT float
T_DOUBLE double
T_STRING const char *
T_OBJECT PyObject *
T_OBJECT_EX PyObject *
T_CHAR char
T_BYTE char
T_UBYTE unsigned char
T_UINT unsigned int
T_USHORT unsigned short
T_ULONG unsigned long
T_BOOL char
T_LONGLONG long long
T_ULONGLONG unsigned long long
T_PYSSIZET Py_ssize_t

T_OBJECT and T_OBJECT_EX differ in that T_OBJECT returns None if the member is NULL and
T_OBJECT_EX raises an AttributeError. Try to use T_OBJECT_EX over T_OBJECT because
T_OBJECT_EX handles use of the del statement on that attribute more correctly than T_OBJECT.
flags can be 0 for write and read access or READONLY for read-only access. Using T_STRING for type
implies READONLY. T_STRING data is interpreted as UTF-8. Only T_OBJECT and T_OBJECT_EX mem-
bers can be deleted. (They are set to NULL).

224 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

Heap allocated types (created using PyType_FromSpec() or similar), PyMemberDef may


contain definitions for the special members __dictoffset__, __weaklistoffset__ and
__vectorcalloffset__, corresponding to tp_dictoffset, tp_weaklistoffset and
tp_vectorcall_offset in type objects. These must be defined with T_PYSSIZET and READONLY,
for example:
static PyMemberDef spam_type_members[] = {
{"__dictoffset__", T_PYSSIZET, offsetof(Spam_object, dict), READONLY},
{NULL} /* Sentinel */
};

PyObject *PyMember_GetOne(const char *obj_addr, struct PyMemberDef *m)


Get an attribute belonging to the object at address obj_addr. The attribute is described by PyMemberDef m.
Returns NULL on error.
int PyMember_SetOne(char *obj_addr, struct PyMemberDef *m, PyObject *o)
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.
type PyGetSetDef
Part of the Stable ABI (including all members). Structure to define property-like access for a type. See also
description of the PyTypeObject.tp_getset slot.

Campo Tipo em C Significado


nome const char * attribute name
get getter C function to get the attribute
set setter optional C function to set or delete the attribute, if omitted the attribute is readonly
doc const char * optional docstring
closure void * optional function pointer, providing additional data for getter and setter

The get function takes one PyObject* parameter (the instance) and a function pointer (the associated
closure):
typedef PyObject *(*getter)(PyObject *, void *);

It should return a new reference on success or NULL with a set exception on failure.
set functions take two PyObject* parameters (the instance and the value to be set) and a function pointer (the
associated closure):
typedef int (*setter)(PyObject *, PyObject *, void *);

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 Objetos tipo

Talvez uma das estruturas mais importantes do sistema de objetos Python seja a estrutura que define um novo tipo: a
estrutura PyTypeObject. Objetos de tipo podem ser manipulados usando qualquer uma das funções PyObject_*
ou PyType_*, mas não oferecem muita coisa interessante para a maioria dos aplicativos Python. Esses objetos são
fundamentais para o comportamento dos objetos, portanto, são muito importantes para o próprio interpretador e para
qualquer módulo de extensão que implemente novos tipos.
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.
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. Objetos tipo 225


The Python/C API, Release 3.10.6

12.3.1 Referências rápidas

“slots tp”

Slot de PyTypeObject1 Type métodos/atributos especiais Info2


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 * %
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] PyObject * __subclasses__
[tp_weaklist] PyObject *
(tp_del) destructor
[tp_version_tag] unsigned int
tp_finalize destructor __del__ X
continua na próxima página

226 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

Tabela 1 – continuação da página anterior


Slot de PyTypeObject1 Type métodos/atributos especiais Info2
O T D I
tp_vectorcall vectorcallfunc

sub-slots

Slot Type 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__
nb_inplace_and binaryfunc __iand__
continua na próxima página

1 A slot name in parentheses indicates it is (effectively) deprecated. Names in angle brackets should be 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.

12.3. Objetos tipo 227


The Python/C API, Release 3.10.6

Tabela 2 – continuação da página anterior


Slot Type special methods
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()
bf_releasebuffer releasebufferproc()

228 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

slot typedefs

typedef Parameter Types Return Type


allocfunc PyObject *
PyTypeObject *
Py_ssize_t

destructor void * void


freefunc void * void
traverseproc int
void *
visitproc
void *

newfunc PyObject *
PyObject *
PyObject *
PyObject *

initproc int
PyObject *
PyObject *
PyObject *

reprfunc PyObject * PyObject *


getattrfunc PyObject *
PyObject *
const char *

setattrfunc int
PyObject *
const char *
PyObject *

getattrofunc PyObject *
PyObject *
PyObject *

setattrofunc int
PyObject *
PyObject *
PyObject *

descrgetfunc PyObject *
PyObject *
PyObject *
PyObject *

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

hashfunc PyObject * Py_hash_t


richcmpfunc PyObject *
The Python/C API, Release 3.10.6

See Slot Type typedefs below for more detail.

12.3.2 PyTypeObject Definition

The structure definition for PyTypeObject can be found in Include/object.h. For convenience of refe-
rence, 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;

/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
(continua na próxima página)

230 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

(continuação da página anterior)

/* Attribute descriptor and subclassing stuff */


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

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


unsigned int tp_version_tag;

destructor tp_finalize;
vectorcallfunc tp_vectorcall;
} 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
Part of the Stable ABI. This is the type object’s reference count, initialized to 1 by the
PyObject_HEAD_INIT macro. Note that for statically allocated type objects, the type’s instances
(objects whose ob_type points back to the type) do not count as references. But for dynamically allocated
type objects, the instances do count as references.
Inheritance:
This field is not inherited by subtypes.
PyTypeObject *PyObject.ob_type
Part of the Stable ABI. 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 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:

12.3. Objetos tipo 231


The Python/C API, Release 3.10.6

This field is inherited by subtypes.


PyObject *PyObject._ob_next
PyObject *PyObject._ob_prev
These fields are only present when the macro Py_TRACE_REFS is defined (see the configure
--with-trace-refs option).
Their initialization to NULL is taken care of by the PyObject_HEAD_INIT macro. For statically allocated
objects, these fields always remain NULL. For dynamically allocated objects, these two fields are used to link
the object into a doubly linked list of all live objects on the heap.
This could be used for various debugging purposes; currently the only uses are the sys.getobjects()
function and to print the objects that are still alive at the end of a run when the environment variable
PYTHONDUMPREFS is set.
Inheritance:
These fields are not inherited by subtypes.

12.3.4 PyVarObject Slots

Py_ssize_t PyVarObject.ob_size
Part of the Stable ABI. For statically allocated type objects, this should be initialized to zero. For dynamically
allocated type objects, this field has a special internal meaning.
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 means
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

232 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

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 instances, all
instances have the same size, given in tp_basicsize.
For a type with variable-length instances, the instances must have an ob_size field, and the instance size
is tp_basicsize plus N times tp_itemsize, where N is the “length” of the object. The value of
N is typically stored in the instance’s ob_size field. There are exceptions: for example, ints use a negative
ob_size to indicate a negative number, and N is abs(ob_size) there. Also, the presence of an ob_size
field in the instance layout doesn’t mean that the instance structure is variable-length (for example, the structure
for the list type has fixed-length instances, yet those instances have a meaningful ob_size field).
The basic size includes the fields in the instance declared by the macro PyObject_HEAD or
PyObject_VAR_HEAD (whichever is used to declare the instance struct) and this in turn includes the
_ob_prev and _ob_next fields if they are present. This means that the only correct way to get an ini-
tializer for the tp_basicsize is to use the sizeof operator on the struct used to declare the instance
layout. The basic size does not include the GC header size.
A note about alignment: if the variable items require a particular alignment, this should be taken care of by the
value of tp_basicsize. Example: suppose a type implements an array of double. tp_itemsize
is sizeof(double). It is the programmer’s responsibility that tp_basicsize is a multiple of
sizeof(double) (assuming this is the alignment requirement for double).
For any type with variable-length instances, this field must not be NULL.
Inheritance:
These fields are inherited separately by subtypes. If the base type has a non-zero tp_itemsize, it is ge-
nerally 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 refe-
rence 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 de-
allocator should be the one used to allocate the instance; this is normally PyObject_Del() if the instance
was allocated using PyObject_New() or PyObject_VarNew(), 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 decrement the re-
ference count for its type object after calling the type deallocator. In order to avoid dangling pointers, the
recommended way to achieve this is:

12.3. Objetos tipo 233


The Python/C API, Release 3.10.6

static void foo_dealloc(foo_object *self) {


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

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

Aviso: It is not recommended for 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 func-
tion.

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.
Inheritance:
This field is always inherited. However, the Py_TPFLAGS_HAVE_VECTORCALL flag is not always inherited.
If it’s not, then the subclass won’t use vectorcall, except when PyVectorcall_Call() is explicitly called.
This is in particular the case for heap types (including subclasses defined in Python).
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.

234 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

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

12.3. Objetos tipo 235


The Python/C API, Release 3.10.6

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

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.
Default:
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.
Default:
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);

236 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

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.
Default:
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 in-
terface. 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:
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.
Default:
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).
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().

12.3. Objetos tipo 237


The Python/C API, Release 3.10.6

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 de Lixo Cíclica. 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.
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 tem-
porary “bound method” object for obj.meth.
Novo na versão 3.8.
Inheritance:
This flag is never inherited by heap types. For extension types, it is inherited whenever tp_descr_get
is inherited.
Py_TPFLAGS_LONG_SUBCLASS
Py_TPFLAGS_LIST_SUBCLASS
Py_TPFLAGS_TUPLE_SUBCLASS
Py_TPFLAGS_BYTES_SUBCLASS
Py_TPFLAGS_UNICODE_SUBCLASS
Py_TPFLAGS_DICT_SUBCLASS
Py_TPFLAGS_BASE_EXC_SUBCLASS

238 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

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.
Novo na versão 3.4.
Obsoleto 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 for static subtypes if tp_call is also inherited. Heap types do not inherit
Py_TPFLAGS_HAVE_VECTORCALL.
Novo na versão 3.9.
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.
Novo 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.
Novo 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 enable 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

12.3. Objetos tipo 239


The Python/C API, Release 3.10.6

Novo 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 enable 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
Novo na versão 3.10.
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 de Lixo
Cíclica.
The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical imple-
mentation of a tp_traverse function simply calls Py_VISIT() on each of the instance’s members that
are Python objects that the instance owns. For example, this is function local_traverse() from the
_thread extension module:

static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
Py_VISIT(self->args);
Py_VISIT(self->kw);
Py_VISIT(self->dict);
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.

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

240 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

the weak reference 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 imple-
ment 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 con-
tained object must not be decremented until after the pointer to the contained object is set to NULL. This is
because decrementing the reference count 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.
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
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.

12.3. Objetos tipo 241


The Python/C API, Release 3.10.6

More information about Python’s garbage collection scheme can be found in section Suporte a Coleta de Lixo
Cíclica.
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 return value’s reference count is properly incremented.
On error, sets an exception and returns NULL from the function.
Novo na versão 3.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.
Default:
PyBaseObject_Type provides a tp_richcompare implementation, which may be inherited. Howe-
ver, 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
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.

242 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

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.
When a type defined by a class statement has no __slots__ declaration, and none of its base types are
weakly referenceable, the type is made weakly referenceable by adding a weak reference list head slot to the
instance layout and setting the tp_weaklistoffset of that slot’s offset.
When a type’s __slots__ declaration contains a slot named __weakref__, that slot becomes the weak
reference list head for instances of the type, and the slot’s offset is stored in the type’s tp_weaklistoffset.
When a type’s __slots__ declaration does not contain a slot named __weakref__, the type inherits its
tp_weaklistoffset from its base type.
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.
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).

12.3. Objetos tipo 243


The Python/C API, Release 3.10.6

struct PyGetSetDef *PyTypeObject.tp_getset


An optional pointer to a static NULL-terminated array of PyGetSetDef structures, declaring computed
attributes 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 requi-
red 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).
Default:
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__()).
Inheritance:
This field is not inherited by subtypes (though the attributes defined in here are inherited through a different
mechanism).
Default:
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.
The function signature is:

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

Inheritance:
This field is inherited by subtypes.

244 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

descrsetfunc PyTypeObject.tp_descr_set
An optional pointer to a function for setting and deleting a descriptor’s value.
The function signature is:

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
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.
If the value of this field is greater than zero, it specifies the offset from the start of the instance structure. If
the value is less than zero, it specifies the offset from the end of the instance structure. A negative offset is
more expensive to use, and should only be used when the instance structure contains a variable-length part.
This is used for example to add an instance variable dictionary to subtypes of str or tuple. Note that the
tp_basicsize field should account for the dictionary added to the end in that case, even though the dictio-
nary is not included in the basic object layout. On a system with a pointer size of 4 bytes, tp_dictoffset
should be set to -4 to indicate that the dictionary is at the very end of the structure.
The real dictionary offset in an instance can be computed from a negative tp_dictoffset as follows:

dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset


if dictoffset is not aligned on sizeof(void*):
round up to sizeof(void*)

where tp_basicsize, tp_itemsize and tp_dictoffset are taken from the type object, and
ob_size is taken from the instance. The absolute value is taken because ints use the sign of ob_size
to store the sign of the number. (There’s never a need to do this calculation yourself; it is done for you by
_PyObject_GetDictPtr().)
Inheritance:
This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means
that the subtype instances store the dictionary at a difference offset than the base type. Since the dictionary is
always found via tp_dictoffset, this should not be a problem.
When a type defined by a class statement has no __slots__ declaration, and none of its base types has an
instance variable dictionary, a dictionary slot is added to the instance layout and the tp_dictoffset is set
to that slot’s offset.
When a type defined by a class statement has a __slots__ declaration, the type inherits its
tp_dictoffset from its base type.
(Adding a slot named __dict__ to the __slots__ declaration does not have the expected effect, it just
causes confusion. Maybe this should be added as a feature just like __weakref__ though.)
Default:
This slot has no default. For static types, if the field is NULL then no __dict__ gets created for instances.
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.
The function signature is:

12.3. Objetos tipo 245


The Python/C API, Release 3.10.6

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.
Default:
For static types this field does not have a default.
allocfunc PyTypeObject.tp_alloc
An optional pointer to an instance allocation function.
The function signature is:

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).
Default:
For dynamic subtypes, this field is always set to PyType_GenericAlloc(), to force a standard heap
allocation 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.
The function signature is:

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 object, and then do only as much further initialization as is absolutely necessary. Initialization that can
safely be 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.
Default:
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.

246 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

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)
Default:
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
distinguish between statically and dynamically allocated types.)
Inheritance:
This field is inherited by subtypes.
Default:
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 is set for types created by a class statement. It should be NULL for statically defined types.
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.
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.
PyObject *PyTypeObject.tp_subclasses
List of weak references to subclasses. Internal use only.
Inheritance:
This field is not inherited.

12.3. Objetos tipo 247


The Python/C API, Release 3.10.6

PyObject *PyTypeObject.tp_weaklist
Weak reference list head, for weak references to this type object. Not inherited. Internal use only.
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);

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)
{
PyObject *error_type, *error_value, *error_traceback;

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


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

/* ... */

/* Restore the saved exception. */


PyErr_Restore(error_type, error_value, error_traceback);
}

Also, note that, 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.
Novo 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:
“Safe object finalization” (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

248 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

type.__call__. If tp_vectorcall is NULL, the default call implementation using __new__ and
__init__ is used.
Inheritance:
This field is never inherited.
Novo na versão 3.9: (the field exists since 3.8 but it’s only used since 3.9)

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

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(), or PyType_FromModuleAndSpec().

12.4 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;
(continua na próxima página)

12.4. Number Object Structures 249


The Python/C API, Release 3.10.6

(continuação da página anterior)


unaryfunc nb_int;
void *nb_reserved;
unaryfunc nb_float;

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

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

unaryfunc nb_index;

binaryfunc nb_matrix_multiply;
binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;

Nota: Binary and ternary functions must check the type of all their operands, and implement the necessary
conversions (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 rena-
med 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

250 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

binaryfunc PyNumberMethods.nb_or
unaryfunc PyNumberMethods.nb_int
void *PyNumberMethods.nb_reserved
unaryfunc PyNumberMethods.nb_float
binaryfunc PyNumberMethods.nb_inplace_add
binaryfunc PyNumberMethods.nb_inplace_subtract
binaryfunc PyNumberMethods.nb_inplace_multiply
binaryfunc PyNumberMethods.nb_inplace_remainder
ternaryfunc PyNumberMethods.nb_inplace_power
binaryfunc PyNumberMethods.nb_inplace_lshift
binaryfunc PyNumberMethods.nb_inplace_rshift
binaryfunc PyNumberMethods.nb_inplace_and
binaryfunc PyNumberMethods.nb_inplace_xor
binaryfunc PyNumberMethods.nb_inplace_or
binaryfunc PyNumberMethods.nb_floor_divide
binaryfunc PyNumberMethods.nb_true_divide
binaryfunc PyNumberMethods.nb_inplace_floor_divide
binaryfunc PyNumberMethods.nb_inplace_true_divide
unaryfunc PyNumberMethods.nb_index
binaryfunc PyNumberMethods.nb_matrix_multiply
binaryfunc PyNumberMethods.nb_inplace_matrix_multiply

12.5 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(),
PyObject_SetSlice() and PyObject_DelSlice(). It has the same signature as !PyOb-
ject_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.5. Mapping Object Structures 251


The Python/C API, Release 3.10.6

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

252 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

(1) Check if the request can be met. If not, raise PyExc_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.
• 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.8 Async Object Structures

Novo 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;
(continua na próxima página)

12.8. Async Object Structures 253


The Python/C API, Release 3.10.6

(continuação da página anterior)


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:

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.


Novo na versão 3.10.

12.9 Slot Type typedefs

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


Part of the Stable ABI. The purpose of this function is to separate memory allocation from memory 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 al-
located 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*)
Part of the Stable ABI.
typedef void (*freefunc)(void*)
See tp_free.
typedef PyObject *(*newfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. See tp_new.
typedef int (*initproc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. See tp_init.

254 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

typedef PyObject *(*reprfunc)(PyObject*)


Part of the Stable ABI. See tp_repr.
typedef PyObject *(*getattrfunc)(PyObject *self, char *attr)
Part of the Stable ABI. Return the value of the named attribute for the object.
typedef int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
Part of the Stable ABI. 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)
Part of the Stable ABI. Return the value of the named attribute for the object.
See tp_getattro.
typedef int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)
Part of the Stable ABI. 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*)
Part of the Stable ABI. See tp_descr_get.
typedef int (*descrsetfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. See tp_descr_set.
typedef Py_hash_t (*hashfunc)(PyObject*)
Part of the Stable ABI. See tp_hash.
typedef PyObject *(*richcmpfunc)(PyObject*, PyObject*, int)
Part of the Stable ABI. See tp_richcompare.
typedef PyObject *(*getiterfunc)(PyObject*)
Part of the Stable ABI. See tp_iter.
typedef PyObject *(*iternextfunc)(PyObject*)
Part of the Stable ABI. See tp_iternext.
typedef Py_ssize_t (*lenfunc)(PyObject*)
Part of the Stable ABI.
typedef int (*getbufferproc)(PyObject*, Py_buffer*, int)
typedef void (*releasebufferproc)(PyObject*, Py_buffer*)
typedef PyObject *(*unaryfunc)(PyObject*)
Part of the Stable ABI.
typedef PyObject *(*binaryfunc)(PyObject*, PyObject*)
Part of the Stable ABI.
typedef PySendResult (*sendfunc)(PyObject*, PyObject*, PyObject**)
See am_send.
typedef PyObject *(*ternaryfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.
typedef PyObject *(*ssizeargfunc)(PyObject*, Py_ssize_t)
Part of the Stable ABI.
typedef int (*ssizeobjargproc)(PyObject*, Py_ssize_t)
Part of the Stable ABI.
typedef int (*objobjproc)(PyObject*, PyObject*)
Part of the Stable ABI.
typedef int (*objobjargproc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI.

12.9. Slot Type typedefs 255


The Python/C API, Release 3.10.6

12.10 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:
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 */
(continua na próxima página)

256 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

(continuação da página anterior)


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

A type that supports weakrefs, instance dicts, and hashing:

typedef struct {
PyObject_HEAD
const char *data;
PyObject *inst_dict;
PyObject *weakreflist;
} 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_weaklistoffset = offsetof(MyObject, weakreflist),
.tp_dictoffset = offsetof(MyObject, inst_dict),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
.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:

12.10. Exemplos 257


The Python/C API, Release 3.10.6

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

static PyTypeObject MyObject_Type = {


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

12.11 Suporte a Coleta de Lixo Cíclica

Python’s support for detecting and collecting garbage which involves circular references requires support from object
types which are “containers” for other objects which may also be containers. Types which do not store references to
other objects, or which only store references to atomic types (such as numbers or strings), do not need to provide any
explicit support for garbage collection.
To create a container type, the tp_flags field of the type object must include the Py_TPFLAGS_HAVE_GC
and provide an implementation of the tp_traverse handler. If instances of the type are mutable, a tp_clear
implementation must also be provided.
Py_TPFLAGS_HAVE_GC
Objects with a type with this flag set must conform with the rules documented here. For convenience these
objects will be referred to as container objects.
Constructors for container types must conform to two rules:
1. The memory for the object must be allocated using PyObject_GC_New() or
PyObject_GC_NewVar().
2. Once all the fields which may contain references to other containers are initialized, it must call
PyObject_GC_Track().
Similarly, the deallocator for the object must conform to a similar pair of rules:
1. Before fields which refer to other containers are invalidated, PyObject_GC_UnTrack() must be called.
2. The object’s memory must be deallocated using 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 im-
plements the garbage collector protocol and the child class does not include the Py_TPFLAGS_HAVE_GC
flag.

TYPE *PyObject_GC_New(TYPE, PyTypeObject *type)


Analogous to PyObject_New() but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
TYPE *PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size)
Analogous to PyObject_NewVar() but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
TYPE *PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize)
Resize an object allocated by PyObject_NewVar(). Returns the resized object or NULL on failure. op
must not be tracked by the collector yet.

258 Capítulo 12. Suporte a implementação de Objetos


The Python/C API, Release 3.10.6

void PyObject_GC_Track(PyObject *op)


Part of the Stable ABI. 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)
Part of the Stable ABI since version 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().
Novo na versão 3.9.
int PyObject_GC_IsFinalized(PyObject *op)
Part of the Stable ABI since version 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().
Novo na versão 3.9.
void PyObject_GC_Del(void *op)
Part of the Stable ABI. Releases memory allocated to an object using PyObject_GC_New() or
PyObject_GC_NewVar().
void PyObject_GC_UnTrack(void *op)
Part of the Stable ABI. 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
removed from the public C API.
The tp_traverse handler accepts a function parameter of this type:
typedef int (*visitproc)(PyObject *object, void *arg)
Part of the Stable ABI. 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)
Part of the Stable ABI. 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:
void Py_VISIT(PyObject *o)
If 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);
(continua na próxima página)

12.11. Suporte a Coleta de Lixo Cíclica 259


The Python/C API, Release 3.10.6

(continuação da página anterior)


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)
Part of the Stable ABI. 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.11.1 Controlling the Garbage Collector State

The C-API provides the following functions for controlling garbage collection runs.
Py_ssize_t PyGC_Collect(void)
Part of the Stable ABI. 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)
Part of the Stable ABI since version 3.10. Enable the garbage collector: similar to gc.enable(). Returns
the previous state, 0 for disabled and 1 for enabled.
Novo na versão 3.10.
int PyGC_Disable(void)
Part of the Stable ABI since version 3.10. Disable the garbage collector: similar to gc.disable(). Returns
the previous state, 0 for disabled and 1 for enabled.
Novo na versão 3.10.
int PyGC_IsEnabled(void)
Part of the Stable ABI since version 3.10. Query the state of the garbage collector: similar to gc.
isenabled(). Returns the current state, 0 for disabled and 1 for enabled.
Novo na versão 3.10.

260 Capítulo 12. Suporte a implementação de Objetos


CAPÍTULO 13

API e Versionamento 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 C API Stability 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.


Todas as macros dadas estão definidas em Include/patchlevel.h.

261
The Python/C API, Release 3.10.6

262 Capítulo 13. API e Versionamento ABI


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 shell 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.
2to3 Uma ferramenta que tenta converter código Python 2.x em código Python 3.x tratando a maioria das incom-
patibilidades que podem ser detectadas com análise do código-fonte e navegação na árvore sintática.
O 2to3 está disponível na biblioteca padrão como lib2to3; um ponto de entrada é disponibilizado como
Tools/scripts/2to3. Veja 2to3-reference.
classe base abstrata Classes bases abstratas complementam tipagem pato, fornecendo uma maneira de definir in-
terfaces quando outras técnicas, como hasattr(), seriam desajeitadas ou sutilmente erradas (por exemplo,
com métodos mágicos). CBAs introduzem subclasses virtuais, classes que não herdam de uma classe mas
ainda são reconhecidas por isinstance() e issubclass(); veja a documentação do módulo abc.
Python vem com muitas CBAs 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 CBAs 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:

263
The Python/C API, Release 3.10.6

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 visto 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 cor-
rotina 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 Um objeto criado por uma função geradora assíncrona.
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 do local (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. Intro-
duzido pela PEP 492.
atributo Um valor associado a um objeto que é referenciado pelo nome separado por um ponto. Por exemplo, se
um objeto o tem um atributo a esse seria referenciado como o.a.
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.
BDFL Abreviação da expressão da língua inglesa “Benevolent Dictator for Life” (em português, “Ditador Benevo-
lente Vitalício”), referindo-se a Guido van Rossum, criador do Python.
arquivo binário Um objeto arquivo capaz de ler e gravar em objetos byte ou similar. 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. Ela não
modifica a contagem de referências do objeto. Ela se torna um ponteiro pendente 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.

264 Apêndice A. Glossário


The Python/C API, Release 3.10.6

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 byte ou similar Um objeto com suporte ao o 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 byte ou similar 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 byte ou similar 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 byte ou similar 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.
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 defi-
niçõ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).
coerção A conversão implícita de uma instância de um tipo para outro durante uma operação que envolve dois
argumentos do mesmo tipo. Por exemplo, int(3.15) converte o número do ponto flutuante no número
inteiro 3, mas em 3+4.5, cada argumento é de um tipo diferente (um int, um float), e ambos devem ser
convertidos para o mesmo tipo antes de poderem ser adicionados ou isso levantará um TypeError. Sem
coerção, todos os argumentos de tipos compatíveis teriam que ser normalizados com o mesmo valor pelo
programador, por exemplo, float(3)+4.5 em vez de apenas 3+4.5.
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.
gerenciador de contexto Um objeto que controla o ambiente visto numa instrução with por meio da definição dos
métodos __enter__() e __exit__(). Veja PEP 343.
variável de contexto Uma variável que pode ter valores diferentes, dependendo do seu contexto. Isso é semelhante
ao armazenamento local de threads, no qual cada thread pode ter um valor diferente para uma variável. No
entanto, com variáveis de contexto, pode haver vários contextos em uma thread e o principal uso para variáveis
de contexto é acompanhar as variáveis em tarefas assíncronas simultâneas. Veja contextvars.
contíguo Um buffer é considerado contíguo exatamente se for contíguo C ou contíguo Fortran. Os buffers de di-
mensã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

265
The Python/C API, Release 3.10.6

podem ser implementadas com a instrução async def. Veja também PEP 492.
função de corrotina Uma função que retorna um objeto do tipo corrotina. Uma função de corrotina pode ser defi-
nida 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.
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 quais-
quer objetos que possuam os métodos __hash__() e __eq__(). Dicionários são estruturas chamadas de
hash na linguagem 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 cha-
mados de visões de dicionário. Eles fornecem uma visão dinâmica das entradas do dicionário, o que significa
que quando o dicioná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
primeira expressão numa classe, função ou módulo. Ainda que sejam ignoradas quando a suíte é executada, é
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.

266 Apêndice A. Glossário


The Python/C API, Release 3.10.6

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 em Python assume a existência de chaves ou
atributos 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() po-
dem ser usadas para obter o tratador de erros e codificação do sistema de arquivos.
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.
Desde o Python 3.3, existem dois tipos de localizador: localizadores de metacaminho para uso com sys.
meta_path, e localizadores de entrada de caminho para uso com sys.path_hooks.
Veja PEP 302, PEP 420 e PEP 451 para mais informações.
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.
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:

267
The Python/C API, Release 3.10.6

def sum_two_numbers(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 compi-
lar o módulo atual usando sintaxe ou semântica que será padrão em uma versão futura de Python. O módulo he
__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.
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 local (incluindo
variá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áu-
sula for definindo uma variável de loop, um range, 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)) # sum of squares 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 implementaçã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 A type that can be parameterized; typically a container class such as list or dict. Used for type
hints and annotations.
For more details, see generic alias types, PEP 483, PEP 484, PEP 585, and the typing module.
GIL Veja bloqueio global do interpretador.
bloqueio 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 multitarefa, às custas de muito
do paralelismo já provido por máquinas multiprocessador.
However, some extension modules, either standard or third-party, are designed so as to release the GIL when
doing computationally intensive tasks such as compression or hashing. Also, the GIL is always released when
doing I/O.

268 Apêndice A. Glossário


The Python/C API, Release 3.10.6

No passado, esforços para criar um interpretador que lidasse plenamente com threads (travando dados com-
partilhados numa granularidade bem mais fina) não foram bem sucedidos devido a queda no desempenho ao
serem executados em processadores de apenas um núcleo. Acredita-se que superar essa questão de desempe-
nho acabaria tornando a implementação muito mais complicada e bem mais difícil de manter.
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.
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 An Integrated Development and Learning Environment for Python. idle is a basic editor and interpreter
environment which ships with the standard distribution of Python.
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)).
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 inter-
pretadas 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 espe-
cial, 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
terminou 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 não sequenciais como dict, objeto arquivo, e obje-
tos de qualquer classe que você definir com um método __iter__() ou com um método __getitem__()
que implemente a semântica de Sequência.

269
The Python/C API, Release 3.10.6

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 nativa 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 exception 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.
CPython implementation detail: CPython does not consistently apply the requirement that an iterator define
__iter__().
função chave Uma função chave ou função colação é um chamável que retorna um valor usado para ordenação ou
classificaçã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 em Python aceitam funções chave para controlar como os elementos são ordenados
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 construída a partir de uma expressão lambda, como lambda r: (r[0], r[2]). Além disso, o
módulo operator dispõe de três construtores para funções chave: attrgetter(), itemgetter() e
o methodcaller(). Consulte o HowTo 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 é cha-
mada. 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 bloqueios ou usando a abordagem EAFP.
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).
locale.getpreferredencoding(False) pode ser usado para obter da codificação da localidade.
Python usa tratador de erros e codificação do sistema de arquivos para converter entre nomes de arquivos e
nomes de arquivos de bytes Unicode.
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).

270 Apêndice A. Glossário


The Python/C API, Release 3.10.6

compreensão de lista Uma maneira compacta de processar todos ou parte dos elementos de uma sequência e re-
tornar 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. Deve definir um método chamado load_module(). Um car-
regador é normalmente devolvido por um localizador. Veja a PEP 302 para detalhes e importlib.abc.
Loader para um classe base abstrata.
método mágico Um sinônimo informal para um método especial.
mapeamento Um objeto contêiner que suporta buscas por chaves arbitrárias e implementa os métodos especificados
em classes base abstratas Mapping ou 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 relacionados a, mas diferentes de, localizadores de entrada de caminho.
Veja importlib.abc.MetaPathFinder para os métodos que localizadores de metacaminho imple-
mentam.
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 precisar 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 A ordem de resolução de métodos do Python 2.3 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
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.
módulo spec 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.
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] # indexed access


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

271
The Python/C API, Release 3.10.6

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 com uma função fábrica collections.
namedtuple(). A segunda técnica também adiciona 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. Existem 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 imple-
mentam 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 da PEP 420 que serve apenas como container para sub pacotes. 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.
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.
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.
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 posonly1 e posonly2 a seguir:

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

• 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 kw_only1 and kw_only2 a seguir:

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

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

272 Apêndice A. Glossário


The Python/C API, Release 3.10.6

• 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 o termo argumento no glossário, a pergunta 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.
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
implementam.
gancho de entrada de caminho Um chamável na lista sys.path_hook 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 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 adicio-
nadas 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 con-
tribuem 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 com-
patibilidade 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 se-
rã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”.

273
The Python/C API, Release 3.10.6

Pythônico Uma ideia ou um pedaço de código que segue de perto os idiomas mais comuns da linguagem Python,
ao invés de implementar códigos usando conceitos comuns a outros idiomas. Por exemplo, um idioma comum
em Python é fazer um loop sobre todos os elementos de uma iterável usando a instrução for. 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(food)):
print(food[i])

Ao contrário do método limpo, ou então, Pythônico:

for piece in food:


print(piece)

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 meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'

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 para um objeto. Quando a contagem de referências de um objeto
atinge zero, ele é desalocado. Contagem de referências geralmente não é visível no código Python, mas é
um elemento chave da implementação CPython. O módulo sys define a função getrefcount() que
programadores podem chamar para retornar a contagem de referências para um objeto em particular.
pacote regular Um pacote tradicional, como um diretório contendo um arquivo __init__.py.
Veja também pacote de espaço de nomes.
__slots__ Uma declaração dentro de uma classe que economiza memória pré-declarando espaço para atributos de
instâ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
especial __getitem__() e que define o método __len__() que devolve o tamanho da sequência. Alguns
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 mapa e não uma sequência porque a busca usa
uma chave imutá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().

274 Apêndice A. Glossário


The Python/C API, Release 3.10.6

compreensão de conjunto Uma maneira compacta de processar todos ou parte dos elementos em iterável e retor-
nar 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.
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.
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.
referência forte Na API C do Python, uma referência forte é uma referência a um objeto que aumenta a contagem de
referências do objeto quando ele é criado e diminui a contagem de referências do objeto quando ele é excluído.
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.
Veja também referência emprestada.
codificador de texto A string in Python is a sequence of Unicode code points (in range U+0000–U+10FFFF). To
store or transfer a string, it needs to be serialized as a sequence of bytes.
Serializing a string into a sequence of bytes is known as “encoding”, and recreating the string from the sequence
of bytes is known as “decoding”.
There are a variety of different text serialization codecs, which are collectively referred to as “text encodings”.
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 byte ou similar.
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 tipo de objeto ele é; cada objeto tem um tipo. Um tipo de objeto é
acessível pelo atributo __class__ ou pode ser recuperado com type(obj).
tipo alias Um sinônimo para um tipo, criado através da atribuição do tipo para um identificador.
Tipos alias são úteis para simplificar dicas de tipo. Por exemplo:

def remove_gray_shades(
colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass

pode tornar-se mais legível desta forma:

Color = tuple[int, int, int]

def remove_gray_shades(colors: list[Color]) -> list[Color]:


pass

Veja typing e PEP 484, a qual descreve esta funcionalidade.

275
The Python/C API, Release 3.10.6

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 ferramentas de análise de
tipos estático, e 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.
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:
field: 'annotation'

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:

count: 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 atuali-
zarem 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 byte-
code emitido pelo compilador de bytecode.
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.

276 Apêndice A. Glossário


APÊNDICE B

Sobre esses documentos

Esses documentos são gerados a partir de reStructuredText pelo Sphinx, um processador de documentos especifica-
mente escrito para documentação Python.
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 escritor de boa
parte do conteúdo;
• the Docutils project for creating reStructuredText and the Docutils suite;
• Fredrik Lundh, pelo seu projeto de referência alternativa em Python, do qual Sphinx pegou muitas boas ideias.

B.1 Contribuidores da Documentação 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!

277
The Python/C API, Release 3.10.6

278 Apêndice B. Sobre esses documentos


APÊNDICE C

História e Licença

C.1 História do software

O Python foi criado no início dos anos 1990 por Guido van Rossum na Stichting Mathematisch Centrum (CWI,
veja https://www.cwi.nl/) na Holanda como um sucessor de uma linguagem chamada ABC. Guido continua a ser o
principal autor de Python, embora inclua muitas contribuições de outros.
Em 1995, Guido continuou seu trabalho em Python na Corporação para Iniciativas Nacionais de Pesquisa (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 principal de desenvolvimento do Python mudaram-se para o BeOpen.com para
formar a equipe BeOpen PythonLabs. Em outubro do mesmo ano, a equipe da PythonLabs mudou para a Digital
Creations (agora Zope Corporation; veja https://www.zope.org/). Em 2001, formou-se a Python Software Foundation
(PSF, veja https://www.python.org/psf/), uma organização sem fins lucrativos criada especificamente para possuir
propriedade intelectual relacionada a Python. A Zope Corporation é um membro patrocinador do 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?


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 não
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: 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

279
The Python/C API, Release 3.10.6

licenças compatíveis com a GPL possibilitam combinar o Python com outro software lançado sob a GPL; os outros
não.

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 o Acordo de Licenciamento PSF.


A partir do Python 3.8.6, exemplos, receitas e outros códigos na documentação são licenciados duplamente sob o
Acordo de Licenciamento PSF 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 ACORDO DE LICENCIAMENTO DA PSF PARA PYTHON 3.10.6

1. This LICENSE AGREEMENT is between the Python Software Foundation␣


,→("PSF"), and

the Individual or Organization ("Licensee") accessing and otherwise␣


,→using Python

3.10.6 software in source or binary form and its associated␣


,→documentation.

2. Subject to the terms and conditions of this License Agreement, PSF␣


,→hereby

grants Licensee a nonexclusive, royalty-free, world-wide license to␣


,→reproduce,

analyze, test, perform and/or display publicly, prepare derivative␣


,→works,

distribute, and otherwise use Python 3.10.6 alone or in any derivative


version, provided, however, that PSF's License Agreement and PSF's␣
,→notice of

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


,→Rights

Reserved" are retained in Python 3.10.6 alone or in any derivative␣


,→version

prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or


incorporates Python 3.10.6 or any part thereof, and wants to make the
derivative work available to others as provided herein, then Licensee␣
,→hereby

agrees to include in any such work a brief summary of the changes made␣
,→to Python

3.10.6.

4. PSF is making Python 3.10.6 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

280 Apêndice C. História e Licença


The Python/C API, Release 3.10.6

USE OF PYTHON 3.10.6 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

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

MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.10.6, OR ANY␣


,→DERIVATIVE

THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material␣


,→breach of

its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any␣


,→relationship

of agency, partnership, or joint venture between PSF and Licensee. ␣


,→This License

Agreement does not grant permission to use PSF trademarks or trade name␣
,→in a

trademark sense to endorse or promote products or services of Licensee,␣


,→or any

third party.

8. By copying, installing or otherwise using Python 3.10.6, 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
(continua na próxima página)

C.2. Termos e condições para acessar ou usar Python 281


The Python/C API, Release 3.10.6

(continuação da página anterior)


agency, partnership, or joint venture between BeOpen and Licensee. This License
Agreement does not grant permission to use BeOpen trademarks or trade names in a
trademark sense to endorse or promote products or services of Licensee, or any
third party. As an exception, the "BeOpen Python" logos available at
http://www.pythonlabs.com/logos.html may be used according to the permissions
granted on that web page.

7. By copying, installing or otherwise using the software, Licensee agrees to be


bound by the terms and conditions of this License Agreement.

C.2.3 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
(continua na próxima página)

282 Apêndice C. História e Licença


The Python/C API, Release 3.10.6

(continuação da página anterior)


Virginia shall govern this License Agreement only as to issues arising under or
with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in
this License Agreement shall be deemed to create any relationship of agency,
partnership, or joint venture between CNRI and Licensee. This License Agreement
does not grant permission to use CNRI trademarks or trade name in a trademark
sense to endorse or promote products or services of Licensee, or any third
party.

8. By clicking on the "ACCEPT" button where indicated, or by copying, installing


or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
conditions of this License Agreement.

C.2.4 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 LICENÇA BSD DE ZERO CLÁUSULA PARA CÓDIGO NA DOCUMENTAÇÃO


DO PYTHON 3.10.6

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

C.2. Termos e condições para acessar ou usar Python 283


The Python/C API, Release 3.10.6

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

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

A C-program for MT19937, with initialization improved 2002/1/26.


Coded by Takuji Nishimura and Makoto Matsumoto.

Before using, initialize the state by using init_genrand(seed)


or init_by_array(init_key, key_length).

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,


All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright


notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. The names of its contributors may not be used to endorse or promote


products derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS


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

Any feedback is very welcome.


http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)

284 Apêndice C. História e Licença


The Python/C API, Release 3.10.6

C.3.2 Soquetes

The socket module uses the functions, getaddrinfo(), and getnameinfo(), which are coded in separate
source files from the WIDE Project, 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.

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 asynchat e 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. Licenças e Reconhecimentos para Software Incorporado 285


The Python/C API, Release 3.10.6

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


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.

286 Apêndice C. História e Licença


The Python/C API, Release 3.10.6

C.3.6 Funções UUencode e UUdecode

O módulo 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
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. Licenças e Reconhecimentos para Software Incorporado 287


The Python/C API, Release 3.10.6

C.3.8 test_epoll

O módulo 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:

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.

288 Apêndice C. História e Licença


The Python/C API, Release 3.10.6

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

The file Python/dtoa.c, which supplies C functions dtoa and strtod for conversion of C doubles to and from
strings, is derived from the file of the same name by David M. Gay, currently available from https://web.archive.org/
web/20220517033456/http://www.netlib.org/fp/dtoa.c. The original file, as retrieved on March 16, 2009, contains
the following copyright and licensing notice:

/****************************************************************
*
* 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. Licenças e Reconhecimentos para Software Incorporado 289


The Python/C API, Release 3.10.6

C.3.12 OpenSSL

The modules hashlib, posix, ssl, crypt use the OpenSSL library for added performance if made available
by the operating system. Additionally, the Windows and macOS installers for Python may include a copy of the
OpenSSL libraries, so we include a copy of the OpenSSL license here:

LICENSE ISSUES
==============

The OpenSSL toolkit stays under a dual license, i.e. both the conditions of
the OpenSSL License and the original SSLeay license apply to the toolkit.
See below for the actual license texts. Actually both licenses are BSD-style
Open Source licenses. In case of any license issues related to OpenSSL
please contact [email protected].

OpenSSL License
---------------

/* ====================================================================
* Copyright (c) 1998-2008 The OpenSSL 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. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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)
(continua na próxima página)

290 Apêndice C. História e Licença


The Python/C API, Release 3.10.6

(continuação da página anterior)


* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* ([email protected]). This product includes software written by Tim
* Hudson ([email protected]).
*
*/

Original SSLeay License


-----------------------

/* Copyright (C) 1995-1998 Eric Young ([email protected])


* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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
(continua na próxima página)

C.3. Licenças e Reconhecimentos para Software Incorporado 291


The Python/C API, Release 3.10.6

(continuação da página anterior)


* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/

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 _ctypes é construída usando uma cópia incluída das fontes libffi, a menos que a compilação esteja
configurada --with-system-libffi:

Copyright (c) 1996-2008 Red Hat, Inc and others.

Permission is hereby granted, free of charge, to any person obtaining


a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,


EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
(continua na próxima página)

292 Apêndice C. História e Licença


The Python/C API, Release 3.10.6

(continuação da página anterior)


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.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 compilaçã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
(continua na próxima página)

C.3. Licenças e Reconhecimentos para Software Incorporado 293


The Python/C API, Release 3.10.6

(continuação da página anterior)


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.

C.3.17 libmpdec

O módulo _decimal é construído usando uma cópia incluída da biblioteca libmpdec, a menos que a compilação
esteja configurada --with-system-libmpdec:

Copyright (c) 2008-2020 Stefan Krah. All rights reserved.

Redistribution and use in source and binary forms, with or without


modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright


notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright


notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

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

C.3.18 Conjunto de 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:

(continua na próxima página)

294 Apêndice C. História e Licença


The Python/C API, Release 3.10.6

(continuação da página anterior)


* Redistributions of works must retain the original copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the W3C nor the names of its contributors may be
used to endorse or promote products derived from this work without
specific prior written permission.

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. Licenças e Reconhecimentos para Software Incorporado 295


The Python/C API, Release 3.10.6

296 Apêndice C. História e Licença


APÊNDICE D

Direitos autorais

Python e essa documentação é:


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

297
The Python/C API, Release 3.10.6

298 Apêndice D. Direitos autorais


Índice

Não alfabético abs


..., 263 função interna, 90
2to3, 263 aguardável, 264
>>>, 263 allocfunc (C type), 254
__all__ (package variable), 64 ambiente virtual, 276
__dict__ (module attribute), 150 anotação, 263
__doc__ (module attribute), 150 anotação de função, 267
__file__ (module attribute), 150 anotação de variável, 276
__future__, 268 API provisória, 273
__import__ argumento, 263
função interna, 64 argumento nomeado, 270
__loader__ (module attribute), 150 argumento posicional, 273
__main__ argv (in module sys), 175
módulo, 11, 172, 183 arquivo binário, 264
__name__ (module attribute), 150 arquivo texto, 275
__package__ (module attribute), 150 ascii
__PYVENV_LAUNCHER__, 196, 201 função interna, 83
__slots__, 274 aspas triplas, 275
_frozen (C struct), 67 atributo, 264
_inittab (C struct), 67
_Py_c_diff (C function), 113
B
_Py_c_neg (C function), 113 BDFL, 264
_Py_c_pow (C function), 114 binaryfunc (C type), 255
_Py_c_prod (C function), 113 bloqueio global do interpretador, 268
_Py_c_quot (C function), 113 buffer interface
_Py_c_sum (C function), 113 (see buffer protocol), 96
_Py_InitializeMain (C function), 207 buffer object
_Py_NoneStruct (C var), 219 (see buffer protocol), 96
_PyBytes_Resize (C function), 116 buffer protocol, 96
_PyCFunctionFast (C type), 222 builtins
_PyCFunctionFastWithKeywords (C type), 222 módulo, 11, 172, 183
_PyFrameEvalFunction (C type), 181 bytearray
_PyInterpreterState_GetEvalFrameFunc objeto, 117
(C function), 181 bytecode, 265
_PyInterpreterState_SetEvalFrameFunc bytes
(C function), 181 função interna, 83
_PyObject_New (C function), 219 objeto, 115
_PyObject_NewVar (C function), 219
_PyTuple_Resize (C function), 137 C
_thread calloc(), 209
módulo, 178 caminho de importação, 269
Capsule
A objeto, 161
abort(), 63 carregador, 271

299
The Python/C API, Release 3.10.6

C-contiguous, 99, 265 F


classe, 265 f-string, 267
classe base abstrata, 263 fatia, 275
classe estilo novo, 272 file
classmethod objeto, 148
função interna, 223 float
cleanup functions, 64 função interna, 92
close() (in module os), 183 floating point
CO_FUTURE_DIVISION (C var), 43 objeto, 112
code object, 147 Fortran contiguous, 99, 265
codificação da localidade, 270 free(), 209
codificador de texto, 275 freefunc (C type), 254
coerção, 265 freeze utility, 67
coleta de lixo, 268 frozenset
compile objeto, 143
função interna, 65 função, 267
complex number função chave, 270
objeto, 113 função de corrotina, 266
compreensão de conjunto, 275 função de retorno, 265
compreensão de dicionário, 266 função genérica, 268
compreensão de lista, 271 função interna
contagem de referências, 274 __import__, 64
contíguo, 265 abs, 90
contiguous, 99 ascii, 83
copyright (in module sys), 175 bytes, 83
corrotina, 265 classmethod, 223
CPython, 266 compile, 65
divmod, 90
D float, 92
decorador, 266 hash, 84, 235
descrgetfunc (C type), 255 int, 91
descritor, 266 len, 84, 92, 94, 139, 142, 144
descrsetfunc (C type), 255 pow, 90, 91
desligamento do interpretador, 269 repr, 83, 235
despacho único, 275 staticmethod, 224
destructor (C type), 254 tuple, 93, 140
dica de tipo, 276 type, 84
dicionário, 266 function
dictionary objeto, 145
objeto, 141
divisão pelo piso, 267 G
divmod gancho de entrada de caminho, 273
função interna, 90 generator, 268
docstring, 266 generator expression, 268
gerador, 268
E gerador assíncrono, 264
EAFP, 267 gerenciador de contexto, 265
entrada de caminho, 273 gerenciador de contexto assíncrono,
EOFError (built-in exception), 149 264
escopo aninhado, 272 getattrfunc (C type), 255
espaço de nomes, 272 getattrofunc (C type), 255
exc_info() (in module sys), 10 getbufferproc (C type), 255
exec_prefix, 4 getiterfunc (C type), 255
executable (in module sys), 174 GIL, 268
exit(), 64 global interpreter lock, 176
expressão, 267
expressão geradora, 268 H
hash

300 Índice
The Python/C API, Release 3.10.6

função interna, 84, 235 objeto, 141


hasheável, 269 máquina virtual, 276
hashfunc (C type), 255 memoryview
objeto, 159
I metaclasse, 271
IDLE, 269 METH_CLASS (variável interna), 223
importação, 269 METH_COEXIST (variável interna), 224
importador, 269 METH_FASTCALL (variável interna), 223
imutável, 269 METH_NOARGS (variável interna), 223
incr_item(), 10, 11 METH_O (variável interna), 223
initproc (C type), 254 METH_STATIC (variável interna), 223
inquiry (C type), 260 METH_VARARGS (variável interna), 223
instancemethod method
objeto, 146 magic, 271
instrução, 275 objeto, 146
int special, 275
função interna, 91 MethodType (in module types), 145, 146
integer método, 271
objeto, 109 método especial, 275
interativo, 269 método mágico, 271
interpretado, 269 module
interpreter lock, 176 objeto, 150
iterador, 270 search path, 11, 172, 174
iterador assíncrono, 264 modules (in module sys), 64, 172
iterador gerador, 268 ModuleType (in module types), 150
iterador gerador assíncrono, 264 módulo, 271
iterável, 269 __main__, 11, 172, 183
iterável assíncrono, 264 _thread, 178
iternextfunc (C type), 255 builtins, 11, 172, 183
signal, 53
K sys, 11, 172, 183
KeyboardInterrupt (built-in exception), 53 módulo de extensão, 267
módulo spec, 271
L MRO, 271
mutável, 271
lambda, 270
LBYL, 270 N
len
newfunc (C type), 254
função interna, 84, 92, 94, 139, 142, 144
nome qualificado, 274
lenfunc (C type), 255
None
list
objeto, 109
objeto, 139
novas linhas universais, 276
lista, 270
numeric
localizador, 267
objeto, 109
localizador baseado no caminho, 273
número complexo, 265
localizador de entrada de caminho, 273
localizador de metacaminho, 271
lock, interpreter, 176
O
long integer object
objeto, 109 code, 147
LONG_MAX, 110 objeto, 272
bytearray, 117
M bytes, 115
magic Capsule, 161
method, 271 complex number, 113
main(), 173, 175 dictionary, 141
malloc(), 209 file, 148
mapeamento, 271 floating point, 112
mapping frozenset, 143

Índice 301
The Python/C API, Release 3.10.6

function, 145 PEP 443, 268


instancemethod, 146 PEP 451, 153, 267
integer, 109 PEP 483, 268
list, 139 PEP 484, 263, 268, 275, 276
long integer, 109 PEP 489, 153
mapping, 141 PEP 492, 264, 266
memoryview, 159 PEP 498, 267
method, 146 PEP 519, 273
module, 150 PEP 523, 181, 182
None, 109 PEP 525, 264
numeric, 109 PEP 526, 263, 276
sequence, 114 PEP 528, 171, 199
set, 143 PEP 529, 126, 171
tuple, 137 PEP 538, 205
type, 6, 105 PEP 539, 187
objeto arquivo, 267 PEP 540, 205
objeto arquivo ou similar, 267 PEP 552, 197
objeto byte ou similar, 265 PEP 578, 63
objeto caminho ou similar, 273 PEP 585, 268
objobjargproc (C type), 255 PEP 587, 189
objobjproc (C type), 255 PEP 590, 85
ordem de resolução de métodos, 271 PEP 623, 118
OverflowError (built-in exception), 110, 111 PEP 634, 239, 240
PEP 3116, 276
P PEP 3119, 83
package variable PEP 3121, 151
__all__, 64 PEP 3147, 66
pacote, 272 PEP 3151, 58
pacote de espaço de nomes, 272 PEP 3155, 274
pacote provisório, 273 Py_ABS (C macro), 5
pacote regular, 274 Py_AddPendingCall (C function), 184
parâmetro, 272 Py_AddPendingCall(), 184
PATH, 12 Py_AtExit (C function), 64
path Py_BEGIN_ALLOW_THREADS, 176
module search, 11, 172, 174 Py_BEGIN_ALLOW_THREADS (C macro), 180
path (in module sys), 11, 172, 174 Py_BLOCK_THREADS (C macro), 180
PEP, 273 Py_buffer (C type), 97
platform (in module sys), 175 Py_buffer.buf (C member), 97
porção, 273 Py_buffer.format (C member), 97
pow Py_buffer.internal (C member), 98
função interna, 90, 91 Py_buffer.itemsize (C member), 97
prefix, 4 Py_buffer.len (C member), 97
Propostas Estendidas Python Py_buffer.ndim (C member), 97
PEP 1, 273 Py_buffer.obj (C member), 97
PEP 7, 3, 5, 6 Py_buffer.readonly (C member), 97
PEP 238, 43, 267 Py_buffer.shape (C member), 98
PEP 278, 276 Py_buffer.strides (C member), 98
PEP 302, 267, 271 Py_buffer.suboffsets (C member), 98
PEP 343, 265 Py_BuildValue (C function), 75
PEP 353, 9 Py_BytesMain (C function), 39
PEP 362, 264, 273 Py_BytesWarningFlag (C var), 170
PEP 383, 126 Py_CHARMASK (C macro), 5
PEP 387, 13 Py_CLEAR (C function), 46
PEP 393, 118, 125 Py_CompileString (C function), 41
PEP 411, 273 Py_CompileString(), 42
PEP 420, 267, 272, 273 Py_CompileStringExFlags (C function), 41
PEP 432, 207, 208 Py_CompileStringFlags (C function), 41
PEP 442, 248 Py_CompileStringObject (C function), 41

302 Índice
The Python/C API, Release 3.10.6

Py_complex (C type), 113 Py_IsInitialized (C function), 172


Py_DebugFlag (C var), 170 Py_IsInitialized(), 12
Py_DecodeLocale (C function), 60 Py_IsNone (C function), 220
Py_DECREF (C function), 46 Py_IsolatedFlag (C var), 171
Py_DecRef (C function), 46 Py_IsTrue (C function), 220
Py_DECREF(), 6 Py_LeaveRecursiveCall (C function), 56
Py_DEPRECATED (C macro), 5 Py_LegacyWindowsFSEncodingFlag (C var),
Py_DontWriteBytecodeFlag (C var), 170 171
Py_Ellipsis (C var), 159 Py_LegacyWindowsStdioFlag (C var), 171
Py_EncodeLocale (C function), 61 Py_LIMITED_API (C macro), 13
Py_END_ALLOW_THREADS, 176 Py_Main (C function), 39
Py_END_ALLOW_THREADS (C macro), 180 PY_MAJOR_VERSION (C macro), 261
Py_EndInterpreter (C function), 183 Py_MAX (C macro), 5
Py_EnterRecursiveCall (C function), 56 Py_MEMBER_SIZE (C macro), 5
Py_eval_input (C var), 42 PY_MICRO_VERSION (C macro), 261
Py_Exit (C function), 63 Py_MIN (C macro), 5
Py_False (C var), 112 PY_MINOR_VERSION (C macro), 261
Py_FatalError (C function), 63 Py_mod_create (C macro), 153
Py_FatalError(), 175 Py_mod_create.create_module (C function),
Py_FdIsInteractive (C function), 59 153
Py_file_input (C var), 42 Py_mod_exec (C macro), 153
Py_Finalize (C function), 172 Py_mod_exec.exec_module (C function), 153
Py_FinalizeEx (C function), 172 Py_NewInterpreter (C function), 183
Py_FinalizeEx(), 64, 172, 183 Py_NewRef (C function), 45
Py_FrozenFlag (C var), 170 Py_None (C var), 109
Py_GenericAlias (C function), 167 Py_NoSiteFlag (C var), 171
Py_GenericAliasType (C var), 168 Py_NotImplemented (C var), 81
Py_GetArgcArgv (C function), 207 Py_NoUserSiteDirectory (C var), 171
Py_GetBuildInfo (C function), 175 Py_OptimizeFlag (C var), 171
Py_GetCompiler (C function), 175 Py_PreInitialize (C function), 193
Py_GetCopyright (C function), 175 Py_PreInitializeFromArgs (C function), 194
Py_GETENV (C macro), 5 Py_PreInitializeFromBytesArgs (C func-
Py_GetExecPrefix (C function), 173 tion), 193
Py_GetExecPrefix(), 12 Py_PRINT_RAW, 149
Py_GetPath (C function), 174 Py_QuietFlag (C var), 171
Py_GetPath(), 12, 173, 174 Py_REFCNT (C function), 221
Py_GetPlatform (C function), 175 PY_RELEASE_LEVEL (C macro), 261
Py_GetPrefix (C function), 173 PY_RELEASE_SERIAL (C macro), 261
Py_GetPrefix(), 12 Py_ReprEnter (C function), 56
Py_GetProgramFullPath (C function), 174 Py_ReprLeave (C function), 56
Py_GetProgramFullPath(), 12 Py_RETURN_FALSE (C macro), 112
Py_GetProgramName (C function), 173 Py_RETURN_NONE (C macro), 109
Py_GetPythonHome (C function), 176 Py_RETURN_NOTIMPLEMENTED (C macro), 81
Py_GetVersion (C function), 174 Py_RETURN_TRUE (C macro), 112
Py_HashRandomizationFlag (C var), 170 Py_RunMain (C function), 207
Py_IgnoreEnvironmentFlag (C var), 170 Py_SET_REFCNT (C function), 221
Py_INCREF (C function), 45 Py_SET_SIZE (C function), 221
Py_IncRef (C function), 46 Py_SET_TYPE (C function), 221
Py_INCREF(), 6 Py_SetPath (C function), 174
Py_Initialize (C function), 172 Py_SetPath(), 174
Py_Initialize(), 11, 173, 183 Py_SetProgramName (C function), 173
Py_InitializeEx (C function), 172 Py_SetProgramName(), 12, 172174
Py_InitializeFromConfig (C function), 203 Py_SetPythonHome (C function), 176
Py_InspectFlag (C var), 171 Py_SetStandardStreamEncoding (C function),
Py_InteractiveFlag (C var), 171 173
Py_Is (C function), 220 Py_single_input (C var), 42
Py_IS_TYPE (C function), 221 Py_SIZE (C function), 221
Py_IsFalse (C function), 221 Py_ssize_t (C type), 9

Índice 303
The Python/C API, Release 3.10.6

PY_SSIZE_T_MAX, 111 Py_UNICODE_ISNUMERIC (C function), 121


Py_STRINGIFY (C macro), 5 Py_UNICODE_ISPRINTABLE (C function), 121
Py_TPFLAGS_BASE_EXC_SUBCLASS (variável in- Py_UNICODE_ISSPACE (C function), 120
terna), 238 Py_UNICODE_ISTITLE (C function), 120
Py_TPFLAGS_BASETYPE (variável interna), 237 Py_UNICODE_ISUPPER (C function), 120
Py_TPFLAGS_BYTES_SUBCLASS (variável interna), Py_UNICODE_JOIN_SURROGATES (C macro), 121
238 Py_UNICODE_TODECIMAL (C function), 121
Py_TPFLAGS_DEFAULT (variável interna), 238 Py_UNICODE_TODIGIT (C function), 121
Py_TPFLAGS_DICT_SUBCLASS (variável interna), Py_UNICODE_TOLOWER (C function), 121
238 Py_UNICODE_TONUMERIC (C function), 121
Py_TPFLAGS_DISALLOW_INSTANTIATION (va- Py_UNICODE_TOTITLE (C function), 121
riável interna), 239 Py_UNICODE_TOUPPER (C function), 121
Py_TPFLAGS_HAVE_FINALIZE (variável interna), Py_UNREACHABLE (C macro), 4
239 Py_UNUSED (C macro), 5
Py_TPFLAGS_HAVE_GC (variável interna), 238 Py_VaBuildValue (C function), 76
Py_TPFLAGS_HAVE_VECTORCALL (variável PY_VECTORCALL_ARGUMENTS_OFFSET (C ma-
interna), 239 cro), 86
Py_TPFLAGS_HEAPTYPE (variável interna), 237 Py_VerboseFlag (C var), 171
Py_TPFLAGS_IMMUTABLETYPE (variável interna), PY_VERSION_HEX (C macro), 261
239 Py_VISIT (C function), 259
Py_TPFLAGS_LIST_SUBCLASS (variável interna), Py_XDECREF (C function), 46
238 Py_XDECREF(), 11
Py_TPFLAGS_LONG_SUBCLASS (variável interna), Py_XINCREF (C function), 45
238 Py_XNewRef (C function), 45
Py_TPFLAGS_MAPPING (variável interna), 239 PyAIter_Check (C function), 95
Py_TPFLAGS_METHOD_DESCRIPTOR (variável in- PyAnySet_Check (C function), 144
terna), 238 PyAnySet_CheckExact (C function), 144
Py_TPFLAGS_READY (variável interna), 237 PyArg_Parse (C function), 74
Py_TPFLAGS_READYING (variável interna), 238 PyArg_ParseTuple (C function), 74
Py_TPFLAGS_SEQUENCE (variável interna), 240 PyArg_ParseTupleAndKeywords (C function),
Py_TPFLAGS_TUPLE_SUBCLASS (variável interna), 74
238 PyArg_UnpackTuple (C function), 74
Py_TPFLAGS_TYPE_SUBCLASS (variável interna), PyArg_ValidateKeywordArguments (C func-
238 tion), 74
Py_TPFLAGS_UNICODE_SUBCLASS (variável in- PyArg_VaParse (C function), 74
terna), 238 PyArg_VaParseTupleAndKeywords (C func-
Py_tracefunc (C type), 185 tion), 74
Py_True (C var), 112 PyASCIIObject (C type), 118
Py_tss_NEEDS_INIT (C macro), 187 PyAsyncMethods (C type), 253
Py_tss_t (C type), 187 PyAsyncMethods.am_aiter (C member), 254
Py_TYPE (C function), 221 PyAsyncMethods.am_anext (C member), 254
Py_UCS1 (C type), 118 PyAsyncMethods.am_await (C member), 254
Py_UCS2 (C type), 118 PyAsyncMethods.am_send (C member), 254
Py_UCS4 (C type), 118 PyBool_Check (C function), 112
Py_UNBLOCK_THREADS (C macro), 180 PyBool_FromLong (C function), 112
Py_UnbufferedStdioFlag (C var), 171 PyBUF_ANY_CONTIGUOUS (C macro), 99
Py_UNICODE (C type), 118 PyBUF_C_CONTIGUOUS (C macro), 99
Py_UNICODE_IS_HIGH_SURROGATE (C macro), PyBUF_CONTIG (C macro), 100
121 PyBUF_CONTIG_RO (C macro), 100
Py_UNICODE_IS_LOW_SURROGATE (C macro), PyBUF_F_CONTIGUOUS (C macro), 99
121 PyBUF_FORMAT (C macro), 99
Py_UNICODE_IS_SURROGATE (C macro), 121 PyBUF_FULL (C macro), 100
Py_UNICODE_ISALNUM (C function), 121 PyBUF_FULL_RO (C macro), 100
Py_UNICODE_ISALPHA (C function), 121 PyBUF_INDIRECT (C macro), 99
Py_UNICODE_ISDECIMAL (C function), 121 PyBUF_ND (C macro), 99
Py_UNICODE_ISDIGIT (C function), 121 PyBUF_RECORDS (C macro), 100
Py_UNICODE_ISLINEBREAK (C function), 120 PyBUF_RECORDS_RO (C macro), 100
Py_UNICODE_ISLOWER (C function), 120 PyBUF_SIMPLE (C macro), 99

304 Índice
The Python/C API, Release 3.10.6

PyBUF_STRIDED (C macro), 100 PyCapsule_GetName (C function), 161


PyBUF_STRIDED_RO (C macro), 100 PyCapsule_GetPointer (C function), 161
PyBUF_STRIDES (C macro), 99 PyCapsule_Import (C function), 162
PyBUF_WRITABLE (C macro), 99 PyCapsule_IsValid (C function), 162
PyBuffer_FillContiguousStrides (C func- PyCapsule_New (C function), 161
tion), 102 PyCapsule_SetContext (C function), 162
PyBuffer_FillInfo (C function), 102 PyCapsule_SetDestructor (C function), 162
PyBuffer_FromContiguous (C function), 102 PyCapsule_SetName (C function), 162
PyBuffer_GetPointer (C function), 102 PyCapsule_SetPointer (C function), 162
PyBuffer_IsContiguous (C function), 102 PyCell_Check (C function), 147
PyBuffer_Release (C function), 101 PyCell_GET (C function), 147
PyBuffer_SizeFromFormat (C function), 102 PyCell_Get (C function), 147
PyBuffer_ToContiguous (C function), 102 PyCell_New (C function), 147
PyBufferProcs, 96 PyCell_SET (C function), 147
PyBufferProcs (C type), 252 PyCell_Set (C function), 147
PyBufferProcs.bf_getbuffer (C member), PyCell_Type (C var), 147
252 PyCellObject (C type), 147
PyBufferProcs.bf_releasebuffer (C mem- PyCFunction (C type), 222
ber), 253 PyCFunctionWithKeywords (C type), 222
PyByteArray_AS_STRING (C function), 117 PyCMethod (C type), 222
PyByteArray_AsString (C function), 117 PyCode_Addr2Line (C function), 148
PyByteArray_Check (C function), 117 PyCode_Check (C function), 148
PyByteArray_CheckExact (C function), 117 PyCode_GetNumFree (C function), 148
PyByteArray_Concat (C function), 117 PyCode_New (C function), 148
PyByteArray_FromObject (C function), 117 PyCode_NewEmpty (C function), 148
PyByteArray_FromStringAndSize (C func- PyCode_NewWithPosOnlyArgs (C function), 148
tion), 117 PyCode_Type (C var), 148
PyByteArray_GET_SIZE (C function), 117 PyCodec_BackslashReplaceErrors (C func-
PyByteArray_Resize (C function), 117 tion), 80
PyByteArray_Size (C function), 117 PyCodec_Decode (C function), 79
PyByteArray_Type (C var), 117 PyCodec_Decoder (C function), 79
PyByteArrayObject (C type), 117 PyCodec_Encode (C function), 79
PyBytes_AS_STRING (C function), 116 PyCodec_Encoder (C function), 79
PyBytes_AsString (C function), 116 PyCodec_IgnoreErrors (C function), 80
PyBytes_AsStringAndSize (C function), 116 PyCodec_IncrementalDecoder (C function), 79
PyBytes_Check (C function), 115 PyCodec_IncrementalEncoder (C function), 79
PyBytes_CheckExact (C function), 115 PyCodec_KnownEncoding (C function), 79
PyBytes_Concat (C function), 116 PyCodec_LookupError (C function), 80
PyBytes_ConcatAndDel (C function), 116 PyCodec_NameReplaceErrors (C function), 80
PyBytes_FromFormat (C function), 115 PyCodec_Register (C function), 79
PyBytes_FromFormatV (C function), 115 PyCodec_RegisterError (C function), 80
PyBytes_FromObject (C function), 115 PyCodec_ReplaceErrors (C function), 80
PyBytes_FromString (C function), 115 PyCodec_StreamReader (C function), 80
PyBytes_FromStringAndSize (C function), 115 PyCodec_StreamWriter (C function), 80
PyBytes_GET_SIZE (C function), 116 PyCodec_StrictErrors (C function), 80
PyBytes_Size (C function), 116 PyCodec_Unregister (C function), 79
PyBytes_Type (C var), 115 PyCodec_XMLCharRefReplaceErrors (C func-
PyBytesObject (C type), 115 tion), 80
pyc baseado em hash, 269 PyCodeObject (C type), 148
PyCallable_Check (C function), 89 PyCompactUnicodeObject (C type), 118
PyCallIter_Check (C function), 157 PyCompilerFlags (C struct), 42
PyCallIter_New (C function), 157 PyCompilerFlags.cf_feature_version (C
PyCallIter_Type (C var), 157 member), 42
PyCapsule (C type), 161 PyCompilerFlags.cf_flags (C member), 42
PyCapsule_CheckExact (C function), 161 PyComplex_AsCComplex (C function), 114
PyCapsule_Destructor (C type), 161 PyComplex_Check (C function), 114
PyCapsule_GetContext (C function), 161 PyComplex_CheckExact (C function), 114
PyCapsule_GetDestructor (C function), 161 PyComplex_FromCComplex (C function), 114

Índice 305
The Python/C API, Release 3.10.6

PyComplex_FromDoubles (C function), 114 PyConfig.PyConfig_SetBytesArgv (C func-


PyComplex_ImagAsDouble (C function), 114 tion), 195
PyComplex_RealAsDouble (C function), 114 PyConfig.PyConfig_SetBytesString (C
PyComplex_Type (C var), 114 function), 195
PyComplexObject (C type), 114 PyConfig.PyConfig_SetString (C function),
PyConfig (C type), 194 194
PyConfig.argv (C member), 195 PyConfig.PyConfig_SetWideStringList (C
PyConfig.base_exec_prefix (C member), 196 function), 195
PyConfig.base_executable (C member), 196 PyConfig.pythonpath_env (C member), 199
PyConfig.base_prefix (C member), 196 PyConfig.quiet (C member), 201
PyConfig.buffered_stdio (C member), 196 PyConfig.run_command (C member), 201
PyConfig.bytes_warning (C member), 196 PyConfig.run_filename (C member), 201
PyConfig.check_hash_pycs_mode (C mem- PyConfig.run_module (C member), 201
ber), 196 PyConfig.show_ref_count (C member), 201
PyConfig.configure_c_stdio (C member), PyConfig.site_import (C member), 201
197 PyConfig.skip_source_first_line (C mem-
PyConfig.dev_mode (C member), 197 ber), 202
PyConfig.dump_refs (C member), 197 PyConfig.stdio_encoding (C member), 202
PyConfig.exec_prefix (C member), 197 PyConfig.stdio_errors (C member), 202
PyConfig.executable (C member), 197 PyConfig.tracemalloc (C member), 202
PyConfig.faulthandler (C member), 197 PyConfig.use_environment (C member), 202
PyConfig.filesystem_encoding (C member), PyConfig.use_hash_seed (C member), 198
197 PyConfig.user_site_directory (C member),
PyConfig.filesystem_errors (C member), 202
198 PyConfig.verbose (C member), 202
PyConfig.hash_seed (C member), 198 PyConfig.warn_default_encoding (C mem-
PyConfig.home (C member), 198 ber), 196
PyConfig.import_time (C member), 198 PyConfig.warnoptions (C member), 203
PyConfig.inspect (C member), 198 PyConfig.write_bytecode (C member), 203
PyConfig.install_signal_handlers (C PyConfig.xoptions (C member), 203
member), 198 PyContext (C type), 163
PyConfig.interactive (C member), 198 PyContext_CheckExact (C function), 164
PyConfig.isolated (C member), 199 PyContext_Copy (C function), 164
PyConfig.legacy_windows_stdio (C mem- PyContext_CopyCurrent (C function), 164
ber), 199 PyContext_Enter (C function), 164
PyConfig.malloc_stats (C member), 199 PyContext_Exit (C function), 164
PyConfig.module_search_paths (C member), PyContext_New (C function), 164
199 PyContext_Type (C var), 163
PyConfig.module_search_paths_set (C PyContextToken (C type), 163
member), 199 PyContextToken_CheckExact (C function), 164
PyConfig.optimization_level (C member), PyContextToken_Type (C var), 164
200 PyContextVar (C type), 163
PyConfig.orig_argv (C member), 200 PyContextVar_CheckExact (C function), 164
PyConfig.parse_argv (C member), 200 PyContextVar_Get (C function), 164
PyConfig.parser_debug (C member), 200 PyContextVar_New (C function), 164
PyConfig.pathconfig_warnings (C member), PyContextVar_Reset (C function), 164
200 PyContextVar_Set (C function), 164
PyConfig.platlibdir (C member), 199 PyContextVar_Type (C var), 163
PyConfig.prefix (C member), 200 PyCoro_CheckExact (C function), 163
PyConfig.program_name (C member), 200 PyCoro_New (C function), 163
PyConfig.pycache_prefix (C member), 201 PyCoro_Type (C var), 163
PyConfig.PyConfig_Clear (C function), 195 PyCoroObject (C type), 163
PyConfig.PyConfig_InitIsolatedConfig PyDate_Check (C function), 165
(C function), 194 PyDate_CheckExact (C function), 165
PyConfig.PyConfig_InitPythonConfig (C PyDate_FromDate (C function), 165
function), 194 PyDate_FromTimestamp (C function), 167
PyConfig.PyConfig_Read (C function), 195 PyDateTime_Check (C function), 165
PyConfig.PyConfig_SetArgv (C function), 195 PyDateTime_CheckExact (C function), 165

306 Índice
The Python/C API, Release 3.10.6

PyDateTime_DATE_GET_FOLD (C function), 166 PyDict_Next (C function), 142


PyDateTime_DATE_GET_HOUR (C function), 166 PyDict_SetDefault (C function), 142
PyDateTime_DATE_GET_MICROSECOND (C func- PyDict_SetItem (C function), 141
tion), 166 PyDict_SetItemString (C function), 141
PyDateTime_DATE_GET_MINUTE (C function), PyDict_Size (C function), 142
166 PyDict_Type (C var), 141
PyDateTime_DATE_GET_SECOND (C function), PyDict_Update (C function), 143
166 PyDict_Values (C function), 142
PyDateTime_DATE_GET_TZINFO (C function), PyDictObject (C type), 141
166 PyDictProxy_New (C function), 141
PyDateTime_DELTA_GET_DAYS (C function), 167 PyDoc_STR (C macro), 6
PyDateTime_DELTA_GET_MICROSECONDS (C PyDoc_STRVAR (C macro), 5
function), 167 PyErr_BadArgument (C function), 48
PyDateTime_DELTA_GET_SECONDS (C function), PyErr_BadInternalCall (C function), 50
167 PyErr_CheckSignals (C function), 53
PyDateTime_FromDateAndTime (C function), PyErr_Clear (C function), 47
165 PyErr_Clear(), 10, 11
PyDateTime_FromDateAndTimeAndFold (C PyErr_ExceptionMatches (C function), 51
function), 165 PyErr_ExceptionMatches(), 11
PyDateTime_FromTimestamp (C function), 167 PyErr_Fetch (C function), 51
PyDateTime_GET_DAY (C function), 166 PyErr_Format (C function), 48
PyDateTime_GET_MONTH (C function), 166 PyErr_FormatV (C function), 48
PyDateTime_GET_YEAR (C function), 166 PyErr_GetExcInfo (C function), 52
PyDateTime_TIME_GET_FOLD (C function), 167 PyErr_GivenExceptionMatches (C function),
PyDateTime_TIME_GET_HOUR (C function), 167 51
PyDateTime_TIME_GET_MICROSECOND (C func- PyErr_NewException (C function), 54
tion), 167 PyErr_NewExceptionWithDoc (C function), 54
PyDateTime_TIME_GET_MINUTE (C function), PyErr_NoMemory (C function), 48
167 PyErr_NormalizeException (C function), 52
PyDateTime_TIME_GET_SECOND (C function), PyErr_Occurred (C function), 51
167 PyErr_Occurred(), 10
PyDateTime_TIME_GET_TZINFO (C function), PyErr_Print (C function), 48
167 PyErr_PrintEx (C function), 47
PyDateTime_TimeZone_UTC (C var), 165 PyErr_ResourceWarning (C function), 51
PyDelta_Check (C function), 165 PyErr_Restore (C function), 52
PyDelta_CheckExact (C function), 165 PyErr_SetExcFromWindowsErr (C function), 49
PyDelta_FromDSU (C function), 166 PyErr_SetExcFromWindowsErrWithFilename
PyDescr_IsData (C function), 158 (C function), 49
PyDescr_NewClassMethod (C function), 158 PyErr_SetExcFromWindowsErrWithFilenameObject
PyDescr_NewGetSet (C function), 157 (C function), 49
PyDescr_NewMember (C function), 157 PyErr_SetExcFromWindowsErrWithFilenameObjects
PyDescr_NewMethod (C function), 157 (C function), 49
PyDescr_NewWrapper (C function), 158 PyErr_SetExcInfo (C function), 52
PyDict_Check (C function), 141 PyErr_SetFromErrno (C function), 48
PyDict_CheckExact (C function), 141 PyErr_SetFromErrnoWithFilename (C func-
PyDict_Clear (C function), 141 tion), 49
PyDict_Contains (C function), 141 PyErr_SetFromErrnoWithFilenameObject
PyDict_Copy (C function), 141 (C function), 49
PyDict_DelItem (C function), 141 PyErr_SetFromErrnoWithFilenameObjects
PyDict_DelItemString (C function), 141 (C function), 49
PyDict_GetItem (C function), 141 PyErr_SetFromWindowsErr (C function), 49
PyDict_GetItemString (C function), 142 PyErr_SetFromWindowsErrWithFilename (C
PyDict_GetItemWithError (C function), 142 function), 49
PyDict_Items (C function), 142 PyErr_SetImportError (C function), 50
PyDict_Keys (C function), 142 PyErr_SetImportErrorSubclass (C function),
PyDict_Merge (C function), 143 50
PyDict_MergeFromSeq2 (C function), 143 PyErr_SetInterrupt (C function), 53
PyDict_New (C function), 141 PyErr_SetInterruptEx (C function), 53

Índice 307
The Python/C API, Release 3.10.6

PyErr_SetNone (C function), 48 PyExc_FutureWarning, 58


PyErr_SetObject (C function), 48 PyExc_GeneratorExit, 57
PyErr_SetString (C function), 48 PyExc_ImportError, 57
PyErr_SetString(), 10 PyExc_ImportWarning, 58
PyErr_SyntaxLocation (C function), 50 PyExc_IndentationError, 57
PyErr_SyntaxLocationEx (C function), 50 PyExc_IndexError, 57
PyErr_SyntaxLocationObject (C function), 50 PyExc_InterruptedError, 57
PyErr_WarnEx (C function), 50 PyExc_IOError, 58
PyErr_WarnExplicit (C function), 51 PyExc_IsADirectoryError, 57
PyErr_WarnExplicitObject (C function), 50 PyExc_KeyboardInterrupt, 57
PyErr_WarnFormat (C function), 51 PyExc_KeyError, 57
PyErr_WriteUnraisable (C function), 48 PyExc_LookupError, 57
PyEval_AcquireLock (C function), 182 PyExc_MemoryError, 57
PyEval_AcquireThread (C function), 182 PyExc_ModuleNotFoundError, 57
PyEval_AcquireThread(), 178 PyExc_NameError, 57
PyEval_EvalCode (C function), 42 PyExc_NotADirectoryError, 57
PyEval_EvalCodeEx (C function), 42 PyExc_NotImplementedError, 57
PyEval_EvalFrame (C function), 42 PyExc_OSError, 57
PyEval_EvalFrameEx (C function), 42 PyExc_OverflowError, 57
PyEval_GetBuiltins (C function), 78 PyExc_PendingDeprecationWarning, 58
PyEval_GetFrame (C function), 78 PyExc_PermissionError, 57
PyEval_GetFuncDesc (C function), 79 PyExc_ProcessLookupError, 57
PyEval_GetFuncName (C function), 79 PyExc_RecursionError, 57
PyEval_GetGlobals (C function), 78 PyExc_ReferenceError, 57
PyEval_GetLocals (C function), 78 PyExc_ResourceWarning, 58
PyEval_InitThreads (C function), 178 PyExc_RuntimeError, 57
PyEval_InitThreads(), 172 PyExc_RuntimeWarning, 58
PyEval_MergeCompilerFlags (C function), 42 PyExc_StopAsyncIteration, 57
PyEval_ReleaseLock (C function), 182 PyExc_StopIteration, 57
PyEval_ReleaseThread (C function), 182 PyExc_SyntaxError, 57
PyEval_ReleaseThread(), 178 PyExc_SyntaxWarning, 58
PyEval_RestoreThread (C function), 179 PyExc_SystemError, 57
PyEval_RestoreThread(), 177, 178 PyExc_SystemExit, 57
PyEval_SaveThread (C function), 178 PyExc_TabError, 57
PyEval_SaveThread(), 177, 178 PyExc_TimeoutError, 57
PyEval_SetProfile (C function), 185 PyExc_TypeError, 57
PyEval_SetTrace (C function), 186 PyExc_UnboundLocalError, 57
PyEval_ThreadsInitialized (C function), 178 PyExc_UnicodeDecodeError, 57
PyExc_ArithmeticError, 57 PyExc_UnicodeEncodeError, 57
PyExc_AssertionError, 57 PyExc_UnicodeError, 57
PyExc_AttributeError, 57 PyExc_UnicodeTranslateError, 57
PyExc_BaseException, 57 PyExc_UnicodeWarning, 58
PyExc_BlockingIOError, 57 PyExc_UserWarning, 58
PyExc_BrokenPipeError, 57 PyExc_ValueError, 57
PyExc_BufferError, 57 PyExc_Warning, 58
PyExc_BytesWarning, 58 PyExc_WindowsError, 58
PyExc_ChildProcessError, 57 PyExc_ZeroDivisionError, 57
PyExc_ConnectionAbortedError, 57 PyException_GetCause (C function), 54
PyExc_ConnectionError, 57 PyException_GetContext (C function), 54
PyExc_ConnectionRefusedError, 57 PyException_GetTraceback (C function), 54
PyExc_ConnectionResetError, 57 PyException_SetCause (C function), 54
PyExc_DeprecationWarning, 58 PyException_SetContext (C function), 54
PyExc_EnvironmentError, 58 PyException_SetTraceback (C function), 54
PyExc_EOFError, 57 PyFile_FromFd (C function), 148
PyExc_Exception, 57 PyFile_GetLine (C function), 149
PyExc_FileExistsError, 57 PyFile_SetOpenCodeHook (C function), 149
PyExc_FileNotFoundError, 57 PyFile_WriteObject (C function), 149
PyExc_FloatingPointError, 57 PyFile_WriteString (C function), 149

308 Índice
The Python/C API, Release 3.10.6

PyFloat_AS_DOUBLE (C function), 113 PyImport_ExecCodeModuleWithPathnames


PyFloat_AsDouble (C function), 113 (C function), 66
PyFloat_Check (C function), 112 PyImport_ExtendInittab (C function), 67
PyFloat_CheckExact (C function), 112 PyImport_FrozenModules (C var), 67
PyFloat_FromDouble (C function), 112 PyImport_GetImporter (C function), 66
PyFloat_FromString (C function), 112 PyImport_GetMagicNumber (C function), 66
PyFloat_GetInfo (C function), 113 PyImport_GetMagicTag (C function), 66
PyFloat_GetMax (C function), 113 PyImport_GetModule (C function), 66
PyFloat_GetMin (C function), 113 PyImport_GetModuleDict (C function), 66
PyFloat_Type (C var), 112 PyImport_Import (C function), 65
PyFloatObject (C type), 112 PyImport_ImportFrozenModule (C function),
PyFrame_GetBack (C function), 78 67
PyFrame_GetCode (C function), 78 PyImport_ImportFrozenModuleObject (C
PyFrame_GetLineNumber (C function), 78 function), 66
PyFrameObject (C type), 42 PyImport_ImportModule (C function), 64
PyFrozenSet_Check (C function), 144 PyImport_ImportModuleEx (C function), 64
PyFrozenSet_CheckExact (C function), 144 PyImport_ImportModuleLevel (C function), 64
PyFrozenSet_New (C function), 144 PyImport_ImportModuleLevelObject (C
PyFrozenSet_Type (C var), 143 function), 64
PyFunction_Check (C function), 145 PyImport_ImportModuleNoBlock (C function),
PyFunction_GetAnnotations (C function), 146 64
PyFunction_GetClosure (C function), 146 PyImport_ReloadModule (C function), 65
PyFunction_GetCode (C function), 145 PyIndex_Check (C function), 92
PyFunction_GetDefaults (C function), 145 PyInstanceMethod_Check (C function), 146
PyFunction_GetGlobals (C function), 145 PyInstanceMethod_Function (C function), 146
PyFunction_GetModule (C function), 145 PyInstanceMethod_GET_FUNCTION (C func-
PyFunction_New (C function), 145 tion), 146
PyFunction_NewWithQualName (C function), PyInstanceMethod_New (C function), 146
145 PyInstanceMethod_Type (C var), 146
PyFunction_SetAnnotations (C function), 146 PyInterpreterState (C type), 178
PyFunction_SetClosure (C function), 146 PyInterpreterState_Clear (C function), 180
PyFunction_SetDefaults (C function), 146 PyInterpreterState_Delete (C function), 180
PyFunction_Type (C var), 145 PyInterpreterState_Get (C function), 181
PyFunctionObject (C type), 145 PyInterpreterState_GetDict (C function),
PyGC_Collect (C function), 260 181
PyGC_Disable (C function), 260 PyInterpreterState_GetID (C function), 181
PyGC_Enable (C function), 260 PyInterpreterState_Head (C function), 186
PyGC_IsEnabled (C function), 260 PyInterpreterState_Main (C function), 186
PyGen_Check (C function), 162 PyInterpreterState_New (C function), 180
PyGen_CheckExact (C function), 162 PyInterpreterState_Next (C function), 186
PyGen_New (C function), 163 PyInterpreterState_ThreadHead (C func-
PyGen_NewWithQualName (C function), 163 tion), 186
PyGen_Type (C var), 162 PyIter_Check (C function), 95
PyGenObject (C type), 162 PyIter_Next (C function), 95
PyGetSetDef (C type), 225 PyIter_Send (C function), 96
PyGILState_Check (C function), 179 PyList_Append (C function), 140
PyGILState_Ensure (C function), 179 PyList_AsTuple (C function), 140
PyGILState_GetThisThreadState (C func- PyList_Check (C function), 139
tion), 179 PyList_CheckExact (C function), 139
PyGILState_Release (C function), 179 PyList_GET_ITEM (C function), 139
PyImport_AddModule (C function), 65 PyList_GET_SIZE (C function), 139
PyImport_AddModuleObject (C function), 65 PyList_GetItem (C function), 139
PyImport_AppendInittab (C function), 67 PyList_GetItem(), 8
PyImport_ExecCodeModule (C function), 65 PyList_GetSlice (C function), 140
PyImport_ExecCodeModuleEx (C function), 65 PyList_Insert (C function), 140
PyImport_ExecCodeModuleObject (C func- PyList_New (C function), 139
tion), 66 PyList_Reverse (C function), 140
PyList_SET_ITEM (C function), 140

Índice 309
The Python/C API, Release 3.10.6

PyList_SetItem (C function), 140 PyMarshal_ReadObjectFromFile (C function),


PyList_SetItem(), 7 68
PyList_SetSlice (C function), 140 PyMarshal_ReadObjectFromString (C func-
PyList_Size (C function), 139 tion), 68
PyList_Sort (C function), 140 PyMarshal_ReadShortFromFile (C function),
PyList_Type (C var), 139 68
PyListObject (C type), 139 PyMarshal_WriteLongToFile (C function), 68
PyLong_AsDouble (C function), 111 PyMarshal_WriteObjectToFile (C function),
PyLong_AsLong (C function), 110 68
PyLong_AsLongAndOverflow (C function), 110 PyMarshal_WriteObjectToString (C func-
PyLong_AsLongLong (C function), 110 tion), 68
PyLong_AsLongLongAndOverflow (C function), PyMem_Calloc (C function), 211
110 PyMem_Del (C function), 212
PyLong_AsSize_t (C function), 111 PyMem_Free (C function), 212
PyLong_AsSsize_t (C function), 111 PyMem_GetAllocator (C function), 214
PyLong_AsUnsignedLong (C function), 111 PyMem_Malloc (C function), 211
PyLong_AsUnsignedLongLong (C function), 111 PyMem_New (C function), 212
PyLong_AsUnsignedLongLongMask (C func- PyMem_RawCalloc (C function), 210
tion), 111 PyMem_RawFree (C function), 211
PyLong_AsUnsignedLongMask (C function), 111 PyMem_RawMalloc (C function), 210
PyLong_AsVoidPtr (C function), 112 PyMem_RawRealloc (C function), 211
PyLong_Check (C function), 109 PyMem_Realloc (C function), 211
PyLong_CheckExact (C function), 109 PyMem_Resize (C function), 212
PyLong_FromDouble (C function), 110 PyMem_SetAllocator (C function), 214
PyLong_FromLong (C function), 109 PyMem_SetupDebugHooks (C function), 214
PyLong_FromLongLong (C function), 109 PyMemAllocatorDomain (C type), 214
PyLong_FromSize_t (C function), 109 PyMemAllocatorDomain.PYMEM_DOMAIN_MEM
PyLong_FromSsize_t (C function), 109 (C macro), 214
PyLong_FromString (C function), 110 PyMemAllocatorDomain.PYMEM_DOMAIN_OBJ
PyLong_FromUnicodeObject (C function), 110 (C macro), 214
PyLong_FromUnsignedLong (C function), 109 PyMemAllocatorDomain.PYMEM_DOMAIN_RAW
PyLong_FromUnsignedLongLong (C function), (C macro), 214
109 PyMemAllocatorEx (C type), 214
PyLong_FromVoidPtr (C function), 110 PyMember_GetOne (C function), 225
PyLong_Type (C var), 109 PyMember_SetOne (C function), 225
PyLongObject (C type), 109 PyMemberDef (C type), 224
PyMapping_Check (C function), 94 PyMemoryView_Check (C function), 160
PyMapping_DelItem (C function), 94 PyMemoryView_FromBuffer (C function), 159
PyMapping_DelItemString (C function), 94 PyMemoryView_FromMemory (C function), 159
PyMapping_GetItemString (C function), 94 PyMemoryView_FromObject (C function), 159
PyMapping_HasKey (C function), 94 PyMemoryView_GET_BASE (C function), 160
PyMapping_HasKeyString (C function), 94 PyMemoryView_GET_BUFFER (C function), 160
PyMapping_Items (C function), 95 PyMemoryView_GetContiguous (C function),
PyMapping_Keys (C function), 94 160
PyMapping_Length (C function), 94 PyMethod_Check (C function), 146
PyMapping_SetItemString (C function), 94 PyMethod_Function (C function), 147
PyMapping_Size (C function), 94 PyMethod_GET_FUNCTION (C function), 147
PyMapping_Values (C function), 95 PyMethod_GET_SELF (C function), 147
PyMappingMethods (C type), 251 PyMethod_New (C function), 147
PyMappingMethods.mp_ass_subscript (C PyMethod_Self (C function), 147
member), 251 PyMethod_Type (C var), 146
PyMappingMethods.mp_length (C member), PyMethodDef (C type), 222
251 PyModule_AddFunctions (C function), 154
PyMappingMethods.mp_subscript (C mem- PyModule_AddIntConstant (C function), 156
ber), 251 PyModule_AddIntMacro (C function), 156
PyMarshal_ReadLastObjectFromFile (C PyModule_AddObject (C function), 155
function), 68 PyModule_AddObjectRef (C function), 154
PyMarshal_ReadLongFromFile (C function), 68

310 Índice
The Python/C API, Release 3.10.6

PyModule_AddStringConstant (C function), PyNumber_InPlaceRemainder (C function), 91


156 PyNumber_InPlaceRshift (C function), 91
PyModule_AddStringMacro (C function), 156 PyNumber_InPlaceSubtract (C function), 90
PyModule_AddType (C function), 156 PyNumber_InPlaceTrueDivide (C function), 91
PyModule_Check (C function), 150 PyNumber_InPlaceXor (C function), 91
PyModule_CheckExact (C function), 150 PyNumber_Invert (C function), 90
PyModule_Create (C function), 152 PyNumber_Long (C function), 91
PyModule_Create2 (C function), 152 PyNumber_Lshift (C function), 90
PyModule_ExecDef (C function), 154 PyNumber_MatrixMultiply (C function), 89
PyModule_FromDefAndSpec (C function), 154 PyNumber_Multiply (C function), 89
PyModule_FromDefAndSpec2 (C function), 154 PyNumber_Negative (C function), 90
PyModule_GetDef (C function), 150 PyNumber_Or (C function), 90
PyModule_GetDict (C function), 150 PyNumber_Positive (C function), 90
PyModule_GetFilename (C function), 150 PyNumber_Power (C function), 90
PyModule_GetFilenameObject (C function), PyNumber_Remainder (C function), 90
150 PyNumber_Rshift (C function), 90
PyModule_GetName (C function), 150 PyNumber_Subtract (C function), 89
PyModule_GetNameObject (C function), 150 PyNumber_ToBase (C function), 92
PyModule_GetState (C function), 150 PyNumber_TrueDivide (C function), 89
PyModule_New (C function), 150 PyNumber_Xor (C function), 90
PyModule_NewObject (C function), 150 PyNumberMethods (C type), 249
PyModule_SetDocString (C function), 154 PyNumberMethods.nb_absolute (C member),
PyModule_Type (C var), 150 250
PyModuleDef (C type), 151 PyNumberMethods.nb_add (C member), 250
PyModuleDef_Init (C function), 152 PyNumberMethods.nb_and (C member), 250
PyModuleDef_Slot (C type), 153 PyNumberMethods.nb_bool (C member), 250
PyModuleDef_Slot.slot (C member), 153 PyNumberMethods.nb_divmod (C member), 250
PyModuleDef_Slot.value (C member), 153 PyNumberMethods.nb_float (C member), 251
PyModuleDef.m_base (C member), 151 PyNumberMethods.nb_floor_divide (C mem-
PyModuleDef.m_clear (C member), 151 ber), 251
PyModuleDef.m_doc (C member), 151 PyNumberMethods.nb_index (C member), 251
PyModuleDef.m_free (C member), 152 PyNumberMethods.nb_inplace_add (C mem-
PyModuleDef.m_methods (C member), 151 ber), 251
PyModuleDef.m_name (C member), 151 PyNumberMethods.nb_inplace_and (C mem-
PyModuleDef.m_size (C member), 151 ber), 251
PyModuleDef.m_slots (C member), 151 PyNumberMethods.nb_inplace_floor_divide
PyModuleDef.m_slots.m_reload (C member), (C member), 251
151 PyNumberMethods.nb_inplace_lshift (C
PyModuleDef.m_traverse (C member), 151 member), 251
PyNumber_Absolute (C function), 90 PyNumberMethods.nb_inplace_matrix_multiply
PyNumber_Add (C function), 89 (C member), 251
PyNumber_And (C function), 90 PyNumberMethods.nb_inplace_multiply (C
PyNumber_AsSsize_t (C function), 92 member), 251
PyNumber_Check (C function), 89 PyNumberMethods.nb_inplace_or (C mem-
PyNumber_Divmod (C function), 90 ber), 251
PyNumber_Float (C function), 91 PyNumberMethods.nb_inplace_power (C
PyNumber_FloorDivide (C function), 89 member), 251
PyNumber_Index (C function), 92 PyNumberMethods.nb_inplace_remainder
PyNumber_InPlaceAdd (C function), 90 (C member), 251
PyNumber_InPlaceAnd (C function), 91 PyNumberMethods.nb_inplace_rshift (C
PyNumber_InPlaceFloorDivide (C function), member), 251
91 PyNumberMethods.nb_inplace_subtract (C
PyNumber_InPlaceLshift (C function), 91 member), 251
PyNumber_InPlaceMatrixMultiply (C func- PyNumberMethods.nb_inplace_true_divide
tion), 91 (C member), 251
PyNumber_InPlaceMultiply (C function), 90 PyNumberMethods.nb_inplace_xor (C mem-
PyNumber_InPlaceOr (C function), 91 ber), 251
PyNumber_InPlacePower (C function), 91 PyNumberMethods.nb_int (C member), 251

Índice 311
The Python/C API, Release 3.10.6

PyNumberMethods.nb_invert (C member), 250 PyObject_GenericGetDict (C function), 82


PyNumberMethods.nb_lshift (C member), 250 PyObject_GenericSetAttr (C function), 82
PyNumberMethods.nb_matrix_multiply (C PyObject_GenericSetDict (C function), 82
member), 251 PyObject_GetAIter (C function), 85
PyNumberMethods.nb_multiply (C member), PyObject_GetArenaAllocator (C function),
250 216
PyNumberMethods.nb_negative (C member), PyObject_GetAttr (C function), 81
250 PyObject_GetAttrString (C function), 82
PyNumberMethods.nb_or (C member), 250 PyObject_GetBuffer (C function), 101
PyNumberMethods.nb_positive (C member), PyObject_GetItem (C function), 84
250 PyObject_GetIter (C function), 84
PyNumberMethods.nb_power (C member), 250 PyObject_HasAttr (C function), 81
PyNumberMethods.nb_remainder (C member), PyObject_HasAttrString (C function), 81
250 PyObject_Hash (C function), 83
PyNumberMethods.nb_reserved (C member), PyObject_HashNotImplemented (C function),
251 84
PyNumberMethods.nb_rshift (C member), 250 PyObject_HEAD (C macro), 220
PyNumberMethods.nb_subtract (C member), PyObject_HEAD_INIT (C macro), 221
250 PyObject_Init (C function), 219
PyNumberMethods.nb_true_divide (C mem- PyObject_InitVar (C function), 219
ber), 251 PyObject_IS_GC (C function), 259
PyNumberMethods.nb_xor (C member), 250 PyObject_IsInstance (C function), 83
PyObject (C type), 220 PyObject_IsSubclass (C function), 83
PyObject_AsCharBuffer (C function), 102 PyObject_IsTrue (C function), 84
PyObject_ASCII (C function), 83 PyObject_Length (C function), 84
PyObject_AsFileDescriptor (C function), 149 PyObject_LengthHint (C function), 84
PyObject_AsReadBuffer (C function), 103 PyObject_Malloc (C function), 212
PyObject_AsWriteBuffer (C function), 103 PyObject_New (C function), 219
PyObject_Bytes (C function), 83 PyObject_NewVar (C function), 219
PyObject_Call (C function), 87 PyObject_Not (C function), 84
PyObject_CallFunction (C function), 87 PyObject._ob_next (C member), 232
PyObject_CallFunctionObjArgs (C function), PyObject._ob_prev (C member), 232
88 PyObject_Print (C function), 81
PyObject_CallMethod (C function), 88 PyObject_Realloc (C function), 213
PyObject_CallMethodNoArgs (C function), 88 PyObject_Repr (C function), 83
PyObject_CallMethodObjArgs (C function), 88 PyObject_RichCompare (C function), 82
PyObject_CallMethodOneArg (C function), 88 PyObject_RichCompareBool (C function), 82
PyObject_CallNoArgs (C function), 87 PyObject_SetArenaAllocator (C function),
PyObject_CallObject (C function), 87 216
PyObject_Calloc (C function), 213 PyObject_SetAttr (C function), 82
PyObject_CallOneArg (C function), 87 PyObject_SetAttrString (C function), 82
PyObject_CheckBuffer (C function), 101 PyObject_SetItem (C function), 84
PyObject_CheckReadBuffer (C function), 103 PyObject_Size (C function), 84
PyObject_Del (C function), 219 PyObject_Str (C function), 83
PyObject_DelAttr (C function), 82 PyObject_Type (C function), 84
PyObject_DelAttrString (C function), 82 PyObject_TypeCheck (C function), 84
PyObject_DelItem (C function), 84 PyObject_VAR_HEAD (C macro), 220
PyObject_Dir (C function), 84 PyObject_Vectorcall (C function), 88
PyObject_Free (C function), 213 PyObject_VectorcallDict (C function), 88
PyObject_GC_Del (C function), 259 PyObject_VectorcallMethod (C function), 89
PyObject_GC_IsFinalized (C function), 259 PyObjectArenaAllocator (C type), 216
PyObject_GC_IsTracked (C function), 259 PyObject.ob_refcnt (C member), 231
PyObject_GC_New (C function), 258 PyObject.ob_type (C member), 231
PyObject_GC_NewVar (C function), 258 PyOS_AfterFork (C function), 60
PyObject_GC_Resize (C function), 258 PyOS_AfterFork_Child (C function), 60
PyObject_GC_Track (C function), 258 PyOS_AfterFork_Parent (C function), 59
PyObject_GC_UnTrack (C function), 259 PyOS_BeforeFork (C function), 59
PyObject_GenericGetAttr (C function), 82 PyOS_CheckStack (C function), 60

312 Índice
The Python/C API, Release 3.10.6

PyOS_double_to_string (C function), 77 PySequence_Count (C function), 93


PyOS_FSPath (C function), 59 PySequence_DelItem (C function), 93
PyOS_getsig (C function), 60 PySequence_DelSlice (C function), 93
PyOS_InputHook (C var), 40 PySequence_Fast (C function), 93
PyOS_ReadlineFunctionPointer (C var), 40 PySequence_Fast_GET_ITEM (C function), 93
PyOS_setsig (C function), 60 PySequence_Fast_GET_SIZE (C function), 93
PyOS_snprintf (C function), 77 PySequence_Fast_ITEMS (C function), 94
PyOS_stricmp (C function), 78 PySequence_GetItem (C function), 92
PyOS_string_to_double (C function), 77 PySequence_GetItem(), 8
PyOS_strnicmp (C function), 78 PySequence_GetSlice (C function), 93
PyOS_vsnprintf (C function), 77 PySequence_Index (C function), 93
PyPreConfig (C type), 192 PySequence_InPlaceConcat (C function), 92
PyPreConfig.allocator (C member), 192 PySequence_InPlaceRepeat (C function), 92
PyPreConfig.coerce_c_locale (C member), PySequence_ITEM (C function), 94
192 PySequence_Length (C function), 92
PyPreConfig.coerce_c_locale_warn (C PySequence_List (C function), 93
member), 193 PySequence_Repeat (C function), 92
PyPreConfig.configure_locale (C member), PySequence_SetItem (C function), 93
192 PySequence_SetSlice (C function), 93
PyPreConfig.dev_mode (C member), 193 PySequence_Size (C function), 92
PyPreConfig.isolated (C member), 193 PySequence_Tuple (C function), 93
PyPreConfig.legacy_windows_fs_encoding PySequenceMethods (C type), 252
(C member), 193 PySequenceMethods.sq_ass_item (C mem-
PyPreConfig.parse_argv (C member), 193 ber), 252
PyPreConfig.PyPreConfig_InitIsolatedConfig PySequenceMethods.sq_concat (C member),
(C function), 192 252
PyPreConfig.PyPreConfig_InitPythonConfig PySequenceMethods.sq_contains (C mem-
(C function), 192 ber), 252
PyPreConfig.use_environment (C member), PySequenceMethods.sq_inplace_concat (C
193 member), 252
PyPreConfig.utf8_mode (C member), 193 PySequenceMethods.sq_inplace_repeat (C
PyProperty_Type (C var), 157 member), 252
PyRun_AnyFile (C function), 39 PySequenceMethods.sq_item (C member), 252
PyRun_AnyFileEx (C function), 39 PySequenceMethods.sq_length (C member),
PyRun_AnyFileExFlags (C function), 39 252
PyRun_AnyFileFlags (C function), 39 PySequenceMethods.sq_repeat (C member),
PyRun_File (C function), 41 252
PyRun_FileEx (C function), 41 PySet_Add (C function), 144
PyRun_FileExFlags (C function), 41 PySet_Check (C function), 144
PyRun_FileFlags (C function), 41 PySet_CheckExact (C function), 144
PyRun_InteractiveLoop (C function), 40 PySet_Clear (C function), 145
PyRun_InteractiveLoopFlags (C function), 40 PySet_Contains (C function), 144
PyRun_InteractiveOne (C function), 40 PySet_Discard (C function), 145
PyRun_InteractiveOneFlags (C function), 40 PySet_GET_SIZE (C function), 144
PyRun_SimpleFile (C function), 40 PySet_New (C function), 144
PyRun_SimpleFileEx (C function), 40 PySet_Pop (C function), 145
PyRun_SimpleFileExFlags (C function), 40 PySet_Size (C function), 144
PyRun_SimpleString (C function), 40 PySet_Type (C var), 143
PyRun_SimpleStringFlags (C function), 40 PySetObject (C type), 143
PyRun_String (C function), 41 PySignal_SetWakeupFd (C function), 53
PyRun_StringFlags (C function), 41 PySlice_AdjustIndices (C function), 159
PySendResult (C type), 95 PySlice_Check (C function), 158
PySeqIter_Check (C function), 157 PySlice_GetIndices (C function), 158
PySeqIter_New (C function), 157 PySlice_GetIndicesEx (C function), 158
PySeqIter_Type (C var), 157 PySlice_New (C function), 158
PySequence_Check (C function), 92 PySlice_Type (C var), 158
PySequence_Concat (C function), 92 PySlice_Unpack (C function), 159
PySequence_Contains (C function), 93 PyState_AddModule (C function), 156

Índice 313
The Python/C API, Release 3.10.6

PyState_FindModule (C function), 156 Pythônico, 274


PyState_RemoveModule (C function), 157 PYTHONINSPECT, 171, 198
PyStatus (C type), 191 PYTHONIOENCODING, 173, 202
PyStatus.err_msg (C member), 191 PYTHONLEGACYWINDOWSFSENCODING, 171, 193
PyStatus.exitcode (C member), 191 PYTHONLEGACYWINDOWSSTDIO, 171, 199
PyStatus.func (C member), 191 PYTHONMALLOC, 210, 213, 215, 216
PyStatus.Py_ExitStatusException (C func- PYTHONMALLOCSTATS, 199, 210
tion), 191 PYTHONNOUSERSITE, 171, 202
PyStatus.PyStatus_Error (C function), 191 PYTHONOPTIMIZE, 171, 200
PyStatus.PyStatus_Exception (C function), PYTHONPATH, 12, 170, 199
191 PYTHONPLATLIBDIR, 199
PyStatus.PyStatus_Exit (C function), 191 PYTHONPROFILEIMPORTTIME, 198
PyStatus.PyStatus_IsError (C function), 191 PYTHONPYCACHEPREFIX, 201
PyStatus.PyStatus_IsExit (C function), 191 PYTHONTRACEMALLOC, 202
PyStatus.PyStatus_NoMemory (C function), PYTHONUNBUFFERED, 171, 196
191 PYTHONUTF8, 193, 205
PyStatus.PyStatus_Ok (C function), 191 PYTHONVERBOSE, 171, 203
PyStructSequence_Desc (C type), 138 PYTHONWARNINGS, 203
PyStructSequence_Field (C type), 138 PyThread_create_key (C function), 188
PyStructSequence_GET_ITEM (C function), 139 PyThread_delete_key (C function), 188
PyStructSequence_GetItem (C function), 139 PyThread_delete_key_value (C function), 188
PyStructSequence_InitType (C function), 138 PyThread_get_key_value (C function), 188
PyStructSequence_InitType2 (C function), PyThread_ReInitTLS (C function), 188
138 PyThread_set_key_value (C function), 188
PyStructSequence_New (C function), 138 PyThread_tss_alloc (C function), 187
PyStructSequence_NewType (C function), 138 PyThread_tss_create (C function), 187
PyStructSequence_SET_ITEM (C function), 139 PyThread_tss_delete (C function), 187
PyStructSequence_SetItem (C function), 139 PyThread_tss_free (C function), 187
PyStructSequence_UnnamedField (C var), PyThread_tss_get (C function), 188
138 PyThread_tss_is_created (C function), 187
PySys_AddAuditHook (C function), 63 PyThread_tss_set (C function), 187
PySys_AddWarnOption (C function), 62 PyThreadState, 176
PySys_AddWarnOptionUnicode (C function), 62 PyThreadState (C type), 178
PySys_AddXOption (C function), 62 PyThreadState_Clear (C function), 180
PySys_Audit (C function), 63 PyThreadState_Delete (C function), 180
PySys_FormatStderr (C function), 62 PyThreadState_DeleteCurrent (C function),
PySys_FormatStdout (C function), 62 180
PySys_GetObject (C function), 62 PyThreadState_Get (C function), 179
PySys_GetXOptions (C function), 62 PyThreadState_GetDict (C function), 182
PySys_ResetWarnOptions (C function), 62 PyThreadState_GetFrame (C function), 181
PySys_SetArgv (C function), 176 PyThreadState_GetID (C function), 181
PySys_SetArgv(), 172 PyThreadState_GetInterpreter (C function),
PySys_SetArgvEx (C function), 175 181
PySys_SetArgvEx(), 11, 172 PyThreadState_New (C function), 180
PySys_SetObject (C function), 62 PyThreadState_Next (C function), 186
PySys_SetPath (C function), 62 PyThreadState_SetAsyncExc (C function), 182
PySys_WriteStderr (C function), 62 PyThreadState_Swap (C function), 179
PySys_WriteStdout (C function), 62 PyTime_Check (C function), 165
Python 3000, 273 PyTime_CheckExact (C function), 165
PYTHON*, 170 PyTime_FromTime (C function), 166
PYTHONCOERCECLOCALE, 205 PyTime_FromTimeAndFold (C function), 166
PYTHONDEBUG, 170, 200 PyTimeZone_FromOffset (C function), 166
PYTHONDONTWRITEBYTECODE, 170, 203 PyTimeZone_FromOffsetAndName (C function),
PYTHONDUMPREFS, 197, 232 166
PYTHONEXECUTABLE, 201 PyTrace_C_CALL (C var), 185
PYTHONFAULTHANDLER, 197 PyTrace_C_EXCEPTION (C var), 185
PYTHONHASHSEED, 170, 198 PyTrace_C_RETURN (C var), 185
PYTHONHOME, 12, 170, 176, 198 PyTrace_CALL (C var), 185

314 Índice
The Python/C API, Release 3.10.6

PyTrace_EXCEPTION (C var), 185 PyTypeObject.tp_as_mapping (C member),


PyTrace_LINE (C var), 185 235
PyTrace_OPCODE (C var), 185 PyTypeObject.tp_as_number (C member), 235
PyTrace_RETURN (C var), 185 PyTypeObject.tp_as_sequence (C member),
PyTraceMalloc_Track (C function), 217 235
PyTraceMalloc_Untrack (C function), 217 PyTypeObject.tp_base (C member), 244
PyTuple_Check (C function), 137 PyTypeObject.tp_bases (C member), 247
PyTuple_CheckExact (C function), 137 PyTypeObject.tp_basicsize (C member), 232
PyTuple_GET_ITEM (C function), 137 PyTypeObject.tp_cache (C member), 247
PyTuple_GET_SIZE (C function), 137 PyTypeObject.tp_call (C member), 236
PyTuple_GetItem (C function), 137 PyTypeObject.tp_clear (C member), 241
PyTuple_GetSlice (C function), 137 PyTypeObject.tp_dealloc (C member), 233
PyTuple_New (C function), 137 PyTypeObject.tp_del (C member), 248
PyTuple_Pack (C function), 137 PyTypeObject.tp_descr_get (C member), 244
PyTuple_SET_ITEM (C function), 137 PyTypeObject.tp_descr_set (C member), 244
PyTuple_SetItem (C function), 137 PyTypeObject.tp_dict (C member), 244
PyTuple_SetItem(), 7 PyTypeObject.tp_dictoffset (C member),
PyTuple_Size (C function), 137 245
PyTuple_Type (C var), 137 PyTypeObject.tp_doc (C member), 240
PyTupleObject (C type), 137 PyTypeObject.tp_finalize (C member), 248
PyType_Check (C function), 105 PyTypeObject.tp_flags (C member), 237
PyType_CheckExact (C function), 105 PyTypeObject.tp_free (C member), 246
PyType_ClearCache (C function), 105 PyTypeObject.tp_getattr (C member), 234
PyType_FromModuleAndSpec (C function), 107 PyTypeObject.tp_getattro (C member), 236
PyType_FromSpec (C function), 107 PyTypeObject.tp_getset (C member), 243
PyType_FromSpecWithBases (C function), 107 PyTypeObject.tp_hash (C member), 235
PyType_GenericAlloc (C function), 106 PyTypeObject.tp_init (C member), 245
PyType_GenericNew (C function), 106 PyTypeObject.tp_is_gc (C member), 247
PyType_GetFlags (C function), 105 PyTypeObject.tp_itemsize (C member), 232
PyType_GetModule (C function), 106 PyTypeObject.tp_iter (C member), 243
PyType_GetModuleState (C function), 107 PyTypeObject.tp_iternext (C member), 243
PyType_GetSlot (C function), 106 PyTypeObject.tp_members (C member), 243
PyType_HasFeature (C function), 106 PyTypeObject.tp_methods (C member), 243
PyType_IS_GC (C function), 106 PyTypeObject.tp_mro (C member), 247
PyType_IsSubtype (C function), 106 PyTypeObject.tp_name (C member), 232
PyType_Modified (C function), 106 PyTypeObject.tp_new (C member), 246
PyType_Ready (C function), 106 PyTypeObject.tp_repr (C member), 235
PyType_Slot (C type), 108 PyTypeObject.tp_richcompare (C member),
PyType_Slot.PyType_Slot.pfunc (C mem- 242
ber), 108 PyTypeObject.tp_richcompare.Py_RETURN_RICHCOMPARE
PyType_Slot.PyType_Slot.slot (C member), (C macro), 242
108 PyTypeObject.tp_setattr (C member), 234
PyType_Spec (C type), 107 PyTypeObject.tp_setattro (C member), 236
PyType_Spec.PyType_Spec.basicsize (C PyTypeObject.tp_str (C member), 236
member), 107 PyTypeObject.tp_subclasses (C member),
PyType_Spec.PyType_Spec.flags (C mem- 247
ber), 107 PyTypeObject.tp_traverse (C member), 240
PyType_Spec.PyType_Spec.itemsize (C PyTypeObject.tp_vectorcall (C member),
member), 107 248
PyType_Spec.PyType_Spec.name (C member), PyTypeObject.tp_vectorcall_offset (C
107 member), 234
PyType_Spec.PyType_Spec.slots (C mem- PyTypeObject.tp_version_tag (C member),
ber), 108 248
PyType_Type (C var), 105 PyTypeObject.tp_weaklist (C member), 247
PyTypeObject (C type), 105 PyTypeObject.tp_weaklistoffset (C mem-
PyTypeObject.tp_alloc (C member), 246 ber), 242
PyTypeObject.tp_as_async (C member), 234 PyTZInfo_Check (C function), 165
PyTypeObject.tp_as_buffer (C member), 237 PyTZInfo_CheckExact (C function), 165

Índice 315
The Python/C API, Release 3.10.6

PyUnicode_1BYTE_DATA (C function), 119 PyUnicode_DecodeUTF7Stateful (C function),


PyUnicode_1BYTE_KIND (C macro), 119 132
PyUnicode_2BYTE_DATA (C function), 119 PyUnicode_DecodeUTF8 (C function), 129
PyUnicode_2BYTE_KIND (C macro), 119 PyUnicode_DecodeUTF8Stateful (C function),
PyUnicode_4BYTE_DATA (C function), 119 129
PyUnicode_4BYTE_KIND (C macro), 119 PyUnicode_DecodeUTF16 (C function), 131
PyUnicode_AS_DATA (C function), 120 PyUnicode_DecodeUTF16Stateful (C func-
PyUnicode_AS_UNICODE (C function), 120 tion), 131
PyUnicode_AsASCIIString (C function), 133 PyUnicode_DecodeUTF32 (C function), 130
PyUnicode_AsCharmapString (C function), 134 PyUnicode_DecodeUTF32Stateful (C func-
PyUnicode_AsEncodedString (C function), 128 tion), 130
PyUnicode_AsLatin1String (C function), 133 PyUnicode_Encode (C function), 129
PyUnicode_AsMBCSString (C function), 134 PyUnicode_EncodeASCII (C function), 133
PyUnicode_AsRawUnicodeEscapeString (C PyUnicode_EncodeCharmap (C function), 134
function), 132 PyUnicode_EncodeCodePage (C function), 135
PyUnicode_AsUCS4 (C function), 124 PyUnicode_EncodeFSDefault (C function), 127
PyUnicode_AsUCS4Copy (C function), 124 PyUnicode_EncodeLatin1 (C function), 133
PyUnicode_AsUnicode (C function), 125 PyUnicode_EncodeLocale (C function), 126
PyUnicode_AsUnicodeAndSize (C function), PyUnicode_EncodeMBCS (C function), 135
125 PyUnicode_EncodeRawUnicodeEscape (C
PyUnicode_AsUnicodeEscapeString (C func- function), 132
tion), 132 PyUnicode_EncodeUnicodeEscape (C func-
PyUnicode_AsUTF8 (C function), 129 tion), 132
PyUnicode_AsUTF8AndSize (C function), 129 PyUnicode_EncodeUTF7 (C function), 132
PyUnicode_AsUTF8String (C function), 129 PyUnicode_EncodeUTF8 (C function), 129
PyUnicode_AsUTF16String (C function), 131 PyUnicode_EncodeUTF16 (C function), 131
PyUnicode_AsUTF32String (C function), 130 PyUnicode_EncodeUTF32 (C function), 130
PyUnicode_AsWideChar (C function), 128 PyUnicode_Fill (C function), 124
PyUnicode_AsWideCharString (C function), PyUnicode_Find (C function), 135
128 PyUnicode_FindChar (C function), 135
PyUnicode_Check (C function), 118 PyUnicode_Format (C function), 136
PyUnicode_CheckExact (C function), 118 PyUnicode_FromEncodedObject (C function),
PyUnicode_Compare (C function), 136 123
PyUnicode_CompareWithASCIIString (C PyUnicode_FromFormat (C function), 122
function), 136 PyUnicode_FromFormatV (C function), 123
PyUnicode_Concat (C function), 135 PyUnicode_FromKindAndData (C function), 122
PyUnicode_Contains (C function), 136 PyUnicode_FromObject (C function), 125
PyUnicode_CopyCharacters (C function), 124 PyUnicode_FromString (C function), 122
PyUnicode_Count (C function), 136 PyUnicode_FromString(), 141
PyUnicode_DATA (C function), 119 PyUnicode_FromStringAndSize (C function),
PyUnicode_Decode (C function), 128 122
PyUnicode_DecodeASCII (C function), 133 PyUnicode_FromUnicode (C function), 125
PyUnicode_DecodeCharmap (C function), 133 PyUnicode_FromWideChar (C function), 128
PyUnicode_DecodeFSDefault (C function), 127 PyUnicode_FSConverter (C function), 126
PyUnicode_DecodeFSDefaultAndSize (C PyUnicode_FSDecoder (C function), 127
function), 127 PyUnicode_GET_DATA_SIZE (C function), 120
PyUnicode_DecodeLatin1 (C function), 133 PyUnicode_GET_LENGTH (C function), 119
PyUnicode_DecodeLocale (C function), 126 PyUnicode_GET_SIZE (C function), 120
PyUnicode_DecodeLocaleAndSize (C func- PyUnicode_GetLength (C function), 124
tion), 126 PyUnicode_GetSize (C function), 125
PyUnicode_DecodeMBCS (C function), 134 PyUnicode_InternFromString (C function),
PyUnicode_DecodeMBCSStateful (C function), 136
134 PyUnicode_InternInPlace (C function), 136
PyUnicode_DecodeRawUnicodeEscape (C PyUnicode_IsIdentifier (C function), 120
function), 132 PyUnicode_Join (C function), 135
PyUnicode_DecodeUnicodeEscape (C func- PyUnicode_KIND (C function), 119
tion), 132 PyUnicode_MAX_CHAR_VALUE (C macro), 120
PyUnicode_DecodeUTF7 (C function), 132 PyUnicode_New (C function), 122

316 Índice
The Python/C API, Release 3.10.6

PyUnicode_READ (C function), 119 PyUnicodeTranslateError_GetEnd (C func-


PyUnicode_READ_CHAR (C function), 119 tion), 55
PyUnicode_ReadChar (C function), 124 PyUnicodeTranslateError_GetObject (C
PyUnicode_READY (C function), 119 function), 55
PyUnicode_Replace (C function), 136 PyUnicodeTranslateError_GetReason (C
PyUnicode_RichCompare (C function), 136 function), 56
PyUnicode_Split (C function), 135 PyUnicodeTranslateError_GetStart (C
PyUnicode_Splitlines (C function), 135 function), 55
PyUnicode_Substring (C function), 124 PyUnicodeTranslateError_SetEnd (C func-
PyUnicode_Tailmatch (C function), 135 tion), 55
PyUnicode_TransformDecimalToASCII (C PyUnicodeTranslateError_SetReason (C
function), 125 function), 56
PyUnicode_Translate (C function), 134 PyUnicodeTranslateError_SetStart (C
PyUnicode_TranslateCharmap (C function), function), 55
134 PyVarObject (C type), 220
PyUnicode_Type (C var), 118 PyVarObject_HEAD_INIT (C macro), 221
PyUnicode_WCHAR_KIND (C macro), 119 PyVarObject.ob_size (C member), 232
PyUnicode_WRITE (C function), 119 PyVectorcall_Call (C function), 86
PyUnicode_WriteChar (C function), 124 PyVectorcall_Function (C function), 86
PyUnicodeDecodeError_Create (C function), PyVectorcall_NARGS (C function), 86
55 PyWeakref_Check (C function), 160
PyUnicodeDecodeError_GetEncoding (C PyWeakref_CheckProxy (C function), 160
function), 55 PyWeakref_CheckRef (C function), 160
PyUnicodeDecodeError_GetEnd (C function), PyWeakref_GET_OBJECT (C function), 160
55 PyWeakref_GetObject (C function), 160
PyUnicodeDecodeError_GetObject (C func- PyWeakref_NewProxy (C function), 160
tion), 55 PyWeakref_NewRef (C function), 160
PyUnicodeDecodeError_GetReason (C func- PyWideStringList (C type), 190
tion), 56 PyWideStringList.items (C member), 190
PyUnicodeDecodeError_GetStart (C func- PyWideStringList.length (C member), 190
tion), 55 PyWideStringList.PyWideStringList_Append
PyUnicodeDecodeError_SetEnd (C function), (C function), 190
55 PyWideStringList.PyWideStringList_Insert
PyUnicodeDecodeError_SetReason (C func- (C function), 190
tion), 56 PyWrapper_New (C function), 158
PyUnicodeDecodeError_SetStart (C func-
tion), 55 R
PyUnicodeEncodeError_Create (C function), realloc(), 209
55 referência emprestada, 264
PyUnicodeEncodeError_GetEncoding (C referência forte, 275
function), 55 releasebufferproc (C type), 255
PyUnicodeEncodeError_GetEnd (C function), repr
55 função interna, 83, 235
PyUnicodeEncodeError_GetObject (C func- reprfunc (C type), 254
tion), 55 richcmpfunc (C type), 255
PyUnicodeEncodeError_GetReason (C func-
tion), 56 S
PyUnicodeEncodeError_GetStart (C func- sdterr
tion), 55 stdin stdout, 173
PyUnicodeEncodeError_SetEnd (C function), search
55 path, module, 11, 172, 174
PyUnicodeEncodeError_SetReason (C func- sendfunc (C type), 255
tion), 56 sequence
PyUnicodeEncodeError_SetStart (C func- objeto, 114
tion), 55 sequência, 274
PyUnicodeObject (C type), 118 set
PyUnicodeTranslateError_Create (C func- objeto, 143
tion), 55 set_all(), 8

Índice 317
The Python/C API, Release 3.10.6

setattrfunc (C type), 255 PYTHONDEBUG, 170, 200


setattrofunc (C type), 255 PYTHONDONTWRITEBYTECODE, 170, 203
setswitchinterval() (in module sys), 176 PYTHONDUMPREFS, 197, 232
SIGINT, 53 PYTHONEXECUTABLE, 201
signal PYTHONFAULTHANDLER, 197
módulo, 53 PYTHONHASHSEED, 170, 198
SIZE_MAX, 111 PYTHONHOME, 12, 170, 176, 198
special PYTHONINSPECT, 171, 198
method, 275 PYTHONIOENCODING, 173, 202
ssizeargfunc (C type), 255 PYTHONLEGACYWINDOWSFSENCODING, 171,
ssizeobjargproc (C type), 255 193
staticmethod PYTHONLEGACYWINDOWSSTDIO, 171, 199
função interna, 224 PYTHONMALLOC, 210, 213, 215, 216
stderr (in module sys), 183 PYTHONMALLOCSTATS, 199, 210
stdin PYTHONNOUSERSITE, 171, 202
stdout sdterr, 173 PYTHONOPTIMIZE, 171, 200
stdin (in module sys), 183 PYTHONPATH, 12, 170, 199
stdout PYTHONPLATLIBDIR, 199
sdterr, stdin, 173 PYTHONPROFILEIMPORTTIME, 198
stdout (in module sys), 183 PYTHONPYCACHEPREFIX, 201
strerror(), 48 PYTHONTRACEMALLOC, 202
string PYTHONUNBUFFERED, 171, 196
PyObject_Str (C function), 83 PYTHONUTF8, 193, 205
sum_list(), 9 PYTHONVERBOSE, 171, 203
sum_sequence(), 9, 10 PYTHONWARNINGS, 203
sys variável de classe, 265
módulo, 11, 172, 183 variável de contexto, 265
SystemError (built-in exception), 150 vectorcallfunc (C type), 85
version (in module sys), 175
T visão de dicionário, 266
ternaryfunc (C type), 255 visitproc (C type), 259
tipagem pato, 266
tipo, 275 Z
tipo alias, 275 Zen do Python, 276
tipo genérico, 268
tratador de erros e codificação do
sistema de arquivos, 267
traverseproc (C type), 259
tupla nomeada, 271
tuple
função interna, 93, 140
objeto, 137
type
função interna, 84
objeto, 6, 105

U
ULONG_MAX, 111
unaryfunc (C type), 255

V
váriavel de ambiente
__PYVENV_LAUNCHER__, 196, 201
exec_prefix, 4
PATH, 12
prefix, 4
PYTHON*, 170
PYTHONCOERCECLOCALE, 205

318 Índice

Você também pode gostar