C Api
C Api
Release 3.10.6
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
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
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
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
A Glossário 263
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.
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
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++.
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:
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}
};
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.
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.
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().
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;
É 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
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.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
10 Capítulo 1. Introdução
The Python/C API, Release 3.10.6
error:
/* Cleanup code, shared by success and failure path */
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.
A única tarefa importante com a qual apenas os incorporadores (em oposição aos escritores de extensão) do inter-
pretador Python precisam se preocupar é a inicialização e, possivelmente, a finalização do interpretador Python. A
maior parte da funcionalidade do interpretador só pode ser usada após a inicialização do interpretador.
A função de inicialização básica é Py_Initialize(). Isso inicializa a tabela de módulos carregados e cria os
módulos fundamentais builtins, __main__ e sys. Ela também inicializa o caminho de pesquisa de módulos
(sys.path).
Py_Initialize() não define a “lista de argumentos de script” (sys.argv). Se esta variável for necessária
para o código Python que será executado posteriormente, 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.
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.
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.
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.
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.
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.
• 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()
• 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()
• 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()
• 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
• 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
• 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()
• 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()
• 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()
• 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()
• 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()
• 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()
• 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()
• 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()
• 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()
• 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()
• 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()
• 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()
• 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()
• 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
• 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()
• 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
• setattrofunc
• setter
• ssizeargfunc
• ssizeobjargproc
• ssizessizeargfunc
• ssizessizeobjargproc
• symtable
• ternaryfunc
• traverseproc
• unaryfunc
• visitproc
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.
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.
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
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;
45
The Python/C API, Release 3.10.6
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.
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).
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
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
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 à
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.
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.)
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)
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.
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);
}
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.
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.
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.
Nota: This function is async-signal-safe. It can be called without the GIL and from a C signal handler.
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.
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 Notas
PyExc_EnvironmentError
PyExc_IOError
2
PyExc_WindowsError
Alterado na versão 3.3: Esses aliases costumavam ser tipos de exceção separados.
Notas:
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:
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.
Aviso: The C fork() call should only be made from the “main” thread (of the “main” interpreter). The
same is true for PyOS_BeforeFork().
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().
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().
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.
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.
64 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6
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.
66 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6
struct _frozen {
const char *name;
const unsigned char *code;
int size;
};
struct _inittab {
const char *name; /* ASCII encoded string */
PyObject* (*initfunc)(void);
};
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
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.
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.
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.
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.
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:
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.
Funções da API
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
PyObject *result = NULL;
74 Capítulo 6. Utilitários
The Python/C API, Release 3.10.6
76 Capítulo 6. Utilitários
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
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.
80 Capítulo 6. Utilitários
CAPÍTULO 7
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.
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
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.
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.
Instances of classes that set tp_call are callable. The signature of the slot is:
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.
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.
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.
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.
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.
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.
if (iterator == NULL) {
/* propagate error */
}
Py_DECREF(iterator);
if (PyErr_Occurred()) {
/* propagate error */
}
else {
/* continue doing useful work */
}
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.
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.
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.
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.
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.
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).
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.
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.
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.
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:
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:
if ndim <= 0:
return ndim == 0 and not shape and not strides
if 0 in shape:
return True
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:
ú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.
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.
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
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.
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.
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.
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.)
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.
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__().
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.
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.
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.
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.
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;
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.
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.
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.
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:
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.
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
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.
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.
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:
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).
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.
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.
wchar_t Support
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
UTF-8 Codecs
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
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:
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().
UTF-16 Codecs
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:
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().
UTF-7 Codecs
Unicode-Escape Codecs
Raw-Unicode-Escape Codecs
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().
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.
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
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
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().
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.
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.
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.
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.
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.
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 *
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().
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.
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.
8.4 Coleções
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().
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:
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:
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
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.
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
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.
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.
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.
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
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).
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.
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).
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:
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.
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.
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:
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:
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.
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
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.
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.
“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.
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
// return error
}
substituído por
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.
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.
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.
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.
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:
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.
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);
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.
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.
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:
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
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.
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().
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.
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.
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
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");
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().
A maioria dos códigos de extensão que manipulam o GIL tem a seguinte estrutura:
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.
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.
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();
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.
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.
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.
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
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.
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.
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.
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 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.
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.
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.
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.
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:
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.
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.
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.
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.
10.1 Exemplo
PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;
189
The Python/C API, Release 3.10.6
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return Py_RunMain();
exception:
PyConfig_Clear(&config);
if (PyStatus_IsExit(status)) {
return status.exitcode;
}
/* Display the error message and exit the process with
non-zero exit code */
Py_ExitStatusException(status);
}
10.2 PyWideStringList
type PyWideStringList
Lista de strings wchar_t*.
Se length é diferente de zero, items deve ser diferente de NULL e todas as strings devem ser diferentes de NULL.
Métodos:
PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)
Anexa item a list.
Python deve ser inicializado previamente antes de chamar essa função.
PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t
*item)
Insere item na list na posição index.
Se index for maior ou igual ao comprimento da list, anexa o item a list.
index deve ser maior que ou igual a 0.
Python deve ser inicializado previamente antes de chamar essa função.
Campos de estrutura
Py_ssize_t length
Comprimento da lista.
wchar_t **items
Itens da lista.
10.3 PyStatus
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();
}
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.
PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);
preconfig.utf8_mode = 1;
status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
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.
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.
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.
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.
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.
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.
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.
void init_python(void)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
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);
status = Py_InitializeFromConfig(&config);
done:
PyConfig_Clear(&config);
return status;
}
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()
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.
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;
status = Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
status = _Py_InitializeMain();
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
}
Gerenciamento de Memória
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.
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().
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.
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.
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.
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)
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.
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.
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.
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.
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.
void PyMem_SetupDebugHooks(void)
Setup debug hooks in the Python memory allocators to detect memory errors.
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.
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().
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).
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)
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;
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.
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.
Este capítulo descreve as funções, tipos e macros usados ao definir novos tipos de objeto.
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.
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.
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;
_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,
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:
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:
type _PyCFunctionFast
Type of the functions used to implement Python callables in C with signature METH_FASTCALL. The function
signature is:
type _PyCFunctionFastWithKeywords
Type of the functions used to implement Python callables in C with signature METH_FASTCALL |
METH_KEYWORDS. The function signature is:
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:
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.
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.
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:
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.
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).
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.
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.
“slots tp”
sub-slots
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:
bf_getbuffer getbufferproc()
bf_releasebuffer releasebufferproc()
slot typedefs
newfunc PyObject *
PyObject *
PyObject *
PyObject *
initproc int
PyObject *
PyObject *
PyObject *
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
The structure definition for PyTypeObject can be found in Include/object.h. For convenience of refe-
rence, this repeats the definition found there:
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;
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
(continua na próxima página)
destructor tp_finalize;
vectorcallfunc tp_vectorcall;
} PyTypeObject;
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:
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.
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
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:
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.
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:
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.
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():
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():
The value -1 should not be returned as a normal return value; when an error occurs during the computation
of the hash value, the function should set an exception and return -1.
When this field is not set (and tp_richcompare is not set), an attempt to take the hash of the object raises
TypeError. This is the same as setting it to PyObject_HashNotImplemented().
This field can be set explicitly to PyObject_HashNotImplemented() to block inheritance of the hash
method from a parent type. This is interpreted as the equivalent of __hash__ = None at the Python
level, causing isinstance(o, collections.Hashable) to correctly return False. Note that the
converse is also true - setting __hash__ = None on a class at the Python level will result in the tp_hash
slot being set to PyObject_HashNotImplemented().
Inheritance:
Group: tp_hash, tp_richcompare
This field is inherited by subtypes together with tp_richcompare: a subtype inherits both of
tp_richcompare and tp_hash, when the subtype’s tp_richcompare and tp_hash are both NULL.
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():
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():
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():
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():
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().
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
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.
Inheritance:
This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.
Ver também:
PEP 634 – Structural Pattern Matching: Specification
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:
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
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:
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.
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:
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 >=
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():
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:
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).
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:
Inheritance:
This field is inherited by subtypes.
descrsetfunc PyTypeObject.tp_descr_set
An optional pointer to a function for setting and deleting a descriptor’s value.
The function signature is:
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:
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:
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:
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.
freefunc PyTypeObject.tp_free
An optional pointer to an instance deallocation function. Its signature is:
(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.
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:
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;
/* ... */
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
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)
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.
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().
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)
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
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
Handle a request to exporter to fill in view as specified by flags. Except for point (3), an implementation of this
function MUST take these steps:
(1) Check if the request can be met. If not, raise 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.
unaryfunc PyAsyncMethods.am_await
The signature of this function is:
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:
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:
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;
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)
typedef struct {
PyObject_HEAD
const char *data;
PyObject *inst_dict;
PyObject *weakreflist;
} MyObject;
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;
typedef struct {
PyObject_HEAD
} MyObject;
typedef struct {
PyObject_VAR_HEAD
const char *data[1];
} MyObject;
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.
static int
my_traverse(Noddy *self, visitproc visit, void *arg)
{
Py_VISIT(self->foo);
(continua na próxima página)
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.
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.
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:
261
The Python/C API, Release 3.10.6
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.
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.
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
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:
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.
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).
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:
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:
• 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:
• 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:
• 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:
• 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])
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:
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().
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
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
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.
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
História e Licença
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.
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.
prepared by Licensee.
agrees to include in any such work a brief summary of the changes made␣
,→to Python
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
Agreement does not grant permission to use PSF trademarks or trade name␣
,→in a
third party.
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.
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.
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."
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.
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.
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.
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.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/.
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.
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.
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
C.3.8 test_epoll
Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
C.3.10 SipHash24
<MIT License>
Copyright (c) 2013 Marek Majkowski <[email protected]>
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/
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.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)
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
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of 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:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of 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:
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.
C.3.16 cfuhash
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:
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.
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:
Direitos autorais
297
The Python/C API, Release 3.10.6
299
The Python/C API, Release 3.10.6
300 Índice
The Python/C API, Release 3.10.6
Índice 301
The Python/C API, Release 3.10.6
302 Índice
The Python/C API, Release 3.10.6
Índice 303
The Python/C API, Release 3.10.6
304 Índice
The Python/C API, Release 3.10.6
Índice 305
The Python/C API, Release 3.10.6
306 Índice
The Python/C API, Release 3.10.6
Índice 307
The Python/C API, Release 3.10.6
308 Índice
The Python/C API, Release 3.10.6
Índice 309
The Python/C API, Release 3.10.6
310 Índice
The Python/C API, Release 3.10.6
Índice 311
The Python/C API, Release 3.10.6
312 Índice
The Python/C API, Release 3.10.6
Índice 313
The Python/C API, Release 3.10.6
314 Índice
The Python/C API, Release 3.10.6
Índice 315
The Python/C API, Release 3.10.6
316 Índice
The Python/C API, Release 3.10.6
Índice 317
The Python/C API, Release 3.10.6
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