The Python C - API
The Python C - API
Versión 3.12.4
1 Introducción 3
1.1 Estándares de codificación . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Archivos de cabecera (Include) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Macros útiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Objetos, tipos y conteos de referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.1 Conteo de Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.2 Tipos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5 Excepciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.6 Integración de Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.7 Depuración de compilaciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Estabilidad de la API en C 15
2.1 Unstable C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Interfaz binaria de aplicación estable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.1 Limited C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.2 Stable ABI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.3 Alcance y rendimiento de la API limitada . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.4 Advertencias de la API limitada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3 Consideraciones de la plataforma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4 Contenido de la API limitada . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4 Conteo de referencias 47
5 Manejo de excepciones 51
5.1 Impresión y limpieza . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 Lanzando excepciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3 Emitir advertencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.4 Consultando el indicador de error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.5 Manejo de señal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5.6 Clases de excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.7 Objetos excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.8 Objetos unicode de excepción . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.9 Control de recursión . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.10 Excepciones estándar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.11 Categorías de advertencia estándar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
6 Utilidades 65
6.1 Utilidades del sistema operativo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
6.2 Funciones del Sistema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
i
6.3 Control de procesos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.4 Importando módulos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.5 Soporte de empaquetado (marshalling) de datos . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.6 Analizando argumentos y construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.6.1 Analizando argumentos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
6.6.2 Construyendo valores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.7 Conversión y formato de cadenas de caracteres . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
6.8 PyHash API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.9 Reflexión . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.10 Registro de códec y funciones de soporte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.10.1 API de búsqueda de códec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.10.2 API de registro para controladores de errores de codificación Unicode . . . . . . . . . . . 87
6.11 Support for Perf Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
ii
8.6 Otros objetos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
8.6.1 Objetos archivo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
8.6.2 Objetos módulo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
8.6.3 Objetos iteradores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.6.4 Objetos descriptores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
8.6.5 Objetos rebanada (slice) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
8.6.6 Objetos de vista de memoria (MemoryView) . . . . . . . . . . . . . . . . . . . . . . . . 179
8.6.7 Objetos de referencia débil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
8.6.8 Cápsulas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
8.6.9 Objetos frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
8.6.10 Objetos generadores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.11 Objetos corrutina . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.12 Objetos de variables de contexto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
8.6.13 Objetos DateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
8.6.14 Objetos para indicaciones de tipado . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
iii
11.7 Personalizar asignadores de memoria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
11.8 Configurar enlaces para detectar errores en las funciones del asignador de memoria de Python . . . 248
11.9 El asignador pymalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
11.9.1 Personalizar asignador de arena de pymalloc . . . . . . . . . . . . . . . . . . . . . . . . 249
11.10 tracemalloc C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
11.11 Ejemplos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
A Glosario 305
iv
C.3.11 strtod y dtoa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
C.3.12 OpenSSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
C.3.13 expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
C.3.14 libffi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
C.3.15 zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
C.3.16 cfuhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
C.3.17 libmpdec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
C.3.18 Conjunto de pruebas W3C C14N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
C.3.19 Audioop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
C.3.20 asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Índice 345
v
vi
The Python/C API, Versión 3.12.4
Este manual documenta la API utilizada por los programadores de C y C ++ que desean escribir módulos de extensión
o incorporar Python. Es un complemento de extending-index, que describe los principios generales de la escritura de
extensión pero no documenta las funciones API en detalle.
Índice general 1
The Python/C API, Versión 3.12.4
2 Índice general
CAPÍTULO 1
Introducción
La interfaz del programador de aplicaciones (API) con Python brinda a los programadores de C y C++ acceso al
intérprete de Python en una variedad de niveles. La API es igualmente utilizable desde C++, pero por brevedad
generalmente se conoce como la API Python/C. Hay dos razones fundamentalmente diferentes para usar la API
Python/C. La primera razón es escribir módulos de extensión para propósitos específicos; Estos son módulos C que
extienden el intérprete de Python. Este es probablemente el uso más común. La segunda razón es usar Python co-
mo componente en una aplicación más grande; Esta técnica se conoce generalmente como integración (embedding)
Python en una aplicación.
Escribir un módulo de extensión es un proceso relativamente bien entendido, donde un enfoque de «libro de cocina»
(cookbook) funciona bien. Hay varias herramientas que automatizan el proceso hasta cierto punto. Si bien las personas
han integrado Python en otras aplicaciones desde su existencia temprana, el proceso de integrar Python es menos
sencillo que escribir una extensión.
Muchas funciones API son útiles independientemente de si está integrando o extendiendo Python; Además, la mayoría
de las aplicaciones que integran Python también necesitarán proporcionar una extensión personalizada, por lo que
probablemente sea una buena idea familiarizarse con la escritura de una extensión antes de intentar integrar Python
en una aplicación real.
Si está escribiendo código C para su inclusión en CPython, debe seguir las pautas y estándares definidos en PEP
7. Estas pautas se aplican independientemente de la versión de Python a la que esté contribuyendo. Seguir estas
convenciones no es necesario para sus propios módulos de extensión de terceros, a menos que eventualmente espere
contribuir con ellos a Python.
3
The Python/C API, Versión 3.12.4
Todas las definiciones de función, tipo y macro necesarias para usar la API Python/C se incluyen en su código
mediante la siguiente línea:
#define PY_SSIZE_T_CLEAN
#include <Python.h>
Esto implica la inclusión de los siguientes archivos de encabezado estándar: <stdio.h>, <string.h>, <errno.
h>, <limits.h>, <assert.h> y <stdlib.h> (si está disponible).
Nota: Dado que Python puede definir algunas definiciones de preprocesador que afectan los encabezados estándar
en algunos sistemas, debe incluir Python.h antes de incluir encabezados estándar.
Se recomienda definir siempre PY_SSIZE_T_CLEAN antes de incluir Python.h. Consulte Analizando argumen-
tos y construyendo valores para obtener una descripción de este macro.
Todos los nombres visibles del usuario definidos por Python.h (excepto los definidos por los encabezados estándar
incluidos) tienen uno de los prefijos Py o _Py. Los nombres que comienzan con _Py son para uso interno de la
implementación de Python y no deben ser utilizados por escritores de extensiones. Los nombres de miembros de
estructura no tienen un prefijo reservado.
Nota: El código de usuario nunca debe definir nombres que comiencen con Py o _Py. Esto confunde al lector y
pone en peligro la portabilidad del código de usuario para futuras versiones de Python, que pueden definir nombres
adicionales que comienzan con uno de estos prefijos.
The header files are typically installed with Python. On Unix, these are located in the directories prefix/
include/pythonversion/ and exec_prefix/include/pythonversion/, where prefix and
exec_prefix are defined by the corresponding parameters to Python’s configure script and version is '%d.
%d' % sys.version_info[:2]. On Windows, the headers are installed in prefix/include, where
prefix is the installation directory specified to the installer.
To include the headers, place both directories (if different) on your compiler’s search path for includes. Do not place
the parent directories on the search path and then use #include <pythonX.Y/Python.h>; this will break on
multi-platform builds since the platform independent headers under prefix include the platform specific headers
from exec_prefix.
Los usuarios de C++ deben tener en cuenta que aunque la API se define completamente usando C, los archivos de
encabezado declaran correctamente que los puntos de entrada son extern "C". Como resultado, no es necesario
hacer nada especial para usar la API desde C++.
Varias macros útiles se definen en los archivos de encabezado de Python. Muchos se definen más cerca de donde son
útiles (por ejemplo Py_RETURN_NONE). Otros de una utilidad más general se definen aquí. Esto no es necesaria-
mente una lista completa.
PyMODINIT_FUNC
Declare an extension module PyInit initialization function. The function return type is PyObject*. The
macro declares any special linkage declarations required by the platform, and for C++ declares the function as
extern "C".
The initialization function must be named PyInit_name, where name is the name of the module, and should
be the only non-static item defined in the module file. Example:
4 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModule_Create(&spam_module);
}
Py_ABS(x)
Retorna el valor absoluto de x.
Added in version 3.3.
Py_ALWAYS_INLINE
Ordena al compilador a siempre usar inline en una función estática inline. El compilador puede ignorarlo y
decidir no usar inline en la función.
Puede ser usado para usar inline en funciones estáticas inline de rendimiento crítico cuando se corre Python en
modo de depuración con inline de funciones deshabilitado. Por ejemplo, MSC deshabilita el inline de funciones
cuando se configura en modo de depuración.
Marcar ciegamente una función estática inline con Py_ALWAYS_INLINE puede resultar en peor rendimientos
(debido a un aumento del tamaño del código, por ejemplo). El compilador es generalmente más inteligente que
el desarrollador para el análisis costo/beneficio.
If Python is built in debug mode (if the Py_DEBUG macro is defined), the Py_ALWAYS_INLINE macro
does nothing.
Debe ser especificado antes del tipo de retorno de la función. Uso:
Py_MIN(x, y)
Retorna el valor mínimo entre x e y.
Added in version 3.3.
Py_NO_INLINE
Deshabilita el uso de inline en una función. Por ejemplo, reduce el consumo de la pila C: útil en compilaciones
LTO+PGO que usan mucho inline (ver bpo-33720).
Uso:
PyDoc_STR(str)
Crea un docstring para la cadena de caracteres de entrada dada o una cadena vacía si los docstrings están
deshabilitados.
6 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
Utilice PyDoc_STR al especificar docstrings para admitir la construcción de Python sin docstrings, como se
especifica en PEP 7.
Ejemplo:
Most Python/C API functions have one or more arguments as well as a return value of type PyObject*. This type
is a pointer to an opaque data type representing an arbitrary Python object. Since all Python object types are treated
the same way by the Python language in most situations (e.g., assignments, scope rules, and argument passing), it
is only fitting that they should be represented by a single C type. Almost all Python objects live on the heap: you
never declare an automatic or static variable of type PyObject, only pointer variables of type PyObject* can
be declared. The sole exception are the type objects; since these must never be deallocated, they are typically static
PyTypeObject objects.
Todos los objetos de Python (incluso los enteros de Python) tienen un tipo (type) y un conteo de referencia (reference
count). El tipo de un objeto determina qué tipo de objeto es (por ejemplo, un número entero, una lista o una función
definida por el usuario; hay muchos más como se explica en types). Para cada uno de los tipos conocidos hay un
macro para verificar si un objeto es de ese tipo; por ejemplo, PyList_Check(a) es verdadero si (y solo si) el
objeto al que apunta a es una lista de Python.
The reference count is important because today’s computers have a finite (and often severely limited) memory size;
it counts how many different places there are that have a strong reference to an object. Such a place could be another
object, or a global (or static) C variable, or a local variable in some C function. When the last strong reference to an
object is released (i.e. its reference count becomes zero), the object is deallocated. If it contains references to other
objects, those references are released. Those other objects may be deallocated in turn, if there are no more references
to them, and so on. (There’s an obvious problem with objects that reference each other here; for now, the solution is
«don’t do that.»)
Reference counts are always manipulated explicitly. The normal way is to use the macro Py_INCREF() to take a
new reference to an object (i.e. increment its reference count by one), and Py_DECREF() to release that reference
(i.e. decrement the reference count by one). The Py_DECREF() macro is considerably more complex than the
incref one, since it must check whether the reference count becomes zero and then cause the object’s deallocator to
be called. The deallocator is a function pointer contained in the object’s type structure. The type-specific deallocator
takes care of releasing references for other objects contained in the object if this is a compound object type, such as
a list, as well as performing any additional finalization that’s needed. There’s no chance that the reference count can
overflow; at least as many bits are used to hold the reference count as there are distinct memory locations in virtual
memory (assuming sizeof(Py_ssize_t) >= sizeof(void*)). Thus, the reference count increment is a
simple operation.
It is not necessary to hold a strong reference (i.e. increment the reference count) for every local variable that contains
a pointer to an object. In theory, the object’s reference count goes up by one when the variable is made to point to
it and it goes down by one when the variable goes out of scope. However, these two cancel each other out, so at the
end the reference count hasn’t changed. The only real reason to use the reference count is to prevent the object from
being deallocated as long as our variable is pointing to it. If we know that there is at least one other reference to the
object that lives at least as long as our variable, there is no need to take a new strong reference (i.e. increment the
reference count) temporarily. An important situation where this arises is in objects that are passed as arguments to C
functions in an extension module that are called from Python; the call mechanism guarantees to hold a reference to
every argument for the duration of the call.
However, a common pitfall is to extract an object from a list and hold on to it for a while without taking a new
reference. Some other operation might conceivably remove the object from the list, releasing that reference, and
possibly deallocating it. The real danger is that innocent-looking operations may invoke arbitrary Python code which
could do this; there is a code path which allows control to flow back to the user from a Py_DECREF(), so almost
any operation is potentially dangerous.
A safe approach is to always use the generic operations (functions whose name begins with PyObject_,
PyNumber_, PySequence_ or PyMapping_). These operations always create a new strong reference (i.e.
increment the reference count) of the object they return. This leaves the caller with the responsibility to call
Py_DECREF() when they are done with the result; this soon becomes second nature.
The reference count behavior of functions in the Python/C API is best explained in terms of ownership of references.
Ownership pertains to references, never to objects (objects are not owned: they are always shared). «Owning a re-
ference» means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership
can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for
eventually releasing it by calling Py_DECREF() or Py_XDECREF() when it’s no longer needed—or passing on
this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is
said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing
needs to be done for a borrowed reference.
Por el contrario, cuando una función de llamada pasa una referencia a un objeto, hay dos posibilidades: la función roba
una referencia al objeto, o no lo hace. Robar una referencia significa que cuando pasa una referencia a una función,
esa función asume que ahora posee esa referencia, y usted ya no es responsable de ella.
Pocas funciones roban referencias; las dos excepciones notables son PyList_SetItem() y
PyTuple_SetItem(), que roban una referencia al elemento (¡pero no a la tupla o lista en la que se colo-
ca el elemento!). Estas funciones fueron diseñadas para robar una referencia debido a un idioma común para
poblar una tupla o lista con objetos recién creados; por ejemplo, el código para crear la tupla (1, 2, "tres")
podría verse así (olvidando el manejo de errores por el momento; una mejor manera de codificar esto se muestra a
continuación):
PyObject *t;
t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));
Aquí PyLong_FromLong() retorna una nueva referencia que es inmediatamente robada por
PyTuple_SetItem(). Cuando quiera seguir usando un objeto aunque se le robe la referencia, use
Py_INCREF() para tomar otra referencia antes de llamar a la función de robo de referencias.
Por cierto, PyTuple_SetItem() es la única forma de establecer elementos de tupla;
PySequence_SetItem() y PyObject_SetItem() se niegan a hacer esto ya que las tuplas son un
tipo de datos inmutable. Solo debe usar PyTuple_SetItem() para las tuplas que está creando usted mismo.
El código equivalente para llenar una lista se puede escribir usando PyList_New() y PyList_SetItem().
Sin embargo, en la práctica, rara vez utilizará estas formas de crear y completar una tupla o lista. Hay una función
genérica, Py_BuildValue(), que puede crear los objetos más comunes a partir de valores C, dirigidos por un
una cadena de caracteres de formato (format string). Por ejemplo, los dos bloques de código anteriores podrían
reemplazarse por lo siguiente (que también se ocupa de la comprobación de errores):
PyObject *tuple, *list;
It is much more common to use PyObject_SetItem() and friends with items whose references you are only
borrowing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding
8 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
references is much saner, since you don’t have to take a new reference just so you can give that reference away («have
it be stolen»). For example, this function sets all items of a list (actually, any mutable sequence) to a given item:
int
set_all(PyObject *target, PyObject *item)
{
Py_ssize_t i, n;
n = PyObject_Length(target);
if (n < 0)
return -1;
for (i = 0; i < n; i++) {
PyObject *index = PyLong_FromSsize_t(i);
if (!index)
return -1;
if (PyObject_SetItem(target, index, item) < 0) {
Py_DECREF(index);
return -1;
}
Py_DECREF(index);
}
return 0;
}
La situación es ligeramente diferente para los valores de retorno de la función. Si bien pasar una referencia a la mayo-
ría de las funciones no cambia sus responsabilidades de propiedad para esa referencia, muchas funciones que retornan
una referencia a un objeto le otorgan la propiedad de la referencia. La razón es simple: en muchos casos, el objeto
retornado se crea sobre la marcha, y la referencia que obtiene es la única referencia al objeto. Por lo tanto, las funcio-
nes genéricas que retornan referencias de objeto, como PyObject_GetItem() y PySequence_GetItem(),
siempre retornan una nueva referencia (la entidad que llama se convierte en el propietario de la referencia).
Es importante darse cuenta de que si posee una referencia retornada por una función depende de a qué función llame
únicamente — el plumaje (el tipo del objeto pasado como argumento a la función) no entra en él! Por lo tanto, si
extrae un elemento de una lista usando PyList_GetItem(), no posee la referencia — pero si obtiene el mismo
elemento de la misma lista usando PySequence_GetItem() (que toma exactamente los mismos argumentos),
usted posee una referencia al objeto retornado.
Aquí hay un ejemplo de cómo podría escribir una función que calcule la suma de los elementos en una lista de enteros;
una vez usando PyList_GetItem(), y una vez usando PySequence_GetItem().
long
sum_list(PyObject *list)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
n = PyList_Size(list);
if (n < 0)
return -1; /* Not a list */
for (i = 0; i < n; i++) {
item = PyList_GetItem(list, i); /* Can't fail */
if (!PyLong_Check(item)) continue; /* Skip non-integers */
value = PyLong_AsLong(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
return total;
}
long
sum_sequence(PyObject *sequence)
{
Py_ssize_t i, n;
long total = 0, value;
PyObject *item;
n = PySequence_Length(sequence);
if (n < 0)
return -1; /* Has no length */
for (i = 0; i < n; i++) {
item = PySequence_GetItem(sequence, i);
if (item == NULL)
return -1; /* Not a sequence, or other failure */
if (PyLong_Check(item)) {
value = PyLong_AsLong(item);
Py_DECREF(item);
if (value == -1 && PyErr_Occurred())
/* Integer too big to fit in a C long, bail out */
return -1;
total += value;
}
else {
Py_DECREF(item); /* Discard reference ownership */
}
}
return total;
}
1.4.2 Tipos
There are few other data types that play a significant role in the Python/C API; most are simple C types such as
int, long, double and char*. A few structure types are used to describe static tables used to list the functions
exported by a module or the data attributes of a new object type, and another is used to describe the value of a
complex number. These will be discussed together with the functions that use them.
type Py_ssize_t
Part of the Stable ABI. Un tipo integral con signo tal que sizeof(Py_ssize_t) ==
sizeof(size_t). C99 no define directamente tal cosa (size_t es un tipo integral sin signo). Vea
PEP 353 para más detalles. PY_SSIZE_T_MAX es el valor positivo más grande del tipo Py_ssize_t.
1.5 Excepciones
El programador de Python solo necesita lidiar con excepciones si se requiere un manejo específico de errores; las
excepciones no manejadas se propagan automáticamente a la persona que llama, luego a la persona que llama, y
así sucesivamente, hasta que llegan al intérprete de nivel superior, donde se informan al usuario acompañado de un
seguimiento de pila (stack traceback).
Para los programadores de C, sin embargo, la comprobación de errores siempre tiene que ser explícita. Todas las
funciones en la API Python/C pueden generar excepciones, a menos que se señale explícitamente en la documentación
de una función. En general, cuando una función encuentra un error, establece una excepción, descarta cualquier
referencia de objeto que posea y retorna un indicador de error. Si no se documenta lo contrario, este indicador
es NULL o -1, dependiendo del tipo de retorno de la función. Algunas funciones retornan un resultado booleano
verdadero/falso, con falso que indica un error. Muy pocas funciones no retornan ningún indicador de error explícito
o tienen un valor de retorno ambiguo, y requieren pruebas explícitas de errores con PyErr_Occurred(). Estas
excepciones siempre se documentan explícitamente.
El estado de excepción se mantiene en el almacenamiento por subproceso (esto es equivalente a usar el almacena-
miento global en una aplicación sin subprocesos). Un subproceso puede estar en uno de dos estados: se ha producido
10 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
una excepción o no. La función PyErr_Occurred() puede usarse para verificar esto: retorna una referencia
prestada al objeto de tipo de excepción cuando se produce una excepción, y NULL de lo contrario. Hay una serie de
funciones para establecer el estado de excepción: PyErr_SetString() es la función más común (aunque no la
más general) para establecer el estado de excepción, y PyErr_Clear() borra la excepción estado.
El estado de excepción completo consta de tres objetos (todos los cuales pueden ser NULL): el tipo de excepción, el
valor de excepción correspondiente y el rastreo. Estos tienen los mismos significados que el resultado de Python de
sys.exc_info(); sin embargo, no son lo mismo: los objetos Python representan la última excepción manejada
por una declaración de Python try … except, mientras que el estado de excepción de nivel C solo existe mientras
se está pasando una excepción entre las funciones de C hasta que llega al bucle principal del intérprete de código de
bytes (bytecode) de Python, que se encarga de transferirlo a sys.exc_info() y amigos.
Tenga en cuenta que a partir de Python 1.5, la forma preferida y segura de subprocesos para acceder al estado de
excepción desde el código de Python es llamar a la función sys.exc_info(), que retorna el estado de excepción
por subproceso para el código de Python. Además, la semántica de ambas formas de acceder al estado de excepción
ha cambiado de modo que una función que detecta una excepción guardará y restaurará el estado de excepción de
su hilo para preservar el estado de excepción de su llamador. Esto evita errores comunes en el código de manejo
de excepciones causado por una función de aspecto inocente que sobrescribe la excepción que se maneja; También
reduce la extensión de vida útil a menudo no deseada para los objetos a los que hacen referencia los marcos de pila
en el rastreo.
Como principio general, una función que llama a otra función para realizar alguna tarea debe verificar si la función
llamada generó una excepción y, de ser así, pasar el estado de excepción a quien la llama (caller). Debe descartar
cualquier referencia de objeto que posea y retornar un indicador de error, pero no debe establecer otra excepción —
que sobrescribirá la excepción que se acaba de generar y perderá información importante sobre la causa exacta del
error.
A simple example of detecting exceptions and passing them on is shown in the sum_sequence() example above.
It so happens that this example doesn’t need to clean up any owned references when it detects an error. The following
example function shows some error cleanup. First, to remind you why you like Python, we show the equivalent Python
code:
int
incr_item(PyObject *dict, PyObject *key)
{
/* Objects all initialized to NULL for Py_XDECREF */
PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
int rv = -1; /* Return value initialized to -1 (failure) */
1.5. Excepciones 11
The Python/C API, Versión 3.12.4
error:
/* Cleanup code, shared by success and failure path */
La única tarea importante de la que solo tienen que preocuparse los integradores (a diferencia de los escritores de
extensión) del intérprete de Python es la inicialización, y posiblemente la finalización, del intérprete de Python. La
mayor parte de la funcionalidad del intérprete solo se puede usar después de que el intérprete se haya inicializado.
La función básica de inicialización es Py_Initialize(). Esto inicializa la tabla de módulos cargados y crea
los módulos fundamentales builtins, __main__, y sys. También inicializa la ruta de búsqueda del módulo
(sys.path).
Py_Initialize() no establece la «lista de argumentos de script» (sys.argv). Si esta variable es necesaria por
el código Python que se ejecutará más tarde, debe establecerse PyConfig.argv y PyConfig.parse_argv:
consulte Python Initialization Configuration.
En la mayoría de los sistemas (en particular, en Unix y Windows, aunque los detalles son ligeramente diferentes),
Py_Initialize() calcula la ruta de búsqueda del módulo basándose en su mejor estimación de la ubicación del
ejecutable del intérprete de Python estándar, suponiendo que la biblioteca de Python se encuentra en una ubicación fija
en relación con el ejecutable del intérprete de Python. En particular, busca un directorio llamado lib/pythonX.Y
relativo al directorio padre donde se encuentra el ejecutable llamado python en la ruta de búsqueda del comando
shell (la variable de entorno PATH).
Por ejemplo, si el ejecutable de Python se encuentra en /usr/local/bin/python, se supondrá que las biblio-
tecas están en /usr/local/lib/pythonX.Y. (De hecho, esta ruta particular también es la ubicación «alterna-
tiva», utilizada cuando no se encuentra un archivo ejecutable llamado python junto con PATH.) El usuario puede
anular este comportamiento configurando la variable de entorno PYTHONHOME, o inserte directorios adicionales
delante de la ruta estándar estableciendo PYTHONPATH.
La aplicación de integración puede dirigir la búsqueda llamando a Py_SetProgramName(file) antes llamando
Py_Initialize(). Tenga en cuenta que PYTHONHOME todavía anula esto y PYTHONPATH todavía se inserta
12 Capítulo 1. Introducción
The Python/C API, Versión 3.12.4
frente a la ruta estándar. Una aplicación que requiere un control total debe proporcionar su propia implementación de
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), y Py_GetProgramFullPath() (todo
definido en Modules/getpath.c).
A veces, es deseable «no inicializar» Python. Por ejemplo, la aplicación puede querer comenzar de nuevo (hacer otra
llamada a Py_Initialize()) o la aplicación simplemente se hace con el uso de Python y quiere liberar memoria
asignada por Python. Esto se puede lograr llamando a Py_FinalizeEx(). La función Py_IsInitialized()
retorna verdadero si Python se encuentra actualmente en el estado inicializado. Se proporciona más información
sobre estas funciones en un capítulo posterior. Tenga en cuenta que Py_FinalizeEx() no libera toda la memoria
asignada por el intérprete de Python, por ejemplo, la memoria asignada por los módulos de extensión actualmente no
se puede liberar.
Python se puede construir con varios macros para permitir verificaciones adicionales del intérprete y los módulos de
extensión. Estas comprobaciones tienden a agregar una gran cantidad de sobrecarga al tiempo de ejecución, por lo
que no están habilitadas de forma predeterminada.
A full list of the various types of debugging builds is in the file Misc/SpecialBuilds.txt in the Python source
distribution. Builds are available that support tracing of reference counts, debugging the memory allocator, or low-
level profiling of the main interpreter loop. Only the most frequently used builds will be described in the remainder
of this section.
Py_DEBUG
Compiling the interpreter with the Py_DEBUG macro defined produces what is generally meant by a debug build of
Python. Py_DEBUG is enabled in the Unix build by adding --with-pydebug to the ./configure command.
It is also implied by the presence of the not-Python-specific _DEBUG macro. When Py_DEBUG is enabled in the
Unix build, compiler optimization is disabled.
Además de la depuración del recuento de referencia que se describe a continuación, se realizan verificaciones adi-
cionales, véase compilaciones de depuración.
Definiendo Py_TRACE_REFS habilita el rastreo de referencias (véase la opción configure
--with-trace-refs). Cuando se define, se mantiene una lista circular doblemente vinculada de objetos
activos al agregar dos campos adicionales a cada PyObject. También se realiza un seguimiento de las asignaciones
totales. Al salir, se imprimen todas las referencias existentes. (En modo interactivo, esto sucede después de cada
declaración ejecutada por el intérprete).
Consulte Misc/SpecialBuilds.txt en la distribución fuente de Python para obtener información más deta-
llada.
14 Capítulo 1. Introducción
CAPÍTULO 2
Estabilidad de la API en C
Unless documented otherwise, Python’s C API is covered by the Backwards Compatibility Policy, PEP 387. Most
changes to it are source-compatible (typically by only adding new API). Changing existing API or removing API is
only done after a deprecation period or to fix serious issues.
CPython’s Application Binary Interface (ABI) is forward- and backwards-compatible across a minor release (if these
are compiled the same way; see Consideraciones de la plataforma below). So, code compiled for Python 3.10.0 will
work on 3.10.8 and vice versa, but will need to be compiled separately for 3.9.x and 3.11.x.
There are two tiers of C API with different stability expectations:
• Unstable API, may change in minor versions without a deprecation period. It is marked by the PyUnstable
prefix in names.
• Limited API, is compatible across several minor releases. When Py_LIMITED_API is defined, only this
subset is exposed from Python.h.
These are discussed in more detail below.
Names prefixed by an underscore, such as _Py_InternalState, are private API that can change without notice
even in patch releases. If you need to use this API, consider reaching out to CPython developers to discuss adding
public API for your use case.
Any API named with the PyUnstable prefix exposes CPython implementation details, and may change in every
minor release (e.g. from 3.9 to 3.10) without any deprecation warnings. However, it will not change in a bugfix release
(e.g. from 3.10.0 to 3.10.1).
It is generally intended for specialized, low-level tools like debuggers.
Projects that use this API are expected to follow CPython development and spend extra effort adjusting to changes.
15
The Python/C API, Versión 3.12.4
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.
Python 3.2 introduced the Limited API, a subset of Python’s C API. Extensions that only use the Limited API can be
compiled once and work with multiple versions of Python. Contents of the Limited API are listed below.
Py_LIMITED_API
Se define esta macro antes de incluir Python.h para optar por usar sólo la API limitada y para seleccionar
la versión de la API limitada.
Define Py_LIMITED_API to the value of PY_VERSION_HEX corresponding to the lowest Python version
your extension supports. The extension will work without recompilation with all Python 3 releases from the
specified one onward, and can use Limited API introduced up to that version.
En lugar de utilizar directamente la macro PY_VERSION_HEX, se codifica una versión menor mínima (por
ejemplo, 0x030A0000 para Python 3.10) para tener estabilidad cuando se compila con futuras versiones de
Python.
También se puede definir Py_LIMITED_API con 3. Esto funciona igual que 0x03020000 (Python 3.2, la
función que introdujo la API limitada).
To enable this, Python provides a Stable ABI: a set of symbols that will remain compatible across Python 3.x versions.
The Stable ABI contains symbols exposed in the Limited API, but also other ones – for example, functions necessary
to support older versions of the Limited API.
En Windows, las extensiones que usan la ABI estable deben estar vinculadas con python3.dll en lugar de una
biblioteca específica de la versión como python39.dll.
En algunas plataformas, Python buscará y cargará archivos de bibliotecas compartidas con el nombre de la etiqueta
abi3 (por ejemplo, mymodule.abi3.so). No comprueba si tales extensiones se ajustan a una ABI estable. El
usuario (o sus herramientas de empaquetado) necesitan asegurarse que, por ejemplo, las extensiones que se crean con
la API limitada 3.10+ no estén instaladas para versiones inferiores de Python.
Todas las funciones de la ABI estable se presentan como funciones en la biblioteca compartida de Python, no sólo
como macros. Esto las hace utilizables desde lenguajes que no usan el preprocesador de C.
El objetivo de la API limitada es permitir todo lo que es posible con la API completa en C, pero posiblemente con
una penalización de rendimiento.
Por ejemplo, mientras PyList_GetItem() está disponible, su variante macro “insegura”
PyList_GET_ITEM() no lo está. La macro puede ser más rápida porque puede confiar en los detalles de
implementación específicos de la versión del objeto de lista.
Sin definirse Py_LIMITED_API, algunas funciones de la API en C están integradas o reemplazadas por macros.
Definir Py_LIMITED_API desactiva esta integración, permitiendo estabilidad mientras que se mejoren las estruc-
turas de datos de Python, pero posiblemente reduzca el rendimiento.
Al dejar fuera la definición de Py_LIMITED_API, es posible compilar una extensión de la API limitada con una ABI
específica de la versión. Esto puede mejorar el rendimiento para esa versión de Python, pero limitará la compatibilidad.
Compilar con Py_LIMITED_API producirá una extensión que se puede distribuir donde una versión específica no
esté disponible - por ejemplo, para los prelanzamientos de una versión próxima de Python.
Note that compiling with Py_LIMITED_API is not a complete guarantee that code conforms to the Limited API or
the Stable ABI. Py_LIMITED_API only covers definitions, but an API also includes other issues, such as expected
semantics.
Un problema contra el que Py_LIMITED_API no protege es llamar una función con argumentos que son inválidos
en una versión inferior de Python. Por ejemplo, se considera una función que empieza a aceptar NULL como un
argumento. Ahora en Python 3.9, NULL selecciona un comportamiento predeterminado, pero en Python 3.8, el
argumento se usará directamente, causando una desreferencia NULL y se detendrá. Un argumento similar funciona
para campos de estructuras.
Otro problema es que algunos campos de estructura no se ocultan actualmente cuando se define Py_LIMITED_API,
aunque son parte de la API limitada.
Por estas razones, recomendamos probar una extensión con todas las versiones menores de Python que soporte, y
preferiblemente compilar con la versión más baja.
También recomendamos revisar la documentación de todas las API usadas para verificar si es parte explícitamente
de la API limitada. Aunque se defina Py_LIMITED_API, algunas declaraciones privadas se exponen por razones
técnicas (o incluso involuntariamente, como errores).
También tome en cuenta que la API limitada no necesariamente es estable: compilar con Py_LIMITED_API con
Python 3.8 significa que la extensión se ejecutará con Python 3.12, pero no necesariamente compilará con Python
3.12. En particular, las partes de la API limitada se pueden quedar obsoletas y eliminarse, siempre que la ABI estable
permanezca estable.
ABI stability depends not only on Python, but also on the compiler used, lower-level libraries and compiler options.
For the purposes of the Stable ABI, these details define a “platform”. They usually depend on the OS type and processor
architecture
Es la responsabilidad de cada distribuidor particular de Python de asegurarse de que todas las versiones de Python
en una plataforma particular se compilen de una forma que no rompa la ABI estable. Este es el caso de las versiones
de Windows y macOS de python.org y muchos distribuidores de terceros.
• PY_VECTORCALL_ARGUMENTS_OFFSET
• PyAIter_Check()
• PyArg_Parse()
• PyArg_ParseTuple()
• PyArg_ParseTupleAndKeywords()
• PyArg_UnpackTuple()
• PyArg_VaParse()
• PyArg_VaParseTupleAndKeywords()
• PyArg_ValidateKeywordArguments()
• PyBaseObject_Type
• PyBool_FromLong()
• PyBool_Type
• PyBuffer_FillContiguousStrides()
• PyBuffer_FillInfo()
• PyBuffer_FromContiguous()
• PyBuffer_GetPointer()
• PyBuffer_IsContiguous()
• PyBuffer_Release()
• PyBuffer_SizeFromFormat()
• PyBuffer_ToContiguous()
• PyByteArrayIter_Type
• PyByteArray_AsString()
• PyByteArray_Concat()
• PyByteArray_FromObject()
• PyByteArray_FromStringAndSize()
• PyByteArray_Resize()
• PyByteArray_Size()
• PyByteArray_Type
• PyBytesIter_Type
• PyBytes_AsString()
• PyBytes_AsStringAndSize()
• PyBytes_Concat()
• PyBytes_ConcatAndDel()
• PyBytes_DecodeEscape()
• PyBytes_FromFormat()
• PyBytes_FromFormatV()
• PyBytes_FromObject()
• PyBytes_FromString()
• PyBytes_FromStringAndSize()
• PyBytes_Repr()
• PyBytes_Size()
• PyBytes_Type
• PyCFunction
• PyCFunctionWithKeywords
• PyCFunction_Call()
• 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_DisplayException()
• PyErr_ExceptionMatches()
• PyErr_Fetch()
• PyErr_Format()
• PyErr_FormatV()
• PyErr_GetExcInfo()
• PyErr_GetHandledException()
• PyErr_GetRaisedException()
• PyErr_GivenExceptionMatches()
• PyErr_NewException()
• PyErr_NewExceptionWithDoc()
• PyErr_NoMemory()
• PyErr_NormalizeException()
• PyErr_Occurred()
• PyErr_Print()
• PyErr_PrintEx()
• PyErr_ProgramText()
• PyErr_ResourceWarning()
• PyErr_Restore()
• PyErr_SetExcFromWindowsErr()
• PyErr_SetExcFromWindowsErrWithFilename()
• PyErr_SetExcFromWindowsErrWithFilenameObject()
• PyErr_SetExcFromWindowsErrWithFilenameObjects()
• PyErr_SetExcInfo()
• PyErr_SetFromErrno()
• PyErr_SetFromErrnoWithFilename()
• PyErr_SetFromErrnoWithFilenameObject()
• PyErr_SetFromErrnoWithFilenameObjects()
• PyErr_SetFromWindowsErr()
• PyErr_SetFromWindowsErrWithFilename()
• PyErr_SetHandledException()
• PyErr_SetImportError()
• PyErr_SetImportErrorSubclass()
• PyErr_SetInterrupt()
• PyErr_SetInterruptEx()
• PyErr_SetNone()
• PyErr_SetObject()
• PyErr_SetRaisedException()
• PyErr_SetString()
• PyErr_SyntaxLocation()
• PyErr_SyntaxLocationEx()
• PyErr_WarnEx()
• PyErr_WarnExplicit()
• PyErr_WarnFormat()
• PyErr_WriteUnraisable()
• PyEval_AcquireLock()
• PyEval_AcquireThread()
• PyEval_CallFunction()
• PyEval_CallMethod()
• PyEval_CallObjectWithKeywords()
• PyEval_EvalCode()
• PyEval_EvalCodeEx()
• PyEval_EvalFrame()
• PyEval_EvalFrameEx()
• PyEval_GetBuiltins()
• PyEval_GetFrame()
• PyEval_GetFuncDesc()
• PyEval_GetFuncName()
• PyEval_GetGlobals()
• PyEval_GetLocals()
• PyEval_InitThreads()
• PyEval_ReleaseLock()
• PyEval_ReleaseThread()
• PyEval_RestoreThread()
• PyEval_SaveThread()
• PyEval_ThreadsInitialized()
• PyExc_ArithmeticError
• PyExc_AssertionError
• PyExc_AttributeError
• PyExc_BaseException
• PyExc_BaseExceptionGroup
• 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_GetArgs()
• PyException_GetCause()
• PyException_GetContext()
• PyException_GetTraceback()
• PyException_SetArgs()
• PyException_SetCause()
• PyException_SetContext()
• PyException_SetTraceback()
• PyFile_FromFd()
• PyFile_GetLine()
• PyFile_WriteObject()
• PyFile_WriteString()
• PyFilter_Type
• PyFloat_AsDouble()
• PyFloat_FromDouble()
• PyFloat_FromString()
• PyFloat_GetInfo()
• PyFloat_GetMax()
• PyFloat_GetMin()
• PyFloat_Type
• PyFrameObject
• PyFrame_GetCode()
• PyFrame_GetLineNumber()
• PyFrozenSet_New()
• PyFrozenSet_Type
• 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
• PyMember_GetOne()
• PyMember_SetOne()
• PyMemoryView_FromBuffer()
• PyMemoryView_FromMemory()
• PyMemoryView_FromObject()
• PyMemoryView_GetContiguous()
• PyMemoryView_Type
• PyMethodDef
• PyMethodDescr_Type
• PyModuleDef
• PyModuleDef_Base
• PyModuleDef_Init()
• PyModuleDef_Type
• PyModule_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_CheckBuffer()
• PyObject_CheckReadBuffer()
• PyObject_ClearWeakRefs()
• PyObject_CopyData()
• PyObject_DelItem()
• PyObject_DelItemString()
• PyObject_Dir()
• PyObject_Format()
• PyObject_Free()
• PyObject_GC_Del()
• PyObject_GC_IsFinalized()
• PyObject_GC_IsTracked()
• PyObject_GC_Track()
• PyObject_GC_UnTrack()
• PyObject_GenericGetAttr()
• PyObject_GenericGetDict()
• PyObject_GenericSetAttr()
• PyObject_GenericSetDict()
• PyObject_GetAIter()
• PyObject_GetAttr()
• PyObject_GetAttrString()
• PyObject_GetBuffer()
• PyObject_GetItem()
• PyObject_GetIter()
• PyObject_GetTypeData()
• PyObject_HasAttr()
• PyObject_HasAttrString()
• PyObject_Hash()
• PyObject_HashNotImplemented()
• PyObject_Init()
• PyObject_InitVar()
• PyObject_IsInstance()
• PyObject_IsSubclass()
• PyObject_IsTrue()
• PyObject_Length()
• PyObject_Malloc()
• PyObject_Not()
• PyObject_Realloc()
• PyObject_Repr()
• PyObject_RichCompare()
• PyObject_RichCompareBool()
• PyObject_SelfIter()
• PyObject_SetAttr()
• PyObject_SetAttrString()
• PyObject_SetItem()
• PyObject_Size()
• PyObject_Str()
• PyObject_Type()
• PyObject_Vectorcall()
• PyObject_VectorcallMethod()
• PyProperty_Type
• PyRangeIter_Type
• PyRange_Type
• PyReversed_Type
• PySeqIter_New()
• PySeqIter_Type
• PySequence_Check()
• PySequence_Concat()
• 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()
• PyStructSequence_UnnamedField
• PySuper_Type
• PySys_AddWarnOption()
• PySys_AddWarnOptionUnicode()
• PySys_AddXOption()
• PySys_FormatStderr()
• PySys_FormatStdout()
• PySys_GetObject()
• PySys_GetXOptions()
• PySys_HasWarnOptions()
• PySys_ResetWarnOptions()
• PySys_SetArgv()
• PySys_SetArgvEx()
• PySys_SetObject()
• PySys_SetPath()
• PySys_WriteStderr()
• PySys_WriteStdout()
• PyThreadState
• PyThreadState_Clear()
• PyThreadState_Delete()
• PyThreadState_Get()
• PyThreadState_GetDict()
• PyThreadState_GetFrame()
• PyThreadState_GetID()
• PyThreadState_GetInterpreter()
• PyThreadState_New()
• PyThreadState_SetAsyncExc()
• PyThreadState_Swap()
• PyThread_GetInfo()
• PyThread_ReInitTLS()
• PyThread_acquire_lock()
• PyThread_acquire_lock_timed()
• PyThread_allocate_lock()
• PyThread_create_key()
• PyThread_delete_key()
• PyThread_delete_key_value()
• PyThread_exit_thread()
• PyThread_free_lock()
• PyThread_get_key_value()
• PyThread_get_stacksize()
• PyThread_get_thread_ident()
• PyThread_get_thread_native_id()
• PyThread_init_thread()
• PyThread_release_lock()
• PyThread_set_key_value()
• PyThread_set_stacksize()
• PyThread_start_new_thread()
• PyThread_tss_alloc()
• PyThread_tss_create()
• PyThread_tss_delete()
• PyThread_tss_free()
• PyThread_tss_get()
• PyThread_tss_is_created()
• PyThread_tss_set()
• PyTraceBack_Here()
• PyTraceBack_Print()
• PyTraceBack_Type
• PyTupleIter_Type
• PyTuple_GetItem()
• PyTuple_GetSlice()
• PyTuple_New()
• PyTuple_Pack()
• PyTuple_SetItem()
• PyTuple_Size()
• PyTuple_Type
• PyTypeObject
• PyType_ClearCache()
• PyType_FromMetaclass()
• PyType_FromModuleAndSpec()
• PyType_FromSpec()
• PyType_FromSpecWithBases()
• PyType_GenericAlloc()
• PyType_GenericNew()
• PyType_GetFlags()
• PyType_GetModule()
• PyType_GetModuleState()
• PyType_GetName()
• PyType_GetQualName()
• PyType_GetSlot()
• PyType_GetTypeDataSize()
• PyType_IsSubtype()
• PyType_Modified()
• PyType_Ready()
• PyType_Slot
• PyType_Spec
• PyType_Type
• PyUnicodeDecodeError_Create()
• PyUnicodeDecodeError_GetEncoding()
• PyUnicodeDecodeError_GetEnd()
• PyUnicodeDecodeError_GetObject()
• PyUnicodeDecodeError_GetReason()
• PyUnicodeDecodeError_GetStart()
• PyUnicodeDecodeError_SetEnd()
• PyUnicodeDecodeError_SetReason()
• PyUnicodeDecodeError_SetStart()
• PyUnicodeEncodeError_GetEncoding()
• PyUnicodeEncodeError_GetEnd()
• PyUnicodeEncodeError_GetObject()
• PyUnicodeEncodeError_GetReason()
• PyUnicodeEncodeError_GetStart()
• PyUnicodeEncodeError_SetEnd()
• PyUnicodeEncodeError_SetReason()
• PyUnicodeEncodeError_SetStart()
• PyUnicodeIter_Type
• PyUnicodeTranslateError_GetEnd()
• PyUnicodeTranslateError_GetObject()
• PyUnicodeTranslateError_GetReason()
• PyUnicodeTranslateError_GetStart()
• PyUnicodeTranslateError_SetEnd()
• PyUnicodeTranslateError_SetReason()
• PyUnicodeTranslateError_SetStart()
• PyUnicode_Append()
• PyUnicode_AppendAndDel()
• PyUnicode_AsASCIIString()
• 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_InternFromString()
• PyUnicode_InternInPlace()
• PyUnicode_IsIdentifier()
• PyUnicode_Join()
• PyUnicode_Partition()
• PyUnicode_RPartition()
• PyUnicode_RSplit()
• PyUnicode_ReadChar()
• PyUnicode_Replace()
• PyUnicode_Resize()
• PyUnicode_RichCompare()
• PyUnicode_Split()
• PyUnicode_Splitlines()
• PyUnicode_Substring()
• PyUnicode_Tailmatch()
• PyUnicode_Translate()
• PyUnicode_Type
• PyUnicode_WriteChar()
• PyVarObject
• PyVarObject.ob_base
• PyVarObject.ob_size
• PyVectorcall_Call()
• PyVectorcall_NARGS()
• PyWeakReference
• PyWeakref_GetObject()
• PyWeakref_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_Version
• Py_XNewRef()
• Py_buffer
• Py_intptr_t
• Py_ssize_t
• Py_uintptr_t
• allocfunc
• binaryfunc
• descrgetfunc
• descrsetfunc
• destructor
• getattrfunc
• getattrofunc
• getbufferproc
• getiterfunc
• getter
• hashfunc
• initproc
• inquiry
• iternextfunc
• lenfunc
• newfunc
• objobjargproc
• objobjproc
• releasebufferproc
• reprfunc
• richcmpfunc
• setattrfunc
• setattrofunc
• setter
• ssizeargfunc
• ssizeobjargproc
• ssizessizeargfunc
• ssizessizeobjargproc
• symtable
• ternaryfunc
• traverseproc
• unaryfunc
• vectorcallfunc
• visitproc
Las funciones en este capítulo te permitirán ejecutar código fuente de Python desde un archivo o un búfer, pero no
te permitirán interactuar de una manera detallada con el intérprete.
Several of these functions accept a start symbol from the grammar as a parameter. The available start symbols are
Py_eval_input, Py_file_input, and Py_single_input. These are described following the functions
which accept them as parameters.
Note also that several of these functions take FILE* parameters. One particular issue which needs to be handled
carefully is that the FILE structure for different C libraries can be different and incompatible. Under Windows (at
least), it is possible for dynamically linked extensions to actually use different libraries, so care should be taken that
FILE* parameters are only passed to these functions if it is certain that they were created by the same library that
the Python runtime is using.
int Py_Main(int argc, wchar_t **argv)
Part of the Stable ABI. El programa principal para el intérprete estándar. Está disponible para programas que
incorporan Python. Los parámetros argc y argv deben prepararse exactamente como los que se pasan a la
función main() de un programa en C (convertido a wchar_t de acuerdo con la configuración regional del
usuario). Es importante tener en cuenta que la lista de argumentos puede ser modificada (pero el contenido
de las cadenas de caracteres señaladas por la lista de argumentos no lo es). El valor de retorno será 0 si el
intérprete acaba normalmente (es decir, sin excepción), 1 si el intérprete acaba debido a una excepción, o 2 si
la lista de parámetros no representa una línea de comando Python válida.
Note that if an otherwise unhandled SystemExit is raised, this function will not return 1, but exit the
process, as long as PyConfig.inspect is zero.
int Py_BytesMain(int argc, char **argv)
Part of the Stable ABI since version 3.8. Similar a Py_Main() pero argv es un arreglo de cadenas de caracteres
de bytes.
Added in version 3.8.
int PyRun_AnyFile(FILE *fp, const char *filename)
Esta es una interfaz simplificada para PyRun_AnyFileExFlags() más abajo, dejando closeit establecido
a 0 y flags establecido a NULL.
int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Esta es una interfaz simplificada para PyRun_AnyFileExFlags() más abajo, dejando closeit establecido
a 0.
41
The Python/C API, Versión 3.12.4
Nota: En Windows, fp debe abrirse en modo binario (por ejemplo, fopen(filename, "rb"). De lo
contrario, Python puede no manejar correctamente el archivo de script con la terminación de línea LF.
int (*PyOS_InputHook)(void)
Part of the Stable ABI. Se puede configurar para que apunte a una función con el prototipo int
func(void). Se llamará a la función cuando el indicador del intérprete de Python esté a punto de estar
inactivo y espere la entrada del usuario desde el terminal. El valor de retorno es ignorado. Sobrescribiendo este
enlace se puede utilizar para integrar la solicitud del intérprete con otros bucles de eventos, como se hace en
Modules/_tkinter.c en el código fuente de Python.
Distinto en la versión 3.12: This function is only called from the main interpreter.
char *(*PyOS_ReadlineFunctionPointer)(FILE*, FILE*, const char*)
Se puede configurar para que apunte a una función con el prototipo char *func (FILE *stdin,
FILE *stdout, char *prompt), sobrescribiendo la función predeterminada utilizada para leer una
sola línea de entrada desde el intérprete. Se espera que la función genere la cadena de caracteres prompt si
no es NULL, y luego lea una línea de entrada del archivo de entrada estándar proporcionado, retornando la
cadena de caracteres resultante. Por ejemplo, el módulo readline establece este enlace para proporcionar
funciones de edición de línea y finalización de tabulación.
El resultado debe ser una cadena de caracteres alocado por PyMem_RawMalloc() o
PyMem_RawRealloc(), o NULL si ocurre un error.
Distinto en la versión 3.4: El resultado debe ser alocado por PyMem_RawMalloc() o
PyMem_RawRealloc(), en vez de ser alocado por PyMem_Malloc() o PyMem_Realloc().
Distinto en la versión 3.12: This function is only called from the main interpreter.
PyObject *PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)
Return value: New reference. Esta es una interfaz simplificada para PyRun_StringFlags() más abajo,
dejando flags establecido a NULL.
PyObject *PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
Return value: New reference. Ejecuta el código fuente de Python desde str en el contexto especificado por los
objetos globals y locals con los indicadores del compilador especificados por flags. globals debe ser un diccio-
nario; locals puede ser cualquier objeto que implemente el protocolo de mapeo. El parámetro start especifica
el token de inicio que se debe usar para analizar el código fuente.
Retorna el resultado de ejecutar el código como un objeto Python, o NULL” si se produjo una excepción.
PyObject *PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)
Return value: New reference. Esta es una interfaz simplificada para PyRun_FileExFlags() más abajo,
dejando closeit establecido a 0 y flags establecido a NULL.
PyObject *PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int
closeit)
Return value: New reference. Esta es una interfaz simplificada para PyRun_FileExFlags() más abajo,
dejando flags establecido a NULL.
PyObject *PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
Return value: New reference. Esta es una interfaz simplificada para PyRun_FileExFlags() más abajo,
dejando closeit establecido a 0.
PyObject *PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
int closeit, PyCompilerFlags *flags)
Return value: New reference. Similar a PyRun_StringFlags(), pero el código fuente de Python se lee
de fp en lugar de una cadena de caracteres en memoria. filename debe ser el nombre del fichero, es decodifi-
cado desde el filesystem encoding and error handler. Si closeit es verdadero, el fichero se cierra antes de que
PyRun_FileExFlags() retorne.
PyObject *Py_CompileString(const char *str, const char *filename, int start)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz simplificada para
Py_CompileStringFlags() más abajo, dejando flags establecido a NULL.
43
The Python/C API, Versión 3.12.4
PyObject *Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)
Return value: New reference. Esta es una interfaz simplificada para Py_CompileStringExFlags() más
abajo, con optimize establecido a -1.
PyObject *Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags,
int optimize)
Return value: New reference. Parse and compile the Python source code in str, returning the resulting code
object. The start token is given by start; this can be used to constrain the code which can be compiled and should
be Py_eval_input, Py_file_input, or Py_single_input. The filename specified by filename is
used to construct the code object and may appear in tracebacks or SyntaxError exception messages. This
returns NULL if the code cannot be parsed or compiled.
El número entero optimize especifica el nivel de optimización del compilador; un valor de -1 selecciona el nivel
de optimización del intérprete como se indica en las opciones -O. Los niveles explícitos son 0 (sin optimización;
__debug__ es verdadero), 1 (los asserts se eliminan, __debug__ es falso) o 2 (los docstrings también se
eliminan) )
Added in version 3.4.
PyObject *Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags
*flags, int optimize)
Return value: New reference. Como Py_CompileStringObject(), pero filename es una cadena de bytes
decodificada a partir del manejador de codificación y errores del sistema de archivos.
Added in version 3.2.
PyObject *PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz simplificada para
PyEval_EvalCodeEx(), con solo el objeto de código y las variables globales y locales. Los otros ar-
gumentos están establecidos en NULL.
PyObject *PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int
argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int
defcount, PyObject *kwdefs, PyObject *closure)
Return value: New reference. Part of the Stable ABI. Evaluar un objeto de código precompilado, dado un
entorno particular para su evaluación. Este entorno consta de un diccionario de variables globales, un objeto de
mapeo de variables locales, arreglos de argumentos, palabras clave y valores predeterminados, un diccionario
de valores predeterminados para argumentos keyword-only y una tupla de cierre de células.
PyObject *PyEval_EvalFrame(PyFrameObject *f)
Return value: New reference. Part of the Stable ABI. Evaluar un marco de ejecución. Esta es una interfaz
simplificada para PyEval_EvalFrameEx(), para compatibilidad con versiones anteriores.
PyObject *PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Return value: New reference. Part of the Stable ABI. Esta es la función principal sin barnizar de la interpretación
de Python. El objeto de código asociado con el marco de ejecución del marco f se ejecuta, interpretando el
código de bytes y ejecutando llamadas según sea necesario. El parámetro adicional throwflag se puede ignorar
por lo general; si es verdadero, entonces se lanza una excepción de inmediato; esto se usa para los métodos
throw() de objetos generadores.
Distinto en la versión 3.4: Esta función ahora incluye una afirmación de depuración para ayudar a garantizar
que no descarte silenciosamente una excepción activa.
int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
Esta función cambia los flags del marco de evaluación actual, y retorna verdad (true) en caso de éxito, falso
(false) en caso de fallo.
int Py_eval_input
El símbolo de inicio de la gramática de Python para expresiones aisladas; para usar con
Py_CompileString().
int Py_file_input
El símbolo de inicio de la gramática de Python para secuencias de declaración leídos desde un archivo u otra
fuente; para usar con Py_CompileString(). Este es el símbolo usado cuando se compile un código fuente
en Python arbitrariamente largo.
int Py_single_input
El símbolo de inicio de la gramática de Python para una declaración única; para usar con
Py_CompileString(). Este es el símbolo usado para el bucle interactivo del intérprete.
struct PyCompilerFlags
Esta es la estructura usada para contener los flags del compilador. En casos donde el código es sólo compilado,
es pasado como int flags, y en casos donde el código es ejecutado, es pasado como PyCompilerFlags
*flags. En este caso, from __future__ import puede modificar los flags.
Whenever PyCompilerFlags *flags is NULL, cf_flags is treated as equal to 0, and any modifica-
tion due to from __future__ import is discarded.
int cf_flags
Flags del compilador.
int cf_feature_version
cf_feature_version es la versión menor de Python. Debe ser inicializado a PY_MINOR_VERSION.
The field is ignored by default, it is used if and only if PyCF_ONLY_AST flag is set in cf_flags.
Distinto en la versión 3.8: Agregado el campo cf_feature_version.
int CO_FUTURE_DIVISION
Este bit puede ser configurado en flags para causar que un operador de división / sea interpretado como una
«división real» de acuerdo a PEP 238.
45
The Python/C API, Versión 3.12.4
Conteo de referencias
The functions and macros in this section are used for managing reference counts of Python objects.
Py_ssize_t Py_REFCNT(PyObject *o)
Get the reference count of the Python object o.
Note that the returned value may not actually reflect how many references to the object are actually held. For
example, some objects are «immortal» and have a very high refcount that does not reflect the actual number of
references. Consequently, do not rely on the returned value to be accurate, other than a value of 0 or 1.
Use the Py_SET_REFCNT() function to set an object reference count.
Distinto en la versión 3.10: Py_REFCNT() is changed to the inline static function.
Distinto en la versión 3.11: The parameter type is no longer const PyObject*.
void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)
Set the object o reference counter to refcnt.
Note that this function has no effect on immortal objects.
Added in version 3.9.
Distinto en la versión 3.12: Immortal objects are not modified.
void Py_INCREF(PyObject *o)
Indicate taking a new strong reference to object o, indicating it is in use and should not be destroyed.
Esta función se usa generalmente para convertir un borrowed reference en un strong reference en su lugar. La
función Py_NewRef() se puede utilizar para crear un nuevo strong reference.
When done using the object, release it by calling Py_DECREF().
El objeto no debe ser NULL; si no está seguro de que no sea NULL, use Py_XINCREF().
Do not expect this function to actually modify o in any way. For at least some objects, this function has no
effect.
Distinto en la versión 3.12: Immortal objects are not modified.
void Py_XINCREF(PyObject *o)
Similar to Py_INCREF(), but the object o can be NULL, in which case this has no effect.
Ver también Py_XNewRef().
47
The Python/C API, Versión 3.12.4
Advertencia: The deallocation function can cause arbitrary Python code to be invoked (e.g. when a class
instance with a __del__() method is deallocated). While exceptions in such code are not propagated,
the executed code has free access to all Python global variables. This means that any object that is reachable
from a global variable should be in a consistent state before Py_DECREF() is invoked. For example, code
to delete an object from a list should copy a reference to the deleted object in a temporary variable, update
the list data structure, and then call Py_DECREF() for the temporary variable.
Py_DECREF(dst);
dst = src;
Py_SETREF(dst, src);
That arranges to set dst to src _before_ releasing the reference to the old value of dst, so that any code triggered
as a side-effect of dst getting torn down no longer believes dst points to a valid object.
Added in version 3.6.
Distinto en la versión 3.12: The macro arguments are now only evaluated once. If an argument has side effects,
these are no longer duplicated.
Py_XSETREF(dst, src)
Variant of Py_SETREF macro that uses Py_XDECREF() instead of Py_DECREF().
Added in version 3.6.
Distinto en la versión 3.12: The macro arguments are now only evaluated once. If an argument has side effects,
these are no longer duplicated.
49
The Python/C API, Versión 3.12.4
Manejo de excepciones
Las funciones descritas en este capítulo le permitirán manejar y lanzar excepciones de Python. Es importante com-
prender algunos de los conceptos básicos del manejo de excepciones de Python. Funciona de manera similar a la
variable POSIX errno: hay un indicador global (por hilo) del último error que ocurrió. La mayoría de las funciones
de C API no borran esto en caso de éxito, pero lo configurarán para indicar la causa del error en caso de falla. La
mayoría de las funciones de C API también retornan un indicador de error, generalmente NULL si se supone que
retornan un puntero, o -1 si retornan un número entero (excepción: las funciones PyArg_* retornan 1 para el éxito
y 0 para el fracaso).
Concretamente, el indicador de error consta de tres punteros de objeto: el tipo de excepción, el valor de la excep-
ción y el objeto de rastreo. Cualquiera de esos punteros puede ser NULL si no está configurado (aunque algunas
combinaciones están prohibidas, por ejemplo, no puede tener un rastreo no NULL si el tipo de excepción es NULL).
Cuando una función debe fallar porque alguna función que llamó falló, generalmente no establece el indicador de
error; la función que llamó ya lo configuró. Es responsable de manejar el error y borrar la excepción o regresar
después de limpiar cualquier recurso que tenga (como referencias de objetos o asignaciones de memoria); debería
no continuar normalmente si no está preparado para manejar el error. Si regresa debido a un error, es importante
indicarle a la persona que llama que se ha establecido un error. Si el error no se maneja o se propaga cuidadosamente,
es posible que las llamadas adicionales a la API de Python/C no se comporten como se espera y pueden fallar de
manera misteriosa.
void PyErr_Clear()
Part of the Stable ABI. Borra el indicador de error. Si el indicador de error no está configurado, no hay efecto.
void PyErr_PrintEx(int set_sys_last_vars)
Part of the Stable ABI. Imprime un rastreo estándar en sys.stderr y borra el indicador de error. A menos
que el error sea un Salida del sistema, en ese caso no se imprime ningún rastreo y el proceso de
Python se cerrará con el código de error especificado por la instancia de Salida del sistema.
51
The Python/C API, Versión 3.12.4
Llame a esta función solo cuando el indicador de error está configurado. De lo contrario, provocará un error
fatal!
If set_sys_last_vars is nonzero, the variable sys.last_exc is set to the printed exception. For
backwards compatibility, the deprecated variables sys.last_type, sys.last_value and sys.
last_traceback are also set to the type, value and traceback of this exception, respectively.
Distinto en la versión 3.12: The setting of sys.last_exc was added.
void PyErr_Print()
Part of the Stable ABI. Alias para PyErr_PrintEx(1).
void PyErr_WriteUnraisable(PyObject *obj)
Part of the Stable ABI. Llama sys.unraisablehook() utilizando la excepción actual y el argumento
obj.
This utility function prints a warning message to sys.stderr when an exception has been set but it is
impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs
in an __del__() method.
The function is called with a single argument obj that identifies the context in which the unraisable exception
occurred. If possible, the repr of obj will be printed in the warning message. If obj is NULL, only the traceback
is printed.
Se debe establecer una excepción al llamar a esta función.
Distinto en la versión 3.4: Print a traceback. Print only traceback if obj is NULL.
Distinto en la versión 3.8: Use sys.unraisablehook().
void PyErr_DisplayException(PyObject *exc)
Part of the Stable ABI since version 3.12. Print the standard traceback display of exc to sys.stderr,
including chained exceptions and notes.
Added in version 3.12.
Estas funciones lo ayudan a configurar el indicador de error del hilo actual. Por conveniencia, algunas de estas fun-
ciones siempre retornarán un puntero NULL para usar en una declaración return.
void PyErr_SetString(PyObject *type, const char *message)
Part of the Stable ABI. This is the most common way to set the error indicator. The first argument specifies the
exception type; it is normally one of the standard exceptions, e.g. PyExc_RuntimeError. You need not
create a new strong reference to it (e.g. with Py_INCREF()). The second argument is an error message; it is
decoded from 'utf-8'.
void PyErr_SetObject(PyObject *type, PyObject *value)
Part of the Stable ABI. Esta función es similar a PyErr_SetString() pero le permite especificar un objeto
Python arbitrario para el «valor» de la excepción.
PyObject *PyErr_Format(PyObject *exception, const char *format, ...)
Return value: Always NULL. Part of the Stable ABI. Esta función establece el indicador de error y retorna
NULL. exception debe ser una clase de excepción Python. El format y los parámetros posteriores ayudan a
formatear el mensaje de error; tienen el mismo significado y valores que en PyUnicode_FromFormat().
format es una cadena de caracteres codificada en ASCII.
PyObject *PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)
Return value: Always NULL. Part of the Stable ABI since version 3.5. Igual que PyErr_Format(), pero
tomando un argumento va_list en lugar de un número variable de argumentos.
Added in version 3.5.
PyErr_SetFromWindowsErr(), with the additional behavior that if filename is not NULL, it is deco-
ded from the filesystem encoding (os.fsdecode()) and passed to the constructor of OSError as a third
parameter to be used to define the filename attribute of the exception instance.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject
*filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar to
PyErr_SetExcFromWindowsErr(), with the additional behavior that if filename is not NULL, it is
passed to the constructor of OSError as a third parameter to be used to define the filename attribute of
the exception instance.
Disponibilidad: Windows.
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject
*filename, PyObject *filename2)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a
PyErr_SetExcFromWindowsErrWithFilenameObject(), pero acepta un segundo objeto de
nombre de archivo.
Disponibilidad: Windows.
Added in version 3.4.
PyObject *PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char
*filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar a
PyErr_SetFromWindowsErrWithFilename(), con un parámetro adicional que especifica el tipo
de excepción que se lanzará.
Disponibilidad: Windows.
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.7. Esta es una función conveniente para subir
ImportError. msg se establecerá como la cadena de mensaje de la excepción. name y path, que pueden ser
NULL, se establecerán como atributos respectivos name y path de ImportError.
Added in version 3.3.
PyObject *PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name,
PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.6. Al igual que
PyErr_SetImportError() pero esta función permite especificar una subclase de ImportError para
aumentar.
Added in version 3.6.
void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Establece información de archivo, línea y desplazamiento para la excepción actual. Si la excepción actual no es
un SyntaxError, establece atributos adicionales, lo que hace que el sub sistema de impresión de excepciones
piense que la excepción es SyntaxError.
Added in version 3.4.
void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)
Part of the Stable ABI since version 3.7. Como PyErr_SyntaxLocationObject(), pero filename es
una cadena de bytes decodificada a partir de filesystem encoding and error handler.
Added in version 3.2.
void PyErr_SyntaxLocation(const char *filename, int lineno)
Part of the Stable ABI. Como PyErr_SyntaxLocationEx(), pero se omite el parámetro col_offset.
void PyErr_BadInternalCall()
Part of the Stable ABI. Esta es una abreviatura de PyErr_SetString(PyExc_SystemError,
message), donde message indica que se invocó una operación interna (por ejemplo, una función de Pyt-
hon/C API) con un argumento ilegal. Es principalmente para uso interno.
Use estas funciones para emitir advertencias desde el código C. Reflejan funciones similares exportadas por el módulo
Python warnings. Normalmente imprimen un mensaje de advertencia a sys.stderr; sin embargo, también es posible
que el usuario haya especificado que las advertencias se conviertan en errores, y en ese caso lanzarán una excepción.
También es posible que las funciones generen una excepción debido a un problema con la maquinaria de advertencia.
El valor de retorno es 0 si no se lanza una excepción, o -1 si se lanza una excepción. (No es posible determinar
si realmente se imprime un mensaje de advertencia, ni cuál es el motivo de la excepción; esto es intencional). Si se
produce una excepción, la persona que llama debe hacer su manejo normal de excepciones (por ejemplo, referencias
propiedad de Py_DECREF() y retornan un valor de error).
int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Part of the Stable ABI. Emite un mensaje de advertencia. El argumento category es una categoría de advertencia
(ver más abajo) o NULL; el argumento message es una cadena de caracteres codificada en UTF-8. stack_level
es un número positivo que proporciona una cantidad de marcos de pila; la advertencia se emitirá desde la línea
de código que se está ejecutando actualmente en ese marco de pila. Un stack_level de 1 es la función que llama
PyErr_WarnEx(), 2 es la función por encima de eso, y así sucesivamente.
Las categorías de advertencia deben ser subclases de PyExc_Warning; PyExc_Warning es una subcla-
se de PyExc_Exception; la categoría de advertencia predeterminada es PyExc_RuntimeWarning.
Las categorías de advertencia estándar de Python están disponibles como variables globales cuyos nombres se
enumeran en Categorías de advertencia estándar.
Para obtener información sobre el control de advertencia, consulte la documentación del módulo warnings
y la opción -W en la documentación de la línea de comandos. No hay API de C para el control de advertencia.
int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno,
PyObject *module, PyObject *registry)
Emite un mensaje de advertencia con control explícito sobre todos los atributos de advertencia. Este es un
contenedor sencillo alrededor de la función Python warnings.warn_explicit(); consulte allí para
obtener más información. Los argumentos module y registry pueden establecerse en NULL para obtener el
efecto predeterminado que se describe allí.
Added in version 3.4.
int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const
char *module, PyObject *registry)
Part of the Stable ABI. Similar a PyErr_WarnExplicitObject() excepto que message y module son
cadenas codificadas UTF-8, y filename se decodifica de filesystem encoding and error handler.
int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI. Función similar a PyErr_WarnEx(), pero usa PyUnicode_FromFormat()
para formatear el mensaje de advertencia. format es una cadena de caracteres codificada en ASCII.
Added in version 3.2.
int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI since version 3.6. Function similar to PyErr_WarnFormat(), but category is
ResourceWarning and it passes source to warnings.WarningMessage.
Added in version 3.6.
PyObject *PyErr_Occurred()
Return value: Borrowed reference. Part of the Stable ABI. Prueba si el indicador de error está configurado.
Si se establece, retorna la excepción type (el primer argumento de la última llamada a una de las funciones
PyErr_Set* o PyErr_Restore()). Si no está configurado, retorna NULL. No posee una referencia al
valor de retorno, por lo que no necesita usar Py_DECREF().
La persona que llama debe retener el GIL.
Nota: No compare el valor de retorno con una excepción específica; use PyErr_ExceptionMatches()
en su lugar, como se muestra a continuación. (La comparación podría fallar fácilmente ya que la excepción
puede ser una instancia en lugar de una clase, en el caso de una excepción de clase, o puede ser una subclase
de la excepción esperada).
{
PyObject *exc = PyErr_GetRaisedException();
PyErr_SetRaisedException(exc);
}
Ver también:
PyErr_GetHandledException(), to save the exception currently being handled.
Added in version 3.12.
void PyErr_SetRaisedException(PyObject *exc)
Part of the Stable ABI since version 3.12. Set exc as the exception currently being raised, clearing the existing
exception if one is set.
Advertencia: This call steals a reference to exc, which must be a valid exception.
Nota: This function is normally only used by legacy code that needs to catch exceptions or save and restore
the error indicator temporarily.
For example:
{
PyObject *type, *value, *traceback;
PyErr_Fetch(&type, &value, &traceback);
Nota: This function is normally only used by legacy code that needs to save and restore the error indicator
temporarily. Use PyErr_Fetch() to save the current error indicator.
Nota: This function does not implicitly set the __traceback__ attribute on the exception value. If setting
the traceback appropriately is desired, the following additional snippet is needed:
if (tb != NULL) {
PyException_SetTraceback(val, tb);
}
PyObject *PyErr_GetHandledException(void)
Part of the Stable ABI since version 3.11. Recupera la instancia de excepción activa, como la que devolvería
sys.exception(). Esto se refiere a una excepción que ya fue capturada, no a una excepción recién lan-
zada. Retorna una nueva referencia a la excepción o NULL. No modifica el estado de excepción del intérprete.
Nota: Esta función normalmente no es utilizada por el código que quiere manejar excepciones. En cam-
bio, se puede usar cuando el código necesita guardar y restaurar el estado de excepción temporalmente. Use
PyErr_SetHandledException() para restaurar o borrar el estado de excepción.
Nota: Esta función normalmente no es utilizada por el código que quiere manejar excepciones. En cam-
bio, se puede usar cuando el código necesita guardar y restaurar el estado de excepción temporalmente. Use
PyErr_GetHandledException() para leer el estado de excepción.
Nota: Esta función normalmente no es utilizada por el código que quiere manejar excepciones. En cam-
bio, se puede usar cuando el código necesita guardar y restaurar el estado de excepción temporalmente. Use
PyErr_SetExcInfo() para restaurar o borrar el estado de excepción.
Nota: Esta función normalmente no es utilizada por el código que quiere manejar excepciones. En cam-
bio, se puede usar cuando el código necesita guardar y restaurar el estado de excepción temporalmente. Use
PyErr_GetExcInfo() para leer el estado de excepción.
int PyErr_CheckSignals()
Part of the Stable ABI. Esta función interactúa con el manejo de señales de Python.
Si la función se llama desde el hilo principal y bajo el intérprete principal de Python, verifica si se ha enviado
una señal a los procesos y, de ser así, invoca el manejador de señales correspondiente. Si el módulo signal
es compatible, esto puede invocar un manejador de señales escrito en Python.
La función intenta manejar todas las señales pendientes y luego devuelve 0. Sin embargo, si un manejador de
señales de Python lanza una excepción, el indicador de error se establece y la función devuelve -1 inmedia-
tamente (de modo que es posible que otras señales pendientes no se hayan manejado todavía: estarán en la
siguiente invocación de PyErr_CheckSignals()).
Si la función se llama desde un hilo no principal, o bajo un intérprete de Python no principal, no hace nada y
devuelve 0.
Esta función se puede llamar mediante un código C de ejecución prolongada que quiere ser interrumpible por
las peticiones del usuario (como presionar Ctrl-C).
Nota: The default Python signal handler for SIGINT raises the KeyboardInterrupt exception.
void PyErr_SetInterrupt()
Part of the Stable ABI. Simulate the effect of a SIGINT signal arriving. This is equivalent to
PyErr_SetInterruptEx(SIGINT).
Nota: Esta función es segura para señales asíncronas. Se puede llamar sin el GIL y desde un manejador de
señales de C.
Nota: Esta función es segura para señales asíncronas. Se puede llamar sin el GIL y desde un manejador de
señales de C.
Implement part of the interpreter’s implementation of except*. orig is the original exception that was caught,
and excs is the list of the exceptions that need to be raised. This list contains the unhandled part of orig, if any,
as well as the exceptions that were raised from the except* clauses (so they have a different traceback from
orig) and those that were reraised (and have the same traceback as orig). Return the ExceptionGroup that
needs to be reraised in the end, or None if there is nothing to reraise.
Added in version 3.12.
Estas dos funciones proporcionan una forma de realizar llamadas recursivas seguras en el nivel C, tanto en el núcleo
como en los módulos de extensión. Son necesarios si el código recursivo no invoca necesariamente el código Python
(que rastrea su profundidad de recursión automáticamente). Tampoco son necesarios para las implementaciones de
tp_call porque call protocol se encarga del manejo de la recursividad.
int Py_EnterRecursiveCall(const char *where)
Part of the Stable ABI since version 3.9. Marca un punto donde una llamada recursiva de nivel C está a punto
de realizarse.
If USE_STACKCHECK is defined, this function checks if the OS stack overflowed using
PyOS_CheckStack(). If this is the case, it sets a MemoryError and returns a nonzero value.
La función verifica si se alcanza el límite de recursión. Si este es el caso, se establece a RecursionError
y se retorna un valor distinto de cero. De lo contrario, se retorna cero.
where debería ser una cadena de caracteres codificada en UTF-8 como "en la comprobación de
instancia" para concatenarse con el mensaje RecursionError causado por el límite de profundidad
de recursión.
Distinto en la versión 3.9: This function is now also available in the limited API.
void Py_LeaveRecursiveCall(void)
Part of the Stable ABI since version 3.9. Termina una Py_EnterRecursiveCall(). Se debe llamar una
vez por cada invocación exitosa de Py_EnterRecursiveCall().
Distinto en la versión 3.9: This function is now also available in the limited API.
La implementación adecuada de tp_repr para los tipos de contenedor requiere un manejo de recursión especial.
Además de proteger la pila, tp_repr también necesita rastrear objetos para evitar ciclos. Las siguientes dos funcio-
nes facilitan esta funcionalidad. Efectivamente, estos son los C equivalentes a reprlib.recursive_repr().
Todas las excepciones estándar de Python están disponibles como variables globales cuyos nombres son PyExc_
seguidos del nombre de excepción de Python. Estos tienen el tipo PyObject*; todos son objetos de clase. Para
completar, aquí están todas las variables:
Nombre en C Notas
PyExc_EnvironmentError
PyExc_IOError
2
PyExc_WindowsError
Distinto en la versión 3.3: Estos alias solían ser tipos de excepción separados.
Notas:
Todas las categorías de advertencia estándar de Python están disponibles como variables globales cuyos nombres son
PyExc_ seguidos del nombre de excepción de Python. Estos tienen el tipo PyObject*; todos son objetos de clase.
Para completar, aquí están todas las variables:
Utilidades
Las funciones de este capítulo realizan varias tareas de utilidad, que van desde ayudar a que el código C sea más portátil
en todas las plataformas, usar módulos Python desde C y analizar argumentos de funciones y construir valores Python
a partir de valores C.
Advertencia: La llamada C fork() solo debe hacerse desde hilo «principal» (del intérprete «principal»).
Lo mismo es cierto para PyOS_BeforeFork().
65
The Python/C API, Versión 3.12.4
o cualquier función similar que clone el proceso actual, independientemente de si la clonación del proceso fue
exitosa. Solo disponible en sistemas donde fork() está definido.
Advertencia: La llamada C fork() solo debe hacerse desde hilo «principal» (del intérprete «principal»).
Lo mismo es cierto para PyOS_AfterFork_Parent().
Advertencia: La llamada C fork() solo debe hacerse desde hilo «principal» (del intérprete «principal»).
Lo mismo es cierto para PyOS_AfterFork_Child().
Advertencia: Esta función no debe llamarse directamente: utilice la API PyConfig con la función
PyConfig_SetBytesString() que asegura que Python está preinicializado.
Esta función no debe llamarse antes de que Python esté preinicializado y para que la configuración local
LC_CTYPE esté correctamente configurada: véase la función Py_PreInitialize().
66 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
Decodifica una cadena de bytes a partir del manejador de codificación y errores del sistema de archivos. Si el
controlador de error es el controlador de error surrogateescape, los bytes no codificables se decodifican como
caracteres en el rango U+DC80..U+DCFF; y si una secuencia de bytes se puede decodificar como un carácter
sustituto, escape los bytes usando el controlador de error surrogateescape en lugar de decodificarlos.
Retorna un puntero a una cadena de caracteres anchos recientemente asignada, use PyMem_RawFree() para
liberar la memoria. Si el tamaño no es NULL, escribe el número de caracteres anchos excluyendo el carácter
nulo en *size
Retorna NULL en caso de error de decodificación o error de asignación de memoria. Si size no es NULL,
*size se establece en (size_t) -1 en caso de error de memoria o en (size_t) -2 en caso de error
de decodificación.
El filesystem encoding and error handler son seleccionados por PyConfig_Read(): ver
filesystem_encoding y filesystem_errors que pertenecen a PyConfig.
Los errores de decodificación nunca deberían ocurrir, a menos que haya un error en la biblioteca C.
Utilice la función Py_EncodeLocale() para codificar la cadena de caracteres en una cadena de bytes.
Ver también:
Las funciones PyUnicode_DecodeFSDefaultAndSize() y PyUnicode_DecodeLocaleAndSize().
Added in version 3.5.
Distinto en la versión 3.7: La función ahora utiliza la codificación UTF-8 en el Modo Python UTF-8.
Distinto en la versión 3.8: The function now uses the UTF-8 encoding on Windows if PyPreConfig.
legacy_windows_fs_encoding is zero;
char *Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
Part of the Stable ABI since version 3.7. Codifica una cadena de caracteres amplios según el término filesystem
encoding and error handler. Si el gestor de errores es surrogateescape error handler, los caracteres sustituidos
en el rango U+DC80..U+DCFF se convierten en bytes 0x80..0xFF.
Retorna un puntero a una cadena de bytes recién asignada, usa PyMem_Free() para liberar la memoria.
Retorna NULL si se genera un error de codificación o error de asignación de memoria.
Si error_pos no es NULL, *error_pos se establece en (size_t)-1 en caso de éxito, o se establece en el
índice del carácter no válido en el error de codificación.
El filesystem encoding and error handler son seleccionados por PyConfig_Read(): ver
filesystem_encoding y filesystem_errors que pertenecen a PyConfig.
Use la función Py_DecodeLocale() para decodificar la cadena de bytes en una cadena de caracteres
anchos.
Advertencia: Esta función no debe llamarse antes de que Python esté preinicializado y para que la confi-
guración local LC_CTYPE esté correctamente configurada: véase la función Py_PreInitialize().
Ver también:
Las funciones PyUnicode_EncodeFSDefault() y PyUnicode_EncodeLocale().
Added in version 3.5.
Distinto en la versión 3.7: La función ahora utiliza la codificación UTF-8 en el Modo Python UTF-8.
Distinto en la versión 3.8: The function now uses the UTF-8 encoding on Windows if PyPreConfig.
legacy_windows_fs_encoding is zero.
Estas son funciones de utilidad que hacen que la funcionalidad del módulo sys sea accesible para el código C. Todos
funcionan con el diccionario del módulo sys del subproceso actual del intérprete, que está contenido en la estructura
interna del estado del subproceso.
PyObject *PySys_GetObject(const char *name)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto name del módulo sys o NULL si
no existe, sin establecer una excepción.
int PySys_SetObject(const char *name, PyObject *v)
Part of the Stable ABI. Establece name en el módulo sys en v a menos que v sea NULL, en cuyo caso name
se elimina del módulo sys. Retorna 0 en caso de éxito, -1 en caso de error.
void PySys_ResetWarnOptions()
Part of the Stable ABI. Restablece sys.warnoptions a una lista vacía. Esta función puede llamarse antes
de Py_Initialize().
void PySys_AddWarnOption(const wchar_t *s)
Part of the Stable ABI. Esta API se mantiene para conservar compatibilidad con versiones anteriores, en su
lugar se debe usar: PyConfig.warnoptions, ver Configuración de inicialización de Python.
Agrega s a sys.warnoptions. Esta función debe llamarse antes de Py_Initialize() para afectar la
lista de filtros de advertencias.
Obsoleto desde la versión 3.11.
void PySys_AddWarnOptionUnicode(PyObject *unicode)
Part of the Stable ABI. Esta API se mantiene para conservar compatibilidad con versiones anteriores, en su
lugar se debe usar: PyConfig.warnoptions, ver Configuración de inicialización de Python.
Agrega unicode a sys.warnoptions.
Nota: esta función no se puede utilizar actualmente desde fuera de la implementación de CPython, ya que debe
llamarse antes de la importación implícita de warnings en Py_Initialize() para que sea efectiva,
pero no se puede llamar hasta que se haya inicializado suficiente tiempo de ejecución para permitir la creación
de objetos Unicode.
Obsoleto desde la versión 3.11.
void PySys_SetPath(const wchar_t *path)
Part of the Stable ABI. Esta API se mantiene para conservar compatibilidad con versiones anteriores, en su lugar
se debe usar: PyConfig.module_search_paths y PyConfig.module_search_paths_set,
ver Python Initialization Configuration.
Establece sys.path en un objeto lista de rutas que se encuentra en path, que debería ser una lista de rutas
separadas con el delimitador de ruta de búsqueda de la plataforma (: en Unix, ; en Windows )
Obsoleto desde la versión 3.11.
void PySys_WriteStdout(const char *format, ...)
Part of the Stable ABI. Escribe la cadena de caracteres de salida descrita por format en sys.stdout. No se
lanzan excepciones, incluso si se produce el truncamiento (ver más abajo).
format debe limitar el tamaño total de la cadena de caracteres de salida formateada a 1000 bytes o menos;
después de 1000 bytes, la cadena de caracteres de salida se trunca. En particular, esto significa que no deben
existir formatos «%s» sin restricciones; estos deben limitarse usando «%.<N>s» donde <N> es un número
decimal calculado de modo que <N> más el tamaño máximo de otro texto formateado no exceda los 1000
bytes. También tenga cuidado con «%f», que puede imprimir cientos de dígitos para números muy grandes.
Si ocurre un problema, o sys.stdout no está configurado, el mensaje formateado se escribe en el real (nivel
C) stdout.
68 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
Ver PEP 578 para una descripción detallada de la auditoría. Las funciones en el tiempo de ejecución y la
biblioteca estándar que generan eventos se enumeran en table de eventos de auditoria. Los detalles se encuentran
en la documentación de cada función.
Lanza un evento de auditoria sys.addaudithook sin argumentos.
typedef int (*Py_AuditHookFunction)(const char *event, PyObject *args, void *userData)
The type of the hook function. event is the C string event argument passed to PySys_Audit(). args
is guaranteed to be a PyTupleObject. userData is the argument passed to PySys_AddAuditHook().
Added in version 3.8.
70 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
El valor de retorno es una nueva referencia al módulo importado o paquete de nivel superior, o NULL con una
excepción establecida en caso de error. Al igual que para __import__(), el valor de retorno cuando se
solicitó un submódulo de un paquete normalmente es el paquete de nivel superior, a menos que se proporcione
un fromlist no vacío.
Las importaciones que fallan eliminan objetos de módulo incompletos, como con
PyImport_ImportModule().
PyObject *PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI since version 3.7. Importa un módulo. Esto se descri-
be mejor haciendo referencia a la función Python incorporada __import__(), ya que la función estándar
__import__() llama a esta función directamente.
El valor de retorno es una nueva referencia al módulo importado o paquete de nivel superior, o NULL con una
excepción establecida en caso de error. Al igual que para __import__(), el valor de retorno cuando se
solicitó un submódulo de un paquete normalmente es el paquete de nivel superior, a menos que se proporcione
un fromlist no vacío.
Added in version 3.3.
PyObject *PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
Return value: New reference. Part of the Stable ABI. Similar a PyImport_ImportModuleLevelObject(),
pero el nombre es una cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
Distinto en la versión 3.3: Los valores negativos para level ya no se aceptan.
PyObject *PyImport_Import(PyObject *name)
Return value: New reference. Part of the Stable ABI. Esta es una interfaz de nivel superior que llama a la
«función de enlace de importación» actual (con un nivel explícito de 0, que significa importación absoluta).
Invoca la función __import__() de las __builtins__ de los globales (globals) actuales. Esto significa
que la importación se realiza utilizando los ganchos de importación instalados en el entorno actual.
Esta función siempre usa importaciones absolutas.
PyObject *PyImport_ReloadModule(PyObject *m)
Return value: New reference. Part of the Stable ABI. Recarga un módulo. Retorna una nueva referencia al
módulo recargado, o NULL con una excepción establecida en caso de error (el módulo todavía existe en este
caso).
PyObject *PyImport_AddModuleObject(PyObject *name)
Return value: Borrowed reference. Part of the Stable ABI since version 3.7. Retorna el objeto módulo corres-
pondiente a un nombre de módulo. El argumento name puede tener la forma package.module. Primero
revise el diccionario de módulos si hay uno allí, y si no, crea uno nuevo y lo agrega al diccionario de módulos.
Retorna NULL con una excepción establecida en caso de error.
Nota: Esta función no carga ni importa el módulo; si el módulo no estaba cargado, obtendrá un objeto de
módulo vacío. Utilice PyImport_ImportModule() o una de sus variantes para importar un módulo. Las
estructuras de paquete implicadas por un nombre punteado para name no se crean si aún no están presentes.
set if an error occurred. name is removed from sys.modules in error cases, even if name was already in
sys.modules on entry to PyImport_ExecCodeModule(). Leaving incompletely initialized modules
in sys.modules is dangerous, as imports of such modules have no way to know that the module object is
an unknown (and probably damaged with respect to the module author’s intents) state.
The module’s __spec__ and __loader__ will be set, if not set already, with the appropriate values. The
spec’s loader will be set to the module’s __loader__ (if set) and to an instance of SourceFileLoader
otherwise.
The module’s __file__ attribute will be set to the code object’s co_filename. If applicable,
__cached__ will also be set.
Esta función volverá a cargar el módulo si ya se importó. Consulte PyImport_ReloadModule() para
conocer la forma prevista de volver a cargar un módulo.
Si name apunta a un nombre punteado de la forma package.module, cualquier estructura de paquete que
no se haya creado aún no se creará.
Ver también PyImport_ExecCodeModuleEx() y PyImport_ExecCodeModuleWithPathnames().
Distinto en la versión 3.12: The setting of __cached__ and __loader__ is deprecated. See
ModuleSpec for alternatives.
PyObject *PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
Return value: New reference. Part of the Stable ABI. Como PyImport_ExecCodeModule(), pero el
atributo __file__ del objeto del módulo se establece en pathname si no es NULL.
Ver también PyImport_ExecCodeModuleWithPathnames().
PyObject *PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
PyObject *cpathname)
Return value: New reference. Part of the Stable ABI since version 3.7. Como
PyImport_ExecCodeModuleEx(), pero el atributo __cached__ del objeto módulo se establece en
cpathname si no es NULL. De las tres funciones, esta es la recomendada para usar.
Added in version 3.3.
Distinto en la versión 3.12: Setting __cached__ is deprecated. See ModuleSpec for alternatives.
PyObject *PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char
*pathname, const char *cpathname)
Return value: New reference. Part of the Stable ABI. Como PyImport_ExecCodeModuleObject(),
pero name, pathname y cpathname son cadenas de caracteres codificadas UTF-8. También se intenta averiguar
cuál debe ser el valor de pathname de cpathname si el primero se establece en NULL.
Added in version 3.2.
Distinto en la versión 3.3: Uses imp.source_from_cache() in calculating the source path if only the
bytecode path is provided.
Distinto en la versión 3.12: No longer uses the removed imp module.
long PyImport_GetMagicNumber()
Part of the Stable ABI. Retorna el número mágico para los archivos de bytecode de Python (también conocido
como archivos .pyc). El número mágico debe estar presente en los primeros cuatro bytes del archivo de código
de bytes, en orden de bytes little-endian. Retorna -1 en caso de error.
Distinto en la versión 3.3: Retorna un valor de -1 en caso de error.
const char *PyImport_GetMagicTag()
Part of the Stable ABI. Retorna la cadena de caracteres de etiqueta mágica para nombres de archivo de có-
digo de bytes Python en formato PEP 3147. Tenga en cuenta que el valor en sys.implementation.
cache_tag es autoritario y debe usarse en lugar de esta función.
Added in version 3.2.
72 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
PyObject *PyImport_GetModuleDict()
Return value: Borrowed reference. Part of the Stable ABI. Retorna el diccionario utilizado para la administración
del módulo (también conocido como sys.modules). Tenga en cuenta que esta es una variable por intérprete.
PyObject *PyImport_GetModule(PyObject *name)
Return value: New reference. Part of the Stable ABI since version 3.8. Retorna el módulo ya importado con el
nombre dado. Si el módulo aún no se ha importado, retorna NULL pero no establece un error. Retorna NULL
y establece un error si falla la búsqueda.
Added in version 3.7.
PyObject *PyImport_GetImporter(PyObject *path)
Return value: New reference. Part of the Stable ABI. Return a finder object for a sys.path/pkg.__path__
item path, possibly by fetching it from the sys.path_importer_cache dict. If it wasn’t yet cached,
traverse sys.path_hooks until a hook is found that can handle the path item. Return None if no hook
could; this tells our caller that the path based finder could not find a finder for this path item. Cache the result
in sys.path_importer_cache. Return a new reference to the finder object.
int PyImport_ImportFrozenModuleObject(PyObject *name)
Part of the Stable ABI since version 3.7. Carga un módulo congelado llamado name. Retorna 1 para el éxito,
0 si no se encuentra el módulo y -1 con una excepción establecida si falla la inicialización. Para acceder al
módulo importado con una carga exitosa, use PyImport_ImportModule(). (Tenga en cuenta el nombre
inapropiado — esta función volvería a cargar el módulo si ya se importó).
Added in version 3.3.
Distinto en la versión 3.4: El atributo __file__ ya no está establecido en el módulo.
int PyImport_ImportFrozenModule(const char *name)
Part of the Stable ABI. Similar a PyImport_ImportFrozenModuleObject(), pero el nombre es una
cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
struct _frozen
Esta es la definición del tipo de estructura para los descriptores de módulos congelados, según lo generado con
la herramienta freeze (ver Tools/freeze en la distribución de código fuente de Python). Su definición,
que se encuentra en Include/import.h, es:
struct _frozen {
const char *name;
const unsigned char *code;
int size;
bool is_package;
};
Distinto en la versión 3.11: El nuevo campo is_package indica si el módulo es un paquete o no. Esto
sustituye a la configuración del campo size con un valor negativo.
const struct _frozen *PyImport_FrozenModules
Este puntero se inicializa para apuntar a un arreglo de registros _frozen, terminado por uno cuyos registros
son todos NULL o cero. Cuando se importa un módulo congelado, se busca en esta tabla. El código de terceros
podría jugar con esto para proporcionar una colección de módulos congelados creada dinámicamente.
int PyImport_AppendInittab(const char *name, PyObject *(*initfunc)(void))
Part of the Stable ABI. Agrega un solo módulo a la tabla existente de módulos incorporados. Este es un con-
tenedor conveniente PyImport_ExtendInittab(), que retorna -1 si la tabla no se puede extender. El
nuevo módulo se puede importar con el nombre name, y utiliza la función initfunc como la función de inicia-
lización llamada en el primer intento de importación. Esto debería llamarse antes de Py_Initialize().
struct _inittab
Structure describing a single entry in the list of built-in modules. Programs which embed Python may use an
array of these structures in conjunction with PyImport_ExtendInittab() to provide additional built-in
modules. The structure consists of two members:
Estas rutinas permiten que el código C funcione con objetos serializados utilizando el mismo formato de datos que
el módulo marshal. Hay funciones para escribir datos en el formato de serialización y funciones adicionales que
se pueden usar para volver a leer los datos. Los archivos utilizados para almacenar datos ordenados deben abrirse en
modo binario.
Los valores numéricos se almacenan con el byte menos significativo primero.
El módulo admite dos versiones del formato de datos: la versión 0 es la versión histórica, la versión 1 comparte
cadenas de caracteres internas en el archivo y al desempaquetar (unmarshalling). La versión 2 usa un formato binario
para números de punto flotante. Py_MARSHAL_VERSION indica el formato de archivo actual (actualmente 2).
void PyMarshal_WriteLongToFile(long value, FILE *file, int version)
Empaqueta (marshal) un entero value long a un archivo file. Esto solo escribirá los 32 bits menos significativos
de value; sin importar el tamaño del tipo long nativo. version indica el formato del archivo.
This function can fail, in which case it sets the error indicator. Use PyErr_Occurred() to check for that.
void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)
Empaqueta (marshal) un objeto Python, value, a un archivo file. version indica el formato del archivo.
This function can fail, in which case it sets the error indicator. Use PyErr_Occurred() to check for that.
PyObject *PyMarshal_WriteObjectToString(PyObject *value, int version)
Return value: New reference. Retorna un objeto de bytes que contiene la representación empaquetada (mars-
halled) de value. version indica el formato del archivo.
Las siguientes funciones permiten volver a leer los valores empaquetados (marshalled).
long PyMarshal_ReadLongFromFile(FILE *file)
Retorna un entero long de C desde el flujo de datos FILE* abierto para lectura. Solo se puede leer un valor
de 32 bits con esta función, independientemente del tamaño nativo del tipo long.
En caso de error, establece la excepción apropiada (EOFError) y retorna -1.
int PyMarshal_ReadShortFromFile(FILE *file)
Retorna un entero short de C desde el flujo de datos FILE* abierto para lectura. Solo se puede leer un valor
de 16 bits con esta función, independientemente del tamaño nativo del tipo short.
En caso de error, establece la excepción apropiada (EOFError) y retorna -1.
PyObject *PyMarshal_ReadObjectFromFile(FILE *file)
Return value: New reference. Retorna un objeto Python del flujo de datos FILE* abierto para lectura.
En caso de error, establece la excepción apropiada (EOFError, ValueError o TypeError) y retorna
NULL.
74 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
Estas funciones son útiles al crear sus propias funciones y métodos de extensiones. Información y ejemplos adicionales
están disponibles en extending-index.
Las tres primeras de estas funciones descritas, PyArg_ParseTuple(),
PyArg_ParseTupleAndKeywords(), y PyArg_Parse(), todas usan cadenas de caracteres de for-
mato que se utilizan para contarle a la función sobre los argumentos esperados. Las cadenas de caracteres de formato
utilizan la misma sintaxis para cada una de estas funciones.
Una cadena de formato consta de cero o más «unidades de formato.» Una unidad de formato describe un objeto
Python; por lo general es un solo carácter o una secuencia de unidades formato entre paréntesis. Con unas pocas
excepciones, una unidad de formato que no es una secuencia entre paréntesis normalmente corresponde a un único
argumento de dirección de estas funciones. En la siguiente descripción, la forma citada es la unidad de formato; la
entrada en paréntesis (redondos) es el tipo de objeto Python que coincida con la unidad de formato; y la entrada entre
corchetes [cuadrados] es el tipo de la variable(s) C cuya dirección debe ser pasada.
Estos formatos permiten acceder a un objeto como un bloque contiguo de memoria. Usted no tiene que proporcionar
almacenamiento en bruto para el Unicode o área de bytes retornada.
A menos que se indique lo contrario, los búferes no son terminados en NULL (NUL-terminated).
There are three ways strings and buffers can be converted to C:
• Formats such as y* and s* fill a Py_buffer structure. This locks the underlying buffer so that the caller can
subsequently use the buffer even inside a Py_BEGIN_ALLOW_THREADS block without the risk of mutable
data being resized or destroyed. As a result, you have to call PyBuffer_Release() after you have finished
processing the data (or in any early abort case).
• The es, es#, et and et# formats allocate the result buffer. You have to call PyMem_Free() after you
have finished processing the data (or in any early abort case).
• Other formats take a str or a read-only bytes-like object, such as bytes, and provide a const char *
pointer to its buffer. In this case the buffer is «borrowed»: it is managed by the corresponding Python object,
and shares the lifetime of this object. You won’t have to release any memory yourself.
To ensure that the underlying buffer may be safely borrowed, the object’s PyBufferProcs.
bf_releasebuffer field must be NULL. This disallows common mutable objects such as bytearray,
but also some read-only objects such as memoryview of bytes.
Besides this bf_releasebuffer requirement, there is no check to verify whether the input object is im-
mutable (e.g. whether it would honor a request for a writable buffer, or whether another thread can mutate the
data).
Nota: Para todas las variantes de formatos # (s#, y#, etc.), la macro PY_SSIZE_T_CLEAN tiene que estar definida
antes de incluir Python.h. En Python 3.9 y versiones anteriores, el tipo del argumento length es Py_ssize_t si
la macro PY_SSIZE_T_CLEAN está definida, o int si no lo está.
Nota: Este formato no acepta objetos de tipo bytes. Si desea aceptar los caminos del sistema
de archivos y convertirlos en cadenas de caracteres C, es preferible utilizar el formato O& con
PyUnicode_FSConverter() como convertidor.
Distinto en la versión 3.5: Anteriormente, TypeError se lanzó cuando se encontraron puntos de código nulos
incrustados en la cadena de caracteres de Python.
s* (str o bytes-like object) [Py_buffer]
Este formato acepta objetos Unicode, así como objetos de tipo bytes. Llena una estructura Py_buffer pro-
porcionada por la persona que llama. En este caso la cadena de caracteres de C resultante puede contener
bytes NUL embebidos. Los objetos Unicode se convierten en cadenas de caracteres C utilizando codificación
'utf-8'.
s# (str, bytes-like object de sólo lectura) [const char *, Py_ssize_t]
Like s*, except that it provides a borrowed buffer. The result is stored into two C variables, the first one a
pointer to a C string, the second one its length. The string may contain embedded null bytes. Unicode objects
are converted to C strings using 'utf-8' encoding.
z (str o None) [const char *]
Como s, pero el objeto Python también puede ser None, en cuyo caso el puntero C se establece en NULL.
z* (str, bytes-like object o None) [Py_buffer]
Como s*, pero el objeto Python también puede ser None, en cuyo caso el miembro de buf de la estructura
Py_buffer se establece en NULL.
z# (str, bytes-like object de sólo lectura o None) [const char *, Py_ssize_t]
Como s#, pero el objeto Python también puede ser None, en cuyo caso el puntero C se establece en NULL.
y (bytes-like object de sólo lectura) [const char *]
This format converts a bytes-like object to a C pointer to a borrowed character string; it does not accept Unicode
objects. The bytes buffer must not contain embedded null bytes; if it does, a ValueError exception is raised.
Distinto en la versión 3.5: Anteriormente, TypeError se lanzó cuando bytes nulos incrustados se encontraron
en el buffer de bytes.
y* (bytes-like object) [Py_buffer]
Esta variante de s* no acepta objetos Unicode, solamente los objetos de tipo bytes. Esta es la forma reco-
mendada para aceptar datos binarios.
y# (bytes-like object de sólo lectura) [const char *, Py_ssize_t]
Esta variante en s# no acepta objetos Unicode, solo objetos similares a bytes.
76 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
S (bytes) [PyBytesObject *]
Requires that the Python object is a bytes object, without attempting any conversion. Raises TypeError
if the object is not a bytes object. The C variable may also be declared as PyObject*.
Y (bytearray) [PyByteArrayObject *]
Requires that the Python object is a bytearray object, without attempting any conversion. Raises
TypeError if the object is not a bytearray object. The C variable may also be declared as PyObject*.
U (str) [PyObject *]
Requires that the Python object is a Unicode object, without attempting any conversion. Raises TypeError
if the object is not a Unicode object. The C variable may also be declared as PyObject*.
w* (bytes-like object de lectura y escritura) [Py_buffer]
Este formato acepta cualquier objeto que implemente la interfaz del búfer de lectura-escritura. Llena la es-
tructura Py_buffer proporcionada por quien llama. El búfer puede contener bytes nulos incrustados. Quien
llama tiene que llamar PyBuffer_Release() cuando termina con el búfer.
es (str) [const char *encoding, char **buffer]
Esta variante en s se usa para codificar Unicode en un búfer de caracteres. Solo funciona para datos codificados
sin bytes NUL integrados.
This format requires two arguments. The first is only used as input, and must be a const char* which
points to the name of an encoding as a NUL-terminated string, or NULL, in which case 'utf-8' encoding
is used. An exception is raised if the named encoding is not known to Python. The second argument must be
a char**; the value of the pointer it references will be set to a buffer with the contents of the argument text.
The text will be encoded in the encoding specified by the first argument.
PyArg_ParseTuple() asignará un búfer del tamaño necesitado, copiará los datos codificados en este búfer
y ajustará *buffer para referenciar el nuevo almacenamiento asignado. Quien llama es responsable para llamar
PyMem_Free() para liberar el búfer asignado después de su uso.
et (str, bytes o bytearray) [const char *encoding, char **buffer]
Igual que es, excepto que los objetos de cadena de caracteres de bytes se pasan sin recodificarlos. En cambio,
la implementación supone que el objeto de cadena de caracteres de bytes utiliza la codificación que se pasa
como parámetro.
es# (str) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
Esta variante en s# se usa para codificar Unicode en un búfer de caracteres. A diferencia del formato es, esta
variante permite datos de entrada que contienen caracteres NUL.
It requires three arguments. The first is only used as input, and must be a const char* which points to the
name of an encoding as a NUL-terminated string, or NULL, in which case 'utf-8' encoding is used. An
exception is raised if the named encoding is not known to Python. The second argument must be a char**;
the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will
be encoded in the encoding specified by the first argument. The third argument must be a pointer to an integer;
the referenced integer will be set to the number of bytes in the output buffer.
Hay dos modos de operación:
Si *buffer señala un puntero NULL, la función asignará un búfer del tamaño necesario, copiará los datos co-
dificados en este búfer y configurará *buffer para hacer referencia al almacenamiento recién asignado. Quien
llama es responsable de llamar a PyMem_Free() para liberar el búfer asignado después del uso.
Si *buffer apunta a un puntero no NULL (un búfer ya asignado), PyArg_ParseTuple() usará esta ubica-
ción como el búfer e interpretará el valor inicial de *buffer_length como el tamaño del búfer. Luego copiará los
datos codificados en el búfer y los terminará en NUL. Si el búfer no es lo suficientemente grande, se establecerá
a ValueError.
En ambos casos, *buffer_length se establece a la longitud de los datos codificados sin el byte NUL final.
et# (str, bytes o bytearray) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
Igual que es#, excepto que los objetos de cadena de caracteres de bytes se pasan sin recodificarlos. En cambio,
la implementación supone que el objeto de cadena de caracteres de bytes utiliza la codificación que se pasa
como parámetro.
Distinto en la versión 3.12: u, u#, Z, and Z# are removed because they used a legacy Py_UNICODE* representation.
Números
Otros objetos
O (object) [PyObject *]
Store a Python object (without any conversion) in a C object pointer. The C program thus receives the ac-
tual object that was passed. A new strong reference to the object is not created (i.e. its reference count is not
increased). The pointer stored is not NULL.
O! (object) [typeobject, PyObject *]
Store a Python object in a C object pointer. This is similar to O, but takes two C arguments: the first is the
address of a Python type object, the second is the address of the C variable (of type PyObject*) into which
the object pointer is stored. If the Python object does not have the required type, TypeError is raised.
78 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
where object is the Python object to be converted and address is the void* argument that was passed to the
PyArg_Parse* function. The returned status should be 1 for a successful conversion and 0 if the conversion
has failed. When the conversion fails, the converter function should raise an exception and leave the content of
address unmodified.
Si el converter retorna Py_CLEANUP_SUPPORTED, se puede llamar por segunda vez si el análisis del argu-
mento finalmente falla, dando al convertidor la oportunidad de liberar cualquier memoria que ya haya asignado.
En esta segunda llamada, el parámetro object será NULL; address tendrá el mismo valor que en la llamada ori-
ginal.
Distinto en la versión 3.1: Py_CLEANUP_SUPPORTED fue agregada.
p (bool) [int]
Prueba el valor pasado por verdad (un booleano predicado p) y convierte el resultado a su valor entero C
verdadero/falso entero equivalente. Establece int en 1 si la expresión era verdadera y 0 si era falsa. Esto acepta
cualquier valor válido de Python. Consulte truth para obtener más información sobre cómo Python prueba los
valores por verdad.
Added in version 3.3.
(items) (tuple) [matching-items]
El objeto debe ser una secuencia de Python cuya longitud es el número de unidades de formato en items. Los
argumentos C deben corresponder a las unidades de formato individuales en items. Las unidades de formato
para secuencias pueden estar anidadas.
It is possible to pass «long» integers (integers whose value exceeds the platform’s LONG_MAX) however no proper
range checking is done — the most significant bits are silently truncated when the receiving field is too small to receive
the value (actually, the semantics are inherited from downcasts in C — your mileage may vary).
Algunos otros caracteres tienen un significado en una cadena de formato. Esto puede no ocurrir dentro de paréntesis
anidados. Son:
|
Indica que los argumentos restantes en la lista de argumentos de Python son opcionales. Las variables C corres-
pondientes a argumentos opcionales deben inicializarse a su valor predeterminado — cuando no se especifica
un argumento opcional, PyArg_ParseTuple() no toca el contenido de las variables C correspondientes.
$
PyArg_ParseTupleAndKeywords() solamente: indica que los argumentos restantes en la lista de ar-
gumentos de Python son solo palabras clave. Actualmente, todos los argumentos de solo palabras clave también
deben ser argumentos opcionales, por lo que | siempre debe especificarse antes de $ en la cadena de formato.
Added in version 3.3.
:
La lista de unidades de formato termina aquí; la cadena después de los dos puntos se usa como el nombre de la
función en los mensajes de error (el «valor asociado» de la excepción que PyArg_ParseTuple() lanza).
;
La lista de unidades de formato termina aquí; la cadena después del punto y coma se usa como mensaje de
error en lugar de del mensaje de error predeterminado. : y ; se excluyen mutuamente.
Note that any Python object references which are provided to the caller are borrowed references; do not release them
(i.e. do not decrement their reference count)!
Los argumentos adicionales pasados a estas funciones deben ser direcciones de variables cuyo tipo está determinado
por la cadena de formato; Estos se utilizan para almacenar valores de la tupla de entrada. Hay algunos casos, como
se describe en la lista de unidades de formato anterior, donde estos parámetros se utilizan como valores de entrada;
deben coincidir con lo especificado para la unidad de formato correspondiente en ese caso.
For the conversion to succeed, the arg object must match the format and the format must be exhausted. On success,
the PyArg_Parse* functions return true, otherwise they return false and raise an appropriate exception. When the
PyArg_Parse* functions fail due to conversion failure in one of the format units, the variables at the addresses
corresponding to that and the following format units are left untouched.
Funciones API
80 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
PyObject *result = NULL;
82 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
call producing the argument found an error and set an exception. Therefore, Py_BuildValue() will
return NULL but won’t raise an exception. If no exception has been raised yet, SystemError is set.
S (object) [PyObject *]
Igual que O.
N (object) [PyObject *]
Same as O, except it doesn’t create a new strong reference. Useful when the object is created by a call to
an object constructor in the argument list.
O& (object) [converter, anything]
Convert anything to a Python object through a converter function. The function is called with anything
(which should be compatible with void*) as its argument and should return a «new» Python object, or
NULL if an error occurred.
(items) (tuple) [matching-items]
Convierta una secuencia de valores C en una tupla de Python con el mismo número de elementos.
[items] (list) [matching-items]
Convierte una secuencia de valores C en una lista de Python con el mismo número de elementos.
{items} (dict) [matching-items]
Convierte una secuencia de valores C en un diccionario Python. Cada par de valores C consecutivos
agrega un elemento al diccionario, que sirve como clave y valor, respectivamente.
Si hay un error en la cadena de formato, se establece la excepción SystemError y se retorna NULL.
PyObject *Py_VaBuildValue(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Idéntico a Py_BuildValue(), excepto que acepta una
va_list en lugar de un número variable de argumentos.
Las siguientes funciones proporcionan cadenas de caracteres independientes de la configuración regional para numerar
las conversiones.
unsigned long PyOS_strtoul(const char *str, char **ptr, int base)
Part of the Stable ABI. Convert the initial part of the string in str to an unsigned long value according
to the given base, which must be between 2 and 36 inclusive, or be the special value 0.
Leading white space and case of characters are ignored. If base is zero it looks for a leading 0b, 0o or 0x to
tell which base. If these are absent it defaults to 10. Base must be 0 or between 2 and 36 (inclusive). If ptr is
non-NULL it will contain a pointer to the end of the scan.
If the converted value falls out of range of corresponding return type, range error occurs (errno is set to
ERANGE) and ULONG_MAX is returned. If no conversion can be performed, 0 is returned.
See also the Unix man page strtoul(3).
Added in version 3.2.
long PyOS_strtol(const char *str, char **ptr, int base)
Part of the Stable ABI. Convert the initial part of the string in str to an long value according to the given
base, which must be between 2 and 36 inclusive, or be the special value 0.
Same as PyOS_strtoul(), but return a long value instead and LONG_MAX on overflows.
See also the Unix man page strtol(3).
Added in version 3.2.
double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)
Part of the Stable ABI. Convert a string s to a double, raising a Python exception on failure. The set of
accepted strings corresponds to the set of strings accepted by Python’s float() constructor, except that s
must not have leading or trailing whitespace. The conversion is independent of the current locale.
Si endptr es NULL, convierte toda la cadena de caracteres. Lanza ValueError y retorna -1.0 si la cadena
de caracteres no es una representación válida de un número de punto flotante.
Si endptr no es NULL, convierte la mayor cantidad posible de la cadena de caracteres y configura *endptr
para que apunte al primer carácter no convertido. Si ningún segmento inicial de la cadena de caracteres es la
representación válida de un número de punto flotante, configura *endptr para que apunte al comienzo de la
cadena de caracteres, lanza ValueError y retorna -1.0.
Si s representa un valor que es demasiado grande para almacenar en un flotante (por ejemplo, "1e500"
es una cadena de caracteres de este tipo en muchas plataformas), entonces si overflow_exception es
NULL retorna Py_HUGE_VAL (con un signo apropiado) y no establece ninguna excepción. De lo contrario,
overflow_exception debe apuntar a un objeto excepción de Python; lanza esa excepción y retorna -1.
0. En ambos casos, configura *endptr para que apunte al primer carácter después del valor convertido.
Si se produce algún otro error durante la conversión (por ejemplo, un error de falta de memoria), establece la
excepción Python adecuada y retorna -1.0.
Added in version 3.1.
char *PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)
Part of the Stable ABI. Convert a double val to a string using supplied format_code, precision, and flags.
format_code debe ser uno de 'e', 'E', 'f', 'F', 'g', 'G' or 'r'. Para 'r', la precision suministrada
debe ser 0 y se ignora. El código de formato 'r' especifica el formato estándar repr().
flags puede ser cero o más de los valores Py_DTSF_SIGN, Py_DTSF_ADD_DOT_0, o Py_DTSF_ALT,
unidos por or (or-ed) juntos:
• Py_DTSF_SIGN significa preceder siempre a la cadena de caracteres retornada con un carácter de signo,
incluso si val no es negativo.
• Py_DTSF_ADD_DOT_0 significa asegurarse de que la cadena de caracteres retornada no se verá como
un número entero.
84 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
• Py_DTSF_ALT significa aplicar reglas de formato «alternativas». Consulte la documentación del espe-
cificador PyOS_snprintf() '#' para obtener más detalles.
Si ptype no es NULL, el valor al que apunta se establecerá en uno de Py_DTST_FINITE,
Py_DTST_INFINITE o Py_DTST_NAN, lo que significa que val es un número finito, un número infinito
o no es un número, respectivamente.
El valor de retorno es un puntero a buffer con la cadena de caracteres convertida o NULL si la conversión falla.
La persona que llama es responsable de liberar la cadena de caracteres retornada llamando a PyMem_Free().
Added in version 3.1.
int PyOS_stricmp(const char *s1, const char *s2)
Case insensitive comparison of strings. The function works almost identically to strcmp() except that it
ignores the case.
int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t size)
Case insensitive comparison of strings. The function works almost identically to strncmp() except that it
ignores the case.
6.9 Reflexión
PyObject *PyEval_GetBuiltins(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las construcciones en el
marco de ejecución actual, o el intérprete del estado del hilo si no se está ejecutando ningún marco actualmente.
PyObject *PyEval_GetLocals(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las variables locales en el
marco de ejecución actual, o NULL si actualmente no se está ejecutando ningún marco.
PyObject *PyEval_GetGlobals(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna un diccionario de las variables globales en
el marco de ejecución actual, o NULL si actualmente no se está ejecutando ningún marco.
PyFrameObject *PyEval_GetFrame(void)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el marco del estado del hilo actual, que es
NULL si actualmente no se está ejecutando ningún marco.
Vea también PyThreadState_GetFrame().
const char *PyEval_GetFuncName(PyObject *func)
Part of the Stable ABI. Retorna el nombre de func si es una función, clase u objeto de instancia; de lo contrario,
el nombre del tipo funcs.
const char *PyEval_GetFuncDesc(PyObject *func)
Part of the Stable ABI. Retorna una cadena de caracteres de descripción, según el tipo de func. Los valores
de retorno incluyen «()» para funciones y métodos, «constructor», «instancia» y «objeto». Concatenado con el
resultado de PyEval_GetFuncName(), el resultado será una descripción de func.
86 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
object se pasa a través de la función de decodificador encontrada por el encoding dado usando el método de
manejo de errores definido por errors. errors puede ser NULL para usar el método predeterminado definido
para el códec. Lanza un LookupError si no se puede encontrar el codificador.
En las siguientes funciones, la cadena de caracteres encoding se busca convertida a todos los caracteres en minúscula,
lo que hace que las codificaciones se busquen a través de este mecanismo sin distinción entre mayúsculas y minúsculas.
Si no se encuentra ningún códec, se establece un KeyError y se retorna NULL.
PyObject *PyCodec_Encoder(const char *encoding)
Return value: New reference. Part of the Stable ABI. Obtiene una función de codificador para el encoding dado.
PyObject *PyCodec_Decoder(const char *encoding)
Return value: New reference. Part of the Stable ABI. Obtiene una función de decodificador para el encoding
dado.
PyObject *PyCodec_IncrementalEncoder(const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtiene un objeto IncrementalEncoder para el
encoding dada.
PyObject *PyCodec_IncrementalDecoder(const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtiene un objeto IncrementalDecoder para el
encoding dado.
PyObject *PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtiene una función de fábrica StreamReader para el
encoding dado.
PyObject *PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)
Return value: New reference. Part of the Stable ABI. Obtiene una función de fábrica StreamWriter por el
encoding dado.
On supported platforms (as of this writing, only Linux), the runtime can take advantage of perf map files to make
Python functions visible to an external profiling tool (such as perf). A running process may create a file in the /tmp
directory, which contains entries that can map a section of executable code to a name. This interface is described in
the documentation of the Linux Perf tool.
In Python, these helper APIs can be used by libraries and features that rely on generating machine code on the fly.
Note that holding the Global Interpreter Lock (GIL) is not required for these APIs.
int PyUnstable_PerfMapState_Init(void)
Open the /tmp/perf-$pid.map file, unless it’s already opened, and create a lock to ensure thread-safe
writes to the file (provided the writes are done through PyUnstable_WritePerfMapEntry()). Nor-
mally, there’s no need to call this explicitly; just use PyUnstable_WritePerfMapEntry() and it will
initialize the state on first call.
Returns 0 on success, -1 on failure to create/open the perf map file, or -2 on failure to create a lock. Check
errno for more information about the cause of a failure.
int PyUnstable_WritePerfMapEntry(const void *code_addr, unsigned int code_size, const char
*entry_name)
Write one single entry to the /tmp/perf-$pid.map file. This function is thread safe. Here is what an
example entry looks like:
# address size name
7f3529fcf759 b py::bar:/run/t.py
Will call PyUnstable_PerfMapState_Init() before writing the entry, if the perf map file is not
already opened. Returns 0 on success, or the same error codes as PyUnstable_PerfMapState_Init()
on failure.
88 Capítulo 6. Utilidades
The Python/C API, Versión 3.12.4
void PyUnstable_PerfMapState_Fini(void)
Close the perf map file opened by PyUnstable_PerfMapState_Init(). This is called by the runtime
itself during interpreter shut-down. In general, there shouldn’t be a reason to explicitly call this, except to handle
specific scenarios such as forking.
90 Capítulo 6. Utilidades
CAPÍTULO 7
Las funciones de este capítulo interactúan con los objetos de Python independientemente de su tipo, o con amplias
clases de tipos de objetos (por ejemplo, todos los tipos numéricos o todos los tipos de secuencia). Cuando se usan en
tipos de objetos para los que no se aplican, lanzarán una excepción de Python.
No es posible utilizar estas funciones en objetos que no se inicializan correctamente, como un objeto de lista que ha
sido creado por PyList_New(), pero cuyos elementos no se han establecido en algunos valores no-NULL aún.
PyObject *Py_NotImplemented
El singleton NotImplemented, se usa para indicar que una operación no está implementada para la com-
binación de tipos dada.
Py_RETURN_NOTIMPLEMENTED
Properly handle returning Py_NotImplemented from within a C function (that is, create a new strong
reference to NotImplemented and return it).
Py_PRINT_RAW
Flag to be used with multiple functions that print the object (like PyObject_Print() and
PyFile_WriteObject()). If passed, these function would use the str() of the object instead of the
repr().
int PyObject_Print(PyObject *o, FILE *fp, int flags)
Print an object o, on file fp. Returns -1 on error. The flags argument is used to enable certain printing options.
The only option currently supported is Py_PRINT_RAW; if given, the str() of the object is written instead
of the repr().
int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
Part of the Stable ABI. Retorna 1 si o tiene el atributo attr_name, y 0 en caso contrario. Esto es equivalente a
la expresión de Python hasattr(o, attr_name). Esta función siempre finaliza exitosamente.
Nota: Exceptions that occur when this calls __getattr__() and __getattribute__() methods are
silently ignored. For proper error handling, use PyObject_GetAttr() instead.
91
The Python/C API, Versión 3.12.4
Nota: Exceptions that occur when this calls __getattr__() and __getattribute__() met-
hods or while creating the temporary str object are silently ignored. For proper error handling, use
PyObject_GetAttrString() instead.
Esta función también puede ser llamada para obtener el __dict__ del objeto o. Se pasa context igual a NULL
cuando se lo llama. Dado que esta función puede necesitar asignar memoria para el diccionario, puede ser más
eficiente llamar a PyObject_GetAttr() para acceder a un atributo del objeto.
En caso de fallo, retorna NULL con una excepción establecida.
Added in version 3.3.
int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
Part of the Stable ABI since version 3.7. Una implementación genérica para el creador de un descriptor
__dict__. Esta implementación no permite que se elimine el diccionario.
Added in version 3.3.
PyObject **_PyObject_GetDictPtr(PyObject *obj)
Retorna un puntero al __dict__ del objeto obj. Si no hay __dict__, retorna NULL sin establecer una
excepción.
Esta función puede necesitar asignar memoria para el diccionario, por lo que puede ser más eficiente llamar a
PyObject_GetAttr() para acceder a un atributo del objeto.
PyObject *PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)
Return value: New reference. Part of the Stable ABI. Compare the values of o1 and o2 using the operation
specified by opid, which must be one of Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, or Py_GE, corresponding
to <, <=, ==, !=, >, or >= respectively. This is the equivalent of the Python expression o1 op o2, where
op is the operator corresponding to opid. Returns the value of the comparison on success, or NULL on failure.
int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)
Part of the Stable ABI. Compare the values of o1 and o2 using the operation specified by opid, like
PyObject_RichCompare(), but returns -1 on error, 0 if the result is false, 1 otherwise.
Nota: If o1 and o2 are the same object, PyObject_RichCompareBool() will always return 1 for Py_EQ and
0 for Py_NE.
Las instancias de clases que establecen tp_call son invocables. La firma del slot es:
Se realiza una llamada usando una tupla para los argumentos posicionales y un dict para los argumentos de palabras
clave, de manera similar a callable(*args, **kwargs) en el código Python. args debe ser no NULL (use
una tupla vacía si no hay argumentos) pero kwargs puede ser NULL si no hay argumentos de palabra clave.
Esta convención no solo es utilizada por tp_call: tp_new y tp_init también pasan argumentos de esta manera.
To call an object, use PyObject_Call() or another call API.
Advertencia: Una clase que admita vectorcall debe también implementar tp_call con la misma semántica.
Distinto en la versión 3.12: The Py_TPFLAGS_HAVE_VECTORCALL flag is now removed from a class when the
class’s __call__() method is reassigned. (This internally sets tp_call only, and thus may make it behave
differently than the vectorcall function.) In earlier Python versions, vectorcall should only be used with immutable
or static types.
Una clase no debería implementar vectorcall si eso fuera más lento que tp_call. Por ejemplo, si el destinatario de la
llamada necesita convertir los argumentos a una tupla args y un dict kwargs de todos modos, entonces no tiene sentido
implementar vectorcall.
Classes can implement the vectorcall protocol by enabling the Py_TPFLAGS_HAVE_VECTORCALL flag and setting
tp_vectorcall_offset to the offset inside the object structure where a vectorcallfunc appears. This is a pointer
to a function with the following signature:
typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Part of the Stable ABI since version 3.12.
• callable es el objeto siendo invocado.
• args es un arreglo en C que consta de los argumentos posicionales seguidos por el
valores de los argumentos de la palabra clave. Puede ser NULL si no hay argumentos.
• nargsf es el número de argumentos posicionales más posiblemente el
PY_VECTORCALL_ARGUMENTS_OFFSET flag. To get the actual number of positional arguments
from nargsf, use PyVectorcall_NARGS().
• kwnames es una tupla que contiene los nombres de los argumentos de la palabra clave;
en otras palabras, las claves del diccionario kwargs. Estos nombres deben ser cadenas (instancias de str
o una subclase) y deben ser únicos. Si no hay argumentos de palabras clave, entonces kwnames puede ser
NULL.
PY_VECTORCALL_ARGUMENTS_OFFSET
Part of the Stable ABI since version 3.12. Si este flag se establece en un argumento vectorcall nargsf, el desti-
natario de la llamada puede cambiar temporalmente args[-1]. En otras palabras, args apunta al argumento
1 (no 0) en el vector asignado. El destinatario de la llamada debe restaurar el valor de args[-1] antes de
regresar.
Para PyObject_VectorcallMethod(), este flag significa en cambio que args[0] puede cambiarse.
Whenever they can do so cheaply (without additional allocation), callers are encouraged to use
PY_VECTORCALL_ARGUMENTS_OFFSET. Doing so will allow callables such as bound methods to ma-
ke their onward calls (which include a prepended self argument) very efficiently.
Added in version 3.8.
Para llamar a un objeto que implementa vectorcall, use una función call API como con cualquier otro invocable.
PyObject_Vectorcall() normalmente será más eficiente.
Control de recursión
Cuando se usa tp_call, los destinatarios no necesitan preocuparse por recursividad: CPython usa
Py_EnterRecursiveCall() y Py_LeaveRecursiveCall() para llamadas realizadas usando tp_call.
Por eficiencia, este no es el caso de las llamadas realizadas mediante vectorcall: el destinatario de la llamada debe
utilizar Py_EnterRecursiveCall y Py_LeaveRecursiveCall si es necesario.
Sin embargo, la función PyVectorcall_NARGS debe usarse para permitir futuras extensiones.
Added in version 3.8.
vectorcallfunc PyVectorcall_Function(PyObject *op)
Si op no admite el protocolo vectorcall (ya sea porque el tipo no lo hace o porque la instancia específica no
lo hace), retorna NULL. De lo contrario, retorna el puntero de la función vectorcall almacenado en op. Esta
función nunca lanza una excepción.
Esto es principalmente útil para verificar si op admite vectorcall, lo cual se puede hacer marcando
PyVectorcall_Function(op) != NULL.
Added in version 3.9.
PyObject *PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict)
Part of the Stable ABI since version 3.12. Llama a la vectorcallfunc de callable con argumentos posi-
cionales y de palabras clave dados en una tupla y dict, respectivamente.
This is a specialized function, intended to be put in the tp_call slot or be used in an implementation of
tp_call. It does not check the Py_TPFLAGS_HAVE_VECTORCALL flag and it does not fall back to
tp_call.
Added in version 3.8.
Hay varias funciones disponibles para llamar a un objeto Python. Cada una convierte sus argumentos a una convención
respaldada por el objeto llamado, ya sea tp_call o vectorcall. Para realizar la menor conversión posible, elija la que
mejor se adapte al formato de datos que tiene disponible.
La siguiente tabla resume las funciones disponibles; consulte la documentación individual para obtener más detalles.
base dos. Esta función puede retornar un valor de punto flotante cuando se pasan dos enteros. Es equivalente
a la expresión de Python o1 / o2.
PyObject *PyNumber_Remainder(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resto de la división entera a la baja entre o1 y
o2, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 % o2.
PyObject *PyNumber_Divmod(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Vea la función incorporada divmod(). Retorna NULL
en caso de falla. Este es el equivalente de la expresión de Python divmod (o1, o2).
PyObject *PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3)
Return value: New reference. Part of the Stable ABI. Consulte la función incorporada pow(). Retorna NULL
en caso de falla. Este es el equivalente de la expresión de Python pow(o1, o2, o3), donde o3 es opcional.
Si se ignora o3, pase Py_None en su lugar (pasar NULL por o3 provocaría un acceso ilegal a la memoria).
PyObject *PyNumber_Negative(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna la negación de o en caso de éxito o NULL en caso
de error. Este es el equivalente de la expresión de Python -o.
PyObject *PyNumber_Positive(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna o en caso de éxito o NULL en caso de error. Este
es el equivalente de la expresión de Python +o.
PyObject *PyNumber_Absolute(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna el valor absoluto de o o NULL en caso de error.
Este es el equivalente de la expresión de Python abs(o).
PyObject *PyNumber_Invert(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna la negación bit a bit de o en caso de éxito o NULL
en caso de error. Este es el equivalente de la expresión de Python ~o.
PyObject *PyNumber_Lshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado del desplazamiento a la izquierda o1
por o2 en caso de éxito o NULL en caso de error. Este es el equivalente de la expresión de Python o1 << o2.
PyObject *PyNumber_Rshift(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado del desplazamiento a la derecha o1
por o2 en caso de éxito o NULL en caso de error. Este es el equivalente de la expresión de Python o1 >> o2.
PyObject *PyNumber_And(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit y» (bitwise and) de o1 y o2 en caso
de éxito y NULL en caso de error. Este es el equivalente de la expresión de Python o1 & o2.
PyObject *PyNumber_Xor(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit o exclusivo» (bitwise exclusive or) de
o1 por o2 en caso de éxito, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 ^
o2.
PyObject *PyNumber_Or(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el «bit a bit o» (bitwise or) de o1 y o2 en caso de
éxito, o NULL en caso de error. Este es el equivalente de la expresión de Python o1 | o2.
PyObject *PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de agregar o1 y o2, o NULL en caso de
falla. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es el equivalente de la declaración
de Python o1 += o2.
PyObject *PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Retorna el resultado de restar o2 de o1, o NULL en caso de
falla. La operación se realiza en su lugar (in-place) cuando o1 lo admite. Este es el equivalente de la declaración
de Python o1 -= o2.
Nota: Exceptions which occur when this calls __getitem__() method are silently ignored. For proper
error handling, use PyObject_GetItem() instead.
Nota: Exceptions that occur when this calls __getitem__() method or while creating the temporary str
object are silently ignored. For proper error handling, use PyMapping_GetItemString() instead.
if (iterator == NULL) {
/* propagate error */
}
(continúe en la próxima página)
Py_DECREF(iterator);
if (PyErr_Occurred()) {
/* propagate error */
}
else {
/* continue doing useful work */
}
type PySendResult
El valor de enumeración utilizado para representar diferentes resultados de PyIter_Send().
Added in version 3.10.
PySendResult PyIter_Send(PyObject *iter, PyObject *arg, PyObject **presult)
Part of the Stable ABI since version 3.10. Envía el valor arg al iterador iter. Retorna:
• PYGEN_RETURN si el iterador regresa. El valor de retorno se retorna a través de presult.
• PYGEN_NEXT si el iterador cede. El valor cedido se retorna a través de presult.
• PYGEN_ERROR si el iterador ha lanzado una excepción. presult se establece en NULL.
Added in version 3.10.
Ciertos objetos disponibles en Python ajustan el acceso a un arreglo de memoria subyacente o buffer. Dichos objetos
incluyen el incorporado bytes y bytearray, y algunos tipos de extensión como array.array. Las bibliotecas
de terceros pueden definir sus propios tipos para fines especiales, como el procesamiento de imágenes o el análisis
numérico.
Si bien cada uno de estos tipos tiene su propia semántica, comparten la característica común de estar respaldados por
un búfer de memoria posiblemente grande. Es deseable, en algunas situaciones, acceder a ese búfer directamente y
sin copia intermedia.
Python proporciona una instalación de este tipo en el nivel C en la forma de protocolo búfer. Este protocolo tiene dos
lados:
• en el lado del productor, un tipo puede exportar una «interfaz de búfer» que permite a los objetos de ese tipo
exponer información sobre su búfer subyacente. Esta interfaz se describe en la sección Estructuras de objetos
búfer;
• en el lado del consumidor, hay varios medios disponibles para obtener un puntero a los datos subyacentes sin
procesar de un objeto (por ejemplo, un parámetro de método).
Los objetos simples como bytes y bytearray exponen su búfer subyacente en forma orientada a bytes. Otras
formas son posibles; por ejemplo, los elementos expuestos por un array.array pueden ser valores de varios bytes.
An example consumer of the buffer interface is the write() method of file objects: any object that can export a
series of bytes through the buffer interface can be written to a file. While write() only needs read-only access
to the internal contents of the object passed to it, other methods such as readinto() need write access to the
contents of their argument. The buffer interface allows objects to selectively allow or reject exporting of read-write
and read-only buffers.
Hay dos formas para que un consumidor de la interfaz del búfer adquiera un búfer sobre un objeto de destino:
• llamar PyObject_GetBuffer() con los parámetros correctos;
• llamar PyArg_ParseTuple() (o uno de sus hermanos) con uno de los y*, w* o s* códigos de formato.
En ambos casos, se debe llamar a PyBuffer_Release() cuando ya no se necesita el búfer. De lo contrario,
podrían surgir varios problemas, como pérdidas de recursos.
Las estructuras de búfer (o simplemente «búferes») son útiles como una forma de exponer los datos binarios de otro
objeto al programador de Python. También se pueden usar como un mecanismo de corte de copia cero. Usando su
capacidad para hacer referencia a un bloque de memoria, es posible exponer cualquier información al programador
Python con bastante facilidad. La memoria podría ser una matriz grande y constante en una extensión C, podría ser
un bloque de memoria sin procesar para su manipulación antes de pasar a una biblioteca del sistema operativo, o
podría usarse para pasar datos estructurados en su formato nativo en memoria .
Contrariamente a la mayoría de los tipos de datos expuestos por el intérprete de Python, los búferes no son punteros
PyObject sino estructuras C simples. Esto les permite ser creados y copiados de manera muy simple. Cuando se
necesita un contenedor genérico alrededor de un búfer, un objeto memoryview puede ser creado.
Para obtener instrucciones breves sobre cómo escribir un objeto de exportación, consulte Estructuras de objetos búfer.
Para obtener un búfer, consulte PyObject_GetBuffer().
type Py_buffer
Part of the Stable ABI (including all members) since version 3.11.
void *buf
Un puntero al inicio de la estructura lógica descrita por los campos del búfer. Puede ser cualquier ubica-
ción dentro del bloque de memoria física subyacente del exportador. Por ejemplo, con negativo strides
el valor puede apuntar al final del bloque de memoria.
Para arreglos contiguous, el valor apunta al comienzo del bloque de memoria.
PyObject *obj
A new reference to the exporting object. The reference is owned by the consumer and automatically
released (i.e. reference count decremented) and set to NULL by PyBuffer_Release(). The field is
the equivalent of the return value of any standard C-API function.
Como un caso especial, para los búferes temporary que están envueltos por
PyMemoryView_FromBuffer() o PyBuffer_FillInfo() este campo es NULL. En
general, los objetos de exportación NO DEBEN usar este esquema.
Py_ssize_t len
product(shape) * itemize. Para arreglos contiguos, esta es la longitud del bloque de memoria
subyacente. Para arreglos no contiguos, es la longitud que tendría la estructura lógica si se copiara en una
representación contigua.
Accede a ((char *)buf)[0] hasta ((char *)buf)[len-1] solo es válido si el búfer se
ha obtenido mediante una solicitud que garantiza la contigüidad. En la mayoría de los casos, dicha soli-
citud será PyBUF_SIMPLE o PyBUF_WRITABLE.
int readonly
Un indicador de si el búfer es de solo lectura. Este campo está controlado por el indicador
PyBUF_WRITABLE.
Py_ssize_t itemsize
Tamaño del elemento en bytes de un solo elemento. Igual que el valor de struct.calcsize()
invocado en valores no NULL format.
Excepción importante: si un consumidor solicita un búfer sin el indicador PyBUF_FORMAT, format
se establecerá en NULL, pero itemsize todavía tiene el valor para el formato original.
Los búferes obtienen generalmente enviando una solicitud de búfer a un objeto de exportación a través de
PyObject_GetBuffer(). Dado que la complejidad de la estructura lógica de la memoria puede variar drásti-
camente, el consumidor usa el argumento flags para especificar el tipo de búfer exacto que puede manejar.
All Py_buffer fields are unambiguously defined by the request type.
Los siguientes campos no están influenciados por flags y siempre deben completarse con los valores correctos: obj,
buf, len, itemsize, ndim.
PyBUF_WRITABLE
Controla el campo readonly. Si se establece, el exportador DEBE proporcionar un búfer de
escritura o, de lo contrario, informar de un error. De lo contrario, el exportador PUEDE propor-
cionar un búfer de solo lectura o de escritura, pero la elección DEBE ser coherente para todos los
consumidores.
PyBUF_FORMAT
Controla el campo format. Si se establece, este campo DEBE completarse correctamente. De lo
contrario, este campo DEBE ser NULL.
PyBUF_WRITABLE puede ser |”d a cualquiera de las banderas en la siguiente sección. Dado que PyBUF_SIMPLE
se define como 0, PyBUF_WRITABLE puede usarse como un indicador independiente para solicitar un búfer de
escritura simple.
PyBUF_FORMAT puede ser |”d para cualquiera de las banderas excepto PyBUF_SIMPLE. Este último ya implica
el formato B (bytes sin signo).
Las banderas que controlan la estructura lógica de la memoria se enumeran en orden decreciente de complejidad.
Tenga en cuenta que cada bandera contiene todos los bits de las banderas debajo de ella.
sí sí NULL
PyBUF_STRIDES
sí NULL NULL
PyBUF_ND
solicitudes de contigüidad
La contigüidad C o Fortran se puede solicitar explícitamente, con y sin información de paso. Sin información de paso,
el búfer debe ser C-contiguo.
sí sí NULL F
PyBUF_F_CONTIGUOUS
sí sí NULL CoF
PyBUF_ANY_CONTIGUOUS
solicitudes compuestas
Todas las solicitudes posibles están completamente definidas por alguna combinación de las banderas en la sección
anterior. Por conveniencia, el protocolo de memoria intermedia proporciona combinaciones de uso frecuente como
indicadores únicos.
En la siguiente tabla U significa contigüidad indefinida. El consumidor tendría que llamar a
PyBuffer_IsContiguous() para determinar la contigüidad.
sí sí si es necesario U 1o0 sí
PyBUF_FULL_RO
sí sí NULL U 0 sí
PyBUF_RECORDS
sí sí NULL U 1o0 sí
PyBUF_RECORDS_RO
sí sí NULL U 0 NULL
PyBUF_STRIDED
La estructura lógica de las matrices de estilo NumPy está definida por itemsize, ndim, shape y strides.
Si ndim == 0, la ubicación de memoria señalada por buf se interpreta como un escalar de tamaño itemsize.
En ese caso, tanto shape como strides son NULL.
Si strides es NULL, el arreglo se interpreta como un arreglo C n-dimensional estándar. De lo contrario, el consu-
midor debe acceder a un arreglo n-dimensional de la siguiente manera:
ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];
item = *((typeof(item) *)ptr);
Como se señaló anteriormente, buf puede apuntar a cualquier ubicación dentro del bloque de memoria real. Un
exportador puede verificar la validez de un búfer con esta función:
def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
"""Verify that the parameters represent a valid array within
the bounds of the allocated memory:
char *mem: start of the physical memory block
memlen: length of the physical memory block
offset: (char *)buf - mem
"""
if offset % itemsize:
return False
if offset < 0 or offset+itemsize > memlen:
return False
if any(v % itemsize for v in strides):
return False
if ndim <= 0:
return ndim == 0 and not shape and not strides
if 0 in shape:
return True
Además de los elementos normales, los arreglos de estilo PIL pueden contener punteros que deben seguirse para
llegar al siguiente elemento en una dimensión. Por ejemplo, el arreglo C tridimensional regular char v[2][2][3]
también se puede ver como un arreglo de 2 punteros a 2 arreglos bidimensionales: char (*v[2])[2][3]. En
la representación de suboffsets, esos dos punteros pueden incrustarse al comienzo de buf, apuntando a dos matrices
char x[2][3] que pueden ubicarse en cualquier lugar de la memoria.
Aquí hay una función que retorna un puntero al elemento en un arreglo N-D a la que apunta un índice N-dimensional
cuando hay strides y suboffsets no NULL:
void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
Py_ssize_t *suboffsets, Py_ssize_t *indices) {
char *pointer = (char*)buf;
int i;
for (i = 0; i < ndim; i++) {
pointer += strides[i] * indices[i];
(continúe en la próxima página)
Las funciones de este capítulo son específicas de ciertos tipos de objetos de Python. Pasarles un objeto del tipo
incorrecto no es una buena idea; si recibe un objeto de un programa Python y no está seguro de que tenga el tipo
correcto, primero debe realizar una verificación de tipo; por ejemplo, para verificar que un objeto es un diccionario,
utilice PyDict_Check(). El capítulo está estructurado como el «árbol genealógico» de los tipos de objetos Python.
Advertencia: Si bien las funciones descritas en este capítulo verifican cuidadosamente el tipo de objetos que se
pasan, muchos de ellos no verifican si se pasa NULL en lugar de un objeto válido. Permitir que se pase NULL
puede causar violaciones de acceso a la memoria y la terminación inmediata del intérprete.
Esta sección describe los objetos de tipo Python y el objeto singleton None.
type PyTypeObject
Part of the Limited API (as an opaque struct). La estructura C de los objetos utilizados para describir los tipos
incorporados.
PyTypeObject PyType_Type
Part of the Stable ABI. Este es el objeto tipo para objetos tipo; es el mismo objeto que type en la capa Python.
int PyType_Check(PyObject *o)
Retorna un valor distinto de cero si el objeto o es un objeto tipo, incluidas las instancias de tipos derivados del
objeto de tipo estándar. Retorna 0 en todos los demás casos. Esta función siempre finaliza con éxito.
int PyType_CheckExact(PyObject *o)
Retorna un valor distinto de cero si el objeto o es un objeto tipo, pero no un subtipo del objeto tipo estándar.
Retorna 0 en todos los demás casos. Esta función siempre finaliza con éxito.
unsigned int PyType_ClearCache()
Part of the Stable ABI. Borra la caché de búsqueda interna. Retorna la etiqueta (tag) de la versión actual.
117
The Python/C API, Versión 3.12.4
Nota: If some of the base classes implements the GC protocol and the provided type does not include the
Py_TPFLAGS_HAVE_GC in its flags, then the GC protocol will be automatically implemented from its pa-
rents. On the contrary, if the type being created does include Py_TPFLAGS_HAVE_GC in its flags then it
must implement the GC protocol itself by at least implementing the tp_traverse handle.
• __new__() is not called on the new class (and it must be set to type.__new__).
• __init__() is not called on the new class.
• __init_subclass__() is not called on any bases.
• __set_name__() is not called on new descriptors.
Added in version 3.12.
PyObject *PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)
Return value: New reference. Part of the Stable ABI since version 3.10. Equivalent to
PyType_FromMetaclass(NULL, module, spec, bases).
Added in version 3.9.
Distinto en la versión 3.10: La función ahora acepta una sola clase como argumento bases y NULL como ranura
tp_doc.
Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the provided base
classes. Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
PyObject *PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
Return value: New reference. Part of the Stable ABI since version 3.3. Equivalent to
PyType_FromMetaclass(NULL, NULL, spec, bases).
Added in version 3.3.
Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the provided base
classes. Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
PyObject *PyType_FromSpec(PyType_Spec *spec)
Return value: New reference. Part of the Stable ABI. Equivalent to PyType_FromMetaclass(NULL,
NULL, spec, NULL).
Distinto en la versión 3.12: The function now finds and uses a metaclass corresponding to the base classes
provided in Py_tp_base[s] slots. Previously, only type instances were returned.
The tp_new of the metaclass is ignored. which may result in incomplete initialization. Creating classes whose
metaclass overrides tp_new is deprecated and in Python 3.14+ it will be no longer allowed.
type PyType_Spec
Part of the Stable ABI (including all members). Estructura que define el comportamiento de un tipo.
const char *name
Nombre del tipo, utilizado para establecer PyTypeObject.tp_name.
int basicsize
If positive, specifies the size of the instance in bytes. It is used to set PyTypeObject.
tp_basicsize.
If zero, specifies that tp_basicsize should be inherited.
If negative, the absolute value specifies how much space instances of the class need in addition to the
superclass. Use PyObject_GetTypeData() to get a pointer to subclass-specific memory reserved
this way.
Distinto en la versión 3.12: Previously, this field could not be negative.
int itemsize
Size of one element of a variable-size type, in bytes. Used to set PyTypeObject.tp_itemsize.
See tp_itemsize documentation for caveats.
If zero, tp_itemsize is inherited. Extending arbitrary variable-sized classes is dangerous, since some
types use a fixed offset for variable-sized memory, which can then overlap fixed-sized memory used by a
subclass. To help prevent mistakes, inheriting itemsize is only possible in the following situations:
• The base is not variable-sized (its tp_itemsize).
• The requested PyType_Spec.basicsize is positive, suggesting that the memory layout of the
base class is known.
• The requested PyType_Spec.basicsize is zero, suggesting that the subclass does not access
the instance’s memory directly.
• With the Py_TPFLAGS_ITEMS_AT_END flag.
unsigned int flags
Banderas (flags) del tipo, que se usan para establecer PyTypeObject.tp_flags.
Si el indicador Py_TPFLAGS_HEAPTYPE no está establecido, PyType_FromSpecWithBases()
lo establece automáticamente.
PyType_Slot *slots
Arreglo de estructuras PyType_Slot. Terminado por el valor de ranura especial {0, NULL}.
Each slot ID should be specified at most once.
type PyType_Slot
Part of the Stable ABI (including all members). Estructura que define la funcionalidad opcional de un tipo, que
contiene una ranura ID y un puntero de valor.
int slot
Distinto en la versión 3.9: Las ranuras en PyBufferProcs se pueden configurar en la API ilimitada.
Distinto en la versión 3.11: bf_getbuffer and bf_releasebuffer are now available under the
limited API.
void *pfunc
El valor deseado de la ranura. En la mayoría de los casos, este es un puntero a una función.
Las ranuras que no sean Py_tp_doc pueden no ser NULL.
Note that the PyTypeObject for None is not directly exposed in the Python/C API. Since None is a singleton,
testing for object identity (using == in C) is sufficient. There is no PyNone_Check() function for the same reason.
PyObject *Py_None
The Python None object, denoting lack of value. This object has no methods and is immortal.
Distinto en la versión 3.12: Py_None is immortal.
Py_RETURN_NONE
Return Py_None from a function.
Todos los enteros se implementan como objetos enteros «largos» (long) de tamaño arbitrario.
En caso de error, la mayoría de las API PyLong_As* retornan (tipo de retorno) -1 que no se puede
distinguir de un número. Use PyErr_Occurred() para desambiguar.
type PyLongObject
Part of the Limited API (as an opaque struct). Este subtipo de PyObject representa un objeto entero de
Python.
PyTypeObject PyLong_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo entero de Python. Este es el
mismo objeto que int en la capa de Python.
int PyLong_Check(PyObject *p)
Retorna verdadero si su argumento es un PyLongObject o un subtipo de PyLongObject. Esta función
siempre finaliza con éxito.
int PyLong_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyLongObject, pero no un subtipo de PyLongObject. Esta
función siempre finaliza con éxito.
PyObject *PyLong_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde v, o
NULL en caso de error.
The current implementation keeps an array of integer objects for all integers between -5 and 256. When you
create an int in that range you actually just get back a reference to the existing object.
PyObject *PyLong_FromUnsignedLong(unsigned long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C
unsigned long, or NULL on failure.
PyObject *PyLong_FromSsize_t(Py_ssize_t v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde un C
Py_ssize_t, o NULL en caso de error.
PyObject *PyLong_FromSize_t(size_t v)
Return value: New reference. Part of the Stable ABI. Retorna un objeto PyLongObject nuevo desde un C
size_t, o NULL en caso de error.
PyObject *PyLong_FromLongLong(long long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C long
long, or NULL on failure.
PyObject *PyLong_FromUnsignedLongLong(unsigned long long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C
unsigned long long, or NULL on failure.
PyObject *PyLong_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto PyLongObject de la parte
entera de v, o NULL en caso de error.
PyObject *PyLong_FromString(const char *str, char **pend, int base)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject based on the string value
in str, which is interpreted according to the radix in base, or NULL on failure. If pend is non-NULL, *pend will
point to the end of str on success or to the first character that could not be processed on error. If base is 0,
str is interpreted using the integers definition; in this case, leading zeros in a non-zero decimal number raises
a ValueError. If base is not 0, it must be between 2 and 36, inclusive. Leading and trailing whitespace
and single underscores after a base specifier and between digits are ignored. If there are no digits or str is not
NULL-terminated following the digits and trailing whitespace, ValueError will be raised.
Ver también:
Python methods int.to_bytes() and int.from_bytes() to convert a PyLongObject to/from an
array of bytes in base 256. You can call those from C using PyObject_CallMethod().
PyObject *PyLong_FromUnicodeObject(PyObject *u, int base)
Return value: New reference. Convierte una secuencia de dígitos Unicode en la cadena de caracteres u en un
valor entero de Python.
Added in version 3.3.
PyObject *PyLong_FromVoidPtr(void *p)
Return value: New reference. Part of the Stable ABI. Crea un entero de Python desde el puntero p. El valor del
puntero se puede recuperar del valor resultante usando PyLong_AsVoidPtr().
long PyLong_AsLong(PyObject *obj)
Part of the Stable ABI. Return a C long representation of obj. If obj is not an instance of PyLongObject,
first call its __index__() method (if present) to convert it to a PyLongObject.
Raise OverflowError if the value of obj is out of range for a long.
Retorna -1 en caso de error. Use PyErr_Occurred() para desambiguar.
Distinto en la versión 3.8: Use __index__() if available.
Distinto en la versión 3.10: This function will no longer use __int__().
long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow)
Part of the Stable ABI. Return a C long representation of obj. If obj is not an instance of PyLongObject,
first call its __index__() method (if present) to convert it to a PyLongObject.
If the value of obj is greater than LONG_MAX or less than LONG_MIN, set *overflow to 1 or -1, respectively,
and return -1; otherwise, set *overflow to 0. If any other exception occurs set *overflow to 0 and return -1
as usual.
Retorna -1 en caso de error. Use PyErr_Occurred() para desambiguar.
Booleans in Python are implemented as a subclass of integers. There are only two booleans, Py_False and
Py_True. As such, the normal creation and deletion functions don’t apply to booleans. The following macros are
available, however.
PyTypeObject PyBool_Type
Part of the Stable ABI. This instance of PyTypeObject represents the Python boolean type; it is the same
object as bool in the Python layer.
int PyBool_Check(PyObject *o)
Retorna verdadero si o es de tipo PyBool_Type. Esta función siempre finaliza con éxito.
PyObject *Py_False
The Python False object. This object has no methods and is immortal.
Distinto en la versión 3.12: Py_False is immortal.
PyObject *Py_True
The Python True object. This object has no methods and is immortal.
Distinto en la versión 3.12: Py_True is immortal.
Py_RETURN_FALSE
Return Py_False from a function.
Py_RETURN_TRUE
Return Py_True from a function.
PyObject *PyBool_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Return Py_True or Py_False, depending on the truth
value of v.
type PyFloatObject
Este subtipo de PyObject representa un objeto de punto flotante de Python.
PyTypeObject PyFloat_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de punto flotante de Python. Este
es el mismo objeto que float en la capa de Python.
int PyFloat_Check(PyObject *p)
Retorna verdadero si su argumento es un PyFloatObject o un subtipo de PyFloatObject. Esta función
siempre finaliza con éxito.
int PyFloat_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyFloatObject, pero no un subtipo de PyFloatObject. Esta
función siempre finaliza con éxito.
PyObject *PyFloat_FromString(PyObject *str)
Return value: New reference. Part of the Stable ABI. Crea un objeto PyFloatObject basado en la cadena
de caracteres en str, o NULL en caso de error.
PyObject *PyFloat_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. Crea un objeto PyFloatObject a partir de v, o NULL
en caso de error.
Las funciones de empaquetar y desempaquetar proporcionan una manera eficiente e independiente de la plataforma
para almacenar valores de coma flotante como cadenas de bytes. Las rutinas Pack producen una cadena de bytes a
partir de un C double, y las rutinas Desempaquetar producen un C double a partir de dicha cadena de bytes. El
sufijo (2, 4 u 8) especifica el número de bytes en la cadena de bytes.
En plataformas que parecen usar formatos IEEE 754, estas funciones actúan copiando los bits. En otras plataformas,
el formato 2-byte es idéntico al formato de media precision IEEE 754 binary16, el formato de 4-byte (32 bits) es
idéntico al formato de precisión simple binario IEEE 754 binary32, y el formato de 8-byte al formato de doble
precisión binario IEEE 754 binary64, aunque el empaquetado de INFs y NaNs (si existen en la plataforma) no se
maneja correctamente, mientras que intentar desempaquetar una cadena de bytes que contenga un IEEE INF o NaN
generará una excepción.
En plataformas que no son IEEE con más precisión, o mayor rango dinámico, que el IEEE 754 admite, no se pue-
den empaquetar todos los valores; en plataformas que no son IEEE con menos precisión o con un rango dinámico
más pequeño, no se pueden desempaquetar todos los valores. Lo que sucede en tales casos es en parte accidental
(desafortunadamente).
Added in version 3.11.
Funciones de Empaquetado
The pack routines write 2, 4 or 8 bytes, starting at p. le is an int argument, non-zero if you want the bytes string in
little-endian format (exponent last, at p+1, p+3, or p+6 p+7), zero if you want big-endian format (exponent first,
at p). The PY_BIG_ENDIAN constant can be used to use the native endian: it is equal to 1 on big endian processor,
or 0 on little endian processor.
Valor retornado: 0 si todo está bien, -1 si hay error (y se establece una excepción, probablemente
OverflowError).
Hay dos problemas en plataformas que no son IEEE:
• Lo que esto hace es indefinido si x es un NaN o infinito.
• -0.0 and +0.0 produce la misma cadena de bytes.
int PyFloat_Pack2(double x, unsigned char *p, int le)
Empaquete un C doble como el formato de media precisión IEEE 754 binary16.
Funciones de Desempaquetado
The unpack routines read 2, 4 or 8 bytes, starting at p. le is an int argument, non-zero if the bytes string is in
little-endian format (exponent last, at p+1, p+3 or p+6 and p+7), zero if big-endian (exponent first, at p). The
PY_BIG_ENDIAN constant can be used to use the native endian: it is equal to 1 on big endian processor, or 0 on
little endian processor.
Valor retornado: Doble desempaquetado. Si hay error, -1.0 y PyErr_Occurred() es verdadero (y se establece
una excepción, probablemente OverflowError).
Hay que tener en cuenta que en una plataforma que no sea IEEE, esto se negará a desempaquetar una cadena de bytes
que representa un NaN o infinito.
double PyFloat_Unpack2(const unsigned char *p, int le)
Descomprima el formato de media precisión IEEE 754 binary16 como un doble C.
double PyFloat_Unpack4(const unsigned char *p, int le)
Descomprima el formato de precisión simple IEEE 754 binary32 como un doble C.
double PyFloat_Unpack8(const unsigned char *p, int le)
Descomprima el formato de doble precisión IEEE 754 binary64 como un doble C.
Los objetos de números complejos de Python se implementan como dos tipos distintos cuando se ven desde la API
de C: uno es el objeto de Python expuesto a los programas de Python, y el otro es una estructura en C que representa
el valor de número complejo real. La API proporciona funciones para trabajar con ambos.
Tenga en cuenta que las funciones que aceptan estas estructuras como parámetros y las retornan como resultados lo
hacen por valor en lugar de desreferenciarlas a través de punteros. Esto es consistente en toda la API.
type Py_complex
La estructura C que corresponde a la porción de valor de un objeto de número complejo de Python. La mayoría
de las funciones para tratar con objetos de números complejos utilizan estructuras de este tipo como valores
de entrada o salida, según corresponda. Se define como:
typedef struct {
double real;
double imag;
} Py_complex;
type PyComplexObject
Este subtipo de PyObject representa un objeto de número complejo de Python.
PyTypeObject PyComplex_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de número complejo de Python.
Es el mismo objeto que complex en la capa de Python.
int PyComplex_Check(PyObject *p)
Retorna verdadero si su argumento es un PyComplexObject o un subtipo de PyComplexObject. Esta
función siempre finaliza con éxito.
int PyComplex_CheckExact(PyObject *p)
Retorna verdadero si su argumento es un PyComplexObject, pero no un subtipo de PyComplexObject.
Esta función siempre finaliza con éxito.
PyObject *PyComplex_FromCComplex(Py_complex v)
Return value: New reference. Crea un nuevo objeto de número complejo de Python a partir de un valor C
Py_complex.
PyObject *PyComplex_FromDoubles(double real, double imag)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto PyComplexObject de real e
imag.
double PyComplex_RealAsDouble(PyObject *op)
Part of the Stable ABI. Return the real part of op as a C double.
double PyComplex_ImagAsDouble(PyObject *op)
Part of the Stable ABI. Return the imaginary part of op as a C double.
Py_complex PyComplex_AsCComplex(PyObject *op)
Retorna el valor Py_complex del número complejo op.
If op is not a Python complex number object but has a __complex__() method, this method will first be
called to convert op to a Python complex number object. If __complex__() is not defined then it falls back
to __float__(). If __float__() is not defined then it falls back to __index__(). Upon failure, this
method returns -1.0 as a real value.
Distinto en la versión 3.8: Use __index__() if available.
Las operaciones genéricas en los objetos de secuencia se discutieron en el capítulo anterior; Esta sección trata sobre
los tipos específicos de objetos de secuencia que son intrínsecos al lenguaje Python.
Estas funciones lanzan TypeError cuando se espera un parámetro de bytes y se llama con un parámetro que no es
bytes.
type PyBytesObject
Este subtipo de PyObject representa un objeto bytes de Python.
PyTypeObject PyBytes_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo bytes de Python; es el mismo
objeto que bytes en la capa de Python.
int PyBytes_Check(PyObject *o)
Retorna verdadero si el objeto o es un objeto bytes o una instancia de un subtipo del tipo bytes. Esta función
siempre finaliza con éxito.
int PyBytes_CheckExact(PyObject *o)
Retorna verdadero si el objeto o es un objeto bytes, pero no una instancia de un subtipo del tipo bytes. Esta
función siempre finaliza con éxito.
PyObject *PyBytes_FromString(const char *v)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto bytes con una copia de la cadena
de caracteres v como valor en caso de éxito y NULL en caso de error. El parámetro v no debe ser NULL; no se
comprobará.
PyObject *PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto bytes con una copia de la cadena
de caracteres v como valor y longitud len en caso de éxito y NULL en caso de error. Si v es NULL, el contenido
del objeto bytes no se inicializa.
PyObject *PyBytes_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI. Toma una cadena de caracteres format del estilo C
printf() y un número variable de argumentos, calcula el tamaño del objeto bytes Python resultante y
retorna un objeto bytes con los valores formateados. Los argumentos variables deben ser tipos C y deben
corresponder exactamente a los caracteres de formato en la cadena de caracteres format. Se permiten los
siguientes caracteres de formato:
Un carácter de formato no reconocido hace que todo el resto de la cadena de caracteres de formato se copie
como está en el objeto de resultado y se descartan los argumentos adicionales.
PyObject *PyBytes_FromFormatV(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Idéntica a PyBytes_FromFormat() excepto que
toma exactamente dos argumentos.
PyObject *PyBytes_FromObject(PyObject *o)
Return value: New reference. Part of the Stable ABI. Retorna la representación en bytes del objeto o que im-
plementa el protocolo de búfer.
Py_ssize_t PyBytes_Size(PyObject *o)
Part of the Stable ABI. Retorna la longitud de los bytes en el objeto bytes o.
Py_ssize_t PyBytes_GET_SIZE(PyObject *o)
Forma macro de PyBytes_Size() pero sin verificación de errores.
char *PyBytes_AsString(PyObject *o)
Part of the Stable ABI. Retorna un puntero al contenido de o. El puntero se refiere al búfer interno de o, que
consiste en len(o) + 1 bytes. El último byte en el búfer siempre es nulo, independientemente de si hay
otros bytes nulos. Los datos no deben modificarse de ninguna manera, a menos que el objeto se haya creado
usando PyBytes_FromStringAndSize(NULL, size). No debe ser desasignado. Si o no es un objeto
de bytes en absoluto, PyBytes_AsString() retorna NULL y lanza un TypeError.
char *PyBytes_AS_STRING(PyObject *string)
Forma macro de PyBytes_AsString() pero sin verificación de errores.
int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)
Part of the Stable ABI. Return the null-terminated contents of the object obj through the output variables buffer
and length. Returns 0 on success.
Si length es NULL, el objeto bytes no puede contener bytes nulos incrustados; en caso contrario, la función
retorna -1 y se lanza un ValueError.
El búfer se refiere a un búfer interno de obj, que incluye un byte nulo adicional al final (no está considerado
en length). Los datos no deben modificarse de ninguna manera, a menos que el objeto se haya creado usando
PyBytes_FromStringAndSize(NULL, size). No debe ser desasignado. Si obj no es un objeto bytes
en absoluto, PyBytes_AsStringAndSize() retorna -1 y lanza TypeError.
Distinto en la versión 3.5: Anteriormente, TypeError se lanzaba cuando se encontraban bytes nulos incrus-
tados en el objeto bytes.
1 Para especificadores de enteros (d, u, ld, lu, zd, zu, i, x): el indicador de conversión 0 tiene efecto incluso cuando se proporciona una precisión.
type PyByteArrayObject
Este subtipo de PyObject representa un objeto arreglo de bytes de Python.
PyTypeObject PyByteArray_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo arreglo de bytes de Python; es el
mismo objeto que bytearray en la capa de Python.
Macros
Objetos unicode
Desde la implementación del PEP 393 en Python 3.3, los objetos Unicode utilizan internamente una variedad de
representaciones, para permitir el manejo del rango completo de caracteres Unicode mientras se mantiene la eficiencia
de memoria. Hay casos especiales para cadenas de caracteres donde todos los puntos de código están por debajo de
128, 256 o 65536; de lo contrario, los puntos de código deben estar por debajo de 1114112 (que es el rango completo
de Unicode).
UTF-8 representation is created on demand and cached in the Unicode object.
Nota: The Py_UNICODE representation has been removed since Python 3.12 with deprecated APIs. See PEP 623
for more information.
Tipo unicode
Estos son los tipos básicos de objetos Unicode utilizados para la implementación de Unicode en Python:
type Py_UCS4
type Py_UCS2
type Py_UCS1
Part of the Stable ABI. Estos tipos son definiciones de tipo (typedefs) para los tipos “enteros sin signo” (unsigned
int) lo suficientemente anchos como para contener caracteres de 32 bits, 16 bits y 8 bits, respectivamente.
Cuando se trate con caracteres Unicode individuales, use Py_UCS4.
Added in version 3.3.
type Py_UNICODE
This is a typedef of wchar_t, which is a 16-bit type or 32-bit type depending on the platform.
Distinto en la versión 3.3: En versiones anteriores, este era un tipo de 16 bits o de 32 bits, dependiendo de si
seleccionó una versión Unicode «estrecha» o «amplia» de Python en el momento de la compilación.
type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject
Estos subtipos de PyObject representan un objeto Python Unicode. En casi todos los casos, no deben usarse
directamente, ya que todas las funciones API que se ocupan de objetos Unicode toman y retornan punteros
PyObject.
Added in version 3.3.
PyTypeObject PyUnicode_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo Python Unicode. Está expuesto
al código de Python como str.
The following APIs are C macros and static inlined functions for fast checks and access to internal read-only data of
Unicode objects:
int PyUnicode_Check(PyObject *obj)
Return true if the object obj is a Unicode object or an instance of a Unicode subtype. This function always
succeeds.
int PyUnicode_CheckExact(PyObject *obj)
Return true if the object obj is a Unicode object, but not an instance of a subtype. This function always succeeds.
int PyUnicode_READY(PyObject *unicode)
Returns 0. This API is kept only for backward compatibility.
Added in version 3.3.
Obsoleto desde la versión 3.10: This API does nothing since Python 3.12.
Py_ssize_t PyUnicode_GET_LENGTH(PyObject *unicode)
Return the length of the Unicode string, in code points. unicode has to be a Unicode object in the «canonical»
representation (not checked).
Added in version 3.3.
Py_UCS1 *PyUnicode_1BYTE_DATA(PyObject *unicode)
Py_UCS2 *PyUnicode_2BYTE_DATA(PyObject *unicode)
Py_UCS4 *PyUnicode_4BYTE_DATA(PyObject *unicode)
Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 integer types for direct cha-
racter access. No checks are performed if the canonical representation has the correct character size; use
PyUnicode_KIND() to select the right function.
Added in version 3.3.
PyUnicode_1BYTE_KIND
PyUnicode_2BYTE_KIND
PyUnicode_4BYTE_KIND
Retorna los valores de la macro PyUnicode_KIND().
Added in version 3.3.
Distinto en la versión 3.12: PyUnicode_WCHAR_KIND has been removed.
int PyUnicode_KIND(PyObject *unicode)
Return one of the PyUnicode kind constants (see above) that indicate how many bytes per character this Uni-
code object uses to store its data. unicode has to be a Unicode object in the «canonical» representation (not
checked).
Added in version 3.3.
void *PyUnicode_DATA(PyObject *unicode)
Return a void pointer to the raw Unicode buffer. unicode has to be a Unicode object in the «canonical» repre-
sentation (not checked).
Added in version 3.3.
Unicode proporciona muchas propiedades de caracteres diferentes. Los que se necesitan con mayor frecuencia están
disponibles a través de estas macros que se asignan a las funciones de C según la configuración de Python.
int Py_UNICODE_ISSPACE(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter de espacio en blanco.
int Py_UNICODE_ISLOWER(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter en minúscula.
int Py_UNICODE_ISUPPER(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter en mayúscula.
int Py_UNICODE_ISTITLE(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter en caso de título (titlecase).
int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter de salto de línea.
int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter decimal o no.
int Py_UNICODE_ISDIGIT(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter de dígitos.
int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)
Retorna 1 o 0 dependiendo de si ch es un carácter numérico.
Para crear objetos Unicode y acceder a sus propiedades de secuencia básicas, use estas API:
PyObject *PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
Return value: New reference. Crea un nuevo objeto Unicode. maxchar debe ser el punto de código máximo que
se colocará en la cadena de caracteres. Como una aproximación, se puede redondear al valor más cercano en
la secuencia 127, 255, 65535, 1114111.
Esta es la forma recomendada de asignar un nuevo objeto Unicode. Los objetos creados con esta función no se
pueden redimensionar.
Added in version 3.3.
PyObject *PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
Return value: New reference. Crea un nuevo objeto Unicode con el tipo kind dado (los valores posibles son
PyUnicode_1BYTE_KIND etc., según lo retornado por PyUnicode_KIND()). El búfer debe apuntar a
un vector (array) de tamaño unidades de 1, 2 o 4 bytes por carácter, según el tipo.
Si es necesario, la entrada buffer se copia y se transforma en la representación canónica. Por ejemplo, si el
buffer es una cadena de caracteres UCS4 (PyUnicode_4BYTE_KIND) y consta solo de puntos de código
en el rango UCS1, se transformará en UCS1 (PyUnicode_1BYTE_KIND).
Added in version 3.3.
PyObject *PyUnicode_FromStringAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from the char buffer str. The bytes
will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. The return value might
be a shared object, i.e. modification of the data is not allowed.
This function raises SystemError when:
• size < 0,
• str is NULL and size > 0
Distinto en la versión 3.12: str == NULL with size > 0 is not allowed anymore.
PyObject *PyUnicode_FromString(const char *str)
Return value: New reference. Part of the Stable ABI. Create a Unicode object from a UTF-8 encoded null-
terminated char buffer str.
PyObject *PyUnicode_FromFormat(const char *format, ...)
Return value: New reference. Part of the Stable ABI. Take a C printf()-style format string and a variable
number of arguments, calculate the size of the resulting Python Unicode string and return a string with the
values formatted into it. The variable arguments must be C types and must correspond exactly to the format
characters in the format ASCII-encoded string.
A conversion specifier contains two or more characters and has the following components, which must occur
in this order:
1. The '%' character, which marks the start of the specifier.
2. Conversion flags (optional), which affect the result of some conversion types.
3. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is given in the next
argument, which must be of type int, and the object to convert comes after the minimum field width
and optional precision.
4. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk),
the actual precision is given in the next argument, which must be of type int, and the value to convert
comes after the precision.
5. Length modifier (optional).
6. Conversion type.
Flag Meaning
0 The conversion will be zero padded for numeric values.
- The converted value is left adjusted (overrides the 0 flag if both are given).
The length modifiers for following integer conversions (d, i, o, u, x, or X) specify the type of the argument
(int by default):
Modifier Types
l long or unsigned long
ll long long or unsigned long long
j intmax_t or uintmax_t
z size_t or ssize_t
t ptrdiff_t
The length modifier l for following conversions s or V specify that the type of the argument is const
wchar_t*.
The conversion specifiers are:
Nota: The width formatter unit is number of characters rather than bytes. The precision formatter unit is
number of bytes or wchar_t items (if the length modifier l is used) for "%s" and "%V" (if the PyObject*
argument is NULL), and a number of characters for "%A", "%U", "%S", "%R" and "%V" (if the PyObject*
argument is not NULL).
Nota: Unlike to C printf() the 0 flag has effect even when a precision is given for integer conversions (d,
i, u, o, x, or X).
Codificación regional
La codificación local actual se puede utilizar para decodificar texto del sistema operativo.
PyObject *PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t length, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7. Decodifica una cadena de caracteres
UTF-8 en Android y VxWorks, o de la codificación de configuración regional actual en otras plataformas. Los
manejadores de errores admitidos son "estricto" y "subrogateescape" (PEP 383). El decodifica-
dor usa el controlador de errores "estricto" si errors es NULL. str debe terminar con un carácter nulo pero
no puede contener caracteres nulos incrustados.
Use PyUnicode_DecodeFSDefaultAndSize() to decode a string from the filesystem encoding and
error handler.
Esta función ignora el modo Python UTF-8.
Ver también:
La función Py_DecodeLocale().
Added in version 3.3.
Distinto en la versión 3.7: La función ahora también usa la codificación de configuración regional actual para el
controlador de errores subrogateescape, excepto en Android. Anteriormente, Py_DecodeLocale()
se usaba para el subrogateescape, y la codificación local actual se usaba para estricto.
Functions encoding to and decoding from the filesystem encoding and error handler (PEP 383 and PEP 529).
To encode file names to bytes during argument parsing, the "O&" converter should be used, passing
PyUnicode_FSConverter() as the conversion function:
int PyUnicode_FSConverter(PyObject *obj, void *result)
Part of the Stable ABI. ParseTuple converter: encode str objects – obtained directly or through the os.
PathLike interface – to bytes using PyUnicode_EncodeFSDefault(); bytes objects are output
as-is. result must be a PyBytesObject* which must be released when it is no longer used.
Added in version 3.1.
Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).
Para decodificar nombres de archivo a str durante el análisis de argumentos, se debe usar el convertidor "O&",
pasando PyUnicode_FSDecoder() como la función de conversión:
int PyUnicode_FSDecoder(PyObject *obj, void *result)
Part of the Stable ABI. ParseTuple converter: decode bytes objects – obtained either directly or indirectly
through the os.PathLike interface – to str using PyUnicode_DecodeFSDefaultAndSize();
str objects are output as-is. result must be a PyUnicodeObject* which must be released when it is no
longer used.
Added in version 3.2.
Distinto en la versión 3.6: Acepta un objeto similar a una ruta (path-like object).
PyObject *PyUnicode_DecodeFSDefaultAndSize(const char *str, Py_ssize_t size)
Return value: New reference. Part of the Stable ABI. Decodifica una cadena desde el codificador de sistema de
archivos y gestor de errores.
If you need to decode a string from the current locale encoding, use
PyUnicode_DecodeLocaleAndSize().
Ver también:
La función Py_DecodeLocale().
soporte wchar_t
Códecs incorporados
Python proporciona un conjunto de códecs integrados que están escritos en C para mayor velocidad. Todos estos
códecs se pueden usar directamente a través de las siguientes funciones.
Muchas de las siguientes API toman dos argumentos de encoding y errors, y tienen la misma semántica que las del
constructor de objetos de cadena incorporado str().
Setting encoding to NULL causes the default encoding to be used which is UTF-8. The file system calls should
use PyUnicode_FSConverter() for encoding file names. This uses the filesystem encoding and error handler
internally.
El manejo de errores se establece mediante errors que también pueden establecerse en NULL, lo que significa usar el
manejo predeterminado definido para el códec. El manejo de errores predeterminado para todos los códecs integrados
es «estricto» (se lanza ValueError).
The codecs all use a similar interface. Only deviations from the following generic ones are documented for simplicity.
Códecs genéricos
Códecs UTF-8
Códecs UTF-32
Si *byteorder es cero, y los primeros cuatro bytes de los datos de entrada son una marca de orden de bytes
(BOM), el decodificador cambia a este orden de bytes y la BOM no se copia en la cadena de caracteres Unicode
resultante. Si *byteorder es -1 o 1, cualquier marca de orden de bytes se copia en la salida.
Una vez completado, *byteorder se establece en el orden de bytes actual al final de los datos de entrada.
Si byteorder es NULL, el códec se inicia en modo de orden nativo.
Retorna NULL si el códec provocó una excepción.
PyObject *PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF32(). Si consumed no es NULL, PyUnicode_DecodeUTF32Stateful()
no tratará las secuencias de bytes UTF-32 incompletas finales (como un número de bytes no divisible por cua-
tro) como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados se
almacenará en consumed.
PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Retorna una cadena de bytes de Python usando la codi-
ficación UTF-32 en orden de bytes nativo. La cadena siempre comienza con una marca BOM. El manejo de
errores es «estricto». Retorna NULL si el códec provocó una excepción.
Códecs UTF-16
Si *byteorder es cero, y los primeros dos bytes de los datos de entrada son una marca de orden de bytes
(BOM), el decodificador cambia a este orden de bytes y la BOM no se copia en la cadena de caracteres Unicode
resultante. Si *byteorder es -1 o 1, cualquier marca de orden de bytes se copia en la salida (donde dará
como resultado un \ufeff o un carácter \ufffe).
After completion, *byteorder is set to the current byte order at the end of input data.
Si byteorder es NULL, el códec se inicia en modo de orden nativo.
Retorna NULL si el códec provocó una excepción.
PyObject *PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI. Si consumed es NULL, se comporta como
PyUnicode_DecodeUTF16(). Si consumed no es NULL, PyUnicode_DecodeUTF16Stateful()
no tratará las secuencias de bytes UTF-16 incompletas finales (como un número impar de bytes o un par sustitu-
to dividido) como un error. Esos bytes no serán decodificados y la cantidad de bytes que han sido decodificados
se almacenará en consumed.
PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Retorna una cadena de bytes de Python usando la codi-
ficación UTF-16 en orden de bytes nativo. La cadena siempre comienza con una marca BOM. El manejo de
errores es «estricto». Retorna NULL si el códec provocó una excepción.
Códecs UTF-7
Estas son las API del códec Unicode escapado en bruto (Raw Unicode Escape):
PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
Raw-Unicode-Escape encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando Unicode escapado en
bruto (Raw-Unicode-Escape) y retorna el resultado como un objeto de bytes. El manejo de errores es «estricto».
Retorna NULL si el códec provocó una excepción.
Códecs Latin-1
Estas son las API del códec Latin-1: Latin-1 corresponde a los primeros 256 ordinales Unicode y solo estos son
aceptados por los códecs durante la codificación.
PyObject *PyUnicode_DecodeLatin1(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
Latin-1 encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando Latin-1 y retorna
el resultado como un objeto de bytes Python. El manejo de errores es «estricto». Retorna NULL si el códec
provocó una excepción.
Códecs ASCII
Estas son las API del códec ASCII. Solo se aceptan datos ASCII de 7 bits. Todos los demás códigos generan errores.
PyObject *PyUnicode_DecodeASCII(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
ASCII encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando ASCII y retorna el
resultado como un objeto de bytes de Python. El manejo de errores es «estricto». Retorna NULL si el códec
provocó una excepción.
This codec is special in that it can be used to implement many different codecs (and this is in fact what was done
to obtain most of the standard codecs included in the encodings package). The codec uses mappings to enco-
de and decode characters. The mapping objects provided must support the __getitem__() mapping interface;
dictionaries and sequences work well.
Estos son las API de códec de mapeo:
PyObject *PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, PyObject *mapping, const char
*errors)
Return value: New reference. Part of the Stable ABI. Create a Unicode object by decoding size bytes of the
encoded string str using the given mapping object. Return NULL if an exception was raised by the codec.
Si mapping es NULL, se aplicará la decodificación Latin-1. De lo contrario, mapping debe asignar bytes ordi-
nales (enteros en el rango de 0 a 255) a cadenas de caracteres Unicode, enteros (que luego se interpretan como
ordinales Unicode) o None. Los bytes de datos sin asignar - los que causan un LookupError, así como los
que se asignan a None, 0xFFFE o '\ ufffe', se tratan como asignaciones indefinidas y causan un error.
PyObject *PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
Return value: New reference. Part of the Stable ABI. Codifica un objeto Unicode usando el objeto mapping
dado y retorna el resultado como un objeto de bytes. El manejo de errores es «estricto». Retorna NULL si el
códec provocó una excepción.
El objeto mapping debe asignar enteros ordinales Unicode a objetos de bytes, enteros en el rango de 0 a 255 o
None. Los ordinales de caracteres no asignados (los que causan un LookupError), así como los asignados
a Ninguno, se tratan como «mapeo indefinido» y causan un error.
La siguiente API de códec es especial en que asigna Unicode a Unicode.
PyObject *PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
Return value: New reference. Part of the Stable ABI. Traduce una cadena de caracteres aplicando una tabla de
mapeo y retornando el objeto Unicode resultante. Retorna NULL cuando el códec provocó una excepción.
La tabla de mapeo debe mapear enteros ordinales Unicode a enteros ordinales Unicode o None (causando la
eliminación del carácter).
Mapping tables need only provide the __getitem__() interface; dictionaries and sequences work well.
Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is.
errors tiene el significado habitual para los códecs. Puede ser NULL, lo que indica que debe usar el manejo de
errores predeterminado.
Estas son las API de códec MBCS. Actualmente solo están disponibles en Windows y utilizan los convertidores Win32
MBCS para implementar las conversiones. Tenga en cuenta que MBCS (o DBCS) es una clase de codificaciones, no
solo una. La codificación de destino está definida por la configuración del usuario en la máquina que ejecuta el códec.
Las siguientes API son capaces de manejar objetos Unicode y cadenas de caracteres en la entrada (nos referimos a
ellos como cadenas de caracteres en las descripciones) y retorna objetos Unicode o enteros según corresponda.
Todos retornan NULL o -1 si ocurre una excepción.
PyObject *PyUnicode_Concat(PyObject *left, PyObject *right)
Return value: New reference. Part of the Stable ABI. Une dos cadenas de caracteres que dan una nueva cadena
de caracteres Unicode.
PyObject *PyUnicode_Split(PyObject *unicode, PyObject *sep, Py_ssize_t maxsplit)
Return value: New reference. Part of the Stable ABI. Divide una cadena de caracteres dando una lista de cadenas
de caracteres Unicode. Si sep es NULL, la división se realizará en todas las subcadenas de espacios en blanco.
De lo contrario, las divisiones ocurren en el separador dado. A lo sumo se realizarán maxsplit divisiones. Si es
negativo, no se establece ningún límite. Los separadores no están incluidos en la lista resultante.
PyObject *PyUnicode_Splitlines(PyObject *unicode, int keepends)
Return value: New reference. Part of the Stable ABI. Split a Unicode string at line breaks, returning a list of
Unicode strings. CRLF is considered to be one line break. If keepends is 0, the Line break characters are not
included in the resulting strings.
PyObject *PyUnicode_Join(PyObject *separator, PyObject *seq)
Return value: New reference. Part of the Stable ABI. Une una secuencia de cadenas de caracteres usando el
separator dado y retorna la cadena de caracteres Unicode resultante.
Py_ssize_t PyUnicode_Tailmatch(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
Part of the Stable ABI. Return 1 if substr matches unicode[start:end] at the given tail end (direction
== -1 means to do a prefix match, direction == 1 a suffix match), 0 otherwise. Return -1 if an error occurred.
Py_ssize_t PyUnicode_Find(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int
direction)
Part of the Stable ABI. Return the first position of substr in unicode[start:end] using the given direction
(direction == 1 means to do a forward search, direction == -1 a backward search). The return value is the index
of the first match; a value of -1 indicates that no match was found, and -2 indicates that an error occurred
and an exception has been set.
Py_ssize_t PyUnicode_FindChar(PyObject *unicode, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int
direction)
Part of the Stable ABI since version 3.7. Return the first position of the character ch in
unicode[start:end] using the given direction (direction == 1 means to do a forward search, di-
rection == -1 a backward search). The return value is the index of the first match; a value of -1 indicates that
no match was found, and -2 indicates that an error occurred and an exception has been set.
Added in version 3.3.
Distinto en la versión 3.7: start and end are now adjusted to behave like unicode[start:end].
Py_ssize_t PyUnicode_Count(PyObject *unicode, PyObject *substr, Py_ssize_t start, Py_ssize_t end)
Part of the Stable ABI. Return the number of non-overlapping occurrences of substr in
unicode[start:end]. Return -1 if an error occurred.
PyObject *PyUnicode_Replace(PyObject *unicode, PyObject *substr, PyObject *replstr, Py_ssize_t
maxcount)
Return value: New reference. Part of the Stable ABI. Replace at most maxcount occurrences of substr in unicode
with replstr and return the resulting Unicode object. maxcount == -1 means replace all occurrences.
int PyUnicode_Compare(PyObject *left, PyObject *right)
Part of the Stable ABI. Compara dos cadenas de caracteres y retorna -1, 0, 1 para menor que, igual y mayor
que, respectivamente.
Esta función retorna -1 en caso de falla, por lo que se debe llamar a PyErr_Occurred() para verificar si
hay errores.
int PyUnicode_CompareWithASCIIString(PyObject *unicode, const char *string)
Part of the Stable ABI. Compare a Unicode object, unicode, with string and return -1, 0, 1 for less than, equal,
and greater than, respectively. It is best to pass only ASCII-encoded strings, but the function interprets the input
string as ISO-8859-1 if it contains non-ASCII characters.
Esta función no lanza excepciones.
PyObject *PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Return value: New reference. Part of the Stable ABI. Comparación enriquecida de dos cadenas de caracteres
Unicode y retorna uno de los siguientes:
• NULL en caso de que se produzca una excepción
• Py_True or Py_False for successful comparisons
• Py_NotImplemented in case the type combination is unknown
Possible values for op are Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, and Py_LE.
PyObject *PyUnicode_Format(PyObject *format, PyObject *args)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto de cadena de caracteres desde
format y args; esto es análogo al format % args.
int PyUnicode_Contains(PyObject *unicode, PyObject *substr)
Part of the Stable ABI. Check whether substr is contained in unicode and return true or false accordingly.
substr has to coerce to a one element Unicode string. -1 is returned if there was an error.
void PyUnicode_InternInPlace(PyObject **p_unicode)
Part of the Stable ABI. Intern the argument *p_unicode in place. The argument must be the address of a
pointer variable pointing to a Python Unicode string object. If there is an existing interned string that is the same
as *p_unicode, it sets *p_unicode to it (releasing the reference to the old string object and creating a new
strong reference to the interned string object), otherwise it leaves *p_unicode alone and interns it (creating
a new strong reference). (Clarification: even though there is a lot of talk about references, think of this function
as reference-neutral; you own the object after the call if and only if you owned it before the call.)
PyObject *PyUnicode_InternFromString(const char *str)
Return value: New reference. Part of the Stable ABI. Una combinación de PyUnicode_FromString() y
PyUnicode_InternInPlace(), que retorna un nuevo objeto de cadena de caracteres Unicode que ha
sido creado internamente o una nueva referencia(«propia») a un objeto de cadena de caracteres interno anterior
con el mismo valor.
type PyTupleObject
Este subtipo de PyObject representa un objeto tupla de Python.
PyTypeObject PyTuple_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo tupla de Python; es el mismo
objeto que tuple en la capa de Python.
int PyTuple_Check(PyObject *p)
Retorna verdadero si p es un objeto tupla o una instancia de un subtipo del tipo tupla. Esta función siempre
finaliza con éxito.
int PyTuple_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto tupla pero no una instancia de un subtipo del tipo tupla. Esta función
siempre finaliza con éxito.
PyObject *PyTuple_New(Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto tupla de tamaño len o NULL en
caso de falla.
PyObject *PyTuple_Pack(Py_ssize_t n, ...)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto tupla de tamaño n, o NULL en
caso de falla. Los valores de tupla se inicializan en los argumentos C posteriores n que apuntan a objetos de
Python. PyTuple_Pack (2, a, b) es equivalente a Py_BuildValue("(OO)", a, b).
Py_ssize_t PyTuple_Size(PyObject *p)
Part of the Stable ABI. Toma un puntero a un objeto de tupla y retorna el tamaño de esa tupla.
Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
Retorna el tamaño de la tupla p, que no debe ser NULL y apunta a una tupla; No se realiza ninguna comprobación
de errores.
PyObject *PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto en la posición pos en la tupla señala-
da por p. Si pos es negativo o está fuera de los límites, retorna NULL y establece una excepción IndexError.
The returned reference is borrowed from the tuple p (that is: it is only valid as long as you hold
a reference to p). To get a strong reference, use Py_NewRef(PyTuple_GetItem(...)) or
PySequence_GetItem().
PyObject *PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Como PyTuple_GetItem(), pero no verifica sus argumentos.
PyObject *PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)
Return value: New reference. Part of the Stable ABI. Return the slice of the tuple pointed to by p between low
and high, or NULL on failure. This is the equivalent of the Python expression p[low:high]. Indexing from
the end of the tuple is not supported.
int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)
Part of the Stable ABI. Inserta una referencia al objeto o en la posición pos de la tupla señalada por p. Retorna
0 en caso de éxito. Si pos está fuera de límites, retorna -1 y establece una excepción IndexError.
Nota: Esta función «roba» una referencia a o y descarta una referencia a un elemento que ya está en la tupla
en la posición afectada.
Nota: Esta función «roba» una referencia a o y, a diferencia de PyTuple_SetItem(), no descarta una
referencia a ningún elemento que se está reemplazando; cualquier referencia en la tupla en la posición pos se
filtrará.
Los objetos de secuencia de estructura son el equivalente en C de los objetos namedtuple(), es decir, una se-
cuencia a cuyos elementos también se puede acceder a través de atributos. Para crear una secuencia de estructura,
primero debe crear un tipo de secuencia de estructura específico.
PyTypeObject *PyStructSequence_NewType(PyStructSequence_Desc *desc)
Return value: New reference. Part of the Stable ABI. Crea un nuevo tipo de secuencia de estructura a partir
de los datos en desc, que se describen a continuación. Las instancias del tipo resultante se pueden crear con
PyStructSequence_New().
void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)
Inicializa una secuencia de estructura tipo type desde desc en su lugar.
int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc)
Lo mismo que PyStructSequence_InitType, pero retorna 0 en caso de éxito y -1 en caso de error.
Added in version 3.4.
type PyStructSequence_Desc
Part of the Stable ABI (including all members). Contiene la meta información de un tipo de secuencia de
estructura para crear.
const char *name
Name of the struct sequence type.
const char *doc
Pointer to docstring for the type or NULL to omit.
PyStructSequence_Field *fields
Pointer to NULL-terminated array with field names of the new type.
int n_in_sequence
Number of fields visible to the Python side (if used as tuple).
type PyStructSequence_Field
Part of the Stable ABI (including all members). Describes a field of a struct sequence. As a struct sequen-
ce is modeled as a tuple, all fields are typed as PyObject*. The index in the fields array of the
PyStructSequence_Desc determines which field of the struct sequence is described.
const char *name
Name for the field or NULL to end the list of named fields, set to
PyStructSequence_UnnamedField to leave unnamed.
const char *doc
Field docstring or NULL to omit.
type PyListObject
Este subtipo de PyObject representa un objeto lista de Python.
PyTypeObject PyList_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de lista de Python. Este es el
mismo objeto que list en la capa de Python.
int PyList_Check(PyObject *p)
Retorna verdadero si p es un objeto de lista o una instancia de un subtipo del tipo lista. Esta función siempre
finaliza con éxito.
int PyList_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto lista, pero no una instancia de un subtipo del tipo lista. Esta función siempre
finaliza con éxito.
PyObject *PyList_New(Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Retorna una nueva lista de longitud len en caso de éxito o
NULL en caso de error.
Nota: Si len es mayor que cero, los elementos del objeto de la lista retornada se establecen en NULL. Por lo
tanto, no puede utilizar funciones API abstractas como PySequence_SetItem() o exponer el objeto al
código Python antes de configurar todos los elementos en un objeto real con PyList_SetItem().
Nota: Esta función «roba» una referencia a item y descarta una referencia a un elemento que ya está en la lista
en la posición afectada.
Nota: Este macro «roba» una referencia a item y, a diferencia de PyList_SetItem(), no descarta una
referencia a ningún elemento que se está reemplazando; cualquier referencia en list en la posición i se filtrará.
type PyDictObject
Este subtipo de PyObject representa un objeto diccionario de Python.
PyTypeObject PyDict_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo diccionario de Python. Este es
el mismo objeto que dict en la capa de Python.
int PyDict_Check(PyObject *p)
Retorna verdadero si p es un objeto dict o una instancia de un subtipo del tipo dict. Esta función siempre
finaliza con éxito.
int PyDict_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto dict, pero no una instancia de un subtipo del tipo dict. Esta función
siempre finaliza con éxito.
PyObject *PyDict_New()
Return value: New reference. Part of the Stable ABI. Retorna un nuevo diccionario vacío, o NULL en caso de
falla.
PyObject *PyDictProxy_New(PyObject *mapping)
Return value: New reference. Part of the Stable ABI. Retorna un objeto a types.MappingProxyType
para una asignación que imponga un comportamiento de solo lectura. Esto normalmente se usa para crear una
vista para evitar la modificación del diccionario para los tipos de clase no dinámicos.
void PyDict_Clear(PyObject *p)
Part of the Stable ABI. Vacía un diccionario existente de todos los pares clave-valor (key-value).
int PyDict_Contains(PyObject *p, PyObject *key)
Part of the Stable ABI. Determine si el diccionario p contiene key. Si un elemento en p coincide con la clave
key, retorna 1; de lo contrario, retorna 0. En caso de error, retorna -1. Esto es equivalente a la expresión de
Python key in p.
PyObject *PyDict_Copy(PyObject *p)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo diccionario que contiene los mismos
pares clave-valor (key-value) que p.
int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
Part of the Stable ABI. Inserta val en el diccionario p con una clave key. key debe ser hashable; si no lo es, se
lanzará TypeError. Retorna 0 en caso de éxito o -1 en caso de error. Esta función no roba una referencia
a val.
int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
Part of the Stable ABI. This is the same as PyDict_SetItem(), but key is specified as a const char*
UTF-8 encoded bytes string, rather than a PyObject*.
int PyDict_DelItem(PyObject *p, PyObject *key)
Part of the Stable ABI. Remove the entry in dictionary p with key key. key must be hashable; if it isn’t,
TypeError is raised. If key is not in the dictionary, KeyError is raised. Return 0 on success or -1 on
failure.
int PyDict_DelItemString(PyObject *p, const char *key)
Part of the Stable ABI. This is the same as PyDict_DelItem(), but key is specified as a const char*
UTF-8 encoded bytes string, rather than a PyObject*.
Nota: Exceptions that occur while this calls __hash__() and __eq__() methods are silently ignored.
Prefer the PyDict_GetItemWithError() function instead.
Distinto en la versión 3.10: Llamar a esta API sin retener el GIL había sido permitido por motivos históricos.Ya
no está permitido.
PyObject *PyDict_GetItemWithError(PyObject *p, PyObject *key)
Return value: Borrowed reference. Part of the Stable ABI. Variante de PyDict_GetItem() que no suprime
las excepciones. Retorna NULL con una excepción establecida si se produjo una excepción. Retorna NULL sin
una excepción establecida si la clave no estaba presente.
PyObject *PyDict_GetItemString(PyObject *p, const char *key)
Return value: Borrowed reference. Part of the Stable ABI. This is the same as PyDict_GetItem(), but key
is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
Nota: Exceptions that occur while this calls __hash__() and __eq__() methods or while creating the
temporary str object are silently ignored. Prefer using the PyDict_GetItemWithError() function
with your own PyUnicode_FromString() key instead.
El diccionario p no debe mutarse durante la iteración. Es seguro modificar los valores de las claves a medida
que recorre el diccionario, pero solo mientras el conjunto de claves no cambie. Por ejemplo:
PyObject *key, *value;
Py_ssize_t pos = 0;
Esta sección detalla la API pública de los objetos set y frozenset. Cualquier funcionalidad que
no esté listada a continuación se accede mejor utilizando el protocolo abstracto de objetos (inclu-
yendo PyObject_CallMethod(), PyObject_RichCompareBool(), PyObject_Hash(),
PyObject_Repr(), PyObject_IsTrue(), PyObject_Print(), y PyObject_GetIter()) o el
protocolo numérico abstracto (incluyendo PyNumber_And(), PyNumber_Subtract(), PyNumber_Or(),
PyNumber_Xor(), PyNumber_InPlaceAnd(), PyNumber_InPlaceSubtract(),
PyNumber_InPlaceOr(), y PyNumber_InPlaceXor()).
type PySetObject
Este subtipo de PyObject se utiliza para mantener los datos internos de los objetos set y frozenset.
Es como un PyDictObject en el sentido de que tiene un tamaño fijo para los conjuntos pequeños (muy
parecido al almacenamiento de tuplas) y apuntará a un bloque de memoria separado y de tamaño variable para
los conjuntos de tamaño medio y grande (muy parecido al almacenamiento de listas). Ninguno de los campos
de esta estructura debe considerarse público y todos están sujetos a cambios. Todo el acceso debe hacerse a
través de la API documentada en lugar de manipular los valores de la estructura.
PyTypeObject PySet_Type
Part of the Stable ABI. Esta es una instancia de PyTypeObject que representa el tipo Python set.
PyTypeObject PyFrozenSet_Type
Part of the Stable ABI. Esta es una instancia de PyTypeObject que representa el tipo Python frozenset.
Los siguientes macros de comprobación de tipos funcionan en punteros a cualquier objeto de Python. Del mismo
modo, las funciones del constructor funcionan con cualquier objeto Python iterable.
int PySet_Check(PyObject *p)
Retorna verdadero si p es un objeto set o una instancia de un subtipo. Esta función siempre finaliza con éxito.
int PyFrozenSet_Check(PyObject *p)
Retorna verdadero si p es un objeto frozenset o una instancia de un subtipo. Esta función siempre finaliza
con éxito.
int PyAnySet_Check(PyObject *p)
Retorna verdadero si p es un objeto set, un objeto frozenset, o una instancia de un subtipo. Esta función
siempre finaliza con éxito.
int PySet_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto set pero no una instancia de un subtipo. Esta función siempre finaliza con
éxito.
Added in version 3.10.
int PyAnySet_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto set o un objeto frozenset pero no una instancia de un subtipo. Esta
función siempre finaliza con éxito.
int PyFrozenSet_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto frozenset pero no una instancia de un subtipo. Esta función siempre
finaliza con éxito.
PyObject *PySet_New(PyObject *iterable)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo set que contiene objetos retornados
por iterable. El iterable puede ser NULL para crear un nuevo conjunto vacío. Retorna el nuevo conjunto en
caso de éxito o NULL en caso de error. Lanza TypeError si iterable no es realmente iterable. El constructor
también es útil para copiar un conjunto (c=set(s)).
PyObject *PyFrozenSet_New(PyObject *iterable)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo frozenset que contiene objetos
retornados por iterable. El iterable puede ser NULL para crear un nuevo conjunto congelado vacío. Retorna
el nuevo conjunto en caso de éxito o NULL en caso de error. Lanza TypeError si iterable no es realmente
iterable.
Las siguientes funciones y macros están disponibles para instancias de set o frozenset o instancias de sus sub-
tipos.
Py_ssize_t PySet_Size(PyObject *anyset)
Part of the Stable ABI. Return the length of a set or frozenset object. Equivalent to len(anyset).
Raises a SystemError if anyset is not a set, frozenset, or an instance of a subtype.
An instance method is a wrapper for a PyCFunction and the new way to bind a PyCFunction to a class object.
It replaces the former call PyMethod_New(func, NULL, class).
PyTypeObject PyInstanceMethod_Type
Esta instancia de PyTypeObject representa el tipo de método de instancia de Python. No está expuesto a
los programas de Python.
int PyInstanceMethod_Check(PyObject *o)
Retorna verdadero si o es un objeto de método de instancia (tiene tipo PyInstanceMethod_Type). El
parámetro no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PyInstanceMethod_New(PyObject *func)
Return value: New reference. Return a new instance method object, with func being any callable object. func is
the function that will be called when the instance method is called.
PyObject *PyInstanceMethod_Function(PyObject *im)
Return value: Borrowed reference. Retorna el objeto de función asociado con el método de instancia im.
PyObject *PyInstanceMethod_GET_FUNCTION(PyObject *im)
Return value: Borrowed reference. Versión macro de PyInstanceMethod_Function() que evita la
comprobación de errores.
Los métodos son objetos de función enlazados. Los métodos siempre están vinculados a una instancia de una clase
definida por el usuario. Los métodos no vinculados (métodos vinculados a un objeto de clase) ya no están disponibles.
PyTypeObject PyMethod_Type
Esta instancia de PyTypeObject representa el tipo de método Python. Esto está expuesto a los programas
de Python como types.MethodType.
int PyMethod_Check(PyObject *o)
Retorna verdadero si o es un objeto de método (tiene tipo PyMethod_Type). El parámetro no debe ser
NULL. Esta función siempre finaliza con éxito.
PyObject *PyMethod_New(PyObject *func, PyObject *self)
Return value: New reference. Retorna un nuevo objeto de método, con func como cualquier objeto invocable
y self la instancia en la que se debe vincular el método. func es la función que se llamará cuando se llame al
método. self no debe ser NULL.
PyObject *PyMethod_Function(PyObject *meth)
Return value: Borrowed reference. Retorna el objeto de función asociado con el método meth.
PyObject *PyMethod_GET_FUNCTION(PyObject *meth)
Return value: Borrowed reference. Versión macro de PyMethod_Function() que evita la comprobación
de errores.
PyObject *PyMethod_Self(PyObject *meth)
Return value: Borrowed reference. Retorna la instancia asociada con el método meth.
PyObject *PyMethod_GET_SELF(PyObject *meth)
Return value: Borrowed reference. Versión macro de PyMethod_Self() que evita la comprobación de
errores.
Los objetos celda (cell) se utilizan para implementar variables a las que hacen referencia varios ámbitos. Para cada
variable, se crea un objeto de celda para almacenar el valor; Las variables locales de cada marco de pila que hace
referencia al valor contienen una referencia a las celdas de ámbitos externos que también usan esa variable. Cuando
se accede al valor, se utiliza el valor contenido en la celda en lugar del objeto de la celda en sí. Esta desreferenciación
del objeto de celda requiere soporte del código de bytes generado; estos no se eliminan automáticamente cuando se
accede a ellos. No es probable que los objetos celda sean útiles en otros lugares.
type PyCellObject
La estructura C utilizada para objetos celda.
PyTypeObject PyCell_Type
El objeto tipo correspondiente a los objetos celda.
int PyCell_Check(PyObject *ob)
Retorna verdadero si ob es un objeto de celda; ob no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PyCell_New(PyObject *ob)
Return value: New reference. Crea y retorna un nuevo objeto de celda que contiene el valor ob. El parámetro
puede ser NULL.
PyObject *PyCell_Get(PyObject *cell)
Return value: New reference. Retorna el contenido de la celda cell.
Los objetos código son un detalle de bajo nivel de la implementación de CPython. Cada uno representa un fragmento
de código ejecutable que aún no se ha vinculado a una función.
type PyCodeObject
La estructura en C de los objetos utilizados para describir objetos código. Los campos de este tipo están sujetos
a cambios en cualquier momento.
PyTypeObject PyCode_Type
This is an instance of PyTypeObject representing the Python code object.
int PyCode_Check(PyObject *co)
Return true if co is a code object. This function always succeeds.
Py_ssize_t PyCode_GetNumFree(PyCodeObject *co)
Return the number of free variables in a code object.
int PyCode_GetFirstFree(PyCodeObject *co)
Return the position of the first free variable in a code object.
PyCodeObject *PyUnstable_Code_New(int argcount, int kwonlyargcount, int nlocals, int stacksize, int flags,
PyObject *code, PyObject *consts, PyObject *names, PyObject
*varnames, PyObject *freevars, PyObject *cellvars, PyObject
*filename, PyObject *name, PyObject *qualname, int firstlineno,
PyObject *linetable, PyObject *exceptiontable)
Return a new code object. If you need a dummy code object to create a frame, use PyCode_NewEmpty()
instead.
Since the definition of the bytecode changes often, calling PyUnstable_Code_New() directly can bind
you to a precise Python version.
The many arguments of this function are inter-dependent in complex ways, meaning that subtle changes to
values are likely to result in incorrect execution or VM crashes. Use this function only with extreme care.
Distinto en la versión 3.11: Added qualname and exceptiontable parameters.
Distinto en la versión 3.12: Renamed from PyCode_New as part of Unstable C API. The old name is depre-
cated, but will remain available until the signature changes again.
To support low-level extensions to frame evaluation, such as external just-in-time compilers, it is possible to attach
arbitrary extra data to code objects.
These functions are part of the unstable C API tier: this functionality is a CPython implementation detail, and the
API may change without deprecation warnings.
Py_ssize_t PyUnstable_Eval_RequestCodeExtraIndex(freefunc free)
Return a new an opaque index value used to adding data to code objects.
You generally call this function once (per interpreter) and use the result with PyCode_GetExtra and
PyCode_SetExtra to manipulate data on individual code objects.
If free is not NULL: when a code object is deallocated, free will be called on non-NULL data stored under the
new index. Use Py_DecRef() when storing PyObject.
Added in version 3.6: as _PyEval_RequestCodeExtraIndex
Distinto en la versión 3.12: Renamed to PyUnstable_Eval_RequestCodeExtraIndex. The old pri-
vate name is deprecated, but will be available until the API changes.
int PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
Set extra to the extra data stored under the given index. Return 0 on success. Set an exception and return -1 on
failure.
If no data was set under the index, set extra to NULL and return 0 without setting an exception.
Added in version 3.6: as _PyCode_GetExtra
Distinto en la versión 3.12: Renamed to PyUnstable_Code_GetExtra. The old private name is depre-
cated, but will be available until the API changes.
int PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
Set the extra data stored under the given index to extra. Return 0 on success. Set an exception and return -1 on
failure.
Added in version 3.6: as _PyCode_SetExtra
Distinto en la versión 3.12: Renamed to PyUnstable_Code_SetExtra. The old private name is depre-
cated, but will be available until the API changes.
These APIs are a minimal emulation of the Python 2 C API for built-in file objects, which used to rely on the
buffered I/O (FILE*) support from the C standard library. In Python 3, files and streams use the new io module,
which defines several layers over the low-level unbuffered I/O of the operating system. The functions described below
are convenience C wrappers over these new APIs, and meant mostly for internal error reporting in the interpreter;
third-party code is advised to access the io APIs instead.
PyObject *PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding,
const char *errors, const char *newline, int closefd)
Return value: New reference. Part of the Stable ABI. Crea un objeto archivo Python a partir del descriptor de
archivo de un archivo ya abierto fd. Los argumentos name, encoding, errors y newline pueden ser NULL para
usar los valores predeterminados; buffering puede ser -1 para usar el valor predeterminado. name se ignora y
se mantiene por compatibilidad con versiones anteriores. Retorna NULL en caso de error. Para obtener una
descripción más completa de los argumentos, consulte la documentación de la función io.open().
Advertencia: Dado que las transmisiones (streams) de Python tienen su propia capa de almacenamiento
en búfer, combinarlas con descriptores de archivos a nivel del sistema operativo puede producir varios
problemas (como un pedido inesperado de datos).
PyTypeObject PyModule_Type
Part of the Stable ABI. Esta instancia de PyTypeObject representa el tipo de módulo Python. Esto está
expuesto a los programas de Python como types.ModuleType.
int PyModule_Check(PyObject *p)
Retorna verdadero si p es un objeto de módulo o un subtipo de un objeto de módulo. Esta función siempre
finaliza con éxito.
int PyModule_CheckExact(PyObject *p)
Retorna verdadero si p es un objeto módulo, pero no un subtipo de PyModule_Type. Esta función siempre
finaliza con éxito.
PyObject *PyModule_NewObject(PyObject *name)
Return value: New reference. Part of the Stable ABI since version 3.7. Retorna un nuevo objeto módu-
lo con el atributo __name__ establecido en name. Los atributos del módulo __name__, __doc__,
__package__, y __loader__ se completan (todos menos __name__ están configurados en None);
quien llama es responsable de proporcionar un atributo __file__.
Added in version 3.3.
Distinto en la versión 3.4: __package__ y __loader__ están configurados en None.
PyObject *PyModule_New(const char *name)
Return value: New reference. Part of the Stable ABI. Similar a PyModule_NewObject(), pero el nombre
es una cadena de caracteres codificada UTF-8 en lugar de un objeto Unicode.
PyObject *PyModule_GetDict(PyObject *module)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto del diccionario que implementa
el espacio de nombres de module; este objeto es el mismo que el atributo __dict__ del objeto módulo. Si
module no es un objeto módulo (o un subtipo de un objeto de módulo), se lanza SystemError y se retorna
NULL.
It is recommended extensions use other PyModule_* and PyObject_* functions rather than directly ma-
nipulate a module’s __dict__.
PyObject *PyModule_GetNameObject(PyObject *module)
Return value: New reference. Part of the Stable ABI since version 3.7. Retorna el valor __name__ del module.
Si el módulo no proporciona uno, o si no es una cadena de caracteres, SystemError se lanza y se retorna
NULL.
Added in version 3.3.
const char *PyModule_GetName(PyObject *module)
Part of the Stable ABI. Similar a PyModule_GetNameObject() pero retorna el nombre codificado a
'utf-8'.
Inicializando módulos en C
Los objetos módulos generalmente se crean a partir de módulos de extensión (bibliotecas compartidas que ex-
portan una función de inicialización) o módulos compilados (donde la función de inicialización se agrega usando
PyImport_AppendInittab()). Consulte building o extendiendo con incrustación para más detalles.
La función de inicialización puede pasar una instancia de definición de módulo a PyModule_Create(), y retornar
el objeto módulo resultante, o solicitar una «inicialización de múltiples fases» retornando la estructura de definición.
type PyModuleDef
Part of the Stable ABI (including all members). La estructura de definición de módulo, que contiene toda
la información necesaria para crear un objeto módulo. Por lo general, solo hay una variable estáticamente
inicializada de este tipo para cada módulo.
PyModuleDef_Base m_base
Always initialize this member to PyModuleDef_HEAD_INIT.
const char *m_name
Nombre para el nuevo módulo.
const char *m_doc
Docstring para el módulo; por lo general, se usa una variable docstring creada con PyDoc_STRVAR.
Py_ssize_t m_size
El estado del módulo se puede mantener en un área de memoria por módulo que se puede recuperar con
PyModule_GetState(), en lugar de en globales estáticos. Esto hace que los módulos sean seguros
para su uso en múltiples sub-interpretadores.
This memory area is allocated based on m_size on module creation, and freed when the module object is
deallocated, after the m_free function has been called, if present.
Establecer m_size en -1 significa que el módulo no admite sub-interpretadores, porque tiene un estado
global.
Establecerlo en un valor no negativo significa que el módulo se puede reinicializar y especifica la cantidad
adicional de memoria que requiere para su estado. Se requiere m_size no negativo para la inicialización
de múltiples fases.
Ver PEP 3121 para más detalles.
PyMethodDef *m_methods
Un puntero a una tabla de funciones de nivel de módulo, descrito por valores PyMethodDef. Puede
ser NULL si no hay funciones presentes.
PyModuleDef_Slot *m_slots
Un conjunto de definiciones de ranura para la inicialización de múltiples fases, terminadas por una entrada
{0, NULL}. Cuando se utiliza la inicialización monofásica, m_slots debe ser NULL.
Distinto en la versión 3.5: Antes de la versión 3.5, este miembro siempre estaba configurado en NULL y
se definía como:
inquiry m_reload
traverseproc m_traverse
Una función transversal para llamar durante el recorrido GC del objeto del módulo, o NULL si no es
necesario.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.
inquiry m_clear
Una función clara para llamar durante la limpieza GC del objeto del módulo, o NULL si no es necesario.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Tal como PyTypeObject.tp_clear, esta función no siempre es llamada antes de la designación de
un módulo. Por ejemplo, cuando el recuento de referencias está listo para determinar que un objeto no se
usa más, la recolección de basura cíclica no se involucra y se llama a m_free directamente.
Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.
freefunc m_free
Una función para llamar durante la desasignación del objeto del módulo, o NULL si no es necesario.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Distinto en la versión 3.9: Ya no se llama antes de que se asigne el estado del módulo.
Inicialización monofásica
La función de inicialización del módulo puede crear y retornar el objeto módulo directamente. Esto se conoce como
«inicialización monofásica» y utiliza una de las siguientes funciones de creación de dos módulos:
PyObject *PyModule_Create(PyModuleDef *def)
Return value: New reference. Create a new module object, given the definition in def. This behaves like
PyModule_Create2() with module_api_version set to PYTHON_API_VERSION.
PyObject *PyModule_Create2(PyModuleDef *def, int module_api_version)
Return value: New reference. Part of the Stable ABI. Crea un nuevo objeto de módulo, dada la definición en
def, asumiendo la versión de API module_api_version. Si esa versión no coincide con la versión del intérprete
en ejecución, se emite un RuntimeWarning.
Nota: La mayoría de los usos de esta función deberían usar PyModule_Create() en su lugar; solo use
esto si está seguro de que lo necesita.
Antes de que se retorne desde la función de inicialización, el objeto del módulo resultante normalmente se llena
utilizando funciones como PyModule_AddObjectRef().
Inicialización multifase
An alternate way to specify extensions is to request «multi-phase initialization». Extension modules created this
way behave more like Python modules: the initialization is split between the creation phase, when the module ob-
ject is created, and the execution phase, when it is populated. The distinction is similar to the __new__() and
__init__() methods of classes.
Unlike modules created using single-phase initialization, these modules are not singletons: if the sys.modules entry
is removed and the module is re-imported, a new module object is created, and the old module is subject to normal
garbage collection – as with Python modules. By default, multiple modules created from the same definition should
be independent: changes to one should not affect the others. This means that all state should be specific to the module
object (using e.g. using PyModule_GetState()), or its contents (such as the module’s __dict__ or individual
classes created with PyType_FromSpec()).
Se espera que todos los módulos creados mediante la inicialización de múltiples fases admitan sub-interpretadores.
Asegurándose de que varios módulos sean independientes suele ser suficiente para lograr esto.
Para solicitar la inicialización de múltiples fases, la función de inicialización (PyInit_modulename) retorna una ins-
tancia de PyModuleDef con un m_slots no vacío. Antes de que se retorna, la instancia PyModuleDef debe
inicializarse con la siguiente función:
PyObject *PyModuleDef_Init(PyModuleDef *def)
Return value: Borrowed reference. Part of the Stable ABI since version 3.5. Asegura que la definición de un
módulo sea un objeto Python correctamente inicializado que informe correctamente su tipo y conteo de refe-
rencias.
Retorna def convertido a PyObject* o NULL si se produjo un error.
Added in version 3.5.
El miembro m_slots de la definición del módulo debe apuntar a un arreglo de estructuras PyModuleDef_Slot:
type PyModuleDef_Slot
int slot
Una ranura ID, elegida entre los valores disponibles que se explican a continuación.
void *value
Valor de la ranura, cuyo significado depende de la ID de la ranura.
Added in version 3.5.
El arreglo m_slots debe estar terminada por una ranura con id 0.
Los tipos de ranura disponibles son:
Py_mod_create
Especifica una función que se llama para crear el objeto del módulo en sí. El puntero value de este espacio debe
apuntar a una función de la firma:
PyObject *create_module(PyObject *spec, PyModuleDef *def)
La función recibe una instancia de ModuleSpec, como se define en PEP 451, y la definición del módulo.
Debería retornar un nuevo objeto de módulo, o establecer un error y retornar NULL.
Esta función debe mantenerse mínima. En particular, no debería llamar a código arbitrario de Python, ya que
intentar importar el mismo módulo nuevamente puede dar como resultado un bucle infinito.
Si se especifican varias ranuras Py_mod_exec, se procesan en el orden en que aparecen en el arreglo m_slots.
Py_mod_multiple_interpreters
Specifies one of the following values:
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
The module does not support being imported in subinterpreters.
Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
The module supports being imported in subinterpreters, but only when they share the main interpreter’s
GIL. (See isolating-extensions-howto.)
Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
The module supports being imported in subinterpreters, even when they have their own GIL. (See
isolating-extensions-howto.)
This slot determines whether or not importing this module in a subinterpreter will fail.
Multiple Py_mod_multiple_interpreters slots may not be specified in one module definition.
If Py_mod_multiple_interpreters is not specified, the import machinery defaults to
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED.
Added in version 3.12.
Ver PEP 489 para más detalles sobre la inicialización de múltiples fases.
Las siguientes funciones se invocan en segundo plano cuando se utiliza la inicialización de múltiples fases. Se pue-
den usar directamente, por ejemplo, al crear objetos de módulo de forma dinámica. Tenga en cuenta que tanto
PyModule_FromDefAndSpec como PyModule_ExecDef deben llamarse para inicializar completamente
un módulo.
PyObject *PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)
Return value: New reference. Create a new module object, given the definition in def and the Mo-
duleSpec spec. This behaves like PyModule_FromDefAndSpec2() with module_api_version set to
PYTHON_API_VERSION.
Added in version 3.5.
PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)
Return value: New reference. Part of the Stable ABI since version 3.7. Create a new module object, given the
definition in def and the ModuleSpec spec, assuming the API version module_api_version. If that version does
not match the version of the running interpreter, a RuntimeWarning is emitted.
Nota: La mayoría de los usos de esta función deberían usar PyModule_FromDefAndSpec() en su lugar;
solo use esto si está seguro de que lo necesita.
Funciones de soporte
La función de inicialización del módulo (si usa la inicialización de fase única) o una función llamada desde un intervalo
de ejecución del módulo (si usa la inicialización de múltiples fases), puede usar las siguientes funciones para ayudar
a inicializar el estado del módulo:
int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
Part of the Stable ABI since version 3.10. Agrega un objeto a module como name. Esta es una función de
conveniencia que se puede usar desde la función de inicialización del módulo.
En caso de éxito, retorna 0. En caso de error, lanza una excepción y retorna -1.
Retorna NULL si value es NULL. Debe llamarse lanzando una excepción en este caso.
Ejemplo de uso
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_DECREF(obj);
return res;
}
El ejemplo puede también ser escrito sin verificar explicitamente si obj es NULL:
static int
add_spam(PyObject *module, int value)
{
(continúe en la próxima página)
Note que Py_XDECREF() debería ser usado en vez de Py_DECREF() en este caso, ya que obj puede ser
NULL.
Added in version 3.10.
int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
Part of the Stable ABI. Similar a PyModule_AddObjectRef(), pero roba una referencia a value en caso
de éxito (en este caso retorna 0).
Se recomienda la nueva función PyModule_AddObjectRef(), ya que es sencillo introducir fugas de
referencias por un uso incorrecto de la función PyModule_AddObject().
Nota: Unlike other functions that steal references, PyModule_AddObject() only releases the reference
to value on success.
Esto significa que su valor de retorno debe ser verificado, y el código de llamada debe Py_DECREF() value
manualmente en caso de error.
Ejemplo de uso
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
if (PyModule_AddObject(module, "spam", obj) < 0) {
Py_DECREF(obj);
return -1;
}
// PyModule_AddObject() stole a reference to obj:
// Py_DECREF(obj) is not needed here
return 0;
}
El ejemplo puede también ser escrito sin verificar explicitamente si obj es NULL:
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (PyModule_AddObject(module, "spam", obj) < 0) {
Py_XDECREF(obj);
return -1;
}
// PyModule_AddObject() stole a reference to obj:
// Py_DECREF(obj) is not needed here
return 0;
}
Note que Py_XDECREF() debería ser usado en vez de Py_DECREF() en este caso, ya que obj puede ser
NULL.
Búsqueda de módulos
La inicialización monofásica crea módulos singleton que se pueden buscar en el contexto del intérprete actual. Esto
permite que el objeto módulo se recupere más tarde con solo una referencia a la definición del módulo.
Estas funciones no funcionarán en módulos creados mediante la inicialización de múltiples fases, ya que se pueden
crear múltiples módulos de este tipo desde una sola definición.
PyObject *PyState_FindModule(PyModuleDef *def)
Return value: Borrowed reference. Part of the Stable ABI. Retorna el objeto módulo que se creó a partir de
def para el intérprete actual. Este método requiere que el objeto módulo se haya adjuntado al estado del intér-
prete con PyState_AddModule() de antemano. En caso de que el objeto módulo correspondiente no se
encuentre o no se haya adjuntado al estado del intérprete, retornará NULL.
int PyState_AddModule(PyObject *module, PyModuleDef *def)
Part of the Stable ABI since version 3.3. Adjunta el objeto del módulo pasado a la función al estado del intérprete.
Esto permite que se pueda acceder al objeto del módulo a través de PyState_FindModule().
Solo es efectivo en módulos creados con la inicialización monofásica.
Python llama a PyState_AddModule automáticamente después de importar un módulo, por lo que es
innecesario (pero inofensivo) llamarlo desde el código de inicialización del módulo. Solo se necesita una lla-
mada explícita si el propio código de inicio del módulo llama posteriormente PyState_FindModule. La
función está destinada principalmente a implementar mecanismos de importación alternativos (ya sea llamán-
dolo directamente o refiriéndose a su implementación para obtener detalles de las actualizaciones de estado
requeridas).
La persona que llama debe retener el GIL.
Retorna 0 en caso de éxito o -1 en caso de error.
Added in version 3.3.
int PyState_RemoveModule(PyModuleDef *def)
Part of the Stable ABI since version 3.3. Elimina el objeto del módulo creado a partir de def del estado del
intérprete. Retorna 0 en caso de éxito o -1 en caso de error.
La persona que llama debe retener el GIL.
Added in version 3.3.
Python provides two general-purpose iterator objects. The first, a sequence iterator, works with an arbitrary sequence
supporting the __getitem__() method. The second works with a callable object and a sentinel value, calling the
callable for each item in the sequence, and ending the iteration when the sentinel value is returned.
PyTypeObject PySeqIter_Type
Part of the Stable ABI. Objeto tipo para objetos iteradores retornados por PySeqIter_New() y la forma
de un argumento de la función incorporada iter() para los tipos de secuencia incorporados.
int PySeqIter_Check(PyObject *op)
Retorna verdadero si el tipo de op es PySeqIter_Type. Esta función siempre finaliza con éxito.
PyObject *PySeqIter_New(PyObject *seq)
Return value: New reference. Part of the Stable ABI. Retorna un iterador que funciona con un objeto de se-
cuencia general, seq. La iteración termina cuando la secuencia lanza IndexError para la operación de
suscripción.
PyTypeObject PyCallIter_Type
Part of the Stable ABI. Objeto tipo para los objetos iteradores retornados por PyCallIter_New() y la
forma de dos argumentos de la función incorporada iter().
int PyCallIter_Check(PyObject *op)
Retorna verdadero si el tipo de op es PyCallIter_Type. Esta función siempre finaliza con éxito.
PyObject *PyCallIter_New(PyObject *callable, PyObject *sentinel)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo iterador. El primer parámetro, callable,
puede ser cualquier objeto invocable de Python que se pueda invocar sin parámetros; cada llamada debe retornar
el siguiente elemento en la iteración. Cuando callable retorna un valor igual a sentinel, la iteración finalizará.
Los «descriptores» son objetos que describen algún atributo de un objeto. Se encuentran en el diccionario de objetos
tipo.
PyTypeObject PyProperty_Type
Part of the Stable ABI. El objeto de tipo para los tipos de descriptor incorporado.
PyObject *PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)
Return value: New reference. Part of the Stable ABI.
PyObject *PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)
Return value: New reference.
PyObject *PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
Return value: New reference. Part of the Stable ABI.
int PyDescr_IsData(PyObject *descr)
Retorna distinto de cero si el descriptor objetos descr describe un atributo de datos, o 0 si describe un método.
descr debe ser un objeto descriptor; no hay comprobación de errores.
PyObject *PyWrapper_New(PyObject*, PyObject*)
Return value: New reference. Part of the Stable ABI.
PyTypeObject PySlice_Type
Part of the Stable ABI. El objeto tipo para objetos rebanadas. Esto es lo mismo que slice en la capa de
Python.
int PySlice_Check(PyObject *ob)
Retorna verdadero si ob es un objeto rebanada; ob no debe ser NULL. Esta función siempre finaliza con éxito.
PyObject *PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
Return value: New reference. Part of the Stable ABI. Retorna un nuevo objeto rebanada con los valores da-
dos. Los parámetros start, stop y step se utilizan como los valores de los atributos del objeto rebanada de los
mismos nombres. Cualquiera de los valores puede ser NULL, en cuyo caso se usará None para el atributo
correspondiente. Retorna NULL si no se puedo asignar el nuevo objeto.
int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t
*step)
Part of the Stable ABI. Recupera los índices start, stop y step del objeto rebanada slice, suponiendo una secuencia
de longitud length. Trata los índices mayores que length como errores.
Returns 0 on success and -1 on error with no exception set (unless one of the indices was not None and failed
to be converted to an integer, in which case -1 is returned with an exception set).
Probablemente no quiera usar esta función.
Distinto en la versión 3.2: El tipo de parámetro para el parámetro slice era PySliceObject* antes.
int PySlice_GetIndicesEx(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t
*step, Py_ssize_t *slicelength)
Part of the Stable ABI. Reemplazo utilizable para PySlice_GetIndices(). Recupera los índices de start,
stop, y step del objeto rebanada slice asumiendo una secuencia de longitud length, y almacena la longitud de
la rebanada en slicelength. Los índices fuera de los límites se recortan de manera coherente con el manejo de
sectores normales.
Retorna 0 en caso de éxito y -1 en caso de error con excepción establecida.
Nota: Esta función se considera no segura para secuencias redimensionables. Su invocación debe ser reem-
plazada por una combinación de PySlice_Unpack() y PySlice_AdjustIndices() donde:
// return error
}
es reemplazado por:
Distinto en la versión 3.2: El tipo de parámetro para el parámetro slice era PySliceObject* antes.
Distinto en la versión 3.6.1: Si Py_LIMITED_API no se establece o establece el valor entre 0x03050400 y
0x03060000 (sin incluir) o 0x03060100 o un superior PySlice_GetIndicesEx() se implementa
como un macro usando PySlice_Unpack() y PySlice_AdjustIndices(). Los argumentos start,
stop y step se evalúan más de una vez.
Obsoleto desde la versión 3.6.1: Si Py_LIMITED_API se establece en un valor menor que 0x03050400 o
entre 0x03060000 y 0x03060100 (sin incluir) PySlice_GetIndicesEx() es una función obsoleta.
Objeto elipsis
PyObject *Py_Ellipsis
The Python Ellipsis object. This object has no methods. Like Py_None, it is an immortal. singleton
object.
Distinto en la versión 3.12: Py_Ellipsis is immortal.
Un objeto memoryview expone la interfaz de búfer a nivel de C como un objeto Python que luego puede pasarse
como cualquier otro objeto.
PyObject *PyMemoryView_FromObject(PyObject *obj)
Return value: New reference. Part of the Stable ABI. Crea un objeto de vista de memoria memoryview a partir
de un objeto que proporciona la interfaz del búfer. Si obj admite exportaciones de búfer de escritura, el objeto
de vista de memoria será de lectura/escritura, de lo contrario puede ser de solo lectura o de lectura/escritura a
discreción del exportador.
PyBUF_READ
Flag to request a readonly buffer.
PyBUF_WRITE
Flag to request a writable buffer.
PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)
Return value: New reference. Part of the Stable ABI since version 3.7. Crea un objeto de vista de memoria
usando mem como el búfer subyacente. flags pueden ser uno de PyBUF_READ o PyBUF_WRITE.
Added in version 3.3.
PyObject *PyMemoryView_FromBuffer(const Py_buffer *view)
Return value: New reference. Part of the Stable ABI since version 3.11. Crea un objeto de vista de
memoria que ajuste la estructura de búfer dada view. Para memorias intermedias de bytes simples,
PyMemoryView_FromMemory() es la función preferida.
PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
Return value: New reference. Part of the Stable ABI. Crea un objeto de vista de memoria memoryview para
un fragmento de memoria contiguo (contiguous, en order “C” o “F” de Fortran) desde un objeto que define la
interfaz del búfer. Si la memoria es contigua, el objeto de vista de memoria apunta a la memoria original. De
lo contrario, se realiza una copia y la vista de memoria apunta a un nuevo objeto de bytes.
Python soporta referencias débiles como objetos de primera clase. Hay dos tipos de objetos específicos que imple-
mentan directamente referencias débiles. El primero es un objeto con referencia simple, y el segundo actúa como un
proxy del objeto original tanto como pueda.
int PyWeakref_Check(PyObject *ob)
Retorna verdadero (true) si ob es una referencia o un objeto proxy. Esta función siempre finaliza con éxito.
int PyWeakref_CheckRef(PyObject *ob)
Retorna verdadero (true) si ob es un objeto de referencia. Esta función siempre finaliza con éxito.
int PyWeakref_CheckProxy(PyObject *ob)
Retorna verdadero (true) si ob es un objeto proxy. Esta función siempre finaliza con éxito.
PyObject *PyWeakref_NewRef(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference object for the object ob. This
will always return a new reference, but is not guaranteed to create a new object; an existing reference object
may be returned. The second parameter, callback, can be a callable object that receives notification when ob is
garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback
may also be None or NULL. If ob is not a weakly referenceable object, or if callback is not callable, None, or
NULL, this will return NULL and raise TypeError.
PyObject *PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
Return value: New reference. Part of the Stable ABI. Return a weak reference proxy object for the object ob.
This will always return a new reference, but is not guaranteed to create a new object; an existing proxy object
may be returned. The second parameter, callback, can be a callable object that receives notification when ob is
garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback
may also be None or NULL. If ob is not a weakly referenceable object, or if callback is not callable, None, or
NULL, this will return NULL and raise TypeError.
PyObject *PyWeakref_GetObject(PyObject *ref)
Return value: Borrowed reference. Part of the Stable ABI. Return the referenced object from a weak reference,
ref. If the referent is no longer live, returns Py_None.
Nota: Esta función retorna una referencia borrowed reference al objeto referenciado. Esto significa que siempre
debe llamar a Py_INCREF() sobre el objeto, excepto cuando no pueda ser destruido antes del último uso de
la referencia prestada.
8.6.8 Cápsulas
Consulta using-capsules para obtener más información sobre el uso de estos objetos.
Added in version 3.1.
type PyCapsule
Este subtipo de PyObject representa un valor opaco, útil para los módulos de extensión C que necesitan
pasar un valor opaco (como un puntero void*) a través del código Python a otro código C . A menudo se usa
para hacer que un puntero de función C definido en un módulo esté disponible para otros módulos, por lo que
el mecanismo de importación regular se puede usar para acceder a las API C definidas en módulos cargados
dinámicamente.
type PyCapsule_Destructor
Part of the Stable ABI. El tipo de devolución de llamada de un destructor para una cápsula. Definido como:
type PyFrameObject
Part of the Limited API (as an opaque struct). La estructura C de los objetos utilizados para describir los objetos
del frame.
No hay miembros públicos en esta estructura.
Distinto en la versión 3.11: Los miembros de esta estructura se han eliminado de la API pública de C. Consulte
la entrada Novedades para más detalles.
Las funciones PyEval_GetFrame() y PyThreadState_GetFrame() pueden utilizarse para obtener un
objeto frame.
Véase también Reflexión.
PyTypeObject PyFrame_Type
The type of frame objects. It is the same object as types.FrameType in the Python layer.
Distinto en la versión 3.11: Previously, this type was only available after including <frameobject.h>.
int PyFrame_Check(PyObject *obj)
Return non-zero if obj is a frame object.
Distinto en la versión 3.11: Previously, this function was only available after including <frameobject.h>.
PyFrameObject *PyFrame_GetBack(PyFrameObject *frame)
Obtiene el frame exterior siguiente.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Added in version 3.9.
PyObject *PyFrame_GetBuiltins(PyFrameObject *frame)
Get the frame’s f_builtins attribute.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Added in version 3.11.
PyCodeObject *PyFrame_GetCode(PyFrameObject *frame)
Part of the Stable ABI since version 3.10. Obtenga el código frame.
Retorna un strong reference.
El resultado (frame code) no puede ser NULL.
Added in version 3.9.
PyObject *PyFrame_GetGenerator(PyFrameObject *frame)
Obtiene el generador, rutina o generador asíncrono al que pertenece este frame, o NULL si este frame no es
propiedad de un generador. No lanza una excepción, incluso si el valor de retorno es NULL.
Retorna un strong reference, o NULL.
Added in version 3.11.
PyObject *PyFrame_GetGlobals(PyFrameObject *frame)
Get the frame’s f_globals attribute.
Retorna una strong reference, o NULL si frame no tiene frame exterior.
Added in version 3.11.
int PyFrame_GetLasti(PyFrameObject *frame)
Get the frame’s f_lasti attribute.
Retorna -1 si frame.f_lasti es None.
Added in version 3.11.
Internal Frames
Los objetos generadores son lo que Python usa para implementar iteradores generadores. Normalmente se
crean iterando sobre una función que produce valores, en lugar de llamar explícitamente PyGen_New() o
PyGen_NewWithQualName().
type PyGenObject
La estructura en C utilizada para los objetos generadores.
PyTypeObject PyGen_Type
El objeto tipo correspondiente a los objetos generadores.
int PyGen_Check(PyObject *ob)
Retorna verdadero si ob es un objeto generador; ob no debe ser NULL. Esta función siempre finaliza con éxito.
int PyGen_CheckExact(PyObject *ob)
Retorna verdadero si el tipo de ob es PyGen_Type; ob no debe ser NULL. Esta función siempre finaliza con
éxito.
PyObject *PyGen_New(PyFrameObject *frame)
Return value: New reference. Crea y retorna un nuevo objeto generador basado en el objeto frame. Una refe-
rencia a frame es robada por esta función. El argumento no debe ser NULL.
PyObject *PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname)
Return value: New reference. Crea y retorna un nuevo objeto generador basado en el objeto frame, con
__name__ y __qualname__ establecido en name y qualname. Una referencia a frame es robada por
esta función. El argumento frame no debe ser NULL.
Nota: En Python 3.7.1, las firmas de todas las variables de contexto C APIs fueron cambiadas para usar punteros
PyObject en lugar de PyContext, PyContextVar, y PyContextToken, por ejemplo:
// in 3.7.0:
PyContext *PyContext_New(void);
// in 3.7.1+:
PyObject *PyContext_New(void);
Various date and time objects are supplied by the datetime module. Before using any of these functions, the header
file datetime.h must be included in your source (note that this is not included by Python.h), and the macro
PyDateTime_IMPORT must be invoked, usually as part of the module initialisation function. The macro puts a
pointer to a C structure into a static variable, PyDateTimeAPI, that is used by the following macros.
type PyDateTime_Date
This subtype of PyObject represents a Python date object.
type PyDateTime_DateTime
This subtype of PyObject represents a Python datetime object.
type PyDateTime_Time
This subtype of PyObject represents a Python time object.
type PyDateTime_Delta
This subtype of PyObject represents the difference between two datetime values.
PyTypeObject PyDateTime_DateType
This instance of PyTypeObject represents the Python date type; it is the same object as datetime.date
in the Python layer.
PyTypeObject PyDateTime_DateTimeType
This instance of PyTypeObject represents the Python datetime type; it is the same object as datetime.
datetime in the Python layer.
PyTypeObject PyDateTime_TimeType
This instance of PyTypeObject represents the Python time type; it is the same object as datetime.time
in the Python layer.
PyTypeObject PyDateTime_DeltaType
This instance of PyTypeObject represents Python type for the difference between two datetime values; it
is the same object as datetime.timedelta in the Python layer.
PyTypeObject PyDateTime_TZInfoType
This instance of PyTypeObject represents the Python time zone info type; it is the same object as
datetime.tzinfo in the Python layer.
Macro para acceder al singleton UTC:
PyObject *PyDateTime_TimeZone_UTC
Retorna la zona horaria singleton que representa UTC, el mismo objeto que datetime.timezone.utc.
Added in version 3.7.
Macros de verificación de tipo:
int PyDate_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DateType or a subtype of PyDateTime_DateType. ob must
not be NULL. This function always succeeds.
int PyDate_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_DateType. ob no debe ser NULL. Esta función siempre
finaliza con éxito.
int PyDateTime_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DateTimeType or a subtype of
PyDateTime_DateTimeType. ob must not be NULL. This function always succeeds.
int PyDateTime_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_DateTimeType. ob no debe ser NULL. Esta función
siempre finaliza con éxito.
int PyTime_Check(PyObject *ob)
Return true if ob is of type PyDateTime_TimeType or a subtype of PyDateTime_TimeType. ob must
not be NULL. This function always succeeds.
int PyTime_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_TimeType. ob no debe ser NULL. Esta función siempre
finaliza con éxito.
int PyDelta_Check(PyObject *ob)
Return true if ob is of type PyDateTime_DeltaType or a subtype of PyDateTime_DeltaType. ob
must not be NULL. This function always succeeds.
int PyDelta_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_DeltaType. ob no debe ser NULL. Esta función siempre
finaliza con éxito.
int PyTZInfo_Check(PyObject *ob)
Return true if ob is of type PyDateTime_TZInfoType or a subtype of PyDateTime_TZInfoType.
ob must not be NULL. This function always succeeds.
int PyTZInfo_CheckExact(PyObject *ob)
Retorna verdadero si ob es de tipo PyDateTime_TZInfoType. ob no debe ser NULL. Esta función siempre
finaliza con éxito.
Macros para crear objetos:
PyObject *PyDate_FromDate(int year, int month, int day)
Return value: New reference. Retorna un objeto datetime.date con el año, mes y día especificados.
PyObject *PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int
usecond)
Return value: New reference. Retorna un objeto datetime.datetime con el año, mes, día, hora, minuto,
segundo y micro segundo especificados.
PyObject *PyDateTime_FromDateAndTimeAndFold(int year, int month, int day, int hour, int minute, int
second, int usecond, int fold)
Return value: New reference. Retorna un objeto datetime.datetime con el año, mes, día, hora, minuto,
segundo, micro segundo y doblez especificados.
Added in version 3.6.
PyObject *PyTime_FromTime(int hour, int minute, int second, int usecond)
Return value: New reference. Retorna un objeto datetime.time con la hora, minuto, segundo y micro
segundo especificados.
PyObject *PyTime_FromTimeAndFold(int hour, int minute, int second, int usecond, int fold)
Return value: New reference. Retorna un objeto datetime.time con la hora, minuto, segundo, micro se-
gundo y doblez especificados.
Added in version 3.6.
PyObject *PyDelta_FromDSU(int days, int seconds, int useconds)
Return value: New reference. Retorna un objeto datetime.timedelta que representa el número dado
de días, segundos y micro segundos. La normalización se realiza de modo que el número resultante de micro
segundos y segundos se encuentre en los rangos documentados para los objetos datetime.timedelta.
PyObject *PyTimeZone_FromOffset(PyObject *offset)
Return value: New reference. Retorna un objeto datetime.timezone con un desplazamiento fijo sin nom-
bre representado por el argumento offset.
Added in version 3.7.
PyObject *PyTimeZone_FromOffsetAndName(PyObject *offset, PyObject *name)
Return value: New reference. Retorna un objeto datetime.timezone con un desplazamiento fijo repre-
sentado por el argumento offset y con tzname name.
Added in version 3.7.
Macros to extract fields from date objects. The argument must be an instance of PyDateTime_Date, including
subclasses (such as PyDateTime_DateTime). The argument must not be NULL, and the type is not checked:
int PyDateTime_GET_YEAR(PyDateTime_Date *o)
Regrese el año, como un int positivo.
int PyDateTime_GET_MONTH(PyDateTime_Date *o)
Regresa el mes, como int del 1 al 12.
int PyDateTime_GET_DAY(PyDateTime_Date *o)
Retorna el día, como int del 1 al 31.
Macros to extract fields from datetime objects. The argument must be an instance of PyDateTime_DateTime,
including subclasses. The argument must not be NULL, and the type is not checked:
int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)
Retorna la hora, como un int de 0 hasta 23.
int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)
Retorna el minuto, como un int de 0 hasta 59.
int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)
Retorna el segundo, como un int de 0 hasta 59.
Se proporcionan varios tipos incorporados para indicaciones de tipado. Actualmente existen dos tipos – GenericAlias
y Union. Solo GenericAlias es expuesto a C.
PyObject *Py_GenericAlias(PyObject *origin, PyObject *args)
Part of the Stable ABI since version 3.9. Create a GenericAlias object. Equivalent to calling the Python
class types.GenericAlias. The origin and args arguments set the GenericAlias“s __origin__
and __args__ attributes respectively. origin should be a PyTypeObject*, and args can be a
PyTupleObject* or any PyObject*. If args passed is not a tuple, a 1-tuple is automatically constructed
and __args__ is set to (args,). Minimal checking is done for the arguments, so the function will succeed
even if origin is not a type. The GenericAlias“s __parameters__ attribute is constructed lazily from
__args__. On failure, an exception is raised and NULL is returned.
Aquí hay un ejemplo sobre cómo hacer un tipo de extensión genérica:
...
static PyMethodDef my_obj_methods[] = {
// Other methods.
...
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}
...
}
Ver también:
The data model method __class_getitem__().
Added in version 3.9.
PyTypeObject Py_GenericAliasType
Part of the Stable ABI since version 3.9. El tipo en C del objeto retornado por Py_GenericAlias().
Equivalente a types.GenericAlias en Python.
Added in version 3.9.
En una aplicación que incorpora Python, se debe llamar a la función Py_Initialize() antes de usar cualquier
otra función de API Python/C; con la excepción de algunas funciones y variables de configuración global.
Las siguientes funciones se pueden invocar de forma segura antes de que se inicializa Python:
• Funciones de configuración:
– PyImport_AppendInittab()
– PyImport_ExtendInittab()
– PyInitFrozenExtensions()
– PyMem_SetAllocator()
– PyMem_SetupDebugHooks()
– PyObject_SetArenaAllocator()
– Py_SetPath()
– Py_SetProgramName()
– Py_SetPythonHome()
– Py_SetStandardStreamEncoding()
– PySys_AddWarnOption()
– PySys_AddXOption()
– PySys_ResetWarnOptions()
• Funciones informativas:
– Py_IsInitialized()
– PyMem_GetAllocator()
– PyObject_GetArenaAllocator()
193
The Python/C API, Versión 3.12.4
– Py_GetBuildInfo()
– Py_GetCompiler()
– Py_GetCopyright()
– Py_GetPlatform()
– Py_GetVersion()
• Utilidades:
– Py_DecodeLocale()
• Asignadores de memoria:
– PyMem_RawMalloc()
– PyMem_RawRealloc()
– PyMem_RawCalloc()
– PyMem_RawFree()
Python tiene variables para la configuración global para controlar diferentes características y opciones. De forma
predeterminada, estos indicadores están controlados por opciones de línea de comando.
Cuando una opción establece un indicador, el valor del indicador es la cantidad de veces que se configuró la opción.
Por ejemplo, -b establece Py_BytesWarningFlag en 1 y -bb establece Py_BytesWarningFlag en 2.
int Py_BytesWarningFlag
This API is kept for backward compatibility: setting PyConfig.bytes_warning should be used instead,
see Python Initialization Configuration.
Emite una advertencia al comparar bytes o bytearray con str o bytes con int. Emite un error si es
mayor o igual a 2.
Establecido por la opción -b.
Obsoleto desde la versión 3.12.
int Py_DebugFlag
This API is kept for backward compatibility: setting PyConfig.parser_debug should be used instead,
see Python Initialization Configuration.
Activa la salida de depuración del analizador (solo para expertos, según las opciones de compilación).
Establecido por la opción -d y la variable de entorno PYTHONDEBUG.
Obsoleto desde la versión 3.12.
int Py_DontWriteBytecodeFlag
This API is kept for backward compatibility: setting PyConfig.write_bytecode should be used instead,
see Python Initialization Configuration.
Si se establece en un valor distinto de cero, Python no intentará escribir archivos .pyc en la importación de
módulos fuente.
Establecido por la opción -B y la variable de entorno PYTHONDONTWRITEBYTECODE.
int Py_LegacyWindowsFSEncodingFlag
This API is kept for backward compatibility: setting PyPreConfig.
legacy_windows_fs_encoding should be used instead, see Python Initialization Configuration.
Si la bandera no es cero, utilice la codificación mbcs con el gestor de errores replace en lugar de la co-
dificación UTF-8 con el gestor de error surrogatepass, para la filesystem encoding and error handler
(codificación del sistema de archivos y gestor de errores).
Establece en 1 si la variable de entorno PYTHONLEGACYWINDOWSFSENCODING está configurada en una
cadena de caracteres no vacía.
Ver PEP 529 para más detalles.
Disponibilidad: Windows.
Obsoleto desde la versión 3.12.
int Py_LegacyWindowsStdioFlag
This API is kept for backward compatibility: setting PyConfig.legacy_windows_stdio should be
used instead, see Python Initialization Configuration.
If the flag is non-zero, use io.FileIO instead of io._WindowsConsoleIO for sys standard streams.
Establece en 1 si la variable de entorno PYTHONLEGACYWINDOWSSTDIO está configurada en una cadena
de caracteres no vacía.
Ver PEP 528 para más detalles.
Disponibilidad: Windows.
Obsoleto desde la versión 3.12.
int Py_NoSiteFlag
This API is kept for backward compatibility: setting PyConfig.site_import should be used instead,
see Python Initialization Configuration.
Deshabilita la importación del módulo site y las manipulaciones dependientes del sitio de sys.path que
conlleva. También deshabilita estas manipulaciones si site se importa explícitamente más tarde (llama a
site.main() si desea que se activen).
Establecido por la opción -S.
Obsoleto desde la versión 3.12.
int Py_NoUserSiteDirectory
This API is kept for backward compatibility: setting PyConfig.user_site_directory should be used
instead, see Python Initialization Configuration.
No agregue el directorio de paquetes de sitio del usuario (site-packages) a sys.
path.
Establecido por las opciones -s y -I, y la variable de entorno PYTHONNOUSERSITE.
Obsoleto desde la versión 3.12.
int Py_OptimizeFlag
This API is kept for backward compatibility: setting PyConfig.optimization_level should be used
instead, see Python Initialization Configuration.
Establecido por la opción -O y la variable de entorno PYTHONOPTIMIZE.
Obsoleto desde la versión 3.12.
int Py_QuietFlag
This API is kept for backward compatibility: setting PyConfig.quiet should be used instead, see Python
Initialization Configuration.
No muestre los mensajes de copyright y de versión incluso en modo interactivo.
void Py_Initialize()
Part of the Stable ABI. Inicializa el intérprete de Python. En una aplicación que incorpora Python, se debe
llamar antes de usar cualquier otra función de API Python/C; vea Antes de la inicialización de Python para ver
algunas excepciones.
Esto inicializa la tabla de módulos cargados (sys.modules) y crea los módulos fundamentales builtins,
__main__ y sys. También inicializa la ruta de búsqueda del módulo (sys.path). No establece sys.
argv; use PySys_SetArgvEx() para eso. Este es un no-op cuando se llama por segunda vez (sin llamar
primero a Py_FinalizeEx()). No hay valor de retorno; es un error fatal si falla la inicialización.
Use the Py_InitializeFromConfig() function to customize the Python Initialization Configuration.
Nota: En Windows, cambia el modo de consola de O_TEXT a O_BINARY, lo que también afectará los usos
de la consola que no sean de Python utilizando C Runtime.
Python. Este es un no-op cuando se llama por segunda vez (sin llamar a Py_Initialize() nuevamente
primero). Normalmente el valor de retorno es 0. Si hubo errores durante la finalización (lavado de datos
almacenados en el búfer), se retorna -1.
Esta función se proporciona por varias razones. Una aplicación de incrustación puede querer reiniciar Python
sin tener que reiniciar la aplicación misma. Una aplicación que ha cargado el intérprete de Python desde una
biblioteca cargable dinámicamente (o DLL) puede querer liberar toda la memoria asignada por Python antes
de descargar la DLL. Durante una búsqueda de pérdidas de memoria en una aplicación, un desarrollador puede
querer liberar toda la memoria asignada por Python antes de salir de la aplicación.
Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause
destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules.
Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated
by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular
references between objects is not freed. Some memory allocated by extension modules may not be freed. Some
extensions may not work properly if their initialization routine is called more than once; this can happen if an
application calls Py_Initialize() and Py_FinalizeEx() more than once.
Genera un evento de auditoría cpython._PySys_ClearAuditHooks sin argumentos.
Added in version 3.6.
void Py_Finalize()
Part of the Stable ABI. Esta es una versión compatible con versiones anteriores de Py_FinalizeEx() que
ignora el valor de retorno.
bibliotecas de tiempo de ejecución de Python relativas al ejecutable del intérprete. El valor predeterminado
es 'python'. El argumento debe apuntar a una cadena de caracteres anchos terminada en cero en almace-
namiento estático cuyo contenido no cambiará mientras dure la ejecución del programa. Ningún código en el
intérprete de Python cambiará el contenido de este almacenamiento.
Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.
Obsoleto desde la versión 3.11.
wchar_t *Py_GetProgramName()
Part of the Stable ABI. Retorna el nombre del programa establecido con Py_SetProgramName(), o el
valor predeterminado. La cadena de caracteres retornada apunta al almacenamiento estático; la persona que
llama no debe modificar su valor.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.
wchar_t *Py_GetPrefix()
Part of the Stable ABI. Return the prefix for installed platform-independent files. This is derived through a
number of complicated rules from the program name set with Py_SetProgramName() and some environ-
ment variables; for example, if the program name is '/usr/local/bin/python', the prefix is '/usr/
local'. The returned string points into static storage; the caller should not modify its value. This corresponds
to the prefix variable in the top-level Makefile and the --prefix argument to the configure script
at build time. The value is available to Python code as sys.prefix. It is only useful on Unix. See also the
next function.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.
wchar_t *Py_GetExecPrefix()
Part of the Stable ABI. Retorna el exec-prefix para los archivos instalados dependientes de la platafor-
ma. Esto se deriva a través de una serie de reglas complicadas del nombre del programa establecido con
Py_SetProgramName() y algunas variables de entorno; por ejemplo, si el nombre del programa es '/
usr/local/bin/python', el prefijo exec es '/usr/local'. La cadena de caracteres retornada apun-
ta al almacenamiento estático; la persona que llama no debe modificar su valor. Esto corresponde a la variable
exec_prefix en el archivo de nivel superior Makefile y el argumento --exec-prefix a la secuen-
cia de comandos (script) configure en tiempo de compilación. El valor está disponible para el código de
Python como sys.exec_prefix. Solo es útil en Unix.
Antecedentes: el prefijo exec difiere del prefijo cuando los archivos dependientes de la plataforma (como eje-
cutables y bibliotecas compartidas) se instalan en un árbol de directorios diferente. En una instalación típica,
los archivos dependientes de la plataforma pueden instalarse en el subárbol /usr/local/plat mientras
que la plataforma independiente puede instalarse en /usr/local.
En términos generales, una plataforma es una combinación de familias de hardware y software, por ejemplo,
las máquinas Sparc que ejecutan el sistema operativo Solaris 2.x se consideran la misma plataforma, pero las
máquinas Intel que ejecutan Solaris 2.x son otra plataforma, y las máquinas Intel que ejecutan Linux son otra
plataforma más. Las diferentes revisiones importantes del mismo sistema operativo generalmente también for-
man plataformas diferentes. Los sistemas operativos que no son Unix son una historia diferente; Las estrategias
de instalación en esos sistemas son tan diferentes que el prefijo y el prefijo exec no tienen sentido y se configu-
ran en la cadena vacía. Tenga en cuenta que los archivos de bytecode compilados de Python son independientes
de la plataforma (¡pero no independientes de la versión de Python con la que fueron compilados!).
Los administradores de sistemas sabrán cómo configurar los programas mount o automount para compartir
/usr/local entre plataformas mientras que /usr/local/plat sea un sistema de archivos diferente
para cada plataforma.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.
wchar_t *Py_GetProgramFullPath()
Part of the Stable ABI. Retorna el nombre completo del programa del ejecutable de Python; esto se calcula co-
mo un efecto secundario de derivar la ruta de búsqueda predeterminada del módulo del nombre del programa
(establecido por Py_SetProgramName() arriba). La cadena de caracteres retornada apunta al almacena-
miento estático; la persona que llama no debe modificar su valor. El valor está disponible para el código de
Python como sys.executable.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.
wchar_t *Py_GetPath()
Part of the Stable ABI. Retorna la ruta de búsqueda del módulo predeterminado; esto se calcula a partir del
nombre del programa (establecido por Py_SetProgramName() antes mencionado) y algunas variables de
entorno. La cadena de caracteres retornada consiste en una serie de nombres de directorio separados por un
carácter delimitador dependiente de la plataforma. El carácter delimitador es ':' en Unix y macOS, ';'
en Windows. La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no
debe modificar su valor. La lista sys.path se inicializa con este valor en el inicio del intérprete; se puede (y
generalmente se realiza) modificar más adelante para cambiar la ruta de búsqueda para cargar módulos.
Esta función ya no se puede llamar antes de Py_Initialize(), de otra forma retornará NULL.
Distinto en la versión 3.10: Todas las siguientes funciones deben llamarse después de Py_Initialize(),
de lo contrario retornará NULL.
void Py_SetPath(const wchar_t*)
Part of the Stable ABI since version 3.7. Esta API se mantiene para la compatibilidad con versiones anterio-
res: en su lugar, se debe usar la configuración de PyConfig.module_search_paths y PyConfig.
module_search_paths_set, consulta Configuración de inicialización de Python.
Establece la ruta de búsqueda del módulo predeterminado. Si se llama a esta función antes de
Py_Initialize(), entonces Py_GetPath() no intentará computar una ruta de búsqueda predetermi-
nada, sino que utilizará la proporcionada en su lugar. Esto es útil si Python está incrustado por una aplicación
que tiene pleno conocimiento de la ubicación de todos los módulos. Los componentes de la ruta deben estar
separados por el carácter delimitador dependiente de la plataforma, el cual es ':' en Unix y macOS, ';' en
Windows.
Esto también hace que sys.executable se configure en la ruta completa del programa (consulte
Py_GetProgramFullPath()) y para sys.prefix y sys.exec_prefix a estar vacío. Depende
de la persona que llama modificarlos si es necesario después de llamar Py_Initialize().
Utilice Py_DecodeLocale() para decodificar una cadena de bytes para obtener una cadena de tipo
wchar_*.
El argumento de ruta se copia internamente, por lo que la persona que llama puede liberarlo después de que se
complete la llamada.
Distinto en la versión 3.8: La ruta completa del programa ahora se usa para sys.executable, en lugar del
nombre del programa.
Obsoleto desde la versión 3.11.
const char *Py_GetVersion()
Part of the Stable ABI. Retorna la versión de este intérprete de Python. Esta es una cadena de caracteres que
se parece a
"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"
La primera palabra (hasta el primer carácter de espacio) es la versión actual de Python; los primeros tres
caracteres son la versión mayor y menor separados por un punto. La cadena de caracteres retornada apunta
al almacenamiento estático; la persona que llama no debe modificar su valor. El valor está disponible para el
código Python como sys.version.
Consulta también la constante Py_Version.
"[GCC 2.7.2.2]"
La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no debe modificar
su valor. El valor está disponible para el código Python como parte de la variable sys.version.
const char *Py_GetBuildInfo()
Part of the Stable ABI. Retorna información sobre el número de secuencia y la fecha y hora de compilación de
la instancia actual de intérprete de Python, por ejemplo:
La cadena de caracteres retornada apunta al almacenamiento estático; la persona que llama no debe modificar
su valor. El valor está disponible para el código Python como parte de la variable sys.version.
void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Part of the Stable ABI. Esta API se mantiene para la compatibilidad con versiones anteriores: en su lugar, se de-
be usar la configuración de PyConfig.argv, PyConfig.parse_argv y PyConfig.safe_path,
consulta Configuración de inicialización de Python.
Establece sys.argv basado en argc y argv. Estos parámetros son similares a los pasados a la función del
programa main() con la diferencia de que la primera entrada debe referirse al archivo de la secuencia de
comandos (script) que se ejecutará en lugar del ejecutable que aloja el intérprete de Python. Si no se ejecuta
una secuencia de comandos (script), la primera entrada en argv puede ser una cadena de caracteres vacía. Si
esta función no puede inicializar sys.argv, una condición fatal se señala usando Py_FatalError().
Si updatepath es cero, esto es todo lo que hace la función. Si updatepath no es cero, la función también modifica
sys.path de acuerdo con el siguiente algoritmo:
• Si el nombre de una secuencia de comandos (script) existente se pasa en argv[0], la ruta absoluta del
directorio donde se encuentra el script se antepone a sys.path.
• De lo contrario (es decir, si argc es 0 o argv[0] no apunta a un nombre de archivo existente), una
cadena de caracteres vacía se antepone a sys.path, que es lo mismo que anteponer el directorio de
trabajo actual (".").
Utilice Py_DecodeLocale() para decodificar una cadena de bytes para obtener una cadena de tipo
wchar_*.
Consulta también los miembros de PyConfig.orig_argv y PyConfig.argv de Python Initialization
Configuration.
Nota: It is recommended that applications embedding the Python interpreter for purposes other than executing
a single script pass 0 as updatepath, and update sys.path themselves if desired. See CVE-2008-5983.
En las versiones anteriores a 3.1.3, puede lograr el mismo efecto quitando manualmente el primer elemento
(popping) sys.path después de haber llamado PySys_SetArgv(), por ejemplo usando
El intérprete de Python no es completamente seguro para hilos (thread-safe). Para admitir programas Python multi-
proceso, hay un bloqueo global, denominado global interpreter lock o GIL, que debe mantener el hilo actual antes de
que pueda acceder de forma segura a los objetos Python. Sin el bloqueo, incluso las operaciones más simples podrían
causar problemas en un programa de hilos múltiples: por ejemplo, cuando dos hilos incrementan simultáneamente el
conteo de referencias del mismo objeto, el conteo de referencias podría terminar incrementándose solo una vez en
lugar de dos veces.
Por lo tanto, existe la regla de que solo el hilo que ha adquirido GIL puede operar en objetos Python o llamar a fun-
ciones API Python/C. Para emular la concurrencia de ejecución, el intérprete regularmente intenta cambiar los hilos
(ver sys.setswitchinterval()). El bloqueo también se libera para bloquear potencialmente las operaciones
de E/S, como leer o escribir un archivo, para que otros hilos de Python puedan ejecutarse mientras tanto.
El intérprete de Python mantiene cierta información de contabilidad específica de hilos dentro de una estructura de
datos llamada PyThreadState. También hay una variable global que apunta a la actual PyThreadState: se
puede recuperar usando PyThreadState_Get().
La mayoría del código de extensión que manipula el GIL tiene la siguiente estructura simple
Py_BEGIN_ALLOW_THREADS
... Do some blocking I/O operation ...
Py_END_ALLOW_THREADS
La macro Py_BEGIN_ALLOW_THREADS abre un nuevo bloque y declara una variable local oculta; la macro
Py_END_ALLOW_THREADS cierra el bloque.
El bloque anterior se expande al siguiente código:
PyThreadState *_save;
_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
PyEval_RestoreThread(_save);
Así es como funcionan estas funciones: el bloqueo global del intérprete se usa para proteger el puntero al estado actual
del hilo. Al liberar el bloqueo y guardar el estado del hilo, el puntero del estado del hilo actual debe recuperarse antes
de que se libere el bloqueo (ya que otro hilo podría adquirir inmediatamente el bloqueo y almacenar su propio estado
de hilo en la variable global). Por el contrario, al adquirir el bloqueo y restaurar el estado del hilo, el bloqueo debe
adquirirse antes de almacenar el puntero del estado del hilo.
Nota: Llamar a las funciones de E/S del sistema es el caso de uso más común para liberar el GIL, pero también
puede ser útil antes de llamar a cálculos de larga duración que no necesitan acceso a objetos de Python, como las
funciones de compresión o criptográficas que operan sobre memorias intermedias. Por ejemplo, los módulos estándar
zlib y hashlib liberan el GIL al comprimir o mezclar datos.
Cuando se crean hilos utilizando las API dedicadas de Python (como el módulo threading), se les asocia auto-
máticamente un estado del hilo y, por lo tanto, el código que se muestra arriba es correcto. Sin embargo, cuando
los hilos se crean desde C (por ejemplo, por una biblioteca de terceros con su propia administración de hilos), no
contienen el GIL, ni existe una estructura de estado de hilos para ellos.
Si necesita llamar al código Python desde estos subprocesos (a menudo esto será parte de una API de devolución
de llamada proporcionada por la biblioteca de terceros mencionada anteriormente), primero debe registrar estos
subprocesos con el intérprete creando una estructura de datos de estado del subproceso, luego adquiriendo el GIL, y
finalmente almacenando su puntero de estado de hilo, antes de que pueda comenzar a usar la API Python/C Cuando
haya terminado, debe restablecer el puntero del estado del hilo, liberar el GIL y finalmente liberar la estructura de
datos del estado del hilo.
Las funciones PyGILState_Ensure() y PyGILState_Release() hacen todo lo anterior automáticamen-
te. El idioma típico para llamar a Python desde un hilo C es:
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
Tenga en cuenta que las funciones PyGILState_* asumen que solo hay un intérprete global (creado
automáticamente por Py_Initialize()). Python admite la creación de intérpretes adicionales (usando
Py_NewInterpreter()), pero la mezcla de varios intérpretes y la API PyGILState_* no está soportada.
Otra cosa importante a tener en cuenta sobre los hilos es su comportamiento frente a la llamada C fork(). En la
mayoría de los sistemas con fork(), después de que un proceso se bifurca, solo existirá el hilo que emitió el fork.
Esto tiene un impacto concreto tanto en cómo se deben manejar las cerraduras como en todo el estado almacenado
en el tiempo de ejecución de CPython.
The fact that only the «current» thread remains means any locks held by other threads will never be released. Python
solves this for os.fork() by acquiring the locks it uses internally before the fork, and releasing them afterwards.
In addition, it resets any lock-objects in the child. When extending or embedding Python, there is no way to inform
Python of additional (non-Python) locks that need to be acquired before or reset after a fork. OS facilities such
as pthread_atfork() would need to be used to accomplish the same thing. Additionally, when extending or
embedding Python, calling fork() directly rather than through os.fork() (and returning to or calling into
Python) may result in a deadlock by one of Python’s internal locks being held by a thread that is defunct after the
fork. PyOS_AfterFork_Child() tries to reset the necessary locks, but is not always able to.
El hecho de que todos los otros hilos desaparezcan también significa que el estado de ejecución de CPython
debe limpiarse correctamente, lo que os.fork() lo hace. Esto significa finalizar todos los demás objetos
PyThreadState que pertenecen al intérprete actual y todos los demás objetos PyInterpreterState. De-
bido a esto y a la naturaleza especial del intérprete «principal», fork() solo debería llamarse en el hilo «principal»
de ese intérprete, donde el CPython global el tiempo de ejecución se inicializó originalmente. La única excepción es
si exec() se llamará inmediatamente después.
Estos son los tipos y funciones más utilizados al escribir código de extensión C o al incrustar el intérprete de Python:
type PyInterpreterState
Part of the Limited API (as an opaque struct). Esta estructura de datos representa el estado compartido por
varios subprocesos cooperantes. Los hilos que pertenecen al mismo intérprete comparten la administración de
su módulo y algunos otros elementos internos. No hay miembros públicos en esta estructura.
Los hilos que pertenecen a diferentes intérpretes inicialmente no comparten nada, excepto el estado del proceso
como memoria disponible, descriptores de archivos abiertos y demás. El bloqueo global del intérprete también
es compartido por todos los hilos, independientemente de a qué intérprete pertenezcan.
type PyThreadState
Part of the Limited API (as an opaque struct). This data structure represents the state of a single thread. The
only public data member is:
PyInterpreterState *interp
This thread’s interpreter state.
void PyEval_InitThreads()
Part of the Stable ABI. Función deprecada que no hace nada.
En Python 3.6 y versiones anteriores, esta función creaba el GIL si no existía.
Distinto en la versión 3.9: La función ahora no hace nada.
Distinto en la versión 3.7: Esta función ahora es llamada por Py_Initialize(), por lo que ya no tiene
que llamarla usted mismo.
Distinto en la versión 3.2: Esta función ya no se puede llamar antes de Py_Initialize().
Obsoleto desde la versión 3.9.
int PyEval_ThreadsInitialized()
Part of the Stable ABI. Retorna un valor distinto de cero si se ha llamado a PyEval_InitThreads().
Esta función se puede invocar sin mantener el GIL y, por lo tanto, se puede utilizar para evitar llamadas a la
API de bloqueo cuando se ejecuta un solo hilo.
Distinto en la versión 3.7: El término GIL ahora se inicializa con Py_Initialize().
Obsoleto desde la versión 3.9.
PyThreadState *PyEval_SaveThread()
Part of the Stable ABI. Libere el bloqueo global del intérprete (si se ha creado) y restablezca el estado del hilo
a NULL, retornando el estado del hilo anterior (que no es NULL). Si se ha creado el bloqueo, el hilo actual debe
haberlo adquirido.
void PyEval_RestoreThread(PyThreadState *tstate)
Part of the Stable ABI. Adquiera el bloqueo global del intérprete (si se ha creado) y establezca el estado del
hilo en tstate, que no debe ser NULL. Si se ha creado el bloqueo, el hilo actual no debe haberlo adquirido, de
lo contrario se produce un deadlock.
Nota: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to
check if the interpreter is in process of being finalized before calling this function to avoid unwanted termina-
tion.
PyThreadState *PyThreadState_Get()
Part of the Stable ABI. Retorna el estado actual del hilo. Se debe mantener el bloqueo global del intérprete.
Cuando el estado actual del hilo es NULL, esto genera un error fatal (por lo que la persona que llama no necesita
verificar NULL).
Nota: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to
check if the interpreter is in process of being finalized before calling this function to avoid unwanted termina-
tion.
void PyGILState_Release(PyGILState_STATE)
Part of the Stable ABI. Libera cualquier recurso previamente adquirido. Después de esta llamada, el estado de
Python será el mismo que antes de la llamada correspondiente PyGILState_Ensure() (pero en general
este estado será desconocido para la persona que llama, de ahí el uso de la API GILState).
Cada llamada a PyGILState_Ensure() debe coincidir con una llamada a PyGILState_Release()
en el mismo hilo.
PyThreadState *PyGILState_GetThisThreadState()
Part of the Stable ABI. Obtenga el estado actual del hilo para este hilo. Puede retornar NULL si no se ha utilizado
la API GILState en el hilo actual. Tenga en cuenta que el subproceso principal siempre tiene dicho estado
de subproceso, incluso si no se ha realizado una llamada de estado de subproceso automático en el subproceso
principal. Esta es principalmente una función auxiliar y de diagnóstico.
int PyGILState_Check()
Retorna 1 si el hilo actual mantiene el GIL y 0 de lo contrario. Esta función se puede llamar desde cualquier
hilo en cualquier momento. Solo si se ha inicializado el hilo de Python y actualmente mantiene el GIL, retornará
1. Esta es principalmente una función auxiliar y de diagnóstico. Puede ser útil, por ejemplo, en contextos de
devolución de llamada o funciones de asignación de memoria cuando saber que el GIL está bloqueado puede
permitir que la persona que llama realice acciones confidenciales o se comporte de otra manera de manera
diferente.
Added in version 3.4.
Las siguientes macros se usan normalmente sin punto y coma final; busque, por ejemplo, el uso en la distribución
fuente de Python.
Py_BEGIN_ALLOW_THREADS
Part of the Stable ABI. Esta macro se expande a {PyThreadState *_save; _save =
PyEval_SaveThread();. Tenga en cuenta que contiene una llave de apertura; debe coincidir con
la siguiente macro Py_END_ALLOW_THREADS. Ver arriba para una discusión más detallada de esta macro.
Py_END_ALLOW_THREADS
Part of the Stable ABI. Esta macro se expande a PyEval_RestoreThread(_save); }. Tenga en cuen-
ta que contiene una llave de cierre; debe coincidir con una macro anterior Py_BEGIN_ALLOW_THREADS.
Ver arriba para una discusión más detallada de esta macro.
Py_BLOCK_THREADS
Part of the Stable ABI. Esta macro se expande a PyEval_RestoreThread(_save);: es equivalente a
Py_END_ALLOW_THREADS sin la llave de cierre.
Py_UNBLOCK_THREADS
Part of the Stable ABI. Esta macro se expande a _save = PyEval_SaveThread();: es equivalente a
Py_BEGIN_ALLOW_THREADS sin la llave de apertura y la declaración de variable.
Nota: Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the
thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to
check if the interpreter is in process of being finalized before calling this function to avoid unwanted termina-
tion.
void PyEval_AcquireLock()
Part of the Stable ABI. Adquiera el bloqueo global de intérprete. El bloqueo debe haber sido creado anterior-
mente. Si este hilo ya tiene el bloqueo, se produce un deadlock.
Obsoleto desde la versión 3.2: Esta función no actualiza el estado actual del hilo. Utilice
PyEval_RestoreThread() o PyEval_AcquireThread() en su lugar.
Nota: Llamar a esta función desde un hilo cuando finalice el tiempo de ejecución terminará el hilo, incluso si
Python no creó el hilo. Puede usar _Py_IsFinalizing() o sys.is_finalizing() para verificar
si el intérprete está en proceso de finalización antes de llamar a esta función para evitar una terminación no
deseada.
Si bien en la mayoría de los usos, solo incrustará un solo intérprete de Python, hay casos en los que necesita crear varios
intérpretes independientes en el mismo proceso y tal vez incluso en el mismo hilo. Los subinterpretes le permiten hacer
eso.
El intérprete «principal» es el primero creado cuando se inicializa el tiempo de ejecución. Suele ser el único intérprete
de Python en un proceso. A diferencia de los subinterpretes, el intérprete principal tiene responsabilidades globales
de proceso únicas, como el manejo de señales. También es responsable de la ejecución durante la inicialización del
tiempo de ejecución y generalmente es el intérprete activo durante la finalización del tiempo de ejecución. La función
PyInterpreterState_Main() retorna un puntero a su estado.
Puede cambiar entre subinterpretes utilizando la función PyThreadState_Swap(). Puede crearlos y destruirlos
utilizando las siguientes funciones:
type PyInterpreterConfig
Structure containing most parameters to configure a sub-interpreter. Its values are used only in
Py_NewInterpreterFromConfig() and never modified by the runtime.
Added in version 3.12.
Structure fields:
int use_main_obmalloc
If this is 0 then the sub-interpreter will use its own «object» allocator state. Otherwise it will use (share)
the main interpreter’s.
If this is 0 then check_multi_interp_extensions must be 1 (non-zero). If this is 1 then gil
must not be PyInterpreterConfig_OWN_GIL.
int allow_fork
If this is 0 then the runtime will not support forking the process in any thread where the sub-interpreter
is currently active. Otherwise fork is unrestricted.
Note that the subprocess module still works when fork is disallowed.
int allow_exec
If this is 0 then the runtime will not support replacing the current process via exec (e.g. os.execv())
in any thread where the sub-interpreter is currently active. Otherwise exec is unrestricted.
Note that the subprocess module still works when exec is disallowed.
int allow_threads
If this is 0 then the sub-interpreter’s threading module won’t create threads. Otherwise threads are
allowed.
int allow_daemon_threads
If this is 0 then the sub-interpreter’s threading module won’t create daemon threads. Otherwise dae-
mon threads are allowed (as long as allow_threads is non-zero).
int check_multi_interp_extensions
If this is 0 then all extension modules may be imported, including legacy (single-phase init) modules,
in any thread where the sub-interpreter is currently active. Otherwise only multi-phase init extension
modules (see PEP 489) may be imported. (Also see Py_mod_multiple_interpreters.)
This must be 1 (non-zero) if use_main_obmalloc is 0.
int gil
This determines the operation of the GIL for the sub-interpreter. It may be one of the following:
PyInterpreterConfig_DEFAULT_GIL
Use the default selection (PyInterpreterConfig_SHARED_GIL).
PyInterpreterConfig_SHARED_GIL
Use (share) the main interpreter’s GIL.
PyInterpreterConfig_OWN_GIL
Use the sub-interpreter’s own GIL.
If this is PyInterpreterConfig_OWN_GIL then PyInterpreterConfig.
use_main_obmalloc must be 0.
PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)
Crea un nuevo subinterprete. Este es un entorno (casi) totalmente separado para la ejecución de código Python.
En particular, el nuevo intérprete tiene versiones separadas e independientes de todos los módulos importados,
incluidos los módulos fundamentales builtins, __main__ y sys. La tabla de módulos cargados (sys.
modules) y la ruta de búsqueda del módulo (sys.path) también están separados. El nuevo entorno no tiene
variable sys.argv. Tiene nuevos objetos de archivo de flujo de E/S estándar sys.stdin, sys.stdout
y sys.stderr (sin embargo, estos se refieren a los mismos descriptores de archivo subyacentes).
The given config controls the options with which the interpreter is initialized.
Upon success, tstate_p will be set to the first thread state created in the new sub-interpreter. This thread state
is made in the current thread state. Note that no actual thread is created; see the discussion of thread states
below. If creation of the new interpreter is unsuccessful, tstate_p is set to NULL; no exception is set since the
exception state is stored in the current thread state and there may not be a current thread state.
Like all other Python/C API functions, the global interpreter lock must be held before calling this function
and is still held when it returns. Likewise a current thread state must be set on entry. On success, the returned
thread state will be set as current. If the sub-interpreter is created with its own GIL then the GIL of the calling
interpreter will be released. When the function returns, the new interpreter’s GIL will be held by the current
thread and the previously interpreter’s GIL will remain released here.
Added in version 3.12.
Sub-interpreters are most effective when isolated from each other, with certain functionality restricted:
PyInterpreterConfig config = {
.use_main_obmalloc = 0,
.allow_fork = 0,
(continúe en la próxima página)
Note that the config is used only briefly and does not get modified. During initialization the config’s values
are converted into various PyInterpreterState values. A read-only copy of the config may be stored
internally on the PyInterpreterState.
Los módulos de extensión se comparten entre (sub) intérpretes de la siguiente manera:
• Para módulos que usan inicialización multifase, por ejemplo PyModule_FromDefAndSpec(), se
crea e inicializa un objeto de módulo separado para cada intérprete. Solo las variables estáticas y globales
de nivel C se comparten entre estos objetos de módulo.
• Para módulos que utilizan inicialización monofásica, por ejemplo PyModule_Create(), la primera
vez que se importa una extensión en particular, se inicializa normalmente y una copia (superficial) del
diccionario de su módulo se guarda. Cuando otro (sub) intérprete importa la misma extensión, se inicializa
un nuevo módulo y se llena con el contenido de esta copia; no se llama a la función init de la extensión.
Los objetos en el diccionario del módulo terminan compartidos entre (sub) intérpretes, lo que puede
causar un comportamiento no deseado (ver Errores y advertencias (Bugs and caveats) a continuación).
Tenga en cuenta que esto es diferente de lo que sucede cuando se importa una extensión después de que el
intérprete se haya reiniciado por completo llamando a Py_FinalizeEx() y Py_Initialize();
en ese caso, la función initmodule de la extensión es llamada nuevamente. Al igual que con la inicia-
lización de múltiples fases, esto significa que solo se comparten variables estáticas y globales de nivel C
entre estos módulos.
PyThreadState *Py_NewInterpreter(void)
Part of the Stable ABI. Create a new sub-interpreter. This is essentially just a wrapper around
Py_NewInterpreterFromConfig() with a config that preserves the existing behavior. The result is
an unisolated sub-interpreter that shares the main interpreter’s GIL, allows fork/exec, allows daemon threads,
and allows single-phase init modules.
void Py_EndInterpreter(PyThreadState *tstate)
Part of the Stable ABI. Destroy the (sub-)interpreter represented by the given thread state. The given thread state
must be the current thread state. See the discussion of thread states below. When the call returns, the current
thread state is NULL. All thread states associated with this interpreter are destroyed. The global interpreter
lock used by the target interpreter must be held before calling this function. No GIL is held when it returns.
Py_FinalizeEx() will destroy all sub-interpreters that haven’t been explicitly destroyed at that point.
Using Py_NewInterpreterFromConfig() you can create a sub-interpreter that is completely isolated from
other interpreters, including having its own GIL. The most important benefit of this isolation is that such an interpreter
can execute Python code without being blocked by other interpreters or blocking any others. Thus a single Python
process can truly take advantage of multiple CPU cores when running Python code. The isolation also encourages a
different approach to concurrency than that of just using threads. (See PEP 554.)
Using an isolated interpreter requires vigilance in preserving that isolation. That especially means not sharing any
objects or mutable state without guarantees about thread-safety. Even objects that are otherwise immutable (e.g.
None, (1, 5)) can’t normally be shared because of the refcount. One simple but less-efficient approach around
this is to use a global lock around all use of some state (or object). Alternately, effectively immutable objects (like
integers or strings) can be made safe in spite of their refcounts by making them «immortal». In fact, this has been
done for the builtin singletons, small integers, and a number of other builtin objects.
If you preserve isolation then you will have access to proper multi-core computing without the complications that
come with free-threading. Failure to preserve isolation will expose you to the full consequences of free-threading,
including races and hard-to-debug crashes.
Aside from that, one of the main challenges of using multiple isolated interpreters is how to communicate between
them safely (not break isolation) and efficiently. The runtime and stdlib do not provide any standard approach to
this yet. A future stdlib module would help mitigate the effort of preserving isolation and expose effective tools for
communicating (and sharing) data between interpreters.
Added in version 3.12.
Debido a que los subinterpretes (y el intérprete principal) son parte del mismo proceso, el aislamiento entre ellos no es
perfecto — por ejemplo, usando operaciones de archivos de bajo nivel como os.close() pueden (accidentalmente
o maliciosamente) afectar los archivos abiertos del otro. Debido a la forma en que las extensiones se comparten entre
(sub) intérpretes, algunas extensiones pueden no funcionar correctamente; esto es especialmente probable cuando
se utiliza la inicialización monofásica o las variables globales (estáticas). Es posible insertar objetos creados en un
subinterprete en un espacio de nombres de otro (sub) intérprete; Esto debe evitarse si es posible.
Se debe tener especial cuidado para evitar compartir funciones, métodos, instancias o clases definidas por el usua-
rio entre los subinterpretes, ya que las operaciones de importación ejecutadas por dichos objetos pueden afectar el
diccionario (sub-) intérprete incorrecto de los módulos cargados. Es igualmente importante evitar compartir objetos
desde los que se pueda acceder a lo anterior.
También tenga en cuenta que la combinación de esta funcionalidad con PyGILState_* APIs es delicada, porque
estas APIs suponen una biyección entre los estados de hilo de Python e hilos a nivel del sistema operativo, una
suposición rota por la presencia de subinterpretes. Se recomienda encarecidamente que no cambie los subinterpretes
entre un par de llamadas coincidentes PyGILState_Ensure() y PyGILState_Release(). Además, las
extensiones (como ctypes) que usan estas APIs para permitir la llamada de código Python desde hilos no creados
por Python probablemente se rompan cuando se usan subinterpretes.
Se proporciona un mecanismo para hacer notificaciones asincrónicas al hilo principal del intérprete. Estas notifica-
ciones toman la forma de un puntero de función y un argumento de puntero nulo.
int Py_AddPendingCall(int (*func)(void*), void *arg)
Part of the Stable ABI. Programa una función para que se llame desde el hilo principal del intérprete. En caso
de éxito, se retorna 0 y se pone en cola func para ser llamado en el hilo principal. En caso de fallo, se retorna
-1 sin establecer ninguna excepción.
Cuando se puso en cola con éxito, func será eventualmente invocado desde el hilo principal del intérprete con
el argumento arg. Se llamará de forma asincrónica con respecto al código Python que se ejecuta normalmente,
pero con ambas condiciones cumplidas:
• en un límite bytecode;
• con el hilo principal que contiene el global interpreter lock (func, por lo tanto, puede usar la API C
completa).
func debe retornar 0 en caso de éxito o -1 en caso de error con una excepción establecida. func no se in-
terrumpirá para realizar otra notificación asíncrona de forma recursiva, pero aún se puede interrumpir para
cambiar hilos si se libera el bloqueo global del intérprete.
Esta función no necesita un estado de hilo actual para ejecutarse y no necesita el bloqueo global del intérprete.
Para llamar a esta función en un subinterprete, quien llama debe mantener el GIL. De lo contrario, la función
func se puede programar para que se llame desde el intérprete incorrecto.
Advertencia: Esta es una función de bajo nivel, solo útil para casos muy especiales. No hay garantía de que
func se llame lo más rápido posible. Si el hilo principal está ocupado ejecutando una llamada al sistema,
no se llamará func antes de que vuelva la llamada del sistema. Esta función generalmente no es adecuada
para llamar a código Python desde hilos C arbitrarios. En su lugar, use PyGILState API.
El intérprete de Python proporciona soporte de bajo nivel para adjuntar funciones de creación de perfiles y seguimiento
de ejecución. Estos se utilizan para herramientas de análisis de perfiles, depuración y cobertura.
Esta interfaz C permite que el código de perfilado o rastreo evite la sobrecarga de llamar a través de objetos invocables
a nivel de Python, haciendo una llamada directa a la función C en su lugar. Los atributos esenciales de la instalación no
han cambiado; la interfaz permite instalar funciones de rastreo por hilos, y los eventos básicos informados a la función
de rastreo son los mismos que se informaron a las funciones de rastreo a nivel de Python en versiones anteriores.
typedef int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
The type of the trace function registered using PyEval_SetProfile() and PyEval_SetTrace().
The first parameter is the object passed to the registration function as obj, frame is the frame object to which the
event pertains, what is one of the constants PyTrace_CALL, PyTrace_EXCEPTION, PyTrace_LINE,
PyTrace_RETURN, PyTrace_C_CALL, PyTrace_C_EXCEPTION, PyTrace_C_RETURN, or
PyTrace_OPCODE, and arg depends on the value of what:
int PyTrace_CALL
El valor del parámetro what para una función Py_tracefunc cuando se informa una nueva llamada a una
función o método, o una nueva entrada en un generador. Tenga en cuenta que la creación del iterador para una
función de generador no se informa ya que no hay transferencia de control al código de bytes de Python en la
marco correspondiente.
int PyTrace_EXCEPTION
El valor del parámetro what para una función Py_tracefunc cuando se ha producido una excepción. La
función de devolución de llamada se llama con este valor para what cuando después de que se procese cualquier
bytecode, después de lo cual la excepción se establece dentro del marco que se está ejecutando. El efecto de
esto es que a medida que la propagación de la excepción hace que la pila de Python se desenrolle, el retorno de
llamada se llama al retornar a cada marco a medida que se propaga la excepción. Solo las funciones de rastreo
reciben estos eventos; el perfilador (profiler) no los necesita.
int PyTrace_LINE
The value passed as the what parameter to a Py_tracefunc function (but not a profiling function) when a
line-number event is being reported. It may be disabled for a frame by setting f_trace_lines to 0 on that
frame.
int PyTrace_RETURN
El valor para el parámetro what para Py_tracefunc funciona cuando una llamada está por regresar.
int PyTrace_C_CALL
El valor del parámetro what para Py_tracefunc funciona cuando una función C está a punto de ser invo-
cada.
int PyTrace_C_EXCEPTION
El valor del parámetro what para funciones Py_tracefunc cuando una función C ha lanzado una excepción.
int PyTrace_C_RETURN
El valor del parámetro what para Py_tracefunc funciona cuando una función C ha retornado.
int PyTrace_OPCODE
The value for the what parameter to Py_tracefunc functions (but not profiling functions) when a new
opcode is about to be executed. This event is not emitted by default: it must be explicitly requested by setting
f_trace_opcodes to 1 on the frame.
void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)
Set the profiler function to func. The obj parameter is passed to the function as its first parameter, and may
be any Python object, or NULL. If the profile function needs to maintain state, using a different value for obj
for each thread provides a convenient and thread-safe place to store it. The profile function is called for all
monitored events except PyTrace_LINE PyTrace_OPCODE and PyTrace_EXCEPTION.
Consulte también la función sys.setprofile().
La persona que llama debe mantener el GIL.
void PyEval_SetProfileAllThreads(Py_tracefunc func, PyObject *obj)
Like PyEval_SetProfile() but sets the profile function in all running threads belonging to the current
interpreter instead of the setting it only on the current thread.
La persona que llama debe mantener el GIL.
As PyEval_SetProfile(), this function ignores any exceptions raised while setting the profile functions
in all threads.
Added in version 3.12.
void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)
Set the tracing function to func. This is similar to PyEval_SetProfile(), except the tracing function
does receive line-number events and per-opcode events, but does not receive any event related to C fun-
ction objects being called. Any trace function registered using PyEval_SetTrace() will not receive
PyTrace_C_CALL, PyTrace_C_EXCEPTION or PyTrace_C_RETURN as a value for the what pa-
rameter.
Consulte también la función sys.settrace().
La persona que llama debe mantener el GIL.
void PyEval_SetTraceAllThreads(Py_tracefunc func, PyObject *obj)
Like PyEval_SetTrace() but sets the tracing function in all running threads belonging to the current
interpreter instead of the setting it only on the current thread.
La persona que llama debe mantener el GIL.
As PyEval_SetTrace(), this function ignores any exceptions raised while setting the trace functions in
all threads.
Added in version 3.12.
Estas funciones solo están destinadas a ser utilizadas por herramientas de depuración avanzadas.
PyInterpreterState *PyInterpreterState_Head()
Retorna el objeto de estado del intérprete al principio de la lista de todos esos objetos.
PyInterpreterState *PyInterpreterState_Main()
Retorna el objeto de estado del intérprete principal.
PyInterpreterState *PyInterpreterState_Next(PyInterpreterState *interp)
Retorna el siguiente objeto de estado de intérprete después de interp de la lista de todos esos objetos.
PyThreadState *PyInterpreterState_ThreadHead(PyInterpreterState *interp)
Retorna el puntero al primer objeto PyThreadState en la lista de hilos asociados con el intérprete interp.
PyThreadState *PyThreadState_Next(PyThreadState *tstate)
Retorna el siguiente objeto de estado del hilo después de tstate de la lista de todos los objetos que pertenecen
al mismo objeto PyInterpreterState.
El intérprete de Python proporciona soporte de bajo nivel para el almacenamiento local de hilos (TLS) que envuelve
la implementación de TLS nativa subyacente para admitir la API de almacenamiento local de hilos de nivel Python
(threading.local). Las APIs de nivel CPython C son similares a las ofrecidas por pthreads y Windows: use
una clave de hilo y funciones para asociar un valor de void* por hilo.
El GIL no necesita ser retenido al llamar a estas funciones; proporcionan su propio bloqueo.
Tenga en cuenta que Python.h no incluye la declaración de las API de TLS, debe incluir pythread.h para usar
el almacenamiento local de hilos.
Nota: Ninguna de estas funciones API maneja la administración de memoria en nombre de los valores void*. Debe
asignarlos y desasignarlos usted mismo. Si los valores void* son PyObject*, estas funciones tampoco realizan
operaciones de conteo de referencias en ellos.
La API de TSS se introduce para reemplazar el uso de la API TLS existente dentro del intérprete de CPython. Esta
API utiliza un nuevo tipo Py_tss_t en lugar de int para representar las claves del hilo.
Added in version 3.7.
Ver también:
«Una nueva C-API para Thread-Local Storage en CPython» (PEP 539)
type Py_tss_t
Esta estructura de datos representa el estado de una clave del hilo, cuya definición puede depender de la imple-
mentación de TLS subyacente, y tiene un campo interno que representa el estado de inicialización de la clave.
No hay miembros públicos en esta estructura.
Cuando Py_LIMITED_API no está definido, la asignación estática de este tipo por Py_tss_NEEDS_INIT
está permitida.
Py_tss_NEEDS_INIT
Esta macro se expande al inicializador para variables Py_tss_t. Tenga en cuenta que esta macro no se
definirá con Py_LIMITED_API.
Asignación dinámica
Asignación dinámica de Py_tss_t, requerida en los módulos de extensión construidos con Py_LIMITED_API,
donde la asignación estática de este tipo no es posible debido a que su implementación es opaca en el momento de la
compilación.
Py_tss_t *PyThread_tss_alloc()
Part of the Stable ABI since version 3.7. Retorna un valor que es el mismo estado que un valor inicializado con
Py_tss_NEEDS_INIT, o NULL en caso de falla de asignación dinámica.
void PyThread_tss_free(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Libera la clave asignada por PyThread_tss_alloc(), después
de llamar por primera vez PyThread_tss_delete() para asegurarse de que los hilos locales asociados
no hayan sido asignados. Esto es un no-op si el argumento clave es NULL.
Nota: Una clave liberada se convierte en un puntero colgante. Debería restablecer la clave a NULL.
Métodos
El parámetro key de estas funciones no debe ser NULL. Además, los comportamientos de PyThread_tss_set()
y PyThread_tss_get() no están definidos si el Py_tss_t dado no ha sido inicializado por
PyThread_tss_create().
int PyThread_tss_is_created(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Retorna un valor distinto de cero si Py_tss_t ha sido inicializado
por PyThread_tss_create().
int PyThread_tss_create(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Retorna un valor cero en la inicialización exitosa de una clave
TSS. El comportamiento no está definido si el valor señalado por el argumento key no se inicializa con
Py_tss_NEEDS_INIT. Esta función se puede invocar repetidamente en la misma tecla: llamarla a una
tecla ya inicializada es un no-op e inmediatamente retorna el éxito.
void PyThread_tss_delete(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Destruye una clave TSS para olvidar los valores asociados con la clave
en todos los hilos y cambie el estado de inicialización de la clave a no inicializado. Una clave destruida se puede
inicializar nuevamente mediante PyThread_tss_create(). Esta función se puede invocar repetidamente
en la misma llave; llamarla en una llave ya destruida es un no-op.
int PyThread_tss_set(Py_tss_t *key, void *value)
Part of the Stable ABI since version 3.7. Retorna un valor cero para indicar la asociación exitosa de un valor a
void* con una clave TSS en el hilo actual. Cada hilo tiene un mapeo distinto de la clave a un valor void*.
void *PyThread_tss_get(Py_tss_t *key)
Part of the Stable ABI since version 3.7. Retorna el valor void* asociado con una clave TSS en el hilo actual.
Esto retorna NULL si no hay ningún valor asociado con la clave en el hilo actual.
Obsoleto desde la versión 3.7: Esta API es reemplazada por API de Almacenamiento Específico de Hilos (TSS, por
sus significado en inglés *Thread Specific Storage*).
Nota: Esta versión de la API no es compatible con plataformas donde la clave TLS nativa se define de una manera
que no se puede transmitir de forma segura a int. En tales plataformas, PyThread_create_key() regresará
inmediatamente con un estado de falla, y las otras funciones TLS serán no operativas en tales plataformas.
Debido al problema de compatibilidad mencionado anteriormente, esta versión de la API no debe usarse en código
nuevo.
int PyThread_create_key()
Part of the Stable ABI.
void PyThread_delete_key(int key)
Part of the Stable ABI.
int PyThread_set_key_value(int key, void *value)
Part of the Stable ABI.
void *PyThread_get_key_value(int key)
Part of the Stable ABI.
void PyThread_delete_key_value(int key)
Part of the Stable ABI.
void PyThread_ReInitTLS()
Part of the Stable ABI.
10.1 Ejemplo
PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;
219
The Python/C API, Versión 3.12.4
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return Py_RunMain();
exception:
PyConfig_Clear(&config);
if (PyStatus_IsExit(status)) {
return status.exitcode;
}
/* Display the error message and exit the process with
non-zero exit code */
Py_ExitStatusException(status);
}
10.2 PyWideStringList
type PyWideStringList
Lista de cadenas de caracteres wchar_t*.
Si length no es cero, items no deben ser NULL y todas las cadenas de caracteres deben ser no NULL.
Métodos:
PyStatus PyWideStringList_Append(PyWideStringList *list, const wchar_t *item)
Agregar item a list.
Python debe estar preinicializado para llamar a esta función.
PyStatus PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item)
Inserta item en list en index.
Si index es mayor o igual que el largo de list, agrega item a list.
index must be greater than or equal to 0.
Python debe estar preinicializado para llamar a esta función.
Campos de estructura:
Py_ssize_t length
Longitud de la lista.
wchar_t **items
Elementos de la lista.
10.3 PyStatus
type PyStatus
Estructura para almacenar el estado de una función de inicialización: éxito, error o salida.
Para un error, puede almacenar el nombre de la función C que creó el error.
Campos de estructura:
int exitcode
Código de salida El argumento pasó a exit().
const char *err_msg
Mensaje de error.
const char *func
El nombre de la función que creó un error puede ser NULL.
Funciones para crear un estado:
PyStatus PyStatus_Ok(void)
Éxito.
PyStatus PyStatus_Error(const char *err_msg)
Error de inicialización con un mensaje.
err_msg no debe ser NULL.
PyStatus PyStatus_NoMemory(void)
Error de asignación de memoria (sin memoria).
PyStatus PyStatus_Exit(int exitcode)
Sale de Python con el código de salida especificado.
Funciones para manejar un estado:
int PyStatus_Exception(PyStatus status)
¿Es el estado un error o una salida? Si es verdadero, la excepción debe ser manejada; por ejemplo llamando
a Py_ExitStatusException().
int PyStatus_IsError(PyStatus status)
¿Es el resultado un error?
int PyStatus_IsExit(PyStatus status)
¿El resultado es una salida?
void Py_ExitStatusException(PyStatus status)
Llama a exit(exitcode) si status es una salida. Imprime el mensaje de error y sale con un código de
salida distinto de cero si status es un error. Solo se debe llamar si PyStatus_Exception(status)
no es cero.
Nota: Internamente, Python usa macros que establecen PyStatus.func, mientras que las funciones para crear
un estado establecen func en NULL.
Ejemplo:
10.4 PyPreConfig
type PyPreConfig
Estructura utilizada para preinicializar Python.
Función para inicializar una preconfiguración:
void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
Inicializa la preconfiguración con Configuración de Python.
void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
Inicializa la preconfiguración con Configuración aislada.
Campos de estructura:
int allocator
Nombre de los asignadores de memoria de Python:
• PYMEM_ALLOCATOR_NOT_SET (0): no cambia asignadores de memoria (usa los valores prede-
terminados)
• PYMEM_ALLOCATOR_DEFAULT (1): asignadores de memoria predeterminados.
• PYMEM_ALLOCATOR_DEBUG (2): asignadores de memoria predeterminados con ganchos de de-
puración.
• PYMEM_ALLOCATOR_MALLOC (3): usa malloc() de la biblioteca C.
• PYMEM_ALLOCATOR_MALLOC_DEBUG (4): fuerza el uso de malloc() con ganchos de depu-
ración.
• PYMEM_ALLOCATOR_PYMALLOC (5): asignador de memoria pymalloc de Python
• PYMEM_ALLOCATOR_PYMALLOC_DEBUG (6): asignador de memoria pymalloc de Python con
ganchos de depuración.
PYMEM_ALLOCATOR_PYMALLOC y PYMEM_ALLOCATOR_PYMALLOC_DEBUG no son compati-
bles si Python es configurado usando --without-pymalloc.
Ver Administración de memorias.
Predeterminado: PYMEM_ALLOCATOR_NOT_SET.
int configure_locale
Set the LC_CTYPE locale to the user preferred locale.
If equals to 0, set coerce_c_locale and coerce_c_locale_warn members to 0.
Vea el locale encoding.
La preinicialización de Python:
• Establecer los asignadores de memoria de Python (PyPreConfig.allocator)
• Configurar la configuración regional LC_CTYPE (locale encoding)
• Establecer el Python UTF-8 Mode (PyPreConfig.utf8_mode)
La preconfiguración actual (tipo PyPreConfig) se almacena en _PyRuntime.preconfig.
Funciones para preinicializar Python:
PyStatus Py_PreInitialize(const PyPreConfig *preconfig)
Preinicializa Python desde la preconfiguración preconfig.
preconfig no debe ser NULL.
PyStatus Py_PreInitializeFromBytesArgs(const PyPreConfig *preconfig, int argc, char *const *argv)
Preinicializa Python desde la preconfiguración preconfig.
Analice los argumentos de la línea de comando argv (cadenas de bytes) si parse_argv de preconfig no es
cero.
preconfig no debe ser NULL.
PyStatus Py_PreInitializeFromArgs(const PyPreConfig *preconfig, int argc, wchar_t *const *argv)
Preinicializa Python desde la preconfiguración preconfig.
Analice los argumentos de la línea de comando argv (cadenas anchas) si parse_argv de preconfig no es
cero.
preconfig no debe ser NULL.
La persona que llama es responsable de manejar las excepciones (error o salida) usando PyStatus_Exception()
y Py_ExitStatusException().
Para Configuración de Python (PyPreConfig_InitPythonConfig()), si Python se inicializa con argumentos
de línea de comando, los argumentos de la línea de comando también deben pasarse para preinicializar Python, ya
que tienen un efecto en la preconfiguración como codificaciones. Por ejemplo, la opción de línea de comando -X
utf8 habilita el Python UTF-8 Mode.
PyMem_SetAllocator() se puede llamar después de Py_PreInitialize() y antes
Py_InitializeFromConfig() para instalar un asignador de memoria personalizado. Se pue-
de llamar antes Py_PreInitialize() si PyPreConfig.allocator está configurado en
PYMEM_ALLOCATOR_NOT_SET.
Las funciones de asignación de memoria de Python como PyMem_RawMalloc() no deben usarse antes de la
preinicialización de Python, mientras que llamar directamente a malloc() y free() siempre es seguro. No se
debe llamar a Py_DecodeLocale() antes de la preinicialización de Python.
Ejemplo usando la preinicialización para habilitar el Python UTF-8 Mode
PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);
preconfig.utf8_mode = 1;
status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();
10.6 PyConfig
type PyConfig
Estructura que contiene la mayoría de los parámetros para configurar Python.
Cuando termine, se debe utilizar la función PyConfig_Clear() para liberar la memoria de configuración.
Métodos de estructura:
void PyConfig_InitPythonConfig(PyConfig *config)
Inicialice la configuración con la Configuración de Python.
void PyConfig_InitIsolatedConfig(PyConfig *config)
Inicialice la configuración con la Configuración Aislada.
PyStatus PyConfig_SetString(PyConfig *config, wchar_t *const *config_str, const wchar_t *str)
Copia la cadena de caracteres anchos str en *config_str.
Preinicializa Python si es necesario.
PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t *const *config_str, const char *str)
Decodifique str usando Py_DecodeLocale() y establezca el resultado en *config_str.
Preinicializa Python si es necesario.
PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t *const *argv)
Configure los argumentos de la línea de comando (miembro argv de config) de la lista argv de cadenas
de caracteres anchas.
Preinicializa Python si es necesario.
PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char *const *argv)
Establezca argumentos de línea de comando (miembro argv de config) de la lista argv de cadenas de
bytes. Decodifica bytes usando Py_DecodeLocale().
Preinicializa Python si es necesario.
PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t
length, wchar_t **items)
Establece la lista de cadenas de caracteres anchas list a length y items.
Preinicializa Python si es necesario.
PyStatus PyConfig_Read(PyConfig *config)
Lee toda la configuración de Python.
Los campos que ya están inicializados no se modifican.
Los campos para la configuración de ruta ya no se calculan ni modifican al llamar a esta función, a partir
de Python 3.11.
La función PyConfig_Read() solo analiza los argumentos PyConfig.argv una vez:
PyConfig.parse_argv se establece en 2 después de analizar los argumentos. Dado que los ar-
gumentos de Python se eliminan de PyConfig.argv, analizar los argumentos dos veces analizaría las
opciones de la aplicación como opciones de Python.
Preinicializa Python si es necesario.
Distinto en la versión 3.10: Los argumentos PyConfig.argv ahora solo se analizan una vez,
PyConfig.parse_argv se establece en 2 después de analizar los argumentos y los argumentos
solo se analizan si PyConfig.parse_argv es igual a 1.
Distinto en la versión 3.11: PyConfig_Read() ya no calcula todas las rutas, por lo que los
campos listados en Python Path Configuration ya no pueden ser actualizados hasta que se llame a
Py_InitializeFromConfig().
void PyConfig_Clear(PyConfig *config)
Libera memoria de configuración.
La mayoría de los método PyConfig preinitializan Python si es necesario. En ese caso, la configuración de
preinicialización de Python (PyPreConfig) se basa en PyConfig. Si se ajustan los campos de configura-
ción que son comunes con PyPreConfig, deben establecerse antes de llamar a un método PyConfig:
• PyConfig.dev_mode
• PyConfig.isolated
• PyConfig.parse_argv
• PyConfig.use_environment
Moreover, if PyConfig_SetArgv() or PyConfig_SetBytesArgv() is used, this method must be
called before other methods, since the preinitialization configuration depends on command line arguments (if
parse_argv is non-zero).
Quien llama de estos métodos es responsable de manejar las excepciones (error o salida) usando
PyStatus_Exception() y Py_ExitStatusException().
Campos de estructura:
PyWideStringList argv
Argumentos de la línea de comando: sys.argv.
Configure parse_argv en 1 para analizar argv de la misma manera que Python normal analiza los
argumentos de la línea de comandos de Python y luego quita los argumentos de Python de argv.
Si argv está vacío, se agrega una cadena vacía para garantizar que sys.argv siempre exista y nunca
esté vacío.
Valor predeterminado: NULL.
Consulte también el miembro orig_argv.
int safe_path
Si es igual a cero, Py_RunMain() agrega una ruta potencialmente insegura a sys.path al inicio:
• Si argv[0] es igual a L"-m" (python -m module), añade el directorio de trabajo actual.
• If running a script (python script.py), prepend the script’s directory. If it’s a symbolic link,
resolve symbolic links.
• En caso contrario (python -c code and python), añade una cadena vacía, que significa el
directorio de trabajo actual.
Set to 1 by the -P command line option and the PYTHONSAFEPATH environment variable.
Default: 0 in Python config, 1 in isolated config.
Added in version 3.11.
wchar_t *base_exec_prefix
sys.base_exec_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
wchar_t *base_executable
Ejecutable base de Python: sys._base_executable.
Establecido por la variable de entorno __PYVENV_LAUNCHER__.
Establecido desde PyConfig.executable si NULL.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
wchar_t *base_prefix
sys.base_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
int buffered_stdio
If equals to 0 and configure_c_stdio is non-zero, disable buffering on the C streams stdout and
stderr.
Set to 0 by the -u command line option and the PYTHONUNBUFFERED environment variable.
stdin siempre se abre en modo de búfer.
Predeterminado: 1.
int bytes_warning
If equals to 1, issue a warning when comparing bytes or bytearray with str, or comparing bytes
with int.
If equal or greater to 2, raise a BytesWarning exception in these cases.
Incrementado por la opción de línea de comando -b.
Predeterminado: 0.
int warn_default_encoding
Si no es cero, emite una advertencia EncodingWarning cuando io.TextIOWrapper usa su co-
dificación predeterminada. Consulte io-encoding-warning para obtener más detalles.
Predeterminado: 0.
Added in version 3.10.
int code_debug_ranges
If equals to 0, disables the inclusion of the end line and column mappings in code objects. Also disables
traceback printing carets to specific error locations.
Set to 0 by the PYTHONNODEBUGRANGES environment variable and by the -X no_debug_ranges
command line option.
Predeterminado: 1.
Added in version 3.11.
wchar_t *check_hash_pycs_mode
Controla el comportamiento de validación de archivos .pyc basados en hash: valor de la opción de línea
de comando --check-hash-based-pycs.
Valores válidos:
• L"always": Calcula el hash el archivo fuente para invalidación independientemente del valor de
la marca “check_source”.
• L"never": suponga que los pycs basados en hash siempre son válidos.
• L"default": El indicador “check_source” en pycs basados en hash determina la invalidación.
Predeterminado: L"default".
Consulte también PEP 552 «Pycs deterministas».
int configure_c_stdio
Si es distinto de cero, configure los flujos estándar de C:
• En Windows, configure el modo binario (O_BINARY) en stdin, stdout y stderr.
• Si buffered_stdio es igual a cero, deshabilite el almacenamiento en búfer de los flujos stdin,
stdout y stderr.
• Si interactive no es cero, habilite el almacenamiento en búfer de flujo en stdin y stdout (solo
stdout en Windows).
Predeterminado: 1 en la configuración de Python, 0 en la configuración aislada.
int dev_mode
Si es distinto de cero, habilita Modo de desarrollo de Python.
Set to 1 by the -X dev option and the PYTHONDEVMODE environment variable.
Por defecto: -1 en modo Python, 0 en modo aislado.
int dump_refs
Dump Python references?
Si no es cero, volcar todos los objetos que aún están vivos en la salida.
Establecido en 1 por la variable de entorno PYTHONDUMPREFS.
Necesita una compilación especial de Python con la macro Py_TRACE_REFS definida: consulte la
opción de configure --with-trace-refs option.
Predeterminado: 0.
wchar_t *exec_prefix
El prefijo de directorio específico del sitio donde se instalan los archivos Python dependientes de la
plataforma: sys.exec_prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
wchar_t *executable
La ruta absoluta del binario ejecutable para el intérprete de Python: sys.executable.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
int faulthandler
¿Habilitar administrador de fallas?
Si no es cero, llama a faulthandler.enable() al inicio.
Establecido en 1 por -X faulthandler y la variable de entorno PYTHONFAULTHANDLER.
Por defecto: -1 en modo Python, 0 en modo aislado.
wchar_t *filesystem_encoding
Codificación del sistema de archvios: sys.getfilesystemencoding().
En macOS, Android y VxWorks: use "utf-8" de forma predeterminada.
En Windows: utilice "utf-8" de forma predeterminada o "mbcs" si
legacy_windows_fs_encoding de PyPreConfig no es cero.
Codificación predeterminada en otras plataformas:
• "utf-8" si PyPreConfig.utf8_mode es distinto de cero.
int use_hash_seed
Funciones de semillas aleatorias hash.
Si use_hash_seed es cero, se elige una semilla al azar en el inicio de Python y se ignora hash_seed.
Establecido por la variable de entorno PYTHONHASHSEED.
Valor predeterminado de use_hash_seed: -1 en modo Python, 0 en modo aislado.
wchar_t *home
Directorio de inicio de Python.
Si se ha llamado a Py_SetPythonHome(), use su argumento si no es NULL.
Establecido por la variable de entorno PYTHONHOME.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
int import_time
Si no es cero, el tiempo de importación del perfil.
Configure el 1 mediante la opción -X importtime y la variable de entorno
PYTHONPROFILEIMPORTTIME.
Predeterminado: 0.
int inspect
Ingresa al modo interactivo después de ejecutar un script o un comando.
If greater than 0, enable inspect: when a script is passed as first argument or the -c option is used, enter
interactive mode after executing the script or the command, even when sys.stdin does not appear to
be a terminal.
Incrementado por la opción de línea de comando -i. Establecido en 1 si la variable de entorno
PYTHONINSPECT no está vacía.
Predeterminado: 0.
int install_signal_handlers
¿Instalar controladores de señales de Python?
Por defecto: 1 en modo Python, 0 en modo aislado.
int interactive
If greater than 0, enable the interactive mode (REPL).
Incrementado por la opción de línea de comando -i.
Predeterminado: 0.
int int_max_str_digits
Configures the integer string conversion length limitation. An initial value of -1 means the value will
be taken from the command line or environment or otherwise default to 4300 (sys.int_info.
default_max_str_digits). A value of 0 disables the limitation. Values greater than zero but less
than 640 (sys.int_info.str_digits_check_threshold) are unsupported and will produ-
ce an error.
Configured by the -X int_max_str_digits command line flag or the
PYTHONINTMAXSTRDIGITS environment variable.
Default: -1 in Python mode. 4300 (sys.int_info.default_max_str_digits) in isolated
mode.
Added in version 3.12.
int isolated
If greater than 0, enable isolated mode:
• Set safe_path to 1: don’t prepend a potentially unsafe path to sys.path at Python startup,
such as the current directory, the script’s directory or an empty string.
• Set use_environment to 0: ignore PYTHON environment variables.
• Set user_site_directory to 0: don’t add the user site directory to sys.path.
• Python REPL no importa readline ni habilita la configuración predeterminada de readline en
mensajes interactivos.
Set to 1 by the -I command line option.
Por defecto: 0 en modo Python, 1 en modo aislado.
See also the Isolated Configuration and PyPreConfig.isolated.
int legacy_windows_stdio
If non-zero, use io.FileIO instead of io._WindowsConsoleIO for sys.stdin, sys.
stdout and sys.stderr.
Establecido en 1 si la variable de entorno PYTHONLEGACYWINDOWSSTDIO está establecida en una
cadena no vacía.
Solo disponible en Windows. La macro #ifdef MS_WINDOWS se puede usar para el código específico
de Windows.
Predeterminado: 0.
Consulte también PEP 528 (Cambiar la codificación de la consola de Windows a UTF-8).
int malloc_stats
Si no es cero, volcar las estadísticas en Asignador de memoria Python pymalloc en la salida.
Establecido en 1 por la variable de entorno PYTHONMALLOCSTATS.
La opción se ignora si Python es configurado usando la opción
--without-pymalloc.
Predeterminado: 0.
wchar_t *platlibdir
Nombre del directorio de la biblioteca de la plataforma: sys.platlibdir.
Establecido por la variable de entorno PYTHONPLATLIBDIR.
Default: value of the PLATLIBDIR macro which is set by the configure --with-platlibdir
option (default: "lib", or "DLLs" on Windows).
Parte de la entrada Python Path Configuration.
Added in version 3.9.
Distinto en la versión 3.11: Esta macro se utiliza ahora en Windows para localizar los módulos de exten-
sión de la biblioteca estándar, normalmente en DLLs. Sin embargo, por compatibilidad, tenga en cuenta
que este valor se ignora para cualquier disposición no estándar, incluyendo las construcciones dentro del
árbol y los entornos virtuales.
wchar_t *pythonpath_env
Module search paths (sys.path) as a string separated by DELIM (os.pathsep).
Establecido por la variable de entorno PYTHONPATH.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
PyWideStringList module_search_paths
int module_search_paths_set
Rutas de búsqueda del módulo: sys.path.
If module_search_paths_set is equal to 0, Py_InitializeFromConfig() will replace
module_search_paths and sets module_search_paths_set to 1.
Por defecto: lista vacía (module_search_paths) y 0 (module_search_paths_set).
Parte de la salida Python Path Configuration.
int optimization_level
Nivel de optimización de compilación:
• 0: Optimizador de mirilla, configure __debug__ en True.
• 1: Nivel 0, elimina las aserciones, establece __debug__ en False.
• 2: Nivel 1, elimina docstrings.
Incrementado por la opción de línea de comando -O. Establecido en el valor de la variable de entorno
PYTHONOPTIMIZE.
Predeterminado: 0.
PyWideStringList orig_argv
La lista de los argumentos originales de la línea de comandos pasados al ejecutable de Python: sys.
orig_argv.
Si la lista orig_argv está vacía y argv no es una lista que solo contiene una cadena vacía,
PyConfig_Read() copia argv en orig_argv antes de modificar argv (si parse_argv no
es cero).
Consulte también el miembro argv y la función Py_GetArgcArgv().
Predeterminado: lista vacía.
Added in version 3.10.
int parse_argv
¿Analizar los argumentos de la línea de comando?
Si es igual a 1, analiza argv de la misma forma que Python normal analiza argumentos de línea de
comando y elimina los argumentos de Python de argv.
La función PyConfig_Read() solo analiza los argumentos PyConfig.argv una vez:
PyConfig.parse_argv se establece en 2 después de analizar los argumentos. Dado que los ar-
gumentos de Python se eliminan de PyConfig.argv, analizar los argumentos dos veces analizaría las
opciones de la aplicación como opciones de Python.
Por defecto: 1 en modo Python, 0 en modo aislado.
Distinto en la versión 3.10: Los argumentos PyConfig.argv ahora solo se analizan si PyConfig.
parse_argv es igual a 1.
int parser_debug
Parser debug mode. If greater than 0, turn on parser debugging output (for expert only, depending on
compilation options).
Incrementado por la opción de línea de comando -d. Establecido en el valor de la variable de entorno
PYTHONDEBUG.
Need a debug build of Python (the Py_DEBUG macro must be defined).
Predeterminado: 0.
int pathconfig_warnings
If non-zero, calculation of path configuration is allowed to log warnings into stderr. If equals to 0,
suppress these warnings.
Por defecto: 1 en modo Python, 0 en modo aislado.
Parte de la entrada Python Path Configuration.
Distinto en la versión 3.11: Ahora también se aplica en Windows.
wchar_t *prefix
El prefijo de directorio específico del sitio donde se instalan los archivos Python independientes de la
plataforma: sys.prefix.
Valor predeterminado: NULL.
Parte de la salida Python Path Configuration.
wchar_t *program_name
Nombre del programa utilizado para inicializar executable y en los primeros mensajes de error du-
rante la inicialización de Python.
• Si se ha llamado a Py_SetProgramName(), usa su argumento.
• En macOS, usa la variable de entorno PYTHONEXECUTABLE si está configurada.
• Si se define la macro WITH_NEXT_FRAMEWORK, utiliza la variable de entorno
__PYVENV_LAUNCHER__ si está configurada.
• Utiliza argv[0] de argv si está disponible y no está vacío.
• De lo contrario, utiliza L"python" en Windows o L"python3" en otras plataformas.
Valor predeterminado: NULL.
Parte de la entrada Python Path Configuration.
wchar_t *pycache_prefix
Directorio donde se escriben los archivos .pyc almacenados en caché: sys.pycache_prefix.
Establecido por la opción de línea de comando -X pycache_prefix=PATH y la variable de entorno
PYTHONPYCACHEPREFIX.
wchar_t *stdio_encoding
wchar_t *stdio_errors
Codificación y errores de codificación de sys.stdin, sys.stdout y sys.stderr (pero sys.
stderr siempre usa el controlador de errores "backslashreplace").
Si se ha llamado a Py_SetStandardStreamEncoding(), utilice sus argumentos error y errors si
no son NULL.
Utilice la variable de entorno PYTHONIOENCODING si no está vacía.
Codificación predeterminada:
• "UTF-8" si PyPreConfig.utf8_mode es distinto de cero.
• De lo contrario, usa el locale encoding.
Manejador de errores predeterminado:
• En Windows: use "surrogateescape".
• "surrogateescape" si PyPreConfig.utf8_mode no es cero o si la configuración regio-
nal LC_CTYPE es «C» o «POSIX».
• "strict" de lo contrario.
int tracemalloc
¿Habilitar tracemalloc?
Si no es cero, llama a tracemalloc.start() al inicio.
Establecido por la opción de línea de comando -X tracemalloc=N y por la variable de entorno
PYTHONTRACEMALLOC.
Por defecto: -1 en modo Python, 0 en modo aislado.
int perf_profiling
Enable compatibility mode with the perf profiler?
If non-zero, initialize the perf trampoline. See perf_profiling for more information.
Set by -X perf command line option and by the PYTHONPERFSUPPORT environment variable.
Default: -1.
Added in version 3.12.
int use_environment
¿Utiliza variables de entorno?
Si es igual a cero, ignora las variables de entorno.
Set to 0 by the -E environment variable.
Predeterminado: 1 en la configuración de Python y 0 en la configuración aislada.
int user_site_directory
Si es distinto de cero, agregue el directorio del sitio del usuario a sys.path.
Establecido en 0 por las opciones de línea de comando -s y -I.
Establecido en 0 por la variable de entorno PYTHONNOUSERSITE.
Por defecto: 1 en modo Python, 0 en modo aislado.
int verbose
Verbose mode. If greater than 0, print a message each time a module is imported, showing the place
(filename or built-in module) from which it is loaded.
If greater than or equal to 2, print a message for each file that is checked for when searching for a module.
Also provides information on module cleanup at exit.
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. Note that since 3.11, many parameters are not calculated until initialization, and so values cannot be read
from the configuration structure. Any values set before initialize is called will be left unchanged by initialization:
PyStatus init_python(const char *program_name)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
status = Py_InitializeFromConfig(&config);
done:
PyConfig_Clear(&config);
return status;
}
– PyConfig.pythonpath_env
– directorio de trabajo actual: para obtener rutas absolutas
– Variable de entorno PATH para obtener la ruta completa del programa (de PyConfig.
program_name)
– Variable de entorno __PYVENV_LAUNCHER__
– (Solo Windows) Rutas de aplicación en el registro en «SoftwarePythonPythonCoreX.YPythonPath» de
HKEY_CURRENT_USER y HKEY_LOCAL_MACHINE (donde X.Y es la versión de Python).
• Campos de salida de configuración de ruta:
– PyConfig.base_exec_prefix
– PyConfig.base_executable
– PyConfig.base_prefix
– PyConfig.exec_prefix
– PyConfig.executable
– PyConfig.module_search_paths_set, PyConfig.module_search_paths
– PyConfig.prefix
Si al menos un «campo de salida» no está establecido, Python calcula la configuración de la ruta para rellenar los
campos no establecidos. Si module_search_paths_set es igual a 0, module_search_paths se anula y
module_search_paths_set se establece en 1.
It is possible to completely ignore the function calculating the default path configuration by setting expli-
citly all path configuration output fields listed above. A string is considered as set even if it is non-empty.
module_search_paths is considered as set if module_search_paths_set is set to 1. In this case,
module_search_paths will be used without modification.
Set pathconfig_warnings to 0 to suppress warnings when calculating the path configuration (Unix only, Win-
dows does not log any warning).
Si base_prefix o los campos base_exec_prefix no están establecidos, heredan su valor de prefix y
exec_prefix respectivamente.
Py_RunMain() y Py_Main() modifican sys.path:
• Si run_filename está configurado y es un directorio que contiene un script __main__.py, anteponga
run_filename a sys.path.
• Si isolated es cero:
– Si run_module está configurado, anteponga el directorio actual a sys.path. No haga nada si el
directorio actual no se puede leer.
– Si run_filename está configurado, anteponga el directorio del nombre del archivo a sys.path.
– De lo contrario, anteponga una cadena de caracteres vacía a sys.path.
Si site_import no es cero, sys.path puede ser modificado por el módulo site. Si
user_site_directory no es cero y el directorio del paquete del sitio del usuario existe, el módulo
site agrega el directorio del paquete del sitio del usuario a sys.path.
La configuración de ruta utiliza los siguientes archivos de configuración:
• pyvenv.cfg
• archivo ._pth (ej: python._pth)
• pybuilddir.txt (sólo Unix)
Si un archivo ._pth está presente:
• Set isolated to 1.
• Set use_environment to 0.
• Set site_import to 0.
• Set safe_path to 1.
La variable de entorno __PYVENV_LAUNCHER__ se usa para establecer PyConfig.base_executable
10.11 Py_RunMain()
int Py_RunMain(void)
Ejecuta el comando (PyConfig.run_command), el script (PyConfig.run_filename) o el módulo
(PyConfig.run_module) especificado en la línea de comando o en la configuración.
Por defecto y cuando se usa la opción -i, ejecuta el REPL.
Finalmente, finaliza Python y retorna un estado de salida que se puede pasar a la función exit().
Consulte Configuración de Python para ver un ejemplo de Python personalizado que siempre se ejecuta en modo
aislado usando Py_RunMain().
10.12 Py_GetArgcArgv()
This section is a private provisional API introducing multi-phase initialization, the core feature of PEP 432:
• Fase de inicialización «Core», «Python mínimo»:
– Tipos incorporados;
– Excepciones incorporadas;
– Módulos incorporados y congelados;
– El módulo sys solo se inicializa parcialmente (por ejemplo sys.path aún no existe).
• Fase de inicialización «principal», Python está completamente inicializado:
– Instala y configura importlib;
– Aplique la Configuración de ruta;
– Instala manejadores de señal;
– Finaliza la inicialización del módulo sys (por ejemplo: crea sys.stdout y sys.path);
– Habilita características opcionales como faulthandler y tracemalloc;
– Importe el módulo site;
– etc.
API provisional privada:
• PyConfig._init_main: if set to 0, Py_InitializeFromConfig() stops at the «Core» initializa-
tion phase.
PyStatus _Py_InitializeMain(void)
Vaya a la fase de inicialización «Principal», finalice la inicialización de Python.
No se importa ningún módulo durante la fase «Core» y el módulo importlib no está configurado: la Configuración
de ruta solo se aplica durante la fase «Principal». Puede permitir personalizar Python en Python para anular o ajustar
Configuración de ruta, tal vez instale un importador personalizado sys.meta_path o un enlace de importación,
etc.
It may become possible to calculate the Path Configuration in Python, after the Core phase and before the Main phase,
which is one of the PEP 432 motivation.
La fase «Núcleo» no está definida correctamente: lo que debería estar y lo que no debería estar disponible en esta
fase aún no se ha especificado. La API está marcada como privada y provisional: la API se puede modificar o incluso
eliminar en cualquier momento hasta que se diseñe una API pública adecuada.
Ejemplo de ejecución de código Python entre las fases de inicialización «Core» y «Main»:
void init_python(void)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
config._init_main = 0;
status = Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
status = _Py_InitializeMain();
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
}
Gestión de la memoria
La gestión de memoria en Python implica un montón privado que contiene todos los objetos de Python y estructu-
ras de datos. El administrador de memoria de Python garantiza internamente la gestión de este montón privado. El
administrador de memoria de Python tiene diferentes componentes que se ocupan de varios aspectos de la gestión
dinámica del almacenamiento, como compartir, segmentación, asignación previa o almacenamiento en caché.
En el nivel más bajo, un asignador de memoria sin procesar asegura que haya suficiente espacio en el montón privado
para almacenar todos los datos relacionados con Python al interactuar con el administrador de memoria del sistema
operativo. Además del asignador de memoria sin procesar, varios asignadores específicos de objeto operan en el
mismo montón e implementan políticas de administración de memoria distintas adaptadas a las peculiaridades de
cada tipo de objeto. Por ejemplo, los objetos enteros se administran de manera diferente dentro del montón que las
cadenas, tuplas o diccionarios porque los enteros implican diferentes requisitos de almacenamiento y compensaciones
de velocidad / espacio. El administrador de memoria de Python delega parte del trabajo a los asignadores específicos
de objeto, pero asegura que este último opere dentro de los límites del montón privado.
Es importante comprender que la gestión del montón de Python la realiza el propio intérprete y que el usuario no
tiene control sobre él, incluso si manipulan regularmente punteros de objetos a bloques de memoria dentro de ese
montón. El administrador de memoria de Python realiza la asignación de espacio de almacenamiento dinámico para
los objetos de Python y otros búferes internos a pedido a través de las funciones de API de Python/C enumeradas en
este documento.
Para evitar daños en la memoria, los escritores de extensiones nunca deberían intentar operar en objetos Python con
las funciones exportadas por la biblioteca C: malloc(), calloc(), realloc() y free(). Esto dará como
resultado llamadas mixtas entre el asignador de C y el administrador de memoria de Python con consecuencias fatales,
ya que implementan diferentes algoritmos y operan en diferentes montones. Sin embargo, uno puede asignar y liberar
de forma segura bloques de memoria con el asignador de la biblioteca C para fines individuales, como se muestra en
el siguiente ejemplo:
PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyBytes_FromString(buf);
(continúe en la próxima página)
241
The Python/C API, Versión 3.12.4
En este ejemplo, la solicitud de memoria para el búfer de E/S es manejada por el asignador de la biblioteca C. El
administrador de memoria de Python solo participa en la asignación del objeto de bytes retornado como resultado.
Sin embargo, en la mayoría de las situaciones, se recomienda asignar memoria del montón de Python específicamente
porque este último está bajo el control del administrador de memoria de Python. Por ejemplo, esto es necesario cuando
el intérprete se amplía con nuevos tipos de objetos escritos en C. Otra razón para usar el montón de Python es el deseo
de informar al administrador de memoria de Python sobre las necesidades de memoria del módulo de extensión.
Incluso cuando la memoria solicitada se usa exclusivamente para fines internos y altamente específicos, delegar todas
las solicitudes de memoria al administrador de memoria de Python hace que el intérprete tenga una imagen más
precisa de su huella de memoria en su conjunto. En consecuencia, bajo ciertas circunstancias, el administrador de
memoria de Python puede o no desencadenar acciones apropiadas, como recolección de basura, compactación de
memoria u otros procedimientos preventivos. Tenga en cuenta que al usar el asignador de la biblioteca C como se
muestra en el ejemplo anterior, la memoria asignada para el búfer de E/S escapa completamente al administrador de
memoria Python.
Ver también:
La variable de entorno PYTHONMALLOC puede usarse para configurar los asignadores de memoria utilizados por
Python.
La variable de entorno PYTHONMALLOCSTATS se puede utilizar para imprimir estadísticas de asignador de me-
moria pymalloc cada vez que se crea un nuevo escenario de objetos pymalloc, y en el apagado.
Todas las funciones de asignación pertenecen a uno de los tres «dominios» diferentes (ver también
PyMemAllocatorDomain). Estos dominios representan diferentes estrategias de asignación y están optimiza-
dos para diferentes propósitos. Los detalles específicos sobre cómo cada dominio asigna memoria o qué funciones
internas llama cada dominio se considera un detalle de implementación, pero para fines de depuración, se puede en-
contrar una tabla simplificada en here. No existe un requisito estricto para usar la memoria retornada por las funciones
de asignación que pertenecen a un dominio dado solo para los propósitos sugeridos por ese dominio (aunque esta
es la práctica recomendada). Por ejemplo, se podría usar la memoria retornada por PyMem_RawMalloc() para
asignar objetos Python o la memoria retornada por PyObject_Malloc() para asignar memoria para búferes.
Los tres dominios de asignación son:
• Dominio sin formato: destinado a asignar memoria para búferes de memoria de uso general donde la asig-
nación debe ir al asignador del sistema o donde el asignador puede operar sin el GIL. La memoria se solicita
directamente al sistema.
• Dominio «Mem»: destinado a asignar memoria para búferes de Python y búferes de memoria de propósito
general donde la asignación debe realizarse con el GIL retenido. La memoria se toma del montículo privado de
Python.
• Dominio de objeto: destinado a asignar memoria perteneciente a objetos de Python. La memoria se toma del
montículo privado de Python.
Cuando se libera memoria previamente asignada por las funciones de asignación que pertenecen a un dominio dado,
se deben utilizar las funciones de desasignación específicas coincidentes. Por ejemplo, PyMem_Free() debe usarse
para liberar memoria asignada usando PyMem_Malloc().
Los siguientes conjuntos de funciones son envoltorios para el asignador del sistema. Estas funciones son seguras para
subprocesos, no es necesario mantener el GIL.
The default raw memory allocator uses the following functions: malloc(), calloc(), realloc() and
free(); call malloc(1) (or calloc(1, 1)) when requesting zero bytes.
Added in version 3.4.
void *PyMem_RawMalloc(size_t n)
Asigna n bytes y retorna un puntero de tipo void* a la memoria asignada, o NULL si la solicitud falla.
Solicitar cero bytes retorna un puntero distinto que no sea NULL si es posible, como si en su lugar se hubiera
llamado a PyMem_RawMalloc(1). La memoria no se habrá inicializado de ninguna manera.
void *PyMem_RawCalloc(size_t nelem, size_t elsize)
Asigna nelem elementos cada uno cuyo tamaño en bytes es elsize y retorna un puntero de tipo void* a la
memoria asignada, o NULL si la solicitud falla. La memoria se inicializa a ceros.
Solicitar elementos cero o elementos de tamaño cero bytes retorna un puntero distinto NULL si es posible,
como si en su lugar se hubiera llamado PyMem_RawCalloc(1, 1).
Added in version 3.5.
void *PyMem_RawRealloc(void *p, size_t n)
Cambia el tamaño del bloque de memoria señalado por p a n bytes. Los contenidos no se modificarán al mínimo
de los tamaños antiguo y nuevo.
Si p es NULL, la llamada es equivalente a PyMem_RawMalloc(n); de lo contrario, si n es igual a cero, el
bloque de memoria cambia de tamaño pero no se libera, y el puntero retornado no es NULL.
A menos que p sea NULL, debe haber sido retornado por una llamada previa a PyMem_RawMalloc(),
PyMem_RawRealloc() o PyMem_RawCalloc().
Si la solicitud falla, PyMem_RawRealloc() retorna NULL y p sigue siendo un puntero válido al área de
memoria anterior.
void PyMem_RawFree(void *p)
Libera el bloque de memoria al que apunta p, que debe haber sido retornado por una llamada anterior a
PyMem_RawMalloc(), PyMem_RawRealloc() o PyMem_RawCalloc(). De lo contrario, o si se
ha llamado antes a PyMem_RawFree(p), se produce un comportamiento indefinido.
Si p es NULL, no se realiza ninguna operación.
Los siguientes conjuntos de funciones, modelados según el estándar ANSI C, pero que especifican el comportamiento
cuando se solicitan cero bytes, están disponibles para asignar y liberar memoria del montón de Python.
El asignador de memoria predeterminado usa el asignador de memorya pymalloc.
Distinto en la versión 3.6: El asignador predeterminado ahora es pymalloc en lugar del malloc() del sistema.
void *PyMem_Malloc(size_t n)
Part of the Stable ABI. Asigna n bytes y retorna un puntero de tipo void* a la memoria asignada, o NULL si
la solicitud falla.
Solicitar cero bytes retorna un puntero distinto que no sea NULL si es posible, como si en su lugar se hubiera
llamado a PyMem_Malloc(1). La memoria no se habrá inicializado de ninguna manera.
Los siguientes conjuntos de funciones, modelados según el estándar ANSI C, pero que especifican el comportamiento
cuando se solicitan cero bytes, están disponibles para asignar y liberar memoria del montón de Python.
Nota: No hay garantía de que la memoria retornada por estos asignadores se pueda convertir con éxito en un ob-
jeto Python al interceptar las funciones de asignación en este dominio mediante los métodos descritos en la sección
Personalizar Asignadores de Memoria.
void *PyObject_Malloc(size_t n)
Part of the Stable ABI. Asigna n bytes y retorna un puntero de tipo void* a la memoria asignada, o NULL si
la solicitud falla.
Solicitar cero bytes retorna un puntero distinto que no sea NULL si es posible, como si en su lugar se hubiera
llamado a PyObject_Malloc(1). La memoria no se habrá inicializado de ninguna manera.
void *PyObject_Calloc(size_t nelem, size_t elsize)
Part of the Stable ABI since version 3.7. Asigna nelem elementos cada uno cuyo tamaño en bytes es elsize y
retorna un puntero de tipo void* a la memoria asignada, o NULL si la solicitud falla. La memoria se inicializa
a ceros.
Solicitar elementos cero o elementos de tamaño cero bytes retorna un puntero distinto NULL si es posible,
como si en su lugar se hubiera llamado PyObject_Calloc(1, 1).
Added in version 3.5.
void *PyObject_Realloc(void *p, size_t n)
Part of the Stable ABI. Cambia el tamaño del bloque de memoria señalado por p a n bytes. Los contenidos no
se modificarán al mínimo de los tamaños antiguo y nuevo.
Si p es NULL, la llamada es equivalente a PyObject_Malloc(n); de lo contrario, si n es igual a cero, el
bloque de memoria cambia de tamaño pero no se libera, y el puntero retornado no es NULL.
A menos que p sea NULL, debe haber sido retornado por una llamada previa a PyObject_Malloc(),
PyObject_Realloc() o PyObject_Calloc().
Si la solicitud falla, PyObject_Realloc() retorna NULL y p sigue siendo un puntero válido al área de
memoria anterior.
void PyObject_Free(void *p)
Part of the Stable ABI. Libera el bloque de memoria al que apunta p, que debe haber sido retornado por una
llamada anterior a PyObject_Malloc(), PyObject_Realloc() o PyObject_Calloc(). De lo
contrario, o si se ha llamado antes a PyObject_Free(p), se produce un comportamiento indefinido.
Si p es NULL, no se realiza ninguna operación.
Leyenda:
• Nombre: valor para variable de entorno PYTHONMALLOC.
• malloc: asignadores del sistema de la biblioteca C estándar, funciones C: malloc(), calloc(),
realloc() y free().
• pymalloc: asignador de memoria pymalloc.
• «+ debug»: con enlaces de depuración en los asignadores de memoria de Python.
• «Debug build»: Compilación de Python en modo de depuración.
Campo Significado
void *ctx contexto de usuario pasado como primer
argumento
void* malloc(void *ctx, size_t size) asignar un bloque de memoria
void* calloc(void *ctx, size_t nelem, asignar un bloque de memoria inicializado
size_t elsize) con ceros
void* realloc(void *ctx, void *ptr, asignar o cambiar el tamaño de un bloque
size_t new_size) de memoria
void free(void *ctx, void *ptr) liberar un bloque de memoria
Distinto en la versión 3.5: The PyMemAllocator structure was renamed to PyMemAllocatorEx and a
new calloc field was added.
type PyMemAllocatorDomain
Enum se utiliza para identificar un dominio asignador. Dominios:
PYMEM_DOMAIN_RAW
Funciones:
• PyMem_RawMalloc()
• PyMem_RawRealloc()
• PyMem_RawCalloc()
• PyMem_RawFree()
PYMEM_DOMAIN_MEM
Funciones:
• PyMem_Malloc(),
• PyMem_Realloc()
• PyMem_Calloc()
• PyMem_Free()
PYMEM_DOMAIN_OBJ
Funciones:
• PyObject_Malloc()
• PyObject_Realloc()
• PyObject_Calloc()
• PyObject_Free()
void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Obtenga el asignador de bloque de memoria del dominio especificado.
void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Establece el asignador de bloque de memoria del dominio especificado.
El nuevo asignador debe retornar un puntero distinto NULL al solicitar cero bytes.
For the PYMEM_DOMAIN_RAW domain, the allocator must be thread-safe: the GIL is not held when the allo-
cator is called.
For the remaining domains, the allocator must also be thread-safe: the allocator may be called in different
interpreters that do not share a GIL.
Si el nuevo asignador no es un enlace (no llama al asignador anterior), se debe llamar a la función
PyMem_SetupDebugHooks() para reinstalar los enlaces de depuración en la parte superior del nuevo
asignador.
Vea también PyPreConfig.allocator y Preinicialización de Python con PyPreConfig.
p[N+S:N+2*S]
Solo se utiliza si la macro PYMEM_DEBUG_SERIALNO está definida (no definida por defecto).
A serial number, incremented by 1 on each call to a malloc-like or realloc-like function. Big-endian size_t.
If «bad memory» is detected later, the serial number gives an excellent way to set a breakpoint on the next run,
to capture the instant at which this block was passed out. The static function bumpserialno() in obmalloc.c is
the only place the serial number is incremented, and exists so you can set such a breakpoint easily.
Una función de tipo realloc o de tipo free primero verifica que los bytes PYMEM_FORBIDDENBYTE en cada
extremo estén intactos. Si se han modificado, la salida de diagnóstico se escribe en stderr y el programa se aborta
mediante Py_FatalError(). El otro modo de falla principal es provocar un error de memoria cuando un programa
lee uno de los patrones de bits especiales e intenta usarlo como una dirección. Si ingresa a un depurador y observa
el objeto, es probable que vea que está completamente lleno de PYMEM_DEADBYTE (lo que significa que se está
usando la memoria liberada) o PYMEM_CLEANBYTE (que significa que se está usando la memoria no inicializada).
Distinto en la versión 3.6: The PyMem_SetupDebugHooks() function now also works on Python compiled in
release mode. On error, the debug hooks now use tracemalloc to get the traceback where a memory block
was allocated. The debug hooks now also check if the GIL is held when functions of PYMEM_DOMAIN_OBJ and
PYMEM_DOMAIN_MEM domains are called.
Distinto en la versión 3.8: Los patrones de bytes 0xCB (PYMEM_CLEANBYTE), 0xDB (PYMEM_DEADBYTE) y
0xFB (PYMEM_FORBIDDENBYTE) se han reemplazado por 0xCD, 0xDD y 0xFD para usar los mismos valores
que la depuración de Windows CRT malloc() y free().
Python has a pymalloc allocator optimized for small objects (smaller or equal to 512 bytes) with a short lifetime. It
uses memory mappings called «arenas» with a fixed size of either 256 KiB on 32-bit platforms or 1 MiB on 64-bit
platforms. It falls back to PyMem_RawMalloc() and PyMem_RawRealloc() for allocations larger than 512
bytes.
pymalloc is the default allocator of the PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) and
PYMEM_DOMAIN_OBJ (ex: PyObject_Malloc()) domains.
El asignador de arena utiliza las siguientes funciones:
• VirtualAlloc() and VirtualFree() on Windows,
• mmap() and munmap() if available,
• malloc() y free() en caso contrario.
Este asignador está deshabilitado si Python está configurado con la opción --without-pymalloc. También
se puede deshabilitar en tiempo de ejecución usando la variable de entorno PYTHONMALLOC (por ejemplo:
PYTHONMALLOC=malloc).
Campo Significado
void *ctx contexto de usuario pasado como primer ar-
gumento
void* alloc(void *ctx, size_t size) asignar una arena de bytes de tamaño
void free(void *ctx, void *ptr, size_t liberar la arena
size)
11.11 Ejemplos
Aquí está el ejemplo de la sección Visión general, reescrito para que el búfer de E/S se asigne desde el montón de
Python utilizando el primer conjunto de funciones:
PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;
PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Del(buf); /* allocated with PyMem_New */
return res;
Tenga en cuenta que en los dos ejemplos anteriores, el búfer siempre se manipula a través de funciones que pertenecen
al mismo conjunto. De hecho, es necesario usar la misma familia de API de memoria para un bloque de memoria
dado, de modo que el riesgo de mezclar diferentes asignadores se reduzca al mínimo. La siguiente secuencia de
código contiene dos errores, uno de los cuales está etiquetado como fatal porque mezcla dos asignadores diferentes
que operan en montones diferentes.:
In addition to the functions aimed at handling raw memory blocks from the Python heap, objects in Python are
allocated and released with PyObject_New, PyObject_NewVar and PyObject_Del().
Esto se explicará en el próximo capítulo sobre cómo definir e implementar nuevos tipos de objetos en C.
Este capítulo describe las funciones, los tipos y las macros utilizados al definir nuevos tipos de objetos.
253
The Python/C API, Versión 3.12.4
called from the tp_dealloc handler specified in the object’s type. The fields of the object should not be
accessed after this call as the memory is no longer a valid Python object.
PyObject _Py_NoneStruct
Objeto que es visible en Python como None. Esto solo se debe acceder utilizando el macro Py_None, que se
evalúa como un puntero a este objeto.
Ver también:
PyModule_Create()
Para asignar y crear módulos de extensión.
Hay un gran número de estructuras que se utilizan en la definición de los tipos de objetos de Python. Esta sección
describe estas estructuras y la forma en que se utilizan.
All Python objects ultimately share a small number of fields at the beginning of the object’s representation in memory.
These are represented by the PyObject and PyVarObject types, which are defined, in turn, by the expansions of
some macros also used, whether directly or indirectly, in the definition of all other Python objects. Additional macros
can be found under reference counting.
type PyObject
Part of the Limited API. (Only some members are part of the stable ABI.) All object types are extensions of this
type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In
a normal «release» build, it contains only the object’s reference count and a pointer to the corresponding type
object. Nothing is actually declared to be a PyObject, but every pointer to a Python object can be cast to a
PyObject*. Access to the members must be done by using the macros Py_REFCNT and Py_TYPE.
type PyVarObject
Part of the Limited API. (Only some members are part of the stable ABI.) This is an extension of PyObject
that adds the ob_size field. This is only used for objects that have some notion of length. This type does not
often appear in the Python/C API. Access to the members must be done by using the macros Py_REFCNT,
Py_TYPE, and Py_SIZE.
PyObject_HEAD
Esta es una macro utilizado cuando se declara nuevos tipos que representan objetos sin una longitud variable.
La macro PyObject_HEAD se expande a:
PyObject ob_base;
PyVarObject 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.
La firma de la función es:
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:
int ml_flags
Flags bits indicating how the call should be constructed.
const char *ml_doc
Points to the contents of the docstring.
The ml_meth is a C function pointer. The functions may be of different types, but they always return PyObject*.
If the function is not of the PyCFunction, the compiler will require a cast in the method table. Even though
PyCFunction defines the first parameter as PyObject*, it is common that the method implementation uses the
specific C type of the self object.
The ml_flags field is a bitfield which can include the following flags. The individual flags indicate either a calling
convention or a binding convention.
Existen estas convenciones de llamada:
METH_VARARGS
This is the typical calling convention, where the methods have the type PyCFunction. The function expects
two PyObject* values. The first one is the self object for methods; for module functions, it is the module
object. The second parameter (often called args) is a tuple object representing all arguments. This parameter
is typically processed using PyArg_ParseTuple() or PyArg_UnpackTuple().
METH_KEYWORDS
Can only be used in certain combinations with other flags: METH_VARARGS | METH_KEYWORDS,
METH_FASTCALL | METH_KEYWORDS and METH_METHOD | METH_FASTCALL | METH_KEYWORDS.
METH_VARARGS | METH_KEYWORDS
Los métodos con estas flags deben ser del tipo PyCFunctionWithKeywords. La función espera tres
parámetros: self, args, kwargs donde kwargs es un diccionario de todos los argumentos de palabras clave o,
posiblemente, NULL si no hay argumentos de palabra clave. Los parámetros se procesan típicamente usando
PyArg_ParseTupleAndKeywords().
METH_FASTCALL
Fast calling convention supporting only positional arguments. The methods have the type
_PyCFunctionFast. The first parameter is self, the second parameter is a C array of PyObject* values
indicating the arguments and the third parameter is the number of arguments (the length of the array).
Added in version 3.7.
Distinto en la versión 3.10: METH_FASTCALL is now part of the stable ABI.
METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL supporting also keyword arguments, with methods of type
_PyCFunctionFastWithKeywords. Keyword arguments are passed the same way as in the vec-
torcall protocol: there is an additional fourth PyObject* parameter which is a tuple representing the names
of the keyword arguments (which are guaranteed to be strings) or possibly NULL if there are no keywords.
The values of the keyword arguments are stored in the args array, after the positional arguments.
Added in version 3.7.
METH_METHOD
Can only be used in the combination with other flags: METH_METHOD | METH_FASTCALL |
METH_KEYWORDS.
METH_METHOD | METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL | METH_KEYWORDS supporting the defining class, that is, the class that
contains the method in question. The defining class might be a superclass of Py_TYPE(self).
El método debe ser de tipo PyCMethod, lo mismo que para METH_FASTCALL | METH_KEYWORDS con
el argumento defining_clase añadido después de self.
Added in version 3.9.
METH_NOARGS
Methods without parameters don’t need to check whether arguments are given if they are listed with the
METH_NOARGS flag. They need to be of type PyCFunction. The first parameter is typically named self
and will hold a reference to the module or object instance. In all cases the second parameter will be NULL.
La función debe tener 2 parámetros. Dado que el segundo parámetro no se usa, Py_UNUSED se puede usar
para evitar una advertencia del compilador.
METH_O
Methods with a single object argument can be listed with the METH_O flag, instead of invoking
PyArg_ParseTuple() with a "O" argument. They have the type PyCFunction, with the self para-
meter, and a PyObject* parameter representing the single argument.
Estas dos constantes no se utilizan para indicar la convención de llamada si no la vinculación cuando su usan con
métodos de las clases. Estos no se pueden usar para funciones definidas para módulos. A lo sumo uno de estos flags
puede establecerse en un método dado.
METH_CLASS
Al método se le pasará el objeto tipo como primer parámetro, en lugar de una instancia del tipo. Esto se
utiliza para crear métodos de clase (class methods), similar a lo que se crea cuando se utiliza la función
classmethod() incorporada.
METH_STATIC
El método pasará NULL como el primer parámetro en lugar de una instancia del tipo. Esto se utiliza para crear
métodos estáticos (static methods), similar a lo que se crea cuando se utiliza la función staticmethod()
incorporada.
En otros controles constantes dependiendo si se carga un método en su lugar (in place) de otra definición con el mismo
nombre del método.
METH_COEXIST
The method will be loaded in place of existing definitions. Without METH_COEXIST, the default is to skip
repeated definitions. Since slot wrappers are loaded before the method table, the existence of a sq_contains
slot, for example, would generate a wrapped method named __contains__() and preclude the loading of
a corresponding PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in
place of the wrapper object and will co-exist with the slot. This is helpful because calls to PyCFunctions are
optimized more than wrapper object calls.
PyObject *PyCMethod_New(PyMethodDef *ml, PyObject *self, PyObject *module, PyTypeObject *cls)
Return value: New reference. Part of the Stable ABI since version 3.9. Turn ml into a Python callable object.
The caller must ensure that ml outlives the callable. Typically, ml is defined as a static variable.
The self parameter will be passed as the self argument to the C function in ml->ml_meth when invoked.
self can be NULL.
The callable object’s __module__ attribute can be set from the given module argument. module should be a
Python string, which will be used as name of the module the function is defined in. If unavailable, it can be set
to None or NULL.
Ver también:
function.__module__
The cls parameter will be passed as the defining_class argument to the C function. Must be set if
METH_METHOD is set on ml->ml_flags.
Added in version 3.9.
PyObject *PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module)
Return value: New reference. Part of the Stable ABI. Equivalent to PyCMethod_New(ml, self,
module, NULL).
PyObject *PyCFunction_New(PyMethodDef *ml, PyObject *self)
Return value: New reference. Part of the Stable ABI since version 3.4. Equivalent to PyCMethod_New(ml,
self, NULL, NULL).
type PyMemberDef
Part of the Stable ABI (including all members). Structure which describes an attribute of a type which corres-
ponds to a C struct member. When defining a class, put a NULL-terminated array of these structures in the
tp_members slot.
Its fields are, in order:
const char *name
Name of the member. A NULL value marks the end of a PyMemberDef[] array.
The string should be static, no copy is made of it.
int type
The type of the member in the C struct. See Member types for the possible values.
Py_ssize_t offset
The offset in bytes that the member is located on the type’s object struct.
int flags
Zero or more of the Member flags, combined using bitwise OR.
const char *doc
The docstring, or NULL. The string should be static, no copy is made of it. Typically, it is defined using
PyDoc_STR.
By default (when flags is 0), members allow both read and write access. Use the Py_READONLY flag
for read-only access. Certain types, like Py_T_STRING, imply Py_READONLY. Only Py_T_OBJECT_EX
(and legacy T_OBJECT) members can be deleted.
For heap-allocated types (created using PyType_FromSpec() or similar), PyMemberDef may
contain a definition for the special member "__vectorcalloffset__", corresponding to
tp_vectorcall_offset in type objects. These must be defined with Py_T_PYSSIZET and
Py_READONLY, for example:
Member flags
Member types
PyMemberDef.type can be one of the following macros corresponding to various C types. When the member is
accessed in Python, it will be converted to the equivalent Python type. When it is set from Python, it will be converted
back to the C type. If that is not possible, an exception such as TypeError or ValueError is raised.
Unless marked (D), attributes defined this way cannot be deleted using e.g. del or delattr().
short int
Py_T_SHORT
int int
Py_T_INT
long int
Py_T_LONG
Py_ssize_t int
Py_T_PYSSIZET
float float
Py_T_FLOAT
double float
Py_T_DOUBLE
type PyGetSetDef
Part of the Stable ABI (including all members). Estructura para definir el acceso para un tipo como el de una
propiedad. Véase también la descripción de la ranura PyTypeObject.tp_getset.
const char *name
nombre del atributo
getter get
C function to get the attribute.
setter set
Optional C function to set or delete the attribute. If NULL, the attribute is read-only.
const char *doc
docstring opcional
void *closure
Optional user data pointer, providing additional data for getter and setter.
typedef PyObject *(*getter)(PyObject*, void*)
Part of the Stable ABI. The get function takes one PyObject* parameter (the instance) and a user data
pointer (the associated closure):
Debe retornar una nueva referencia en caso de éxito o NULL con una excepción establecida en caso de error.
typedef int (*setter)(PyObject*, PyObject*, void*)
Part of the Stable ABI. set functions take two PyObject* parameters (the instance and the value to be set)
and a user data pointer (the associated closure):
En caso de que el atributo deba suprimirse el segundo parámetro es NULL. Debe retornar 0 en caso de éxito o
-1 con una excepción explícita en caso de fallo.
Perhaps one of the most important structures of the Python object system is the structure that defines a new type: the
PyTypeObject structure. Type objects can be handled using any of the PyObject_* or PyType_* functions,
but do not offer much that’s interesting to most Python applications. These objects are fundamental to how objects
behave, so they are very important to the interpreter itself and to any extension module that implements new types.
Los objetos de tipo son bastante grandes en comparación con la mayoría de los tipos estándar. La razón del tamaño
es que cada objeto de tipo almacena una gran cantidad de valores, principalmente punteros de función C, cada uno
de los cuales implementa una pequeña parte de la funcionalidad del tipo. Los campos del objeto tipo se examinan en
detalle en esta sección. Los campos se describirán en el orden en que aparecen en la estructura.
Además de la siguiente referencia rápida, la sección Ejemplos proporciona una visión rápida del significado y uso de
PyTypeObject.
sub-ranuras (sub-slots)
<>: Names in angle brackets should be initially set to NULL and treated as read-only.
[]: Names in square brackets are for internal use only.
<R> (as a prefix) means the field is required (must be non-NULL).
2 Columnas:
bf_getbuffer getbufferproc()
continúe en la próxima página
ranura de 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 267
PyObject *
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;
(continúe en la próxima página)
destructor tp_finalize;
vectorcallfunc tp_vectorcall;
The type object structure extends the PyVarObject structure. The ob_size field is used for dynamic types (crea-
ted by type_new(), usually called from a class statement). Note that PyType_Type (the metatype) initializes
tp_itemsize, which means that its instances (i.e. type objects) must have the ob_size field.
Py_ssize_t PyObject.ob_refcnt
Part of the Stable ABI. This is the type object’s reference count, initialized to 1 by the
PyObject_HEAD_INIT macro. Note that for statically allocated type objects, the type’s instances
(objects whose ob_type points back to the type) do not count as references. But for dynamically allocated
type objects, the instances do count as references.
Herencia:
Este campo no es heredado por los subtipos.
PyTypeObject *PyObject.ob_type
Part of the Stable ABI. Este es el tipo del tipo, en otras palabras, su metatipo. Se inicializa mediante el ar-
gumento de la macro PyObject_HEAD_INIT, y su valor normalmente debería ser &PyType_Type. Sin
embargo, para los módulos de extensión cargables dinámicamente que deben ser utilizables en Windows (al
menos), el compilador se queja de que este no es un inicializador válido. Por lo tanto, la convención es pasar
NULL al macro PyObject_HEAD_INIT e inicializar este campo explícitamente al comienzo de la función
de inicialización del módulo, antes de hacer cualquier otra cosa. Esto normalmente se hace así:
Foo_Type.ob_type = &PyType_Type;
This should be done before any instances of the type are created. PyType_Ready() checks if ob_type
is NULL, and if so, initializes it to the ob_type field of the base class. PyType_Ready() will not change
this field if it is non-zero.
Herencia:
Este campo es heredado por subtipos.
PyObject *PyObject._ob_next
PyObject *PyObject._ob_prev
Estos campos solo están presentes cuando se define la macro Py_TRACE_REFS (ver la opción
configure --with-trace-refs).
Their initialization to NULL is taken care of by the PyObject_HEAD_INIT macro. For statically allocated
objects, these fields always remain NULL. For dynamically allocated objects, these two fields are used to link
the object into a doubly linked list of all live objects on the heap.
Esto podría usarse para varios propósitos de depuración; actualmente, los únicos usos son la función sys.
getobjects() y para imprimir los objetos que aún están vivos al final de una ejecución cuando se establece
la variable de entorno PYTHONDUMPREFS.
Herencia:
Estos campos no son heredados por subtipos.
Py_ssize_t PyVarObject.ob_size
Part of the Stable ABI. Para objetos de tipo estáticamente asignados, debe inicializarse a cero. Para objetos de
tipo dinámicamente asignados, este campo tiene un significado interno especial.
Herencia:
Este campo no es heredado por los subtipos.
Each slot has a section describing inheritance. If PyType_Ready() may set a value when the field is set to
NULL then there will also be a «Default» section. (Note that many fields set on PyBaseObject_Type and
PyType_Type effectively act as defaults.)
const char *PyTypeObject.tp_name
Pointer to a NUL-terminated string containing the name of the type. For types that are accessible as module
globals, the string should be the full module name, followed by a dot, followed by the type name; for built-in
types, it should be just the type name. If the module is a submodule of a package, the full package name is
part of the full module name. For example, a type named T defined in module M in subpackage Q in package
P should have the tp_name initializer "P.Q.M.T".
Para objetos de tipo dinámicamente asignados, éste debe ser sólo el nombre del tipo, y el nombre del módulo
almacenado explícitamente en el dict tipo que el valor de '__module__' clave.
Para objetos de tipo estáticamente asignados, el campo tp_name debe contener un punto. Todo lo que está antes
del último punto se hace accesible como el atributo __module__, y todo lo que está después del último punto
se hace accesible como el atributo __name__.
Si no hay ningún punto, todo el campo tp_name se hace accesible como el atributo __name__, y el atributo
__module__ no está definido (a menos que sea explícitamente establecido en el diccionario, como se explicó
anteriormente). Esto significa que su tipo será imposible de guardar como pickle. Además, no figurará en la
documentación del módulo creado con pydoc.
Este campo no debe ser NULL. Es el único campo obligatorio en PyTypeObject() (que no sea potencial-
mente tp_itemsize).
Herencia:
Este campo no es heredado por los subtipos.
Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize
Estos campos permiten calcular el tamaño en bytes de instancias del tipo.
Hay dos tipos de tipos: los tipos con instancias de longitud fija tienen un campo cero tp_itemsize, los
tipos con instancias de longitud variable tienen un campo distinto de cero tp_itemsize. Para un tipo con
instancias de longitud fija, todas las instancias tienen el mismo tamaño, dado en tp_basicsize.
For a type with variable-length instances, the instances must have an ob_size field, and the instance size
is tp_basicsize plus N times tp_itemsize, where N is the «length» of the object. The value of N
is typically stored in the instance’s ob_size field. There are exceptions: for example, ints use a negative
ob_size to indicate a negative number, and N is abs(ob_size) there. Also, the presence of an ob_size
field in the instance layout doesn’t mean that the instance structure is variable-length (for example, the structure
for the list type has fixed-length instances, yet those instances have a meaningful ob_size field).
The basic size includes the fields in the instance declared by the macro PyObject_HEAD or
PyObject_VAR_HEAD (whichever is used to declare the instance struct) and this in turn includes the
_ob_prev and _ob_next fields if they are present. This means that the only correct way to get an initializer
for the tp_basicsize is to use the sizeof operator on the struct used to declare the instance layout. The
basic size does not include the GC header size.
Una nota sobre la alineación: si los elementos variables requieren una alineación particular, esto debe
ser atendido por el valor de tp_basicsize. Ejemplo: supongamos que un tipo implementa un arreglo
de dobles (double). tp_itemsize es sizeof(double). Es responsabilidad del programador que
tp_basicsize es un múltiplo de sizeof(double) (suponiendo que este sea el requisito de alineación
para double).
Para cualquier tipo con instancias de longitud variable, este campo no debe ser NULL.
Herencia:
Estos campos se heredan por separado por subtipos. Si el tipo base tiene un miembro distinto de cero
tp_itemsize, generalmente no es seguro establecer tp_itemsize en un valor diferente de cero en un
subtipo ( aunque esto depende de la implementación del tipo base).
destructor PyTypeObject.tp_dealloc
Un puntero a la función destructor de instancias. Esta función debe definirse a menos que el tipo garantice que
sus instancias nunca se desasignarán (como es el caso de los singletons None y Ellipsis). La firma de la
función es:
The destructor function is called by the Py_DECREF() and Py_XDECREF() macros when the new referen-
ce count is zero. At this point, the instance is still in existence, but there are no references to it. The destructor
function should free all references which the instance owns, free all memory buffers owned by the instance
(using the freeing function corresponding to the allocation function used to allocate the buffer), and call the
type’s tp_free function. If the type is not subtypable (doesn’t have the Py_TPFLAGS_BASETYPE flag
bit set), it is permissible to call the object deallocator directly instead of via tp_free. The object dealloca-
tor should be the one used to allocate the instance; this is normally PyObject_Del() if the instance was
allocated using PyObject_New or PyObject_NewVar, or PyObject_GC_Del() if the instance was
allocated using PyObject_GC_New or PyObject_GC_NewVar.
If the type supports garbage collection (has the Py_TPFLAGS_HAVE_GC flag bit set), the destructor should
call PyObject_GC_UnTrack() before clearing any member fields.
Finally, if the type is heap allocated (Py_TPFLAGS_HEAPTYPE), the deallocator should release the owned
reference to its type object (via Py_DECREF()) after calling the type deallocator. In order to avoid dangling
pointers, the recommended way to achieve this is:
Herencia:
Este campo es heredado por subtipos.
Py_ssize_t PyTypeObject.tp_vectorcall_offset
Un desplazamiento opcional a una función por instancia que implementa la llamada al objeto usando vectorcall
protocol, una alternativa más eficiente del simple tp_call.
This field is only used if the flag Py_TPFLAGS_HAVE_VECTORCALL is set. If so, this must be a positive
integer containing the offset in the instance of a vectorcallfunc pointer.
The vectorcallfunc pointer may be NULL, in which case the instance behaves as if
Py_TPFLAGS_HAVE_VECTORCALL was not set: calling the instance falls back to tp_call.
Cualquier clase que establezca _Py_TPFLAGS_HAVE_VECTORCALL también debe establecer tp_call
y asegurarse de que su comportamiento sea coherente con la función vectorcallfunc. Esto se puede hacer con-
figurando tp_call en PyVectorcall_Call().
Distinto en la versión 3.8: Antes de la versión 3.8, este slot se llamaba tp_print. En Python 2.x, se usó para
imprimir en un archivo. En Python 3.0 a 3.7, no se usó.
Distinto en la versión 3.12: Before version 3.12, it was not recommended for mutable heap types to implement
the vectorcall protocol. When a user sets __call__ in Python code, only tp_call is updated, likely making
it inconsistent with the vectorcall function. Since 3.12, setting __call__ will disable vectorcall optimization
by clearing the Py_TPFLAGS_HAVE_VECTORCALL flag.
Herencia:
This field is always inherited. However, the Py_TPFLAGS_HAVE_VECTORCALL flag is not always inherited.
If it’s not set, then the subclass won’t use vectorcall, except when PyVectorcall_Call() is explicitly
called.
getattrfunc PyTypeObject.tp_getattr
Un puntero opcional a la función «obtener atributo cadena de caracteres» (get-attribute-string).
Este campo está en desuso. Cuando se define, debe apuntar a una función que actúe igual que la función
tp_getattro, pero tomando una cadena de caracteres C en lugar de un objeto de cadena Python para dar
el nombre del atributo.
Herencia:
Group: tp_getattr, tp_getattro
Este campo es heredado por los subtipos junto con tp_getattro: un subtipo hereda ambos tp_getattr
y tp_getattro de su base escriba cuando los subtipos tp_getattr y tp_getattro son ambos NULL.
setattrfunc PyTypeObject.tp_setattr
Un puntero opcional a la función para configurar y eliminar atributos.
Este campo está en desuso. Cuando se define, debe apuntar a una función que actúe igual que la función
tp_setattro, pero tomando una cadena de caracteres C en lugar de un objeto de cadena Python para dar
el nombre del atributo.
Herencia:
Group: tp_setattr, tp_setattro
Este campo es heredado por los subtipos junto con tp_setattro: un subtipo hereda ambos tp_setattr
y tp_setattro de su base escriba cuando los subtipos tp_setattr y tp_setattro son ambos NULL.
PyAsyncMethods *PyTypeObject.tp_as_async
Puntero a una estructura adicional que contiene campos relevantes solo para los objetos que implementan los
protocolos «esperable» (awaitable) y «iterador asíncrono» (asynchronous iterator) en el nivel C. Ver Estructuras
de objetos asíncronos para más detalles.
Added in version 3.5: Anteriormente conocidos como tp_compare y tp_reserved.
Herencia:
El campo tp_as_async no se hereda, pero los campos contenidos se heredan individualmente.
reprfunc PyTypeObject.tp_repr
Un puntero opcional a una función que implementa la función incorporada repr().
La firma es la misma que para PyObject_Repr():
La función debe retornar una cadena de caracteres o un objeto Unicode. Idealmente, esta función debería
retornar una cadena que, cuando se pasa a eval(), dado un entorno adecuado, retorna un objeto con el
mismo valor. Si esto no es factible, debe retornar una cadena que comience con '<' y termine con '>' desde
la cual se puede deducir tanto el tipo como el valor del objeto.
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Cuando este campo no está configurado, se retorna una cadena de caracteres de la forma <%s object at
%p>, donde %s se reemplaza por el nombre del tipo y %p por dirección de memoria del objeto.
PyNumberMethods *PyTypeObject.tp_as_number
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el pro-
tocolo numérico. Estos campos están documentados en Estructuras de objetos de números.
Herencia:
El campo tp_as_number no se hereda, pero los campos contenidos se heredan individualmente.
PySequenceMethods *PyTypeObject.tp_as_sequence
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el pro-
tocolo de secuencia. Estos campos están documentados en estructuras de secuencia.
Herencia:
El campo tp_as_sequence no se hereda, pero los campos contenidos se heredan individualmente.
PyMappingMethods *PyTypeObject.tp_as_mapping
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan el pro-
tocolo de mapeo. Estos campos están documentados en Estructuras de objetos mapeo.
Herencia:
El campo tp_as_mapping no se hereda, pero los campos contenidos se heredan individualmente.
hashfunc PyTypeObject.tp_hash
Un puntero opcional a una función que implementa la función incorporada hash().
La firma es la misma que para PyObject_Hash():
El valor -1 no debe retornarse como un valor de retorno normal; Cuando se produce un error durante el cálculo
del valor hash, la función debe establecer una excepción y retornar -1.
When this field is not set (and tp_richcompare is not set), an attempt to take the hash of the object raises
TypeError. This is the same as setting it to PyObject_HashNotImplemented().
Este campo se puede establecer explícitamente en PyObject_HashNotImplemented() para bloquear
la herencia del método hash de un tipo primario. Esto se interpreta como el equivalente de __hash__ =
None en el nivel de Python, lo que hace que isinstance(o, collections.Hashable) retor-
ne correctamente False. Tenga en cuenta que lo contrario también es cierto: establecer __hash__ =
None en una clase en el nivel de Python dará como resultado que la ranura tp_hash se establezca en
PyObject_HashNotImplemented().
Herencia:
Group: tp_hash, tp_richcompare
Este campo es heredado por subtipos junto con tp_richcompare: un subtipo hereda ambos
tp_richcompare y tp_hash, cuando los subtipos tp_richcompare y tp_hash son ambos NULL.
ternaryfunc PyTypeObject.tp_call
Un puntero opcional a una función que implementa la llamada al objeto. Esto debería ser NULL si el objeto no
es invocable. La firma es la misma que para PyObject_Call():
Herencia:
Este campo es heredado por subtipos.
reprfunc PyTypeObject.tp_str
Un puntero opcional a una función que implementa la operación integrada str(). (Tenga en cuenta que str
es un tipo ahora, y str() llama al constructor para ese tipo. Este constructor llama a PyObject_Str()
para hacer el trabajo real, y PyObject_Str() llamará a este controlador.)
La firma es la misma que para PyObject_Str():
La función debe retornar una cadena de caracteres o un objeto Unicode. Debe ser una representación de cadena
«amigable» del objeto, ya que esta es la representación que será utilizada, entre otras cosas, por la función
print().
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Cuando este campo no está configurado, se llama a PyObject_Repr() para retornar una representación
de cadena de caracteres.
getattrofunc PyTypeObject.tp_getattro
Un puntero opcional a la función «obtener atributo» (get-attribute).
La firma es la misma que para PyObject_GetAttr():
Además, se debe admitir la configuración de value en NULL para eliminar un atributo. Por lo general, es
conveniente establecer este campo en PyObject_GenericSetAttr(), que implementa la forma normal
de establecer los atributos del objeto.
Herencia:
Group: tp_setattr, tp_setattro
Los subtipos heredan este campo junto con tp_setattr: un subtipo hereda ambos tp_setattr y
tp_setattro de su base escriba cuando los subtipos tp_setattr y tp_setattro son ambos NULL.
Por defecto:
PyBaseObject_Type uses PyObject_GenericSetAttr().
PyBufferProcs *PyTypeObject.tp_as_buffer
Puntero a una estructura adicional que contiene campos relevantes solo para objetos que implementan la interfaz
del búfer. Estos campos están documentados en Estructuras de objetos búfer.
Herencia:
El campo tp_as_buffer no se hereda, pero los campos contenidos se heredan individualmente.
unsigned long PyTypeObject.tp_flags
Este campo es una máscara de bits de varias banderas. Algunas banderas indican semántica variante para ciertas
situaciones; otros se utilizan para indicar que ciertos campos en el tipo de objeto (o en las estructuras de ex-
tensión a las que se hace referencia a través de tp_as_number, tp_as_sequence, tp_as_mapping,
y tp_as_buffer) que históricamente no siempre estuvieron presentes son válidos; si dicho bit de bandera
está claro, no se debe acceder a los campos de tipo que protege y se debe considerar que tienen un valor cero
o NULL.
Herencia:
Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag
bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if
the extension structure is inherited, i.e. the base type’s value of the flag bit is copied into the subtype together
with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the
tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype
and the tp_traverse and tp_clear fields in the subtype exist and have NULL values. .. XXX are most
flag bits really inherited individually?
Por defecto:
PyBaseObject_Type uses Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE.
Máscaras de bits:
Las siguientes máscaras de bits están definidas actualmente; estos se pueden unidos por OR usando el operador
| para formar el valor del campo tp_flags. El macro PyType_HasFeature() toma un tipo y un valor
de banderas, tp y f, y comprueba si tp->tp_flags & f no es cero.
Py_TPFLAGS_HEAPTYPE
This bit is set when the type object itself is allocated on the heap, for example, types created dynamically
using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference
to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when
an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the
instance’s ob_type gets INCREF’ed or DECREF’ed). Heap types should also support garbage collection
as they can form a reference cycle with their own module object.
Herencia:
???
Py_TPFLAGS_BASETYPE
Este bit se establece cuando el tipo se puede usar como el tipo base de otro tipo. Si este bit es claro, el
tipo no puede subtiparse (similar a una clase «final» en Java).
Herencia:
???
Py_TPFLAGS_READY
Este bit se establece cuando el objeto tipo ha sido completamente inicializado por PyType_Ready().
Herencia:
???
Py_TPFLAGS_READYING
Este bit se establece mientras PyType_Ready() está en el proceso de inicialización del objeto tipo.
Herencia:
???
Py_TPFLAGS_HAVE_GC
This bit is set when the object supports garbage collection. If this bit is set, instances must be created
using PyObject_GC_New and destroyed using PyObject_GC_Del(). More information in section
Apoyo a la recolección de basura cíclica. This bit also implies that the GC-related fields tp_traverse
and tp_clear are present in the type object.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear
fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and
tp_clear fields in the subtype exist and have NULL values.
Py_TPFLAGS_DEFAULT
This is a bitmask of all the bits that pertain to the existence of certain fields in
the type object and its extension structures. Currently, it includes the following bits:
Py_TPFLAGS_HAVE_STACKLESS_EXTENSION.
Herencia:
???
Py_TPFLAGS_METHOD_DESCRIPTOR
Este bit indica que los objetos se comportan como métodos independientes.
Si este indicador está configurado para type(meth), entonces:
• meth.__get__(obj, cls)(*args, **kwds) (con obj no None) debe ser equivalente
a meth(obj, *args, **kwds).
Py_TPFLAGS_LIST_SUBCLASS
Py_TPFLAGS_TUPLE_SUBCLASS
Py_TPFLAGS_BYTES_SUBCLASS
Py_TPFLAGS_UNICODE_SUBCLASS
Py_TPFLAGS_DICT_SUBCLASS
Py_TPFLAGS_BASE_EXC_SUBCLASS
Py_TPFLAGS_TYPE_SUBCLASS
Estas marcas son utilizadas por funciones como PyLong_Check() para determinar rápidamente si un
tipo es una subclase de un tipo incorporado; dichos controles específicos son más rápidos que un control
genérico, como PyObject_IsInstance(). Los tipos personalizados que heredan de los elementos
integrados deben tener su tp_flags configurado correctamente, o el código que interactúa con dichos
tipos se comportará de manera diferente dependiendo del tipo de verificación que se use.
Py_TPFLAGS_HAVE_FINALIZE
Este bit se establece cuando la ranura tp_finalize está presente en la estructura de tipo.
Added in version 3.4.
Obsoleto desde la versión 3.8: Este indicador ya no es necesario, ya que el intérprete asume que: el espacio
tp_finalize siempre está presente en la estructura de tipos.
Py_TPFLAGS_HAVE_VECTORCALL
Este bit se establece cuando la clase implementa protocolo vectorcall. Consulte
tp_vectorcall_offset para obtener más detalles.
Herencia:
This bit is inherited if tp_call is also inherited.
Added in version 3.9.
Distinto en la versión 3.12: This flag is now removed from a class when the class’s __call__() method
is reassigned.
This flag can now be inherited by mutable classes.
Py_TPFLAGS_IMMUTABLETYPE
Este bit se establece para objetos de tipo que son inmutables: los atributos de tipo no se pueden establecer
ni eliminar.
PyType_Ready() aplica automáticamente este indicador a static types.
Herencia:
Este flag no se hereda.
Added in version 3.10.
Py_TPFLAGS_DISALLOW_INSTANTIATION
No permita la creación de instancias del tipo: establezca tp_new en NULL y no cree la clave __new__
en el diccionario de tipos.
La bandera debe establecerse antes de crear el tipo, no después. Por ejemplo, debe establecerse antes de
que se llame a PyType_Ready() en el tipo.
La bandera se establece automáticamente en static types si tp_base es NULL o
&PyBaseObject_Type y tp_new es NULL.
Herencia:
This flag is not inherited. However, subclasses will not be instantiable unless they provide a non-NULL
tp_new (which is only possible via the C API).
Nota: To disallow instantiating a class directly but allow instantiating its subclasses (e.g. for an abstract
base class), do not use this flag. Instead, make tp_new only succeed for subclasses.
Herencia:
Herencia:
This flag is inherited by types that do not already set Py_TPFLAGS_MAPPING.
Ver también:
PEP 634 - Coincidencia de patrones estructurales: especificación
Added in version 3.10.
Py_TPFLAGS_VALID_VERSION_TAG
Internal. Do not set or unset this flag. To indicate that a class has changed call PyType_Modified()
Advertencia: This flag is present in header files, but is an internal feature and should not be used. It
will be removed in a future version of CPython
Se puede encontrar más información sobre el esquema de recolección de basura de Python en la sección Apoyo
a la recolección de basura cíclica.
The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical imple-
mentation of a tp_traverse function simply calls Py_VISIT() on each of the instance’s members that
are Python objects that the instance owns. For example, this is function local_traverse() from the
_thread extension module:
static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
Py_VISIT(self->args);
Py_VISIT(self->kw);
Py_VISIT(self->dict);
(continúe en la próxima página)
Tenga en cuenta que Py_VISIT() solo se llama a aquellos miembros que pueden participar en los ciclos de
referencia. Aunque también hay un miembro self->key, solo puede ser NULL o una cadena de caracteres
de Python y, por lo tanto, no puede ser parte de un ciclo de referencia.
Por otro lado, incluso si sabe que un miembro nunca puede ser parte de un ciclo, como ayuda para la depuración
puede visitarlo de todos modos solo para que la función get_referents() del módulo gc lo incluirá.
Advertencia: Al implementar tp_traverse, solo se deben visitar los miembros que tienen la instancia
owns (por tener referencias fuertes). Por ejemplo, si un objeto admite referencias débiles a través de la ranura
tp_weaklist, el puntero que respalda la lista vinculada (a lo que apunta tp_weaklist) no debe visitarse
ya que la instancia no posee directamente las referencias débiles a sí misma (la lista de referencias débiles
está ahí para respaldar la maquinaria de referencia débil, pero la instancia no tiene una fuerte referencia a
los elementos dentro de ella, ya que pueden eliminarse incluso si la instancia todavía está viva).
Tenga en cuenta que Py_VISIT() requiere los parámetros visit y arg para local_traverse() para
tener estos nombres específicos; no les llames de ninguna manera.
Las instancias de heap-allocated types contienen una referencia a su tipo. Por lo tanto, su función transver-
sal debe visitar Py_TYPE(self) o delegar esta responsabilidad llamando a tp_traverse de otro tipo
asignado al heap (como una superclase asignada al heap). Si no es así, es posible que el objeto de tipo no se
recolecte como basura.
Distinto en la versión 3.9: Se espera que los tipos asignados al heap visiten Py_TYPE(self) en
tp_traverse. En versiones anteriores de Python, debido al bug 40217, hacer esto puede provocar fallas en
las subclases.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the
flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.
inquiry PyTypeObject.tp_clear
An optional pointer to a clear function for the garbage collector. This is only used if the
Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:
int tp_clear(PyObject *);
La función miembro tp_clear se usa para romper los ciclos de referencia en la basura cíclica detectada
por el recolector de basura. En conjunto, todas las funciones tp_clear en el sistema deben combinarse para
romper todos los ciclos de referencia. Esto es sutil y, en caso de duda, proporcione una función tp_clear.
Por ejemplo, el tipo de tupla no implementa una función tp_clear, porque es posible demostrar que ningún
ciclo de referencia puede estar compuesto completamente de tuplas. Por lo tanto, las funciones tp_clear de
otros tipos deben ser suficientes para romper cualquier ciclo que contenga una tupla. Esto no es inmediatamente
obvio, y rara vez hay una buena razón para evitar la implementación de tp_clear.
Las implementaciones de tp_clear deberían descartar las referencias de la instancia a las de sus miembros
que pueden ser objetos de Python, y establecer sus punteros a esos miembros en NULL, como en el siguiente
ejemplo:
static int
local_clear(localobject *self)
{
Py_CLEAR(self->key);
Py_CLEAR(self->args);
Py_CLEAR(self->kw);
(continúe en la próxima página)
The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the contained
object must not be released (via Py_DECREF()) until after the pointer to the contained object is set to NULL.
This is because releasing the reference may cause the contained object to become trash, triggering a chain of
reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks,
associated with the contained object). If it’s possible for such code to reference self again, it’s important that
the pointer to the contained object be NULL at that time, so that self knows the contained object can no longer
be used. The Py_CLEAR() macro performs the operations in a safe order.
Tenga en cuenta que tp_clear no se llama siempre antes de que se desasigne una instancia. Por ejemplo,
cuando el recuento de referencias es suficiente para determinar que un objeto ya no se utiliza, el recolector de
basura cíclico no está involucrado y se llama directamente a tp_dealloc.
Debido a que el objetivo de tp_clear es romper los ciclos de referencia, no es necesario borrar objetos
contenidos como cadenas de caracteres de Python o enteros de Python, que no pueden participar en los ciclos
de referencia. Por otro lado, puede ser conveniente borrar todos los objetos Python contenidos y escribir la
función tp_dealloc para invocar tp_clear.
Se puede encontrar más información sobre el esquema de recolección de basura de Python en la sección Apoyo
a la recolección de basura cíclica.
Herencia:
Group: Py_TPFLAGS_HAVE_GC, tp_traverse, tp_clear
This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit:
the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the
subtype.
richcmpfunc PyTypeObject.tp_richcompare
Un puntero opcional a la función de comparación enriquecida, cuya firma es:
Se garantiza que el primer parámetro será una instancia del tipo definido por PyTypeObject.
La función debería retornar el resultado de la comparación (generalmente Py_True o Py_False). Si la
comparación no está definida, debe retornar Py_NotImplemented, si se produce otro error, debe retornar
NULL y establecer una condición de excepción.
Las siguientes constantes se definen para ser utilizadas como el tercer argumento para tp_richcompare y
para PyObject_RichCompare():
Constante Comparación
<
Py_LT
<=
Py_LE
==
Py_EQ
!=
Py_NE
>
Py_GT
>=
Py_GE
El siguiente macro está definido para facilitar la escritura de funciones de comparación enriquecidas:
Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, op)
Retorna Py_True o Py_False de la función, según el resultado de una comparación. VAL_A y
VAL_B deben ser ordenados por operadores de comparación C (por ejemplo, pueden ser enteros
o punto flotantes de C). El tercer argumento especifica la operación solicitada, como por ejemplo
PyObject_RichCompare().
The returned value is a new strong reference.
En caso de error, establece una excepción y retorna NULL de la función.
Added in version 3.7.
Herencia:
Group: tp_hash, tp_richcompare
Este campo es heredado por subtipos junto con tp_hash: un subtipo hereda tp_richcompare y
tp_hash cuando el subtipo tp_richcompare y tp_hash son ambos NULL.
Por defecto:
PyBaseObject_Type provides a tp_richcompare implementation, which may be inherited. However,
if only tp_hash is defined, not even the inherited function is used and instances of the type will not be able
to participate in any comparisons.
Py_ssize_t PyTypeObject.tp_weaklistoffset
While this field is still supported, Py_TPFLAGS_MANAGED_WEAKREF should be used instead, if at all pos-
sible.
If the instances of this type are weakly referenceable, this field is greater than zero and contains the offset in
the instance structure of the weak reference list head (ignoring the GC header, if present); this offset is used
by PyObject_ClearWeakRefs() and the PyWeakref_* functions. The instance structure needs to
include a field of type PyObject* which is initialized to NULL.
No confunda este campo con tp_weaklist; ese es el encabezado de la lista para referencias débiles al objeto
de tipo en sí.
It is an error to set both the Py_TPFLAGS_MANAGED_WEAKREF bit and tp_weaklist.
Herencia:
Este campo es heredado por subtipos, pero consulte las reglas que se enumeran a continuación. Un subtipo
puede anular este desplazamiento; Esto significa que el subtipo utiliza un encabezado de lista de referen-
cia débil diferente que el tipo base. Dado que el encabezado de la lista siempre se encuentra a través de
tp_weaklistoffset, esto no debería ser un problema.
Por defecto:
If the Py_TPFLAGS_MANAGED_WEAKREF bit is set in the tp_dict field, then tp_weaklistoffset
will be set to a negative value, to indicate that it is unsafe to use this field.
getiterfunc PyTypeObject.tp_iter
An optional pointer to a function that returns an iterator for the object. Its presence normally signals that the
instances of this type are iterable (although sequences may be iterable without this function).
Esta función tiene la misma firma que PyObject_GetIter():
PyObject *tp_iter(PyObject *self);
Herencia:
Este campo es heredado por subtipos.
iternextfunc PyTypeObject.tp_iternext
An optional pointer to a function that returns the next item in an iterator. The signature is:
PyObject *tp_iternext(PyObject *self);
Cuando el iterador está agotado, debe retornar NULL; a la excepción StopIteration puede o no estable-
cerse. Cuando se produce otro error, también debe retornar NULL. Su presencia indica que las instancias de
este tipo son iteradores.
Los tipos de iterador también deberían definir la función tp_iter, y esa función debería retornar la instancia
de iterador en sí (no una nueva instancia de iterador).
Esta función tiene la misma firma que PyIter_Next().
Herencia:
Este campo es heredado por subtipos.
struct PyMethodDef *PyTypeObject.tp_methods
Un puntero opcional a un arreglo estático terminado en NULL de estructuras PyMethodDef, declarando
métodos regulares de este tipo.
Para cada entrada en el arreglo, se agrega una entrada al diccionario del tipo (ver tp_dict a continuación)
que contiene un descriptor method.
Herencia:
Los subtipos no heredan este campo (los métodos se heredan mediante un mecanismo diferente).
struct PyMemberDef *PyTypeObject.tp_members
Un puntero opcional a un arreglo estático terminado en NULL de estructuras PyMemberDef, declarando
miembros de datos regulares (campos o ranuras) de instancias de este tipo.
Para cada entrada en el arreglo, se agrega una entrada al diccionario del tipo (ver tp_dict a continuación)
que contiene un descriptor member.
Herencia:
Los subtipos no heredan este campo (los miembros se heredan mediante un mecanismo diferente).
struct PyGetSetDef *PyTypeObject.tp_getset
Un puntero opcional a un arreglo estático terminado en NULL de estructuras PyGetSetDef, declarando
atributos calculados de instancias de este tipo.
Para cada entrada en el arreglo, se agrega una entrada al diccionario del tipo (ver tp_dict a continuación)
que contiene un descriptor getset.
Herencia:
Este campo no es heredado por los subtipos (los atributos computados se heredan a través de un mecanismo
diferente).
PyTypeObject *PyTypeObject.tp_base
Un puntero opcional a un tipo base del que se heredan las propiedades de tipo. En este nivel, solo se admite
una herencia única; La herencia múltiple requiere la creación dinámica de un objeto tipo llamando al metatipo.
Nota: La inicialización de ranuras está sujeta a las reglas de inicialización de globales. C99 re-
quiere que los inicializadores sean «constantes de dirección». Los designadores de funciones como
PyType_GenericNew(), con conversión implícita a un puntero, son constantes de dirección C99 váli-
das.
However, the unary “&” operator applied to a non-static variable like PyBaseObject_Type is not required
to produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers are
strictly standard conforming in this particular behavior.
En consecuencia, tp_base debe establecerse en la función init del módulo de extensión.
Herencia:
Este campo no es heredado por los subtipos (obviamente).
Por defecto:
Este campo predeterminado es &PyBaseObject_Type (que para los programadores de Python se conoce
como el tipo objeto).
PyObject *PyTypeObject.tp_dict
El diccionario del tipo se almacena aquí por PyType_Ready().
This field should normally be initialized to NULL before PyType_Ready is called; it may also be initialized to
a dictionary containing initial attributes for the type. Once PyType_Ready() has initialized the type, extra
attributes for the type may be added to this dictionary only if they don’t correspond to overloaded operations
(like __add__()). Once initialization for the type has finished, this field should be treated as read-only.
Some types may not store their dictionary in this slot. Use PyType_GetDict() to retrieve the dictionary
for an arbitrary type.
Distinto en la versión 3.12: Internals detail: For static builtin types, this is always NULL. Instead, the dict for
such types is stored on PyInterpreterState. Use PyType_GetDict() to get the dict for an arbitrary
type.
Herencia:
Este campo no es heredado por los subtipos (aunque los atributos definidos aquí se heredan a través de un
mecanismo diferente).
Por defecto:
Si este campo es NULL, PyType_Ready() le asignará un nuevo diccionario.
descrgetfunc PyTypeObject.tp_descr_get
Un puntero opcional a una función «obtener descriptor» (descriptor ger).
La firma de la función es:
Herencia:
Este campo es heredado por subtipos.
descrsetfunc PyTypeObject.tp_descr_set
Un puntero opcional a una función para configurar y eliminar el valor de un descriptor.
La firma de la función es:
The self argument is the instance to be initialized; the args and kwds arguments represent positional and keyword
arguments of the call to __init__().
La función tp_init, si no es NULL, se llama cuando una instancia se crea normalmente llamando a su tipo,
después de la función tp_new del tipo ha retornado una instancia del tipo. Si la función tp_new retorna
una instancia de otro tipo que no es un subtipo del tipo original, no se llama la función tp_init; if tp_new
retorna una instancia de un subtipo del tipo original, se llama al subtipo tp_init.
Retorna 0 en caso de éxito, -1 y establece una excepción en caso de error.
Herencia:
Este campo es heredado por subtipos.
Por defecto:
Para tipos estáticos, este campo no tiene un valor predeterminado.
allocfunc PyTypeObject.tp_alloc
Un puntero opcional a una función de asignación de instancia.
La firma de la función es:
Herencia:
Este campo es heredado por subtipos estáticos, pero no por subtipos dinámicos (subtipos creados por una
declaración de clase).
Por defecto:
Para subtipos dinámicos, este campo siempre se establece en PyType_GenericAlloc(), para forzar una
estrategia de asignación de heap estándar.
For static subtypes, PyBaseObject_Type uses PyType_GenericAlloc(). That is the recommended
value for all statically defined types.
newfunc PyTypeObject.tp_new
Un puntero opcional a una función de creación de instancias.
La firma de la función es:
El argumento subtype es el tipo de objeto que se está creando; los argumentos args y kwds representan argu-
mentos posicionales y de palabras clave de la llamada al tipo. Tenga en cuenta que subtype no tiene que ser igual
al tipo cuya función tp_new es llamada; puede ser un subtipo de ese tipo (pero no un tipo no relacionado).
La función tp_new debería llamar a subtype->tp_alloc(subtype, nitems) para asignar espacio
para el objeto, y luego hacer solo la inicialización adicional que sea absolutamente necesaria. La inicialización
que se puede ignorar o repetir de forma segura debe colocarse en el controlador tp_init. Una buena regla
general es que para los tipos inmutables, toda la inicialización debe tener lugar en tp_new, mientras que para
los tipos mutables, la mayoría de las inicializaciones se deben diferir a tp_init.
Set the Py_TPFLAGS_DISALLOW_INSTANTIATION flag to disallow creating instances of the type in
Python.
Herencia:
Este campo se hereda por subtipos, excepto que no lo heredan tipos estáticos cuyo tp_base es NULL o
&PyBaseObject_Type.
Por defecto:
Para tipos estáticos, este campo no tiene ningún valor predeterminado. Esto significa que si la ranura se define
como NULL, no se puede llamar al tipo para crear nuevas instancias; presumiblemente hay alguna otra forma
de crear instancias, como una función de fábrica.
freefunc PyTypeObject.tp_free
Un puntero opcional a una función de desasignación de instancia. Su firma es:
Este campo es heredado por subtipos estáticos, pero no por subtipos dinámicos (subtipos creados por una
declaración de clase)
Por defecto:
In dynamic subtypes, this field is set to a deallocator suitable to match PyType_GenericAlloc() and the
value of the Py_TPFLAGS_HAVE_GC flag bit.
For static subtypes, PyBaseObject_Type uses PyObject_Del().
inquiry PyTypeObject.tp_is_gc
Un puntero opcional a una función llamada por el recolector de basura.
The garbage collector needs to know whether a particular object is collectible or not. Normally, it is sufficient
to look at the object’s type’s tp_flags field, and check the Py_TPFLAGS_HAVE_GC flag bit. But some
types have a mixture of statically and dynamically allocated instances, and the statically allocated instances are
not collectible. Such types should define this function; it should return 1 for a collectible instance, and 0 for a
non-collectible instance. The signature is:
(El único ejemplo de esto son los tipos en sí. El metatipo, PyType_Type, define esta función para distinguir
entre tipos estática y dinámicamente asignados.)
Herencia:
Este campo es heredado por subtipos.
Por defecto:
This slot has no default. If this field is NULL, Py_TPFLAGS_HAVE_GC is used as the functional equivalent.
PyObject *PyTypeObject.tp_bases
Tupla de tipos base.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
For dynamically created classes, the Py_tp_bases slot can be used instead of the bases argument of
PyType_FromSpecWithBases(). The argument form is preferred.
Advertencia: Multiple inheritance does not work well for statically defined types. If you set tp_bases
to a tuple, Python will not raise an error, but some slots will only be inherited from the first base.
Herencia:
Este campo no se hereda.
PyObject *PyTypeObject.tp_mro
Tupla que contiene el conjunto expandido de tipos base, comenzando con el tipo en sí y terminando con
object, en orden de resolución de método.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
Herencia:
Este campo no se hereda; se calcula fresco por PyType_Ready().
PyObject *PyTypeObject.tp_cache
No usado. Solo para uso interno.
Herencia:
Este campo no se hereda.
void *PyTypeObject.tp_subclasses
A collection of subclasses. Internal use only. May be an invalid pointer.
To get a list of subclasses, call the Python method __subclasses__().
Distinto en la versión 3.12: For some types, this field does not hold a valid PyObject*. The type was changed
to void* to indicate this.
Herencia:
Este campo no se hereda.
PyObject *PyTypeObject.tp_weaklist
Cabecera de lista de referencia débil, para referencias débiles a este tipo de objeto. No heredado Solo para uso
interno.
Distinto en la versión 3.12: Internals detail: For the static builtin types this is always NULL, even if weakrefs
are added. Instead, the weakrefs for each are stored on PyInterpreterState. Use the public C-API or
the internal _PyObject_GET_WEAKREFS_LISTPTR() macro to avoid the distinction.
Herencia:
Este campo no se hereda.
destructor PyTypeObject.tp_del
Este campo está en desuso. Use tp_finalize en su lugar.
unsigned int PyTypeObject.tp_version_tag
Se usa para indexar en el caché de métodos. Solo para uso interno.
Herencia:
Este campo no se hereda.
destructor PyTypeObject.tp_finalize
Un puntero opcional a una función de finalización de instancia. Su firma es:
Si tp_finalize está configurado, el intérprete lo llama una vez cuando finaliza una instancia. Se llama
desde el recolector de basura (si la instancia es parte de un ciclo de referencia aislado) o justo antes de que el
objeto se desasigne. De cualquier manera, se garantiza que se invocará antes de intentar romper los ciclos de
referencia, asegurando que encuentre el objeto en un estado sano.
tp_finalize no debe mutar el estado de excepción actual; por lo tanto, una forma recomendada de escribir
un finalizador no trivial es:
static void
local_finalize(PyObject *self)
{
PyObject *error_type, *error_value, *error_traceback;
/* ... */
Además, tenga en cuenta que, en un Python que ha recolectado basura, se puede llamar a tp_dealloc desde
cualquier hilo de Python, no solo el hilo que creó el objeto (si el objeto se convierte en parte de un ciclo de
conteo de referencias, ese ciclo puede ser recogido por una recolección de basura en cualquier hilo). Esto no
es un problema para las llamadas a la API de Python, ya que el hilo en el que se llama tp_dealloc será
el propietario del Bloqueo Global del Intérprete (GIL, por sus siglas en inglés Global Interpreter Lock). Sin
embargo, si el objeto que se destruye a su vez destruye objetos de alguna otra biblioteca C o C++, se debe tener
cuidado para garantizar que la destrucción de esos objetos en el hilo que se llama tp_dealloc no violará
ningún supuesto de la biblioteca.
Herencia:
Este campo es heredado por subtipos.
Added in version 3.4.
Distinto en la versión 3.8: Before version 3.8 it was necessary to set the Py_TPFLAGS_HAVE_FINALIZE
flags bit in order for this field to be used. This is no longer required.
Ver también:
«Finalización segura de objetos» (PEP 442)
vectorcallfunc PyTypeObject.tp_vectorcall
Vectorcall function to use for calls of this type object. In other words, it is used to implement vectorcall for
type.__call__. If tp_vectorcall is NULL, the default call implementation using __new__() and
__init__() is used.
Herencia:
Este campo nunca se hereda.
Added in version 3.9: (el campo existe desde 3.8 pero solo se usa desde 3.9)
unsigned char PyTypeObject.tp_watched
Internal. Do not use.
Added in version 3.12.
Tradicionalmente, los tipos definidos en el código C son static, es decir, una estructura estática PyTypeObject se
define directamente en el código y se inicializa usando PyType_Ready().
Esto da como resultado tipos que están limitados en relación con los tipos definidos en Python:
• Los tipos estáticos están limitados a una base, es decir, no pueden usar herencia múltiple.
• Los objetos de tipo estático (pero no necesariamente sus instancias) son inmutables. No es posible agregar o
modificar los atributos del objeto tipo desde Python.
• Los objetos de tipo estático se comparten en sub intérpretes, por lo que no deben incluir ningún estado específico
del sub interpretador.
Also, since PyTypeObject is only part of the Limited API as an opaque struct, any extension modules using static
types must be compiled for a specific Python minor version.
An alternative to static types is heap-allocated types, or heap types for short, which correspond closely to classes created
by Python’s class statement. Heap types have the Py_TPFLAGS_HEAPTYPE flag set.
This is done by filling a PyType_Spec structure and calling PyType_FromSpec(),
PyType_FromSpecWithBases(), PyType_FromModuleAndSpec(), or
PyType_FromMetaclass().
type PyNumberMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo numérico.
Cada función es utilizada por la función de un nombre similar documentado en la sección Protocolo de números.
Aquí está la definición de la estructura:
typedef struct {
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;
unaryfunc nb_negative;
unaryfunc nb_positive;
unaryfunc nb_absolute;
inquiry nb_bool;
unaryfunc nb_invert;
binaryfunc nb_lshift;
binaryfunc nb_rshift;
binaryfunc nb_and;
binaryfunc nb_xor;
binaryfunc nb_or;
unaryfunc nb_int;
void *nb_reserved;
unaryfunc nb_float;
binaryfunc nb_inplace_add;
binaryfunc nb_inplace_subtract;
binaryfunc nb_inplace_multiply;
binaryfunc nb_inplace_remainder;
ternaryfunc nb_inplace_power;
binaryfunc nb_inplace_lshift;
binaryfunc nb_inplace_rshift;
binaryfunc nb_inplace_and;
binaryfunc nb_inplace_xor;
binaryfunc nb_inplace_or;
binaryfunc nb_floor_divide;
binaryfunc nb_true_divide;
binaryfunc nb_inplace_floor_divide;
binaryfunc nb_inplace_true_divide;
unaryfunc nb_index;
binaryfunc nb_matrix_multiply;
binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;
Nota: Las funciones binarias y ternarias deben verificar el tipo de todos sus operandos e implementar las con-
versiones necesarias (al menos uno de los operandos es una instancia del tipo definido). Si la operación no está
definida para los operandos dados, las funciones binarias y ternarias deben retornar Py_NotImplemented,
si se produce otro error, deben retornar NULL y establecer una excepción.
Nota: The nb_reserved field should always be NULL. It was previously called nb_long, and was renamed
in Python 3.0.1.
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
type PyMappingMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo de mapeo.
Tiene tres miembros:
lenfunc PyMappingMethods.mp_length
Esta función es utilizada por PyMapping_Size() y PyObject_Size(), y tiene la misma firma. Esta
ranura puede establecerse en NULL si el objeto no tiene una longitud definida.
binaryfunc PyMappingMethods.mp_subscript
Esta función es utilizada por PyObject_GetItem() y PySequence_GetSlice(), y tie-
ne la misma firma que PyObject_GetItem(). Este espacio debe llenarse para que la función
PyMapping_Check() retorna 1, de lo contrario puede ser NULL.
objobjargproc PyMappingMethods.mp_ass_subscript
This function is used by PyObject_SetItem(), PyObject_DelItem(),
PySequence_SetSlice() and PySequence_DelSlice(). It has the same signature as
PyObject_SetItem(), but v can also be set to NULL to delete an item. If this slot is NULL, the
object does not support item assignment and deletion.
type PySequenceMethods
Esta estructura contiene punteros a las funciones que utiliza un objeto para implementar el protocolo de se-
cuencia.
lenfunc PySequenceMethods.sq_length
Esta función es utilizada por PySequence_Size() y PyObject_Size(), y tiene la misma firma. Tam-
bién se usa para manejar índices negativos a través de los espacios sq_item y sq_ass_item.
binaryfunc PySequenceMethods.sq_concat
Esta función es utilizada por PySequence_Concat() y tiene la misma firma. También es utilizado por el
operador +, después de intentar la suma numérica a través de la ranura nb_add.
ssizeargfunc PySequenceMethods.sq_repeat
Esta función es utilizada por PySequence_Repeat() y tiene la misma firma. También es utilizado por el
operador *, después de intentar la multiplicación numérica a través de la ranura nb_multiply.
ssizeargfunc PySequenceMethods.sq_item
Esta función es utilizada por PySequence_GetItem() y tiene la misma firma. También es utilizado por
PyObject_GetItem(), después de intentar la suscripción a través de la ranura mp_subscript. Este
espacio debe llenarse para que la función PySequence_Check() retorna 1, de lo contrario puede ser
NULL.
Negative indexes are handled as follows: if the sq_length slot is filled, it is called and the sequence length is
used to compute a positive index which is passed to sq_item. If sq_length is NULL, the index is passed
as is to the function.
ssizeobjargproc PySequenceMethods.sq_ass_item
Esta función es utilizada por PySequence_SetItem() y tiene la misma firma. También lo usan
PyObject_SetItem() y PyObject_DelItem(), después de intentar la asignación y eliminación del
elemento a través de la ranura mp_ass_subscript. Este espacio puede dejarse en NULL si el objeto no
admite la asignación y eliminación de elementos.
objobjproc PySequenceMethods.sq_contains
Esta función puede ser utilizada por PySequence_Contains() y tiene la misma firma. Este espacio puede
dejarse en NULL, en este caso PySequence_Contains() simplemente atraviesa la secuencia hasta que
encuentra una coincidencia.
binaryfunc PySequenceMethods.sq_inplace_concat
Esta función es utilizada por PySequence_InPlaceConcat() y tiene la misma firma. Debe-
ría modificar su primer operando y retornarlo. Este espacio puede dejarse en NULL, en este caso
PySequence_InPlaceConcat() volverá a PySequence_Concat(). También es utilizado por
la asignación aumentada +=, después de intentar la suma numérica en el lugar a través de la ranura
nb_inplace_add.
ssizeargfunc PySequenceMethods.sq_inplace_repeat
Esta función es utilizada por PySequence_InPlaceRepeat() y tiene la misma firma. Debe-
ría modificar su primer operando y retornarlo. Este espacio puede dejarse en NULL, en este caso
PySequence_InPlaceRepeat() volverá a PySequence_Repeat(). También es utilizado por la
asignación aumentada *=, después de intentar la multiplicación numérica en el lugar a través de la ranura
nb_inplace_multiply.
type PyBufferProcs
Esta estructura contiene punteros a las funciones requeridas por Buffer protocol. El protocolo define cómo un
objeto exportador puede exponer sus datos internos a objetos de consumo.
getbufferproc PyBufferProcs.bf_getbuffer
La firma de esta función es:
Maneja una solicitud a exporter para completar view según lo especificado por flags. Excepto por el punto (3),
una implementación de esta función DEBE seguir estos pasos:
(1) Check if the request can be met. If not, raise BufferError, set view->obj to NULL and return -1.
(2) Rellene los campos solicitados.
(3) Incrementa un contador interno para el número de exportaciones (exports).
(4) Set view->obj to exporter and increment view->obj.
(5) Retorna 0.
Si exporter es parte de una cadena o árbol de proveedores de búfer, se pueden usar dos esquemas principales:
• Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference
to itself.
• Redirect: The buffer request is redirected to the root object of the tree. Here, view->obj will be a new
reference to the root object.
Los campos individuales de view se describen en la sección Estructura de búfer, las reglas sobre cómo debe
reaccionar un exportador a solicitudes específicas se encuentran en la sección Tipos de solicitud de búfer.
Toda la memoria señalada en la estructura Py_buffer pertenece al exportador y debe permanecer válida
hasta que no queden consumidores. format, shape, strides, suboffsets y internal son de solo
lectura para el consumidor.
PyBuffer_FillInfo() proporciona una manera fácil de exponer un búfer de bytes simple mientras se
trata correctamente con todos los tipos de solicitud.
PyObject_GetBuffer() es la interfaz para el consumidor que envuelve esta función.
releasebufferproc PyBufferProcs.bf_releasebuffer
La firma de esta función es:
Maneja una solicitud para liberar los recursos del búfer. Si no es necesario liberar recursos,
PyBufferProcs.bf_releasebuffer puede ser NULL. De lo contrario, una implementación están-
dar de esta función tomará estos pasos opcionales:
(1) Disminuir un contador interno para el número de exportaciones.
(2) Si el contador es 0, libera toda la memoria asociada con view.
El exportador DEBE utilizar el campo internal para realizar un seguimiento de los recursos específicos del
búfer. Se garantiza que este campo permanecerá constante, mientras que un consumidor PUEDE pasar una
copia del búfer original como argumento view.
This function MUST NOT decrement view->obj, since that is done automatically in
PyBuffer_Release() (this scheme is useful for breaking reference cycles).
PyBuffer_Release() es la interfaz para el consumidor que envuelve esta función.
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
sendfunc am_send;
} PyAsyncMethods;
unaryfunc PyAsyncMethods.am_await
La firma de esta función es:
The returned object must be an iterator, i.e. PyIter_Check() must return 1 for it.
Este espacio puede establecerse en NULL si un objeto no es awaitable.
unaryfunc PyAsyncMethods.am_aiter
La firma de esta función es:
Must return an awaitable object. See __anext__() for details. This slot may be set to NULL.
sendfunc PyAsyncMethods.am_send
La firma de esta función es:
Consulte PyIter_Send() para obtener más detalles. Esta ranura se puede establecer en NULL.
Added in version 3.10.
12.10 Ejemplos
Los siguientes son ejemplos simples de definiciones de tipo Python. Incluyen el uso común que puede encontrar.
Algunos demuestran casos difíciles de esquina (corner cases). Para obtener más ejemplos, información práctica y un
tutorial, consulte «definiendo nuevos tipos» (defining-new-types) y «tópicos de nuevos tipos (new-types-topics).
Un tipo estático básico:
typedef struct {
PyObject_HEAD
const char *data;
} MyObject;
También puede encontrar código más antiguo (especialmente en la base de código CPython) con un inicializador más
detallado:
static PyTypeObject MyObject_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"mymod.MyObject", /* tp_name */
sizeof(MyObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)myobj_dealloc, /* tp_dealloc */
0, /* tp_vectorcall_offset */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_as_async */
(reprfunc)myobj_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
0, /* tp_flags */
PyDoc_STR("My objects"), /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(continúe en la próxima página)
typedef struct {
PyObject_HEAD
const char *data;
} 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;
El soporte de Python para detectar y recolectar basura que involucra referencias circulares requiere el soporte de
tipos de objetos que son «contenedores» para otros objetos que también pueden ser contenedores. Los tipos que no
almacenan referencias a otros objetos, o que solo almacenan referencias a tipos atómicos (como números o cadenas),
no necesitan proporcionar ningún soporte explícito para la recolección de basura.
To create a container type, the tp_flags field of the type object must include the Py_TPFLAGS_HAVE_GC
and provide an implementation of the tp_traverse handler. If instances of the type are mutable, a tp_clear
implementation must also be provided.
Py_TPFLAGS_HAVE_GC
Los objetos con un tipo con este indicador establecido deben cumplir con las reglas documentadas aquí. Por
conveniencia, estos objetos se denominarán objetos contenedor.
Los constructores para tipos de contenedores deben cumplir con dos reglas:
1. The memory for the object must be allocated using PyObject_GC_New or PyObject_GC_NewVar.
2. Una vez que se inicializan todos los campos que pueden contener referencias a otros contenedores, debe llamar
a PyObject_GC_Track().
Del mismo modo, el desasignador (deallocator) para el objeto debe cumplir con un par similar de reglas:
1. Antes de invalidar los campos que se refieren a otros contenedores, debe llamarse
PyObject_GC_UnTrack().
2. La memoria del objeto debe ser desasignada (deallocated) usando PyObject_GC_Del().
PyObject_GC_New(TYPE, typeobj)
Analogous to PyObject_New but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
PyObject_GC_NewVar(TYPE, typeobj, size)
Analogous to PyObject_NewVar but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
PyObject *PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *type, size_t extra_size)
Analogous to PyObject_GC_New but allocates extra_size bytes at the end of the object (at offset
tp_basicsize). The allocated memory is initialized to zeros, except for the Python object header.
The extra data will be deallocated with the object, but otherwise it is not managed by Python.
Advertencia: The function is marked as unstable because the final mechanism for reserving extra data after
an instance is not yet decided. For allocating a variable number of fields, prefer using PyVarObject and
tp_itemsize instead.
static int
my_traverse(Noddy *self, visitproc visit, void *arg)
{
Py_VISIT(self->foo);
Py_VISIT(self->bar);
return 0;
}
El manejador tp_clear debe ser del tipo query, o NULL si el objeto es inmutable.
typedef int (*inquiry)(PyObject *self)
Part of the Stable ABI. Descarta referencias que pueden haber creado ciclos de referencia. Los objetos inmu-
tables no tienen que definir este método ya que nunca pueden crear directamente ciclos de referencia. Tenga
en cuenta que el objeto aún debe ser válido después de llamar a este método (no solo llame a Py_DECREF()
en una referencia). El recolector de basura llamará a este método si detecta que este objeto está involucrado
en un ciclo de referencia.
La C-API proporciona las siguientes funciones para controlar las ejecuciones de recolección de basura.
Py_ssize_t PyGC_Collect(void)
Part of the Stable ABI. Realiza una recolección de basura completa, si el recolector de basura está habilitado.
(Tenga en cuenta que gc.collect() lo ejecuta incondicionalmente).
Retorna el número de objetos recolectados e inalcanzables que no se pueden recolectar. Si el recolector de
basura está deshabilitado o ya está recolectando, retorna 0 inmediatamente. Los errores durante la recolección
de basura se pasan a sys.unraisablehook. Esta función no genera excepciones.
int PyGC_Enable(void)
Part of the Stable ABI since version 3.10. Habilita el recolector de basura: similar a gc.enable(). Retorna
el estado anterior, 0 para deshabilitado y 1 para habilitado.
Added in version 3.10.
int PyGC_Disable(void)
Part of the Stable ABI since version 3.10. Deshabilita el recolector de basura: similar a gc.disable().
Retorna el estado anterior, 0 para deshabilitado y 1 para habilitado.
Added in version 3.10.
int PyGC_IsEnabled(void)
Part of the Stable ABI since version 3.10. Consulta el estado del recolector de basura: similar a gc.
isenabled(). Retorna el estado actual, 0 para deshabilitado y 1 para habilitado.
Added in version 3.10.
The C-API provides the following interface for querying information about the garbage collector.
void PyUnstable_GC_VisitObjects(gcvisitobjects_t callback, void *arg)
Run supplied callback on all live GC-capable objects. arg is passed through to all invocations of callback.
Advertencia: If new objects are (de)allocated by the callback it is undefined if they will be visited.
Garbage collection is disabled during operation. Explicitly running a collection in the callback may lead to
undefined behaviour e.g. visiting the same objects multiple times or not at all.
CPython expone su número de versión en las siguientes macros. Tenga en cuenta que estos corresponden a la versión
con la que se construye el código, no necesariamente la versión utilizada en tiempo de ejecución.
Consulte Estabilidad de la API en C para obtener una discusión sobre la estabilidad de API y ABI en todas las
versiones.
PY_MAJOR_VERSION
El 3 en 3.4.1a2.
PY_MINOR_VERSION
El 4 en 3.4.1a2.
PY_MICRO_VERSION
El 1 en 3.4.1a2.
PY_RELEASE_LEVEL
La a en 3.4.1a2. Puede ser 0xA para la versión alfa, 0xB para la versión beta, 0xC para la versión candidata
o 0xF para la versión final.
PY_RELEASE_SERIAL
El 2 en 3.4.1a2, cero para lanzamientos finales.
PY_VERSION_HEX
El número de versión de Python codificado en un solo entero.
La información de la versión subyacente se puede encontrar tratándola como un número de 32 bits de la si-
guiente manera:
303
The Python/C API, Versión 3.12.4
Glosario
>>>
El prompt en el shell interactivo de Python por omisión. Frecuentemente vistos en ejemplos de código que
pueden ser ejecutados interactivamente en el intérprete.
...
Puede referirse a:
• El prompt en el shell interactivo de Python por omisión cuando se ingresa código para un bloque indentado
de código, y cuando se encuentra entre dos delimitadores que emparejan (paréntesis, corchetes, llaves o
comillas triples), o después de especificar un decorador.
• La constante incorporada Ellipsis.
2to3
Una herramienta que intenta convertir código de Python 2.x a Python 3.x arreglando la mayoría de las incom-
patibilidades que pueden ser detectadas analizando el código y recorriendo el árbol de análisis sintáctico.
2to3 está disponible en la biblioteca estándar como lib2to3; un punto de entrada independiente es provisto
como Tools/scripts/2to3. Vea 2to3-reference.
clase base abstracta
Las clases base abstractas (ABC, por sus siglas en inglés Abstract Base Class) complementan al duck-typing
brindando un forma de definir interfaces con técnicas como hasattr() que serían confusas o sutilmente
erróneas (por ejemplo con magic methods). Las ABC introduce subclases virtuales, las cuales son clases que
no heredan desde una clase pero aún así son reconocidas por isinstance() y issubclass(); vea la
documentación del módulo abc. Python viene con muchas ABC incorporadas para las estructuras de datos(
en el módulo collections.abc), números (en el módulo numbers ) , flujos de datos (en el módulo io
) , buscadores y cargadores de importaciones (en el módulo importlib.abc ) . Puede crear sus propios
ABCs con el módulo abc.
anotación
Una etiqueta asociada a una variable, atributo de clase, parámetro de función o valor de retorno, usado por
convención como un type hint.
Las anotaciones de variables no pueden ser accedidas en tiempo de ejecución, pero las anotaciones de variables
globales, atributos de clase, y funciones son almacenadas en el atributo especial __annotations__ de
módulos, clases y funciones, respectivamente.
Consulte variable annotation, function annotation, PEP 484 y PEP 526, que describen esta funcionalidad.
Consulte también annotations-howto para conocer las mejores prácticas sobre cómo trabajar con anotaciones.
305
The Python/C API, Versión 3.12.4
argumento
Un valor pasado a una function (o method) cuando se llama a la función. Hay dos clases de argumentos:
• argumento nombrado: es un argumento precedido por un identificador (por ejemplo, nombre=) en una
llamada a una función o pasado como valor en un diccionario precedido por **. Por ejemplo 3 y 5 son
argumentos nombrados en las llamadas a complex():
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
• argumento posicional son aquellos que no son nombrados. Los argumentos posicionales deben aparecer
al principio de una lista de argumentos o ser pasados como elementos de un iterable precedido por *. Por
ejemplo, 3 y 5 son argumentos posicionales en las siguientes llamadas:
complex(3, 5)
complex(*(3, 5))
Los argumentos son asignados a las variables locales en el cuerpo de la función. Vea en la sección calls las
reglas que rigen estas asignaciones. Sintácticamente, cualquier expresión puede ser usada para representar un
argumento; el valor evaluado es asignado a la variable local.
Vea también el parameter en el glosario, la pregunta frecuente la diferencia entre argumentos y parámetros, y
PEP 362.
administrador asincrónico de contexto
Un objeto que controla el entorno visible en un sentencia async with al definir los métodos
__aenter__() y __aexit__(). Introducido por PEP 492.
generador asincrónico
Una función que retorna un asynchronous generator iterator. Es similar a una función corrutina definida con
async def excepto que contiene expresiones yield para producir series de variables usadas en un ciclo
async for.
Usualmente se refiere a una función generadora asincrónica, pero puede referirse a un iterador generador
asincrónico en ciertos contextos. En aquellos casos en los que el significado no está claro, usar los términos
completos evita la ambigüedad.
Una función generadora asincrónica puede contener expresiones await así como sentencias async for, y
async with.
iterador generador asincrónico
Un objeto creado por una función asynchronous generator.
Este es un asynchronous iterator el cual cuando es llamado usa el método __anext__() retornando un
objeto a la espera (awaitable) el cual ejecutará el cuerpo de la función generadora asincrónica hasta la siguiente
expresión yield.
Cada yield suspende temporalmente el procesamiento, recordando el estado local de ejecución (incluyendo
a las variables locales y las sentencias try pendientes). Cuando el iterador del generador asincrónico vuelve
efectivamente con otro objeto a la espera (awaitable) retornado por el método __anext__(), retoma donde
lo dejó. Vea PEP 492 y PEP 525.
iterable asincrónico
Un objeto, que puede ser usado en una sentencia async for. Debe retornar un asynchronous iterator de su
método __aiter__(). Introducido por PEP 492.
iterador asincrónico
Un objeto que implementa los métodos __aiter__() y __anext__(). __anext__() debe retornar
un objeto awaitable. async for resuelve los esperables retornados por un método de iterador asincrónico
__anext__() hasta que lanza una excepción StopAsyncIteration. Introducido por PEP 492.
atributo
Un valor asociado a un objeto al que se suele hacer referencia por su nombre utilizando expresiones punteadas.
Por ejemplo, si un objeto o tiene un atributo a se referenciaría como o.a.
Es posible dar a un objeto un atributo cuyo nombre no sea un identificador definido por identifiers, por ejemplo
usando setattr(), si el objeto lo permite. Dicho atributo no será accesible utilizando una expresión con
puntos, y en su lugar deberá ser recuperado con getattr().
a la espera
Un objeto que puede utilizarse en una expresión await. Puede ser una corutina o un objeto con un método
__await__(). Véase también PEP 492.
BDFL
Sigla de Benevolent Dictator For Life, benevolente dictador vitalicio, es decir Guido van Rossum, el creador de
Python.
archivo binario
A file object able to read and write bytes-like objects. Examples of binary files are files opened in binary
mode ('rb', 'wb' or 'rb+'), sys.stdin.buffer, sys.stdout.buffer, and instances of io.
BytesIO and gzip.GzipFile.
Vea también text file para un objeto archivo capaz de leer y escribir objetos str.
referencia prestada
En la API C de Python, una referencia prestada es una referencia a un objeto, donde el código usando el objeto
no posee la referencia. Se convierte en un puntero colgante si se destruye el objeto. Por ejemplo, una recolección
de basura puede eliminar el último strong reference del objeto y así destruirlo.
Se recomienda llamar a Py_INCREF() en la referencia prestada para convertirla en una referencia fuerte in
situ, excepto cuando el objeto no se puede destruir antes del último uso de la referencia prestada. La función
Py_NewRef() se puede utilizar para crear una nueva referencia fuerte.
objetos tipo binarios
Un objeto que soporta Protocolo búfer y puede exportar un búfer C-contiguous. Esto incluye todas los objetos
bytes, bytearray, y array.array, así como muchos objetos comunes memoryview. Los objetos
tipo binarios pueden ser usados para varias operaciones que usan datos binarios; éstas incluyen compresión,
salvar a archivos binarios, y enviarlos a través de un socket.
Algunas operaciones necesitan que los datos binarios sean mutables. La documentación frecuentemente se re-
fiere a éstos como «objetos tipo binario de lectura y escritura». Ejemplos de objetos de búfer mutables incluyen
a bytearray y memoryview de la bytearray. Otras operaciones que requieren datos binarios alma-
cenados en objetos inmutables («objetos tipo binario de sólo lectura»); ejemplos de éstos incluyen bytes y
memoryview del objeto bytes.
bytecode
El código fuente Python es compilado en bytecode, la representación interna de un programa python en el
intérprete CPython. El bytecode también es guardado en caché en los archivos .pyc de tal forma que ejecutar
el mismo archivo es más fácil la segunda vez (la recompilación desde el código fuente a bytecode puede ser
evitada). Este «lenguaje intermedio» deberá corren en una virtual machine que ejecute el código de máquina
correspondiente a cada bytecode. Note que los bytecodes no tienen como requisito trabajar en las diversas
máquina virtuales de Python, ni de ser estable entre versiones Python.
Una lista de las instrucciones en bytecode está disponible en la documentación de el módulo dis.
callable
Un callable es un objeto que puede ser llamado, posiblemente con un conjunto de argumentos (véase argument),
con la siguiente sintaxis:
Una function, y por extensión un method, es un callable. Una instancia de una clase que implementa el método
__call__() también es un callable.
retrollamada
Una función de subrutina que se pasa como un argumento para ejecutarse en algún momento en el futuro.
clase
Una plantilla para crear objetos definidos por el usuario. Las definiciones de clase normalmente contienen
definiciones de métodos que operan una instancia de la clase.
307
The Python/C API, Versión 3.12.4
variable de clase
Una variable definida en una clase y prevista para ser modificada sólo a nivel de clase (es decir, no en una
instancia de la clase).
número complejo
Una extensión del sistema familiar de número reales en el cual los números son expresados como la suma
de una parte real y una parte imaginaria. Los números imaginarios son múltiplos de la unidad imaginaria (la
raíz cuadrada de -1), usualmente escrita como i en matemáticas o j en ingeniería. Python tiene soporte
incorporado para números complejos, los cuales son escritos con la notación mencionada al final.; la parte
imaginaria es escrita con un sufijo j, por ejemplo, 3+1j. Para tener acceso a los equivalentes complejos del
módulo math module, use cmath. El uso de números complejos es matemática bastante avanzada. Si no le
parecen necesarios, puede ignorarlos sin inconvenientes.
administrador de contextos
An object which controls the environment seen in a with statement by defining __enter__() and
__exit__() methods. See PEP 343.
variable de contexto
Una variable que puede tener diferentes valores dependiendo del contexto. Esto es similar a un almacenamiento
de hilo local Thread-Local Storage en el cual cada hilo de ejecución puede tener valores diferentes para una
variable. Sin embargo, con las variables de contexto, podría haber varios contextos en un hilo de ejecución
y el uso principal de las variables de contexto es mantener registro de las variables en tareas concurrentes
asíncronas. Vea contextvars.
contiguo
Un búfer es considerado contiguo con precisión si es C-contiguo o Fortran contiguo. Los búferes cero dimensio-
nales con C y Fortran contiguos. En los arreglos unidimensionales, los ítems deben ser dispuestos en memoria
uno siguiente al otro, ordenados por índices que comienzan en cero. En arreglos unidimensionales C-contiguos,
el último índice varía más velozmente en el orden de las direcciones de memoria. Sin embargo, en arreglos
Fortran contiguos, el primer índice vería más rápidamente.
corrutina
Las corrutinas son una forma más generalizadas de las subrutinas. A las subrutinas se ingresa por un punto y se
sale por otro punto. Las corrutinas pueden se iniciadas, finalizadas y reanudadas en muchos puntos diferentes.
Pueden ser implementadas con la sentencia async def. Vea además PEP 492.
función corrutina
Un función que retorna un objeto coroutine . Una función corrutina puede ser definida con la sentencia async
def, y puede contener las palabras claves await, async for, y async with. Las mismas son introdu-
cidas en PEP 492.
CPython
La implementación canónica del lenguaje de programación Python, como se distribuye en python.org. El tér-
mino «CPython» es usado cuando es necesario distinguir esta implementación de otras como Jython o IronPyt-
hon.
decorador
Una función que retorna otra función, usualmente aplicada como una función de transformación empleando la
sintaxis @envoltorio. Ejemplos comunes de decoradores son classmethod() y staticmethod().
La sintaxis del decorador es meramente azúcar sintáctico, las definiciones de las siguientes dos funciones son
semánticamente equivalentes:
def f(arg):
...
f = staticmethod(f)
@staticmethod
def f(arg):
...
El mismo concepto existe para clases, pero son menos usadas. Vea la documentación de function definitions y
class definitions para mayor detalle sobre decoradores.
descriptor
Any object which defines the methods __get__(), __set__(), or __delete__(). When a class at-
tribute is a descriptor, its special binding behavior is triggered upon attribute lookup. Normally, using a.b to
get, set or delete an attribute looks up the object named b in the class dictionary for a, but if b is a descriptor,
the respective descriptor method gets called. Understanding descriptors is a key to a deep understanding of
Python because they are the basis for many features including functions, methods, properties, class methods,
static methods, and reference to super classes.
Para obtener más información sobre los métodos de los descriptores, consulte descriptors o Guía práctica de
uso de los descriptores.
diccionario
An associative array, where arbitrary keys are mapped to values. The keys can be any object with
__hash__() and __eq__() methods. Called a hash in Perl.
comprensión de diccionarios
Una forma compacta de procesar todos o parte de los elementos en un iterable y retornar un diccionario con los
resultados. results = {n: n ** 2 for n in range(10)} genera un diccionario que contiene la
clave n asignada al valor n ** 2. Ver comprehensions.
vista de diccionario
Los objetos retornados por los métodos dict.keys(), dict.values(), y dict.items() son lla-
mados vistas de diccionarios. Proveen una vista dinámica de las entradas de un diccionario, lo que significa que
cuando el diccionario cambia, la vista refleja éstos cambios. Para forzar a la vista de diccionario a convertirse
en una lista completa, use list(dictview). Vea dict-views.
docstring
A string literal which appears as the first expression in a class, function or module. While ignored when the
suite is executed, it is recognized by the compiler and put into the __doc__ attribute of the enclosing class,
function or module. Since it is available via introspection, it is the canonical place for documentation of the
object.
tipado de pato
Un estilo de programación que no revisa el tipo del objeto para determinar si tiene la interfaz correcta; en
vez de ello, el método o atributo es simplemente llamado o usado («Si se ve como un pato y grazna como un
pato, debe ser un pato»). Enfatizando las interfaces en vez de hacerlo con los tipos específicos, un código bien
diseñado pues tener mayor flexibilidad permitiendo la sustitución polimórfica. El tipado de pato duck-typing
evita usar pruebas llamando a type() o isinstance(). (Nota: si embargo, el tipado de pato puede ser
complementado con abstract base classes. En su lugar, generalmente pregunta con hasattr() o EAFP.
EAFP
Del inglés Easier to ask for forgiveness than permission, es más fácil pedir perdón que pedir permiso. Este estilo
de codificación común en Python asume la existencia de claves o atributos válidos y atrapa las excepciones si esta
suposición resulta falsa. Este estilo rápido y limpio está caracterizado por muchas sentencias try y except.
Esta técnica contrasta con estilo LBYL usual en otros lenguajes como C.
expresión
Una construcción sintáctica que puede ser evaluada, hasta dar un valor. En otras palabras, una expresión es
una acumulación de elementos de expresión tales como literales, nombres, accesos a atributos, operadores
o llamadas a funciones, todos ellos retornando valor. A diferencia de otros lenguajes, no toda la sintaxis del
lenguaje son expresiones. También hay statements que no pueden ser usadas como expresiones, como la while.
Las asignaciones también son sentencias, no expresiones.
módulo de extensión
Un módulo escrito en C o C++, usando la API para C de Python para interactuar con el núcleo y el código del
usuario.
f-string
Son llamadas f-strings las cadenas literales que usan el prefijo 'f' o 'F', que es una abreviatura para formatted
string literals. Vea también PEP 498.
objeto archivo
An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resour-
ce. Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type
309
The Python/C API, Versión 3.12.4
of storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes,
etc.). File objects are also called file-like objects or streams.
Existen tres categorías de objetos archivo: crudos raw archivos binarios, con búfer archivos binarios y archivos
de texto. Sus interfaces son definidas en el módulo io. La forma canónica de crear objetos archivo es usando
la función open().
objetos tipo archivo
Un sinónimo de file object.
codificación del sistema de archivos y manejador de errores
Controlador de errores y codificación utilizado por Python para decodificar bytes del sistema operativo y co-
dificar Unicode en el sistema operativo.
La codificación del sistema de archivos debe garantizar la decodificación exitosa de todos los bytes por debajo
de 128. Si la codificación del sistema de archivos no proporciona esta garantía, las funciones de API pueden
lanzar UnicodeError.
Las funciones sys.getfilesystemencoding() y sys.getfilesystemencodeerrors() se
pueden utilizar para obtener la codificación del sistema de archivos y el controlador de errores.
La codificación del sistema de archivos y el manejador de errores se configuran al inicio de Pyt-
hon mediante la función PyConfig_Read(): consulte los miembros filesystem_encoding y
filesystem_errors de PyConfig.
Vea también locale encoding.
buscador
Un objeto que trata de encontrar el loader para el módulo que está siendo importado.
There are two types of finder: meta path finders for use with sys.meta_path, and path entry finders for
use with sys.path_hooks.
See importsystem and importlib for much more detail.
división entera a la baja
Una división matemática que se redondea hacia el entero menor más cercano. El operador de la división entera
a la baja es //. Por ejemplo, la expresión 11 // 4 evalúa 2 a diferencia del 2.75 retornado por la verdadera
división de números flotantes. Note que (-11) // 4 es -3 porque es -2.75 redondeado para abajo. Ver
PEP 238.
función
Una serie de sentencias que retornan un valor al que las llama. También se le puede pasar cero o más argumentos
los cuales pueden ser usados en la ejecución de la misma. Vea también parameter, method, y la sección function.
anotación de función
Una annotation del parámetro de una función o un valor de retorno.
Las anotaciones de funciones son usadas frecuentemente para indicadores de tipo, por ejemplo, se espera que
una función tome dos argumentos de clase int y también se espera que retorne dos valores int:
recolección de basura
El proceso de liberar la memoria de lo que ya no está en uso. Python realiza recolección de basura (garbage
collection) llevando la cuenta de las referencias, y el recogedor de basura cíclico es capaz de detectar y romper
las referencias cíclicas. El recogedor de basura puede ser controlado mediante el módulo gc .
generador
Una función que retorna un generator iterator. Luce como una función normal excepto que contiene la expresión
yield para producir series de valores utilizables en un bucle for o que pueden ser obtenidas una por una con
la función next().
Usualmente se refiere a una función generadora, pero puede referirse a un iterador generador en ciertos contex-
tos. En aquellos casos en los que el significado no está claro, usar los términos completos evita la ambigüedad.
iterador generador
Un objeto creado por una función generator.
Cada yield suspende temporalmente el procesamiento, recordando el estado de ejecución local (incluyendo
las variables locales y las sentencias try pendientes). Cuando el «iterador generado» vuelve, retoma donde ha
dejado, a diferencia de lo que ocurre con las funciones que comienzan nuevamente con cada invocación.
expresión generadora
Una expresión que retorna un iterador. Luce como una expresión normal seguida por la cláusula for definiendo
así una variable de bucle, un rango y una cláusula opcional if. La expresión combinada genera valores para la
función contenedora:
función genérica
Una función compuesta de muchas funciones que implementan la misma operación para diferentes tipos. Qué
implementación deberá ser usada durante la llamada a la misma es determinado por el algoritmo de despacho.
Vea también la entrada de glosario single dispatch, el decorador functools.singledispatch(), y
PEP 443.
tipos genéricos
Un type que se puede parametrizar; normalmente un container class como list o dict. Usado para type
hints y annotations.
Para más detalles, véase generic alias types, PEP 483, PEP 484, PEP 585, y el módulo typing.
GIL
Vea global interpreter lock.
bloqueo global del intérprete
Mecanismo empleado por el intérprete CPython para asegurar que sólo un hilo ejecute el bytecode Python por
vez. Esto simplifica la implementación de CPython haciendo que el modelo de objetos (incluyendo algunos
críticos como dict) están implícitamente a salvo de acceso concurrente. Bloqueando el intérprete completo
se simplifica hacerlo multi-hilos, a costa de mucho del paralelismo ofrecido por las máquinas con múltiples
procesadores.
Sin embargo, algunos módulos de extensión, tanto estándar como de terceros, están diseñados para liberar el
GIL cuando se realizan tareas computacionalmente intensivas como la compresión o el hashing. Además, el
GIL siempre es liberado cuando se hace entrada/salida.
Esfuerzos previos hechos para crear un intérprete «sin hilos» (uno que bloquee los datos compartidos con una
granularidad mucho más fina) no han sido exitosos debido a que el rendimiento sufrió para el caso más común
de un solo procesador. Se cree que superar este problema de rendimiento haría la implementación mucho más
compleja y por tanto, más costosa de mantener.
311
The Python/C API, Versión 3.12.4
hash-based pyc
Un archivo cache de bytecode que usa el hash en vez de usar el tiempo de la última modificación del archivo
fuente correspondiente para determinar su validez. Vea pyc-invalidation.
hashable
An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__()
method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which
compare equal must have the same hash value.
Ser hashable hace a un objeto utilizable como clave de un diccionario y miembro de un set, porque éstas
estructuras de datos usan los valores de hash internamente.
La mayoría de los objetos inmutables incorporados en Python son hashables; los contenedores mutables (como
las listas o los diccionarios) no lo son; los contenedores inmutables (como tuplas y conjuntos frozensets) son
hashables si sus elementos son hashables . Los objetos que son instancias de clases definidas por el usuario son
hashables por defecto. Todos se comparan como desiguales (excepto consigo mismos), y su valor de hash está
derivado de su función id().
IDLE
Un Entorno Integrado de Desarrollo y Aprendizaje para Python. idle es un editor básico y un entorno de
intérprete que se incluye con la distribución estándar de Python.
inmutable
Un objeto con un valor fijo. Los objetos inmutables son números, cadenas y tuplas. Éstos objetos no pueden ser
alterados. Un nuevo objeto debe ser creado si un valor diferente ha de ser guardado. Juegan un rol importante
en lugares donde es necesario un valor de hash constante, por ejemplo como claves de un diccionario.
ruta de importación
Una lista de las ubicaciones (o entradas de ruta) que son revisadas por path based finder al importar módulos.
Durante la importación, ésta lista de localizaciones usualmente viene de sys.path, pero para los subpaquetes
también puede incluir al atributo __path__ del paquete padre.
importar
El proceso mediante el cual el código Python dentro de un módulo se hace alcanzable desde otro código Python
en otro módulo.
importador
Un objeto que buscan y lee un módulo; un objeto que es tanto finder como loader.
interactivo
Python tiene un intérprete interactivo, lo que significa que puede ingresar sentencias y expresiones en el prompt
del intérprete, ejecutarlos de inmediato y ver sus resultados. Sólo ejecute python sin argumentos (podría
seleccionarlo desde el menú principal de su computadora). Es una forma muy potente de probar nuevas ideas
o inspeccionar módulos y paquetes (recuerde help(x)).
interpretado
Python es un lenguaje interpretado, a diferencia de uno compilado, a pesar de que la distinción puede ser
difusa debido al compilador a bytecode. Esto significa que los archivos fuente pueden ser corridos directamente,
sin crear explícitamente un ejecutable que es corrido luego. Los lenguajes interpretados típicamente tienen
ciclos de desarrollo y depuración más cortos que los compilados, sin embargo sus programas suelen correr más
lentamente. Vea también interactive.
apagado del intérprete
Cuando se le solicita apagarse, el intérprete Python ingresa a un fase especial en la cual gradualmente libera to-
dos los recursos reservados, como módulos y varias estructuras internas críticas. También hace varias llamadas
al recolector de basura. Esto puede disparar la ejecución de código de destructores definidos por el usuario o
weakref callbacks. El código ejecutado durante la fase de apagado puede encontrar varias excepciones debido
a que los recursos que necesita pueden no funcionar más (ejemplos comunes son los módulos de bibliotecas o
los artefactos de advertencias warnings machinery)
La principal razón para el apagado del intérpreter es que el módulo __main__ o el script que estaba corriendo
termine su ejecución.
iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such
as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes
you define with an __iter__() method or with a __getitem__() method that implements sequence
semantics.
Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(),
…). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator
for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not
necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for
you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator,
sequence, and generator.
iterador
An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing
it to the built-in function next()) return successive items in the stream. When no more data are available
a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any furt-
her calls to its __next__() method just raise StopIteration again. Iterators are required to have an
__iter__() method that returns the iterator object itself so every iterator is also iterable and may be used
in most places where other iterables are accepted. One notable exception is code which attempts multiple ite-
ration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the
iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted
iterator object used in the previous iteration pass, making it appear like an empty container.
Puede encontrar más información en typeiter.
Detalles de implementación de CPython: CPython does not consistently apply the requirement that an ite-
rator define __iter__().
función clave
Una función clave o una función de colación es un invocable que retorna un valor usado para el ordenamiento
o clasificación. Por ejemplo, locale.strxfrm() es usada para producir claves de ordenamiento que se
adaptan a las convenciones específicas de ordenamiento de un locale.
Cierta cantidad de herramientas de Python aceptan funciones clave para controlar como los elementos son
ordenados o agrupados. Incluyendo a min(), max(), sorted(), list.sort(), heapq.merge(),
heapq.nsmallest(), heapq.nlargest(), y itertools.groupby().
Hay varias formas de crear una función clave. Por ejemplo, el método str.lower() puede servir como
función clave para ordenamientos que no distingan mayúsculas de minúsculas. Como alternativa, una fun-
ción clave puede ser realizada con una expresión lambda como lambda r: (r[0], r[2]). Ade-
más, operator.attrgetter(), operator.itemgetter() y operator.methodcaller()
son tres constructores de funciones clave. Consulte Sorting HOW TO para ver ejemplos de cómo crear y utilizar
funciones clave.
argumento nombrado
Vea argument.
lambda
Una función anónima de una línea consistente en un sola expression que es evaluada cuando la función es
llamada. La sintaxis para crear una función lambda es lambda [parameters]: expression
LBYL
Del inglés Look before you leap, «mira antes de saltar». Es un estilo de codificación que prueba explícitamente
las condiciones previas antes de hacer llamadas o búsquedas. Este estilo contrasta con la manera EAFP y está
caracterizado por la presencia de muchas sentencias if.
En entornos multi-hilos, el método LBYL tiene el riesgo de introducir condiciones de carrera entre los hilos
que están «mirando» y los que están «saltando». Por ejemplo, el código, if key in mapping: return
mapping[key] puede fallar si otro hilo remueve key de mapping después del test, pero antes de retornar el
valor. Este problema puede ser resuelto usando bloqueos o empleando el método EAFP.
lista
A built-in Python sequence. Despite its name it is more akin to an array in other languages than to a linked list
313
The Python/C API, Versión 3.12.4
especificador de módulo
Un espacio de nombres que contiene la información relacionada a la importación usada al leer un módulo. Una
instancia de importlib.machinery.ModuleSpec.
MRO
Vea method resolution order.
mutable
Los objetos mutables pueden cambiar su valor pero mantener su id(). Vea también immutable.
tupla nombrada
La denominación «tupla nombrada» se aplica a cualquier tipo o clase que hereda de una tupla y cuyos elementos
indexables son también accesibles usando atributos nombrados. Este tipo o clase puede tener además otras
capacidades.
Varios tipos incorporados son tuplas nombradas, incluyendo los valores retornados por time.localtime()
y os.stat(). Otro ejemplo es sys.float_info:
Some named tuples are built-in types (such as the above examples). Alternatively, a named tuple can be created
from a regular class definition that inherits from tuple and that defines named fields. Such a class can be
written by hand, or it can be created by inheriting typing.NamedTuple, or with the factory function
collections.namedtuple(). The latter techniques also add some extra methods that may not be found
in hand-written or built-in named tuples.
espacio de nombres
El lugar donde la variable es almacenada. Los espacios de nombres son implementados como diccionarios. Hay
espacio de nombre local, global, e incorporado así como espacios de nombres anidados en objetos (en méto-
dos). Los espacios de nombres soportan modularidad previniendo conflictos de nombramiento. Por ejemplo,
las funciones builtins.open y os.open() se distinguen por su espacio de nombres. Los espacios de
nombres también ayuda a la legibilidad y mantenibilidad dejando claro qué módulo implementa una función.
Por ejemplo, escribiendo random.seed() o itertools.islice() queda claro que éstas funciones
están implementadas en los módulos random y itertools, respectivamente.
paquete de espacios de nombres
Un PEP 420 package que sirve sólo para contener subpaquetes. Los paquetes de espacios de nombres pueden
no tener representación física, y específicamente se diferencian de los regular package porque no tienen un
archivo __init__.py.
Vea también module.
alcances anidados
La habilidad de referirse a una variable dentro de una definición encerrada. Por ejemplo, una función definida
dentro de otra función puede referir a variables en la función externa. Note que los alcances anidados por defecto
sólo funcionan para referencia y no para asignación. Las variables locales leen y escriben sólo en el alcance más
interno. De manera semejante, las variables globales pueden leer y escribir en el espacio de nombres global.
Con nonlocal se puede escribir en alcances exteriores.
clase de nuevo estilo
Old name for the flavor of classes now used for all class objects. In earlier Python versions, only
new-style classes could use Python’s newer, versatile features like __slots__, descriptors, properties,
__getattribute__(), class methods, and static methods.
objeto
Cualquier dato con estado (atributo o valor) y comportamiento definido (métodos). También es la más básica
clase base para cualquier new-style class.
315
The Python/C API, Versión 3.12.4
paquete
Un module Python que puede contener submódulos o recursivamente, subpaquetes. Técnicamente, un paquete
es un módulo Python con un atributo __path__.
Vea también regular package y namespace package.
parámetro
Una entidad nombrada en una definición de una function (o método) que especifica un argument (o en algunos
casos, varios argumentos) que la función puede aceptar. Existen cinco tipos de argumentos:
• posicional o nombrado: especifica un argumento que puede ser pasado tanto como posicional o como
nombrado. Este es el tipo por defecto de parámetro, como foo y bar en el siguiente ejemplo:
• sólo posicional: especifica un argumento que puede ser pasado sólo por posición. Los parámetros sólo
posicionales pueden ser definidos incluyendo un carácter / en la lista de parámetros de la función después
de ellos, como posonly1 y posonly2 en el ejemplo que sigue:
• sólo nombrado: especifica un argumento que sólo puede ser pasado por nombre. Los parámetros sólo por
nombre pueden ser definidos incluyendo un parámetro posicional de una sola variable o un simple *`
antes de ellos en la lista de parámetros en la definición de la función, como kw_only1 y kw_only2 en el
ejemplo siguiente:
• variable posicional: especifica una secuencia arbitraria de argumentos posicionales que pueden ser brin-
dados (además de cualquier argumento posicional aceptado por otros parámetros). Este parámetro puede
ser definido anteponiendo al nombre del parámetro *, como a args en el siguiente ejemplo:
• variable nombrado: especifica que arbitrariamente muchos argumentos nombrados pueden ser brindados
(además de cualquier argumento nombrado ya aceptado por cualquier otro parámetro). Este parámetro
puede ser definido anteponiendo al nombre del parámetro con **, como kwargs en el ejemplo precedente.
Los parámetros puede especificar tanto argumentos opcionales como requeridos, así como valores por defecto
para algunos argumentos opcionales.
Vea también el glosario de argument, la pregunta respondida en la diferencia entre argumentos y parámetros,
la clase inspect.Parameter, la sección function , y PEP 362.
entrada de ruta
Una ubicación única en el import path que el path based finder consulta para encontrar los módulos a importar.
buscador de entradas de ruta
Un finder retornado por un invocable en sys.path_hooks (esto es, un path entry hook) que sabe cómo
localizar módulos dada una path entry.
Vea en importlib.abc.PathEntryFinder los métodos que los buscadores de entradas de ruta im-
plementan.
gancho a entrada de ruta
A callable on the sys.path_hooks list which returns a path entry finder if it knows how to find modules
on a specific path entry.
buscador basado en ruta
Uno de los meta buscadores de ruta por defecto que busca un import path para los módulos.
objeto tipo ruta
Un objeto que representa una ruta del sistema de archivos. Un objeto tipo ruta puede ser tanto una str como
un bytes representando una ruta, o un objeto que implementa el protocolo os.PathLike. Un objeto que
soporta el protocolo os.PathLike puede ser convertido a ruta del sistema de archivo de clase str o bytes
for i in range(len(food)):
print(food[i])
nombre calificado
Un nombre con puntos mostrando la ruta desde el alcance global del módulo a la clase, función o método
definido en dicho módulo, como se define en PEP 3155. Para las funciones o clases de más alto nivel, el
nombre calificado es el igual al nombre del objeto:
317
The Python/C API, Versión 3.12.4
>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'
Cuando es usado para referirse a los módulos, nombre completamente calificado significa la ruta con puntos
completo al módulo, incluyendo cualquier paquete padre, por ejemplo, email.mime.text:
contador de referencias
El número de referencias a un objeto. Cuando el contador de referencias de un objeto cae hasta cero, éste se
desaloja. Algunos objetos son «inmortales» y tienen recuentos de referencias que nunca se modifican, y por
lo tanto los objetos nunca son desalojan. El conteo de referencias generalmente no es visible para el código
Python, pero es un elemento clave de la implementación de CPython. Los programadores pueden llamar a la
función sys.getrefcount() para obtener el número de referencias de un objeto concreto.
paquete regular
Un package tradicional, como aquellos con un directorio conteniendo el archivo __init__.py.
Vea también namespace package.
__slots__
Es una declaración dentro de una clase que ahorra memoria predeclarando espacio para las atributos de la
instancia y eliminando diccionarios de la instancia. Aunque es popular, esta técnica es algo dificultosa de lograr
correctamente y es mejor reservarla para los casos raros en los que existen grandes cantidades de instancias en
aplicaciones con uso crítico de memoria.
secuencia
An iterable which supports efficient element access using integer indices via the __getitem__() spe-
cial method and defines a __len__() method that returns the length of the sequence. Some built-in se-
quence types are list, str, tuple, and bytes. Note that dict also supports __getitem__() and
__len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary immutable
keys rather than integers.
The collections.abc.Sequence abstract base class defines a much richer interface that goes be-
yond just __getitem__() and __len__(), adding count(), index(), __contains__(), and
__reversed__(). Types that implement this expanded interface can be registered explicitly using
register(). For more documentation on sequence methods generally, see Common Sequence Operations.
comprensión de conjuntos
Una forma compacta de procesar todos o parte de los elementos en un iterable y retornar un conjunto con los
resultados. results = {c for c in 'abracadabra' if c not in 'abc'} genera el con-
junto de cadenas {'r', 'd'}. Ver comprehensions.
despacho único
Una forma de despacho de una generic function donde la implementación es elegida a partir del tipo de un sólo
argumento.
rebanada
Un objeto que contiene una porción de una sequence. Una rebanada es creada usando la notación de suscripto,
[] con dos puntos entre los números cuando se ponen varios, como en nombre_variable[1:3:5]. La
notación con corchete (suscrito) usa internamente objetos slice.
método especial
Un método que es llamado implícitamente por Python cuando ejecuta ciertas operaciones en un tipo, como la
adición. Estos métodos tienen nombres que comienzan y terminan con doble barra baja. Los métodos especiales
están documentados en specialnames.
sentencia
Una sentencia es parte de un conjunto (un «bloque» de código). Una sentencia tanto es una expression como
alguna de las varias sintaxis usando una palabra clave, como if, while o for.
static type checker
An external tool that reads Python code and analyzes it, looking for issues such as incorrect types. See also type
hints and the typing module.
referencia fuerte
En la API de C de Python, una referencia fuerte es una referencia a un objeto que es propiedad del código que
mantiene la referencia. La referencia fuerte se toma llamando a Py_INCREF() cuando se crea la referencia
y se libera con Py_DECREF() cuando se elimina la referencia.
La función Py_NewRef() se puede utilizar para crear una referencia fuerte a un objeto. Por lo general, se
debe llamar a la función Py_DECREF() en la referencia fuerte antes de salir del alcance de la referencia
fuerte, para evitar filtrar una referencia.
Consulte también borrowed reference.
codificación de texto
Una cadena de caracteres en Python es una secuencia de puntos de código Unicode (en el rango U+0000–
U+10FFFF). Para almacenar o transferir una cadena de caracteres, es necesario serializarla como una secuen-
cia de bytes.
La serialización de una cadena de caracteres en una secuencia de bytes se conoce como «codificación», y la
recreación de la cadena de caracteres a partir de la secuencia de bytes se conoce como «decodificación».
Existe una gran variedad de serializaciones de texto codecs, que se denominan colectivamente «codificaciones
de texto».
archivo de texto
Un file object capaz de leer y escribir objetos str. Frecuentemente, un archivo de texto también accede a
un flujo de datos binario y maneja automáticamente el text encoding. Ejemplos de archivos de texto que son
abiertos en modo texto ('r' o 'w'), sys.stdin, sys.stdout, y las instancias de io.StringIO.
Vea también binary file por objeto de archivos capaces de leer y escribir objeto tipo binario.
cadena con triple comilla
Una cadena que está enmarcada por tres instancias de comillas (») o apostrofes (“). Aunque no brindan nin-
guna funcionalidad que no está disponible usando cadenas con comillas simple, son útiles por varias razones.
Permiten incluir comillas simples o dobles sin escapar dentro de las cadenas y pueden abarcar múltiples líneas
sin el uso de caracteres de continuación, haciéndolas particularmente útiles para escribir docstrings.
tipo
El tipo de un objeto Python determina qué tipo de objeto es; cada objeto tiene un tipo. El tipo de un objeto
puede ser accedido por su atributo __class__ o puede ser conseguido usando type(obj).
alias de tipos
Un sinónimo para un tipo, creado al asignar un tipo a un identificador.
Los alias de tipos son útiles para simplificar los indicadores de tipo. Por ejemplo:
def remove_gray_shades(
colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass
319
The Python/C API, Versión 3.12.4
class C:
field: 'annotation'
Las anotaciones de variables son frecuentemente usadas para type hints: por ejemplo, se espera que esta variable
tenga valores de clase int:
count: int = 0
Estos documentos son generados por reStructuredText desarrollado por Sphinx, un procesador de documentos espe-
cíficamente escrito para la documentación de Python.
El desarrollo de la documentación y su cadena de herramientas es un esfuerzo enteramente voluntario, al igual que
Python. Si tu quieres contribuir, por favor revisa la página reporting-bugs para más información de cómo hacerlo.
Los nuevos voluntarios son siempre bienvenidos!
Agradecemos a:
• Fred L. Drake, Jr., el creador original de la documentación del conjunto de herramientas de Python y escritor
de gran parte del contenido;
• el proyecto Docutils para creación de reStructuredText y la suite Docutils;
• Fredrik Lundh por su proyecto Referencia Alternativa de Python del que Sphinx obtuvo muchas buenas ideas.
Muchas personas han contribuido para el lenguaje de Python, la librería estándar de Python, y la documentación de
Python. Revisa Misc/ACKS la distribución de Python para una lista parcial de contribuidores.
Es solamente con la aportación y contribuciones de la comunidad de Python que Python tiene tan fantástica docu-
mentación – Muchas gracias!
321
The Python/C API, Versión 3.12.4
Historia y Licencia
Python fue creado a principios de la década de 1990 por Guido van Rossum en Stichting Mathematisch Centrum
(CWI, ver https://www.cwi.nl/) en los Países Bajos como sucesor de un idioma llamado ABC. Guido sigue siendo el
autor principal de Python, aunque incluye muchas contribuciones de otros.
En 1995, Guido continuó su trabajo en Python en la Corporation for National Research Initiatives (CNRI, consulte
https://www.cnri.reston.va.us/) en Reston, Virginia, donde lanzó varias versiones del software.
En mayo de 2000, Guido y el equipo de desarrollo central de Python se trasladaron a BeOpen.com para formar el
equipo de BeOpen PythonLabs. En octubre del mismo año, el equipo de PythonLabs se trasladó a Digital Creations
(ahora Zope Corporation; consulte https://www.zope.org/). En 2001, se formó la Python Software Foundation (PSF,
consulte https://www.python.org/psf/), una organización sin fines de lucro creada específicamente para poseer la
propiedad intelectual relacionada con Python. Zope Corporation es miembro patrocinador del PSF.
Todas las versiones de Python son de código abierto (consulte https://opensource.org/ para conocer la definición de
código abierto). Históricamente, la mayoría de las versiones de Python, pero no todas, también han sido compatibles
con GPL; la siguiente tabla resume las distintas versiones.
Nota: Compatible con GPL no significa que estemos distribuyendo Python bajo la GPL. Todas las licencias de
Python, a diferencia de la GPL, le permiten distribuir una versión modificada sin que los cambios sean de código
323
The Python/C API, Versión 3.12.4
abierto. Las licencias compatibles con GPL permiten combinar Python con otro software que se publica bajo la GPL;
los otros no lo hacen.
Gracias a los muchos voluntarios externos que han trabajado bajo la dirección de Guido para hacer posibles estos
lanzamientos.
prepared by Licensee.
agrees to include in any such work a brief summary of the changes made␣
,→to Python
3.12.4.
USE OF PYTHON 3.12.4 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.12.4
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A␣
,→RESULT OF
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 sección es una lista incompleta, pero creciente, de licencias y reconocimientos para software de terceros incor-
porado en la distribución de Python.
La extensión C _random subyacente al módulo random incluye código basado en una descarga de http://www.
math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html. Los siguientes son los comentarios textuales
del código original:
C.3.2 Sockets
El módulo socket usa las funciones, getaddrinfo(), y getnameinfo(), que están codificadas en archivos
fuente separados del Proyecto WIDE, http://www.wide.ad.jp /.
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
El archivo Python/pyhash.c contiene la implementación de Marek Majkowski del algoritmo SipHash24 de Dan
Bernstein. Contiene la siguiente nota:
<MIT License>
Copyright (c) 2013 Marek Majkowski <[email protected]>
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/
El archivo Python/dtoa.c, que proporciona las funciones de C dtoa y strtod para la conversión de dobles C hacia
y desde cadenas de caracteres, se deriva del archivo del mismo nombre por David M. Gay, actualmente disponible
en https://web.archive.org/web/20220517033456/http://www.netlib.org/fp/dtoa.c. El archivo original, recuperado el
16 de marzo de 2009, contiene el siguiente aviso de licencia y derechos de autor:
/****************************************************************
*
* The author of this software is David M. Gay.
*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
***************************************************************/
C.3.12 OpenSSL
Los módulos hashlib, posix, ssl, crypt utilizan la biblioteca OpenSSL para un rendimiento adicional si el
sistema operativo la pone a disposición. Además, los instaladores de Windows y macOS para Python pueden incluir
una copia de las bibliotecas de OpenSSL, por lo que incluimos una copia de la licencia de OpenSSL aquí. Para la
version OpenSSL 3.0, y versiones posteriores derivadas, se aplica la Apache License v2:
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
C.3.13 expat
La extensión pyexpat se construye usando una copia incluida de las fuentes de expatriados a menos que la cons-
trucción esté configurada --with-system-expat:
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
C.3.14 libffi
La extensión C _ctypes subyacente al módulo ctypes se construye usando una copia incluida de las fuentes de
libffi a menos que la construcción esté configurada --with-system-libffi:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
C.3.15 zlib
La extensión zlib se crea utilizando una copia incluida de las fuentes de zlib si la versión de zlib encontrada en el
sistema es demasiado antigua para ser utilizada para la compilación:
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
La extension C _decimal subyacente al módulo decimal se construye usando una copia incluida de la biblioteca
libmpdec a menos que la construcción esté configurada --with-system-libmpdec:
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.19 Audioop
The audioop module uses the code base in g771.c file of the SoX project. https://sourceforge.net/projects/sox/files/
sox/12.17.7/sox-12.17.7.tar.gz
This source code is a product of Sun Microsystems, Inc. and is provided for unrestricted use. Users may
copy or modify this source code without charge.
SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLU-
DING THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICU-
LAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTI-
CE.
Sun source code is provided with no support and without any obligation on the part of Sun Microsystems,
Inc. to assist in its use, correction, modification or enhancement.
SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE INFRIN-
GEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE OR
ANY PART THEREOF.
In no event will Sun Microsystems, Inc. be liable for any lost revenue or profits or other special, indirect
and consequential damages, even if Sun has been advised of the possibility of such damages.
Sun Microsystems, Inc. 2550 Garcia Avenue Mountain View, California 94043
C.3.20 asyncio
Parts of the asyncio module are incorporated from uvloop 0.16, which is distributed under the MIT license:
Derechos de autor
Consulte Historia y Licencia para obtener información completa sobre licencias y permisos.
343
The Python/C API, Versión 3.12.4
345
The Python/C API, Versión 3.12.4
346 Índice
The Python/C API, Versión 3.12.4
Índice 347
The Python/C API, Versión 3.12.4
348 Índice
The Python/C API, Versión 3.12.4
Índice 349
The Python/C API, Versión 3.12.4
350 Índice
The Python/C API, Versión 3.12.4
Índice 351
The Python/C API, Versión 3.12.4
352 Índice
The Python/C API, Versión 3.12.4
Índice 353
The Python/C API, Versión 3.12.4
354 Índice
The Python/C API, Versión 3.12.4
Índice 355
The Python/C API, Versión 3.12.4
356 Índice
The Python/C API, Versión 3.12.4
Índice 357
The Python/C API, Versión 3.12.4
358 Índice
The Python/C API, Versión 3.12.4
Índice 359
The Python/C API, Versión 3.12.4
360 Índice
The Python/C API, Versión 3.12.4
Índice 361
The Python/C API, Versión 3.12.4
362 Índice
The Python/C API, Versión 3.12.4
Índice 363
The Python/C API, Versión 3.12.4
364 Índice
The Python/C API, Versión 3.12.4
Índice 365
The Python/C API, Versión 3.12.4
U
ULONG_MAX (C macro), 125
unaryfunc (C type), 296
USE_STACKCHECK (C macro), 66
V
variable de clase, 308
variable de contexto, 308
variables de entorno
__PYVENV_LAUNCHER__, 227, 232
PATH, 12
PYTHONCOERCECLOCALE, 237
PYTHONDEBUG, 194, 232
PYTHONDEVMODE, 228
PYTHONDONTWRITEBYTECODE, 194, 235
PYTHONDUMPREFS, 228, 270
PYTHONEXECUTABLE, 232
PYTHONFAULTHANDLER, 228
PYTHONHASHSEED, 195, 229
PYTHONHOME, 12, 195, 202, 229
PYTHONINSPECT, 195, 229
PYTHONINTMAXSTRDIGITS, 230
PYTHONIOENCODING, 198, 234
PYTHONLEGACYWINDOWSFSENCODING, 196,
223
PYTHONLEGACYWINDOWSSTDIO, 196, 230
PYTHONMALLOC, 242, 246, 248, 249
PYTHONMALLOCSTATS, 230, 242
PYTHONNODEBUGRANGES, 227
PYTHONNOUSERSITE, 196, 234
PYTHONOPTIMIZE, 196, 231
PYTHONPATH, 12, 195, 231
PYTHONPERFSUPPORT, 234
PYTHONPLATLIBDIR, 231
PYTHONPROFILEIMPORTTIME, 229
PYTHONPYCACHEPREFIX, 232
PYTHONSAFEPATH, 226
PYTHONTRACEMALLOC, 234
PYTHONUNBUFFERED, 197, 227
PYTHONUTF8, 223, 237
PYTHONVERBOSE, 197, 235
PYTHONWARNINGS, 235
vectorcallfunc (C type), 97
version (in module sys), 200, 201
visitproc (C type), 301
vista de diccionario, 309
W
WRITE_RESTRICTED (C macro), 260
Z
Zen de Python, 320
366 Índice