c-api
c-api
Release 3.14.0a7
1 Introduction 3
1.1 Language version compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Coding standards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Include Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Useful macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Objects, Types and Reference Counts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5.1 Reference Counts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5.2 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.6 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.7 Embedding Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.8 Debugging Builds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2 C API Stability 15
2.1 Unstable C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Stable Application Binary Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2.1 Limited C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2.2 Stable ABI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.3 Limited API Scope and Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.4 Limited API Caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.3 Platform Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.4 Contents of Limited API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4 Reference Counting 47
5 Exception Handling 51
5.1 Printing and clearing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.2 Raising exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3 Issuing warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.4 Querying the error indicator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.5 Signal Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
5.6 Exception Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.7 Exception Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
5.8 Unicode Exception Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.9 Recursion Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.10 Standard Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.11 Standard Warning Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
6 Utilities 67
6.1 Operating System Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
6.2 System Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.3 Process Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.4 Importing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.5 Data marshalling support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
i
6.6 Parsing arguments and building values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.6.1 Parsing arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
6.6.2 Building values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
6.7 String conversion and formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.8 PyHash API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6.9 Reflection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.10 Codec registry and support functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.10.1 Codec lookup API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.10.2 Registry API for Unicode encoding error handlers . . . . . . . . . . . . . . . . . . . . . 91
6.11 PyTime C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.11.1 Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.11.2 Clock Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.11.3 Raw Clock Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.11.4 Conversion functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.12 Support for Perf Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
ii
8.5.6 Extra information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
8.6 Other Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
8.6.1 File Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
8.6.2 Module Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
8.6.3 Iterator Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
8.6.4 Descriptor Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
8.6.5 Slice Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
8.6.6 MemoryView objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
8.6.7 Weak Reference Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
8.6.8 Capsules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
8.6.9 Frame Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
8.6.10 Generator Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
8.6.11 Coroutine Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
8.6.12 Context Variables Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
8.6.13 DateTime Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
8.6.14 Objects for Type Hinting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
iii
10.4.5 Preinitialize Python with PyPreConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
10.4.6 PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
10.4.7 Initialization with PyConfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
10.4.8 Isolated Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
10.4.9 Python Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
10.4.10 Python Path Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
10.5 Py_GetArgcArgv() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
10.6 Delaying main module execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
iv
A Glossary 339
D Copyright 379
Index 381
v
vi
The Python/C API, Release 3.14.0a7
This manual documents the API used by C and C++ programmers who want to write extension modules or embed
Python. It is a companion to extending-index, which describes the general principles of extension writing but does
not document the API functions in detail.
CONTENTS 1
The Python/C API, Release 3.14.0a7
2 CONTENTS
CHAPTER
ONE
INTRODUCTION
The Application Programmer’s Interface to Python gives C and C++ programmers access to the Python interpreter
at a variety of levels. The API is equally usable from C++, but for brevity it is generally referred to as the Python/C
API. There are two fundamentally different reasons for using the Python/C API. The first reason is to write extension
modules for specific purposes; these are C modules that extend the Python interpreter. This is probably the most
common use. The second reason is to use Python as a component in a larger application; this technique is generally
referred to as embedding Python in an application.
Writing an extension module is a relatively well-understood process, where a “cookbook” approach works well. There
are several tools that automate the process to some extent. While people have embedded Python in other applications
since its early existence, the process of embedding Python is less straightforward than writing an extension.
Many API functions are useful independent of whether you’re embedding or extending Python; moreover, most
applications that embed Python will need to provide a custom extension as well, so it’s probably a good idea to
become familiar with writing an extension before attempting to embed Python in a real application.
#define PY_SSIZE_T_CLEAN
#include <Python.h>
This implies inclusion of the following standard headers: <stdio.h>, <string.h>, <errno.h>, <limits.h>,
<assert.h> and <stdlib.h> (if available).
® Note
Since Python may define some pre-processor definitions which affect the standard headers on some systems, you
must include Python.h before any standard headers are included.
3
The Python/C API, Release 3.14.0a7
It is recommended to always define PY_SSIZE_T_CLEAN before including Python.h. See Parsing arguments
and building values for a description of this macro.
All user visible names defined by Python.h (except those defined by the included standard headers) have one of the
prefixes Py or _Py. Names beginning with _Py are for internal use by the Python implementation and should not be
used by extension writers. Structure member names do not have a reserved prefix.
® Note
User code should never define names that begin with Py or _Py. This confuses the reader, and jeopardizes the
portability of the user code to future Python versions, which may define additional names beginning with one of
these prefixes.
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 installa-
tion 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.
C++ users should note that although the API is defined entirely using C, the header files properly declare the entry
points to be extern "C". As a result, there is no need to do anything special to use the API from C++.
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:
PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModule_Create(&spam_module);
}
Py_ABS(x)
Return the absolute value of x.
Added in version 3.3.
4 Chapter 1. Introduction
The Python/C API, Release 3.14.0a7
Py_ALWAYS_INLINE
Ask the compiler to always inline a static inline function. The compiler can ignore it and decide to not inline
the function.
It can be used to inline performance critical static inline functions when building Python in debug mode with
function inlining disabled. For example, MSC disables function inlining when building in debug mode.
Marking blindly a static inline function with Py_ALWAYS_INLINE can result in worse performances (due
to increased code size for example). The compiler is usually smarter than the developer for the cost/benefit
analysis.
If Python is built in debug mode (if the Py_DEBUG macro is defined), the Py_ALWAYS_INLINE macro does
nothing.
It must be specified before the function return type. Usage:
Py_MAX(x, y)
Return the maximum value between x and y.
Added in version 3.3.
Py_MEMBER_SIZE(type, member)
Return the size of a structure (type) member in bytes.
Added in version 3.6.
Py_MIN(x, y)
Return the minimum value between x and y.
Added in version 3.3.
Py_NO_INLINE
Disable inlining on a function. For example, it reduces the C stack consumption: useful on LTO+PGO builds
which heavily inline code (see bpo-33720).
Usage:
Py_UNREACHABLE()
Use this when you have a code path that cannot be reached by design. For example, in the default: clause
in a switch statement for which all possible values are covered in case statements. Use this in places where
you might be tempted to put an assert(0) or abort() call.
In release mode, the macro helps the compiler to optimize the code, and avoids a warning about unreachable
code. For example, the macro is implemented with __builtin_unreachable() on GCC in release mode.
A use for Py_UNREACHABLE() is following a call a function that never returns but that is not declared
_Py_NO_RETURN.
If a code path is very unlikely code but can be reached under exceptional case, this macro must not be used.
For example, under low memory condition or if a system call returns a value out of the expected range. In this
case, it’s better to report the error to the caller. If the error cannot be reported to caller, Py_FatalError()
can be used.
Added in version 3.7.
Py_UNUSED(arg)
Use this for unused arguments in a function definition to silence compiler warnings. Example: int func(int
a, int Py_UNUSED(b)) { return a; }.
Added in version 3.4.
PyDoc_STRVAR(name, str)
Creates a variable with name name that can be used in docstrings. If Python is built without docstrings, the
value will be empty.
Use PyDoc_STRVAR for docstrings to support building Python without docstrings, as specified in PEP 7.
Example:
PyDoc_STR(str)
Creates a docstring for the given input string or an empty string if docstrings are disabled.
Use PyDoc_STR in specifying docstrings to support building Python without docstrings, as specified in PEP
7.
Example:
6 Chapter 1. Introduction
The Python/C API, Release 3.14.0a7
declared. The sole exception are the type objects; since these must never be deallocated, they are typically static
PyTypeObject objects.
All Python objects (even Python integers) have a type and a reference count. An object’s type determines what kind
of object it is (e.g., an integer, a list, or a user-defined function; there are many more as explained in types). For each
of the well-known types there is a macro to check whether an object is of that type; for instance, PyList_Check(a)
is true if (and only if) the object pointed to by a is a Python list.
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.
a reference to the object, or it does not. Stealing a reference means that when you pass a reference to a function, that
function assumes that it now owns that reference, and you are not responsible for it any longer.
Few functions steal references; the two notable exceptions are PyList_SetItem() and PyTuple_SetItem(),
which steal a reference to the item (but not to the tuple or list into which the item is put!). These functions were
designed to steal a reference because of a common idiom for populating a tuple or list with newly created objects; for
example, the code to create the tuple (1, 2, "three") could look like this (forgetting about error handling for
the moment; a better way to code this is shown below):
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"));
Here, PyLong_FromLong() returns a new reference which is immediately stolen by PyTuple_SetItem(). When
you want to keep using an object although the reference to it will be stolen, use Py_INCREF() to grab another
reference before calling the reference-stealing function.
Incidentally, PyTuple_SetItem() is the only way to set tuple items; PySequence_SetItem() and
PyObject_SetItem() refuse to do this since tuples are an immutable data type. You should only use
PyTuple_SetItem() for tuples that you are creating yourself.
Equivalent code for populating a list can be written using PyList_New() and PyList_SetItem().
However, in practice, you will rarely use these ways of creating and populating a tuple or list. There’s a generic
function, Py_BuildValue(), that can create most common objects from C values, directed by a format string.
For example, the above two blocks of code could be replaced by the following (which also takes care of the error
checking):
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
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);
}
(continues on next page)
8 Chapter 1. Introduction
The Python/C API, Release 3.14.0a7
The situation is slightly different for function return values. While passing a reference to most functions does not
change your ownership responsibilities for that reference, many functions that return a reference to an object give you
ownership of the reference. The reason is simple: in many cases, the returned object is created on the fly, and the
reference you get is the only reference to the object. Therefore, the generic functions that return object references,
like PyObject_GetItem() and PySequence_GetItem(), always return a new reference (the caller becomes the
owner of the reference).
It is important to realize that whether you own a reference returned by a function depends on which function you call
only — the plumage (the type of the object passed as an argument to the function) doesn’t enter into it! Thus, if you
extract an item from a list using PyList_GetItem(), you don’t own the reference — but if you obtain the same
item from the same list using PySequence_GetItem() (which happens to take exactly the same arguments), you
do own a reference to the returned object.
Here is an example of how you could write a function that computes the sum of the items in a list of integers; once
using PyList_GetItem(), and once using 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);
(continues on next page)
1.5.2 Types
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. A signed integral type such that sizeof(Py_ssize_t) == sizeof(size_t).
C99 doesn’t define such a thing directly (size_t is an unsigned integral type). See PEP 353 for details.
PY_SSIZE_T_MAX is the largest positive value of type Py_ssize_t.
1.6 Exceptions
The Python programmer only needs to deal with exceptions if specific error handling is required; unhandled excep-
tions are automatically propagated to the caller, then to the caller’s caller, and so on, until they reach the top-level
interpreter, where they are reported to the user accompanied by a stack traceback.
For C programmers, however, error checking always has to be explicit. All functions in the Python/C API can raise
exceptions, unless an explicit claim is made otherwise in a function’s documentation. In general, when a function
encounters an error, it sets an exception, discards any object references that it owns, and returns an error indicator.
If not documented otherwise, this indicator is either NULL or -1, depending on the function’s return type. A few
functions return a Boolean true/false result, with false indicating an error. Very few functions return no explicit error
indicator or have an ambiguous return value, and require explicit testing for errors with PyErr_Occurred(). These
exceptions are always explicitly documented.
Exception state is maintained in per-thread storage (this is equivalent to using global storage in an unthreaded appli-
cation). A thread can be in one of two states: an exception has occurred, or not. The function PyErr_Occurred()
can be used to check for this: it returns a borrowed reference to the exception type object when an exception has
occurred, and NULL otherwise. There are a number of functions to set the exception state: PyErr_SetString()
is the most common (though not the most general) function to set the exception state, and PyErr_Clear() clears
the exception state.
The full exception state consists of three objects (all of which can be NULL): the exception type, the corresponding
exception value, and the traceback. These have the same meanings as the Python result of sys.exc_info();
however, they are not the same: the Python objects represent the last exception being handled by a Python try …
except statement, while the C level exception state only exists while an exception is being passed on between C
functions until it reaches the Python bytecode interpreter’s main loop, which takes care of transferring it to sys.
exc_info() and friends.
Note that starting with Python 1.5, the preferred, thread-safe way to access the exception state from Python code
is to call the function sys.exc_info(), which returns the per-thread exception state for Python code. Also, the
semantics of both ways to access the exception state have changed so that a function which catches an exception will
save and restore its thread’s exception state so as to preserve the exception state of its caller. This prevents common
bugs in exception handling code caused by an innocent-looking function overwriting the exception being handled; it
also reduces the often unwanted lifetime extension for objects that are referenced by the stack frames in the traceback.
10 Chapter 1. Introduction
The Python/C API, Release 3.14.0a7
As a general principle, a function that calls another function to perform some task should check whether the called
function raised an exception, and if so, pass the exception state on to its caller. It should discard any object references
that it owns, and return an error indicator, but it should not set another exception — that would overwrite the exception
that was just raised, and lose important information about the exact cause of the 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) */
error:
/* Cleanup code, shared by success and failure path */
1.6. Exceptions 11
The Python/C API, Release 3.14.0a7
This example represents an endorsed use of the goto statement in C! It illustrates the use of
PyErr_ExceptionMatches() and PyErr_Clear() to handle specific exceptions, and the use of Py_XDECREF()
to dispose of owned references that may be NULL (note the 'X' in the name; Py_DECREF() would crash when
confronted with a NULL reference). It is important that the variables used to hold owned references are initialized to
NULL for this to work; likewise, the proposed return value is initialized to -1 (failure) and only set to success after
the final call made is successful.
The embedding application can steer the search by setting PyConfig.program_name before calling
Py_InitializeFromConfig(). Note that PYTHONHOME still overrides this and PYTHONPATH is still inserted
in front of the standard path. An application that requires total control has to provide its own implementation of
Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), and Py_GetProgramFullPath() (all defined in
Modules/getpath.c).
Sometimes, it is desirable to “uninitialize” Python. For instance, the application may want to start over (make another
call to Py_Initialize()) or the application is simply done with its use of Python and wants to free memory allo-
cated by Python. This can be accomplished by calling Py_FinalizeEx(). The function Py_IsInitialized()
returns true if Python is currently in the initialized state. More information about these functions is given in a later
chapter. Notice that Py_FinalizeEx() does not free all memory allocated by the Python interpreter, e.g. memory
allocated by extension modules currently cannot be released.
12 Chapter 1. Introduction
The Python/C API, Release 3.14.0a7
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.
In addition to the reference count debugging described below, extra checks are performed, see Python Debug Build.
Defining Py_TRACE_REFS enables reference tracing (see the configure --with-trace-refs option). When
defined, a circular doubly linked list of active objects is maintained by adding two extra fields to every PyObject.
Total allocations are tracked as well. Upon exit, all existing references are printed. (In interactive mode this happens
after every statement run by the interpreter.)
Please refer to Misc/SpecialBuilds.txt in the Python source distribution for more detailed information.
14 Chapter 1. Introduction
CHAPTER
TWO
C API STABILITY
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 Platform Considerations below). So, code compiled for Python 3.10.0 will work on
3.10.8 and vice versa, but will need to be compiled separately for 3.9.x and 3.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.
15
The Python/C API, Release 3.14.0a7
Rather than using the PY_VERSION_HEX macro directly, hardcode a minimum minor version (e.g.
0x030A0000 for Python 3.10) for stability when compiling with future Python versions.
You can also define Py_LIMITED_API to 3. This works the same as 0x03020000 (Python 3.2, the version
that introduced Limited API).
® Note
The Stable ABI prevents ABI issues, like linker errors due to missing symbols or data corruption due to changes in
structure layouts or function signatures. However, other changes in Python can change the behavior of extensions.
See Python’s Backwards Compatibility Policy (PEP 387) for details.
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.
On Windows, extensions that use the Stable ABI should be linked against python3.dll rather than a version-specific
library such as python39.dll.
On some platforms, Python will look for and load shared library files named with the abi3 tag (e.g. mymodule.
abi3.so). It does not check if such extensions conform to a Stable ABI. The user (or their packaging tools) need to
ensure that, for example, extensions built with the 3.10+ Limited API are not installed for lower versions of Python.
All functions in the Stable ABI are present as functions in Python’s shared library, not solely as macros. This makes
them usable from languages that don’t use the C preprocessor.
For these reasons, we recommend testing an extension with all minor Python versions it supports, and preferably to
build with the lowest such version.
We also recommend reviewing documentation of all used API to check if it is explicitly part of the Limited API. Even
with Py_LIMITED_API defined, a few private declarations are exposed for technical reasons (or even unintentionally,
as bugs).
Also note that the Limited API is not necessarily stable: compiling with Py_LIMITED_API with Python 3.8 means
that the extension will run with Python 3.12, but it will not necessarily compile with Python 3.12. In particular, parts
of the Limited API may be deprecated and removed, provided that the Stable ABI stays stable.
• 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
• PyCFunctionFast
• PyCFunctionFastWithKeywords
• PyCFunctionWithKeywords
• PyCFunction_GetFlags()
• PyCFunction_GetFunction()
• PyCFunction_GetSelf()
• PyCFunction_New()
• PyCFunction_NewEx()
• PyCFunction_Type
• PyCMethod_New()
• PyCallIter_New()
• PyCallIter_Type
• PyCallable_Check()
• PyCapsule_Destructor
• PyCapsule_GetContext()
• PyCapsule_GetDestructor()
• PyCapsule_GetName()
• PyCapsule_GetPointer()
• PyCapsule_Import()
• PyCapsule_IsValid()
• PyCapsule_New()
• PyCapsule_SetContext()
• PyCapsule_SetDestructor()
• PyCapsule_SetName()
• PyCapsule_SetPointer()
• PyCapsule_Type
• PyClassMethodDescr_Type
• PyCodec_BackslashReplaceErrors()
• PyCodec_Decode()
• PyCodec_Decoder()
• PyCodec_Encode()
• PyCodec_Encoder()
• PyCodec_IgnoreErrors()
• 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_GetItemRef()
• PyDict_GetItemString()
• PyDict_GetItemStringRef()
• PyDict_GetItemWithError()
• PyDict_Items()
• PyDict_Keys()
• PyDict_Merge()
• PyDict_MergeFromSeq2()
• PyDict_New()
• PyDict_Next()
• PyDict_SetItem()
• PyDict_SetItemString()
• PyDict_Size()
• PyDict_Type
• PyDict_Update()
• PyDict_Values()
• PyEllipsis_Type
• PyEnum_Type
• PyErr_BadArgument()
• PyErr_BadInternalCall()
• PyErr_CheckSignals()
• PyErr_Clear()
• PyErr_Display()
• PyErr_DisplayException()
• PyErr_ExceptionMatches()
• PyErr_Fetch()
• PyErr_Format()
• PyErr_FormatV()
• PyErr_GetExcInfo()
• PyErr_GetHandledException()
• PyErr_GetRaisedException()
• PyErr_GivenExceptionMatches()
• PyErr_NewException()
• PyErr_NewExceptionWithDoc()
• PyErr_NoMemory()
• PyErr_NormalizeException()
• PyErr_Occurred()
• PyErr_Print()
• PyErr_PrintEx()
• PyErr_ProgramText()
• PyErr_ResourceWarning()
• PyErr_Restore()
• PyErr_SetExcFromWindowsErr()
• PyErr_SetExcFromWindowsErrWithFilename()
• PyErr_SetExcFromWindowsErrWithFilenameObject()
• PyErr_SetExcFromWindowsErrWithFilenameObjects()
• PyErr_SetExcInfo()
• PyErr_SetFromErrno()
• PyErr_SetFromErrnoWithFilename()
• PyErr_SetFromErrnoWithFilenameObject()
• PyErr_SetFromErrnoWithFilenameObjects()
• PyErr_SetFromWindowsErr()
• PyErr_SetFromWindowsErrWithFilename()
• PyErr_SetHandledException()
• PyErr_SetImportError()
• PyErr_SetImportErrorSubclass()
• PyErr_SetInterrupt()
• PyErr_SetInterruptEx()
• PyErr_SetNone()
• PyErr_SetObject()
• PyErr_SetRaisedException()
• PyErr_SetString()
• PyErr_SyntaxLocation()
• PyErr_SyntaxLocationEx()
• PyErr_WarnEx()
• PyErr_WarnExplicit()
• PyErr_WarnFormat()
• PyErr_WriteUnraisable()
• PyEval_AcquireThread()
• PyEval_EvalCode()
• PyEval_EvalCodeEx()
• PyEval_EvalFrame()
• PyEval_EvalFrameEx()
• PyEval_GetBuiltins()
• PyEval_GetFrame()
• PyEval_GetFrameBuiltins()
• PyEval_GetFrameGlobals()
• PyEval_GetFrameLocals()
• PyEval_GetFuncDesc()
• PyEval_GetFuncName()
• PyEval_GetGlobals()
• PyEval_GetLocals()
• PyEval_InitThreads()
• PyEval_ReleaseThread()
• PyEval_RestoreThread()
• PyEval_SaveThread()
• PyExc_ArithmeticError
• PyExc_AssertionError
• 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_AddModuleRef()
• PyImport_AppendInittab()
• PyImport_ExecCodeModule()
• PyImport_ExecCodeModuleEx()
• PyImport_ExecCodeModuleObject()
• PyImport_ExecCodeModuleWithPathnames()
• PyImport_GetImporter()
• PyImport_GetMagicNumber()
• PyImport_GetMagicTag()
• PyImport_GetModule()
• PyImport_GetModuleDict()
• PyImport_Import()
• PyImport_ImportFrozenModule()
• PyImport_ImportFrozenModuleObject()
• PyImport_ImportModule()
• PyImport_ImportModuleLevel()
• PyImport_ImportModuleLevelObject()
• PyImport_ImportModuleNoBlock()
• PyImport_ReloadModule()
• PyIndex_Check()
• PyInterpreterState
• PyInterpreterState_Clear()
• PyInterpreterState_Delete()
• PyInterpreterState_Get()
• PyInterpreterState_GetDict()
• PyInterpreterState_GetID()
• PyInterpreterState_New()
• PyIter_Check()
• PyIter_Next()
• PyIter_NextItem()
• PyIter_Send()
• PyListIter_Type
• PyListRevIter_Type
• PyList_Append()
• PyList_AsTuple()
• PyList_GetItem()
• PyList_GetItemRef()
• PyList_GetSlice()
• PyList_Insert()
• PyList_New()
• PyList_Reverse()
• PyList_SetItem()
• PyList_SetSlice()
• PyList_Size()
• PyList_Sort()
• PyList_Type
• PyLongObject
• PyLongRangeIter_Type
• PyLong_AsDouble()
• PyLong_AsInt()
• PyLong_AsInt32()
• PyLong_AsInt64()
• PyLong_AsLong()
• PyLong_AsLongAndOverflow()
• PyLong_AsLongLong()
• PyLong_AsLongLongAndOverflow()
• PyLong_AsNativeBytes()
• PyLong_AsSize_t()
• PyLong_AsSsize_t()
• PyLong_AsUInt32()
• PyLong_AsUInt64()
• PyLong_AsUnsignedLong()
• PyLong_AsUnsignedLongLong()
• PyLong_AsUnsignedLongLongMask()
• PyLong_AsUnsignedLongMask()
• PyLong_AsVoidPtr()
• PyLong_FromDouble()
• PyLong_FromInt32()
• PyLong_FromInt64()
• PyLong_FromLong()
• PyLong_FromLongLong()
• PyLong_FromNativeBytes()
• PyLong_FromSize_t()
• PyLong_FromSsize_t()
• PyLong_FromString()
• PyLong_FromUInt32()
• PyLong_FromUInt64()
• PyLong_FromUnsignedLong()
• PyLong_FromUnsignedLongLong()
• PyLong_FromUnsignedNativeBytes()
• PyLong_FromVoidPtr()
• PyLong_GetInfo()
• PyLong_Type
• PyMap_Type
• PyMapping_Check()
• PyMapping_GetItemString()
• PyMapping_GetOptionalItem()
• PyMapping_GetOptionalItemString()
• PyMapping_HasKey()
• PyMapping_HasKeyString()
• PyMapping_HasKeyStringWithError()
• PyMapping_HasKeyWithError()
• PyMapping_Items()
• PyMapping_Keys()
• PyMapping_Length()
• PyMapping_SetItemString()
• PyMapping_Size()
• PyMapping_Values()
• PyMem_Calloc()
• PyMem_Free()
• PyMem_Malloc()
• PyMem_RawCalloc()
• PyMem_RawFree()
• PyMem_RawMalloc()
• PyMem_RawRealloc()
• PyMem_Realloc()
• PyMemberDef
• PyMemberDescr_Type
• PyMember_GetOne()
• PyMember_SetOne()
• PyMemoryView_FromBuffer()
• PyMemoryView_FromMemory()
• PyMemoryView_FromObject()
• PyMemoryView_GetContiguous()
• PyMemoryView_Type
• PyMethodDef
• PyMethodDescr_Type
• PyModuleDef
• PyModuleDef_Base
• PyModuleDef_Init()
• PyModuleDef_Type
• PyModule_Add()
• PyModule_AddFunctions()
• PyModule_AddIntConstant()
• PyModule_AddObject()
• PyModule_AddObjectRef()
• PyModule_AddStringConstant()
• PyModule_AddType()
• PyModule_Create2()
• PyModule_ExecDef()
• PyModule_FromDefAndSpec2()
• PyModule_GetDef()
• PyModule_GetDict()
• PyModule_GetFilename()
• PyModule_GetFilenameObject()
• PyModule_GetName()
• PyModule_GetNameObject()
• PyModule_GetState()
• PyModule_New()
• PyModule_NewObject()
• PyModule_SetDocString()
• PyModule_Type
• PyNumber_Absolute()
• PyNumber_Add()
• 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_AsFileDescriptor()
• PyObject_Bytes()
• PyObject_Call()
• PyObject_CallFunction()
• PyObject_CallFunctionObjArgs()
• PyObject_CallMethod()
• PyObject_CallMethodObjArgs()
• PyObject_CallNoArgs()
• PyObject_CallObject()
• PyObject_Calloc()
• PyObject_CheckBuffer()
• PyObject_ClearWeakRefs()
• PyObject_CopyData()
• PyObject_DelAttr()
• PyObject_DelAttrString()
• PyObject_DelItem()
• PyObject_DelItemString()
• PyObject_Dir()
• PyObject_Format()
• PyObject_Free()
• PyObject_GC_Del()
• PyObject_GC_IsFinalized()
• PyObject_GC_IsTracked()
• PyObject_GC_Track()
• PyObject_GC_UnTrack()
• PyObject_GenericGetAttr()
• PyObject_GenericGetDict()
• PyObject_GenericSetAttr()
• PyObject_GenericSetDict()
• PyObject_GetAIter()
• PyObject_GetAttr()
• PyObject_GetAttrString()
• PyObject_GetBuffer()
• PyObject_GetItem()
• PyObject_GetIter()
• PyObject_GetOptionalAttr()
• PyObject_GetOptionalAttrString()
• PyObject_GetTypeData()
• PyObject_HasAttr()
• PyObject_HasAttrString()
• PyObject_HasAttrStringWithError()
• PyObject_HasAttrWithError()
• PyObject_Hash()
• PyObject_HashNotImplemented()
• PyObject_Init()
• PyObject_InitVar()
• PyObject_IsInstance()
• PyObject_IsSubclass()
• PyObject_IsTrue()
• PyObject_Length()
• PyObject_Malloc()
• PyObject_Not()
• PyObject_Realloc()
• PyObject_Repr()
• PyObject_RichCompare()
• PyObject_RichCompareBool()
• 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_Audit()
• PySys_AuditTuple()
• PySys_FormatStderr()
• PySys_FormatStdout()
• PySys_GetObject()
• PySys_GetXOptions()
• PySys_ResetWarnOptions()
• PySys_SetArgv()
• PySys_SetArgvEx()
• PySys_SetObject()
• PySys_WriteStderr()
• PySys_WriteStdout()
• PyThreadState
• PyThreadState_Clear()
• PyThreadState_Delete()
• PyThreadState_Get()
• PyThreadState_GetDict()
• 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_Freeze()
• PyType_FromMetaclass()
• PyType_FromModuleAndSpec()
• PyType_FromSpec()
• PyType_FromSpecWithBases()
• PyType_GenericAlloc()
• PyType_GenericNew()
• PyType_GetBaseByToken()
• PyType_GetFlags()
• PyType_GetFullyQualifiedName()
• PyType_GetModule()
• PyType_GetModuleByDef()
• PyType_GetModuleName()
• PyType_GetModuleState()
• PyType_GetName()
• PyType_GetQualName()
• PyType_GetSlot()
• PyType_GetTypeDataSize()
• PyType_IsSubtype()
• PyType_Modified()
• PyType_Ready()
• PyType_Slot
• PyType_Spec
• PyType_Type
• PyUnicodeDecodeError_Create()
• PyUnicodeDecodeError_GetEncoding()
• PyUnicodeDecodeError_GetEnd()
• PyUnicodeDecodeError_GetObject()
• PyUnicodeDecodeError_GetReason()
• PyUnicodeDecodeError_GetStart()
• PyUnicodeDecodeError_SetEnd()
• PyUnicodeDecodeError_SetReason()
• PyUnicodeDecodeError_SetStart()
• PyUnicodeEncodeError_GetEncoding()
• PyUnicodeEncodeError_GetEnd()
• 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_Equal()
• PyUnicode_EqualToUTF8()
• PyUnicode_EqualToUTF8AndSize()
• PyUnicode_FSConverter()
• PyUnicode_FSDecoder()
• PyUnicode_Find()
• PyUnicode_FindChar()
• PyUnicode_Format()
• PyUnicode_FromEncodedObject()
• PyUnicode_FromFormat()
• PyUnicode_FromFormatV()
• PyUnicode_FromObject()
• PyUnicode_FromOrdinal()
• PyUnicode_FromString()
• PyUnicode_FromStringAndSize()
• PyUnicode_FromWideChar()
• PyUnicode_GetDefaultEncoding()
• PyUnicode_GetLength()
• PyUnicode_InternFromString()
• PyUnicode_InternInPlace()
• PyUnicode_IsIdentifier()
• PyUnicode_Join()
• PyUnicode_Partition()
• PyUnicode_RPartition()
• PyUnicode_RSplit()
• PyUnicode_ReadChar()
• PyUnicode_Replace()
• PyUnicode_Resize()
• PyUnicode_RichCompare()
• PyUnicode_Split()
• PyUnicode_Splitlines()
• PyUnicode_Substring()
• PyUnicode_Tailmatch()
• PyUnicode_Translate()
• PyUnicode_Type
• PyUnicode_WriteChar()
• PyVarObject
• PyVarObject.ob_base
• PyVarObject.ob_size
• PyVectorcall_Call()
• PyVectorcall_NARGS()
• PyWeakReference
• PyWeakref_GetObject()
• PyWeakref_GetRef()
• PyWeakref_NewProxy()
• PyWeakref_NewRef()
• PyWrapperDescr_Type
• PyWrapper_New()
• PyZip_Type
• Py_AddPendingCall()
• Py_AtExit()
• Py_BEGIN_ALLOW_THREADS
• Py_BLOCK_THREADS
• Py_BuildValue()
• Py_BytesMain()
• Py_CompileString()
• Py_DecRef()
• Py_DecodeLocale()
• Py_END_ALLOW_THREADS
• Py_EncodeLocale()
• Py_EndInterpreter()
• Py_EnterRecursiveCall()
• Py_Exit()
• Py_FatalError()
• Py_FileSystemDefaultEncodeErrors
• Py_FileSystemDefaultEncoding
• Py_Finalize()
• Py_FinalizeEx()
• Py_GenericAlias()
• Py_GenericAliasType
• Py_GetBuildInfo()
• Py_GetCompiler()
• Py_GetConstant()
• Py_GetConstantBorrowed()
• Py_GetCopyright()
• Py_GetExecPrefix()
• Py_GetPath()
• Py_GetPlatform()
• Py_GetPrefix()
• Py_GetProgramFullPath()
• Py_GetProgramName()
• Py_GetPythonHome()
• Py_GetRecursionLimit()
• Py_GetVersion()
• Py_HasFileSystemDefaultEncoding
• Py_IncRef()
• Py_Initialize()
• Py_InitializeEx()
• Py_Is()
• Py_IsFalse()
• Py_IsFinalizing()
• Py_IsInitialized()
• Py_IsNone()
• Py_IsTrue()
• Py_LeaveRecursiveCall()
• Py_Main()
• Py_MakePendingCalls()
• Py_NewInterpreter()
• Py_NewRef()
• Py_PACK_FULL_VERSION()
• Py_PACK_VERSION()
• Py_REFCNT()
• Py_ReprEnter()
• Py_ReprLeave()
• Py_SetProgramName()
• Py_SetPythonHome()
• Py_SetRecursionLimit()
• Py_TYPE()
• 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
THREE
The functions in this chapter will let you execute Python source code given in a file or a buffer, but they will not let
you interact in a more detailed way with the interpreter.
Several of these functions accept a start symbol from the grammar as a parameter. The available start symbols are
Py_eval_input, Py_file_input, and Py_single_input. These are described following the functions which
accept them as parameters.
Note also that several of these functions take FILE* parameters. One particular issue which needs to be handled
carefully is that the FILE structure for different C libraries can be different and incompatible. Under Windows (at
least), it is possible for dynamically linked extensions to actually use different libraries, so care should be taken that
FILE* parameters are only passed to these functions if it is certain that they were created by the same library that
the Python runtime is using.
int PyRun_AnyFile(FILE *fp, const char *filename)
This is a simplified interface to PyRun_AnyFileExFlags() below, leaving closeit set to 0 and flags set to
NULL.
43
The Python/C API, Release 3.14.0a7
int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)
Similar to PyRun_SimpleStringFlags(), but the Python source code is read from fp instead of an in-
memory string. filename should be the name of the file, it is decoded from filesystem encoding and error
handler. If closeit is true, the file is closed before PyRun_SimpleFileExFlags() returns.
® Note
On Windows, fp should be opened as binary mode (e.g. fopen(filename, "rb")). Otherwise, Python
may not handle script file with LF line ending correctly.
object that implements the mapping protocol. The parameter start specifies the start token that should be used
to parse the source code.
Returns the result of executing the code as a Python object, or NULL if an exception was raised.
PyObject *PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)
Return value: New reference. This is a simplified interface to PyRun_FileExFlags() below, leaving closeit
set to 0 and flags set to NULL.
PyObject *PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int
closeit)
Return value: New reference. This is a simplified interface to PyRun_FileExFlags() below, leaving flags
set to NULL.
PyObject *PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags)
Return value: New reference. This is a simplified interface to PyRun_FileExFlags() below, leaving closeit
set to 0.
PyObject *PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals,
int closeit, PyCompilerFlags *flags)
Return value: New reference. Similar to PyRun_StringFlags(), but the Python source code is read from
fp instead of an in-memory string. filename should be the name of the file, it is decoded from the filesystem
encoding and error handler. If closeit is true, the file is closed before PyRun_FileExFlags() returns.
PyObject *Py_CompileString(const char *str, const char *filename, int start)
Return value: New reference. Part of the Stable ABI. This is a simplified interface to
Py_CompileStringFlags() below, leaving flags set to NULL.
PyObject *Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)
Return value: New reference. This is a simplified interface to Py_CompileStringExFlags() below, with
optimize set to -1.
PyObject *Py_CompileStringObject(const char *str, PyObject *filename, int start, 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.
The integer optimize specifies the optimization level of the compiler; a value of -1 selects the optimization
level of the interpreter as given by -O options. Explicit levels are 0 (no optimization; __debug__ is true), 1
(asserts are removed, __debug__ is false) or 2 (docstrings are removed too).
Added in version 3.4.
PyObject *Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags,
int optimize)
Return value: New reference. Like Py_CompileStringObject(), but filename is a byte string decoded
from the filesystem encoding and error handler.
Added in version 3.2.
PyObject *PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
Return value: New reference. Part of the Stable ABI. This is a simplified interface to PyEval_EvalCodeEx(),
with just the code object, and global and local variables. The other arguments are set to NULL.
PyObject *PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int
argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int
defcount, PyObject *kwdefs, PyObject *closure)
Return value: New reference. Part of the Stable ABI. Evaluate a precompiled code object, given a particular
45
The Python/C API, Release 3.14.0a7
environment for its evaluation. This environment consists of a dictionary of global variables, a mapping object
of local variables, arrays of arguments, keywords and defaults, a dictionary of default values for keyword-only
arguments and a closure tuple of cells.
PyObject *PyEval_EvalFrame(PyFrameObject *f)
Return value: New reference. Part of the Stable ABI. Evaluate an execution frame. This is a simplified interface
to PyEval_EvalFrameEx(), for backward compatibility.
PyObject *PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
Return value: New reference. Part of the Stable ABI. This is the main, unvarnished function of Python in-
terpretation. The code object associated with the execution frame f is executed, interpreting bytecode and
executing calls as needed. The additional throwflag parameter can mostly be ignored - if true, then it causes
an exception to immediately be thrown; this is used for the throw() methods of generator objects.
Changed in version 3.4: This function now includes a debug assertion to help ensure that it does not silently
discard an active exception.
int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
This function changes the flags of the current evaluation frame, and returns true on success, false on failure.
int Py_eval_input
The start symbol from the Python grammar for isolated expressions; for use with Py_CompileString().
int Py_file_input
The start symbol from the Python grammar for sequences of statements as read from a file or other source; for
use with Py_CompileString(). This is the symbol to use when compiling arbitrarily long Python source
code.
int Py_single_input
The start symbol from the Python grammar for a single statement; for use with Py_CompileString(). This
is the symbol used for the interactive interpreter loop.
struct PyCompilerFlags
This is the structure used to hold compiler flags. In cases where code is only being compiled, it is passed as
int flags, and in cases where code is being executed, it is passed as PyCompilerFlags *flags. In this
case, from __future__ import can modify flags.
Whenever PyCompilerFlags *flags is NULL, cf_flags is treated as equal to 0, and any modification
due to from __future__ import is discarded.
int cf_flags
Compiler flags.
int cf_feature_version
cf_feature_version is the minor Python version. It should be initialized to PY_MINOR_VERSION.
The field is ignored by default, it is used if and only if PyCF_ONLY_AST flag is set in cf_flags.
Changed in version 3.8: Added cf_feature_version field.
The available compiler flags are accessible as macros:
PyCF_ALLOW_TOP_LEVEL_AWAIT
PyCF_ONLY_AST
PyCF_OPTIMIZED_AST
PyCF_TYPE_COMMENTS
See compiler flags in documentation of the ast Python module, which exports these constants under the
same names.
int CO_FUTURE_DIVISION
This bit can be set in flags to cause division operator / to be interpreted as “true division” according to
PEP 238.
FOUR
REFERENCE COUNTING
The functions and macros in this section are used for managing reference counts of Python objects.
Py_ssize_t Py_REFCNT(PyObject *o)
Part of the Stable ABI since version 3.14. 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.
Changed in version 3.10: Py_REFCNT() is changed to the inline static function.
Changed in version 3.11: The parameter type is no longer const PyObject*.
void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)
Set the object o reference counter to refcnt.
On Python build with Free Threading, if refcnt is larger than UINT32_MAX, the object is made immortal.
This function has no effect on immortal objects.
Added in version 3.9.
Changed in version 3.12: Immortal objects are not modified.
void Py_INCREF(PyObject *o)
Indicate taking a new strong reference to object o, indicating it is in use and should not be destroyed.
This function has no effect on immortal objects.
This function is usually used to convert a borrowed reference to a strong reference in-place. The Py_NewRef()
function can be used to create a new strong reference.
When done using the object, release is by calling Py_DECREF().
The object must not be NULL; if you aren’t sure that it isn’t NULL, use Py_XINCREF().
Do not expect this function to actually modify o in any way. For at least some objects, this function has no
effect.
Changed in version 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.
See also Py_XNewRef().
PyObject *Py_NewRef(PyObject *o)
Part of the Stable ABI since version 3.10. Create a new strong reference to an object: call Py_INCREF() on o
and return the object o.
When the strong reference is no longer needed, Py_DECREF() should be called on it to release the reference.
The object o must not be NULL; use Py_XNewRef() if o can be NULL.
47
The Python/C API, Release 3.14.0a7
For example:
Py_INCREF(obj);
self->attr = obj;
self->attr = Py_NewRef(obj);
Á Warning
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.
Changed in version 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.
Changed in version 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, Release 3.14.0a7
FIVE
EXCEPTION HANDLING
The functions described in this chapter will let you handle and raise Python exceptions. It is important to understand
some of the basics of Python exception handling. It works somewhat like the POSIX errno variable: there is a
global indicator (per thread) of the last error that occurred. Most C API functions don’t clear this on success, but will
set it to indicate the cause of the error on failure. Most C API functions also return an error indicator, usually NULL
if they are supposed to return a pointer, or -1 if they return an integer (exception: the PyArg_* functions return 1
for success and 0 for failure).
Concretely, the error indicator consists of three object pointers: the exception’s type, the exception’s value, and the
traceback object. Any of those pointers can be NULL if non-set (although some combinations are forbidden, for
example you can’t have a non-NULL traceback if the exception type is NULL).
When a function must fail because some function it called failed, it generally doesn’t set the error indicator; the
function it called already set it. It is responsible for either handling the error and clearing the exception or returning
after cleaning up any resources it holds (such as object references or memory allocations); it should not continue
normally if it is not prepared to handle the error. If returning due to an error, it is important to indicate to the caller
that an error has been set. If the error is not handled or carefully propagated, additional calls into the Python/C API
may not behave as intended and may fail in mysterious ways.
® Note
The error indicator is not the result of sys.exc_info(). The former corresponds to an exception that is not yet
caught (and is therefore still propagating), while the latter returns an exception after it is caught (and has therefore
stopped propagating).
51
The Python/C API, Release 3.14.0a7
int PyErr_BadArgument()
Part of the Stable ABI. This is a shorthand for PyErr_SetString(PyExc_TypeError, message), where
message indicates that a built-in operation was invoked with an illegal argument. It is mostly for internal use.
PyObject *PyErr_NoMemory()
Return value: Always NULL. Part of the Stable ABI. This is a shorthand for
PyErr_SetNone(PyExc_MemoryError); it returns NULL so an object allocation function can write
return PyErr_NoMemory(); when it runs out of memory.
Availability: Windows.
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)
Return value: Always NULL. Part of the Stable ABI on Windows since version 3.7. Similar to
PyErr_SetFromWindowsErr(), with the additional behavior that if filename is not NULL, it is decoded
from the filesystem encoding (os.fsdecode()) and passed to the constructor of OSError as a third param-
eter to be used to define the filename attribute of the exception instance.
Availability: 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.
Availability: 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 to
PyErr_SetExcFromWindowsErrWithFilenameObject(), but accepts a second filename object.
Availability: 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 to
PyErr_SetFromWindowsErrWithFilename(), with an additional parameter specifying the exception
type to be raised.
Availability: Windows.
PyObject *PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)
Return value: Always NULL. Part of the Stable ABI since version 3.7. This is a convenience function to raise
ImportError. msg will be set as the exception’s message string. name and path, both of which can be NULL,
will be set as the ImportError’s respective name and path attributes.
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. Much like PyErr_SetImportError()
but this function allows for specifying a subclass of ImportError to raise.
Added in version 3.6.
void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
Set file, line, and offset information for the current exception. If the current exception is not a SyntaxError,
then it sets additional attributes, which make the exception printing subsystem think the exception is a
SyntaxError.
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. Like PyErr_SyntaxLocationObject(), but filename is a byte
string decoded from the filesystem encoding and error handler.
Added in version 3.2.
void PyErr_SyntaxLocation(const char *filename, int lineno)
Part of the Stable ABI. Like PyErr_SyntaxLocationEx(), but the col_offset parameter is omitted.
void PyErr_BadInternalCall()
Part of the Stable ABI. This is a shorthand for PyErr_SetString(PyExc_SystemError, message),
where message indicates that an internal operation (e.g. a Python/C API function) was invoked with an illegal
argument. It is mostly for internal use.
that warnings are to be turned into errors, and in that case they will raise an exception. It is also possible that the
functions raise an exception because of a problem with the warning machinery. The return value is 0 if no exception
is raised, or -1 if an exception is raised. (It is not possible to determine whether a warning message is actually printed,
nor what the reason is for the exception; this is intentional.) If an exception is raised, the caller should do its normal
exception handling (for example, Py_DECREF() owned references and return an error value).
int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
Part of the Stable ABI. Issue a warning message. The category argument is a warning category (see below)
or NULL; the message argument is a UTF-8 encoded string. stack_level is a positive number giving a number
of stack frames; the warning will be issued from the currently executing line of code in that stack frame. A
stack_level of 1 is the function calling PyErr_WarnEx(), 2 is the function above that, and so forth.
Warning categories must be subclasses of PyExc_Warning; PyExc_Warning is a subclass of
PyExc_Exception; the default warning category is PyExc_RuntimeWarning. The standard Python warn-
ing categories are available as global variables whose names are enumerated at Standard Warning Categories.
For information about warning control, see the documentation for the warnings module and the -W option in
the command line documentation. There is no C API for warning control.
int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno,
PyObject *module, PyObject *registry)
Issue a warning message with explicit control over all warning attributes. This is a straightforward wrapper
around the Python function warnings.warn_explicit(); see there for more information. The module and
registry arguments may be set to NULL to get the default effect described there.
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 to PyErr_WarnExplicitObject() except that message and module are
UTF-8 encoded strings, and filename is decoded from the filesystem encoding and error handler.
int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
Part of the Stable ABI. Function similar to PyErr_WarnEx(), but use PyUnicode_FromFormat() to format
the warning message. format is an ASCII-encoded string.
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.
® Note
Do not compare the return value to a specific exception; use PyErr_ExceptionMatches() instead,
shown below. (The comparison could easily fail since the exception may be an instance instead of a class,
in the case of a class exception, or it may be a subclass of the expected exception.)
{
PyObject *exc = PyErr_GetRaisedException();
PyErr_SetRaisedException(exc);
}
µ See also
Á Warning
® Note
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);
® Note
This function is normally only used by legacy code that needs to save and restore the error indicator tem-
porarily. Use PyErr_Fetch() to save the current error indicator.
® Note
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. Retrieve the active exception instance, as would be returned by
sys.exception(). This refers to an exception that was already caught, not to an exception that was freshly
raised. Returns a new reference to the exception or NULL. Does not modify the interpreter’s exception state.
® Note
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when
code needs to save and restore the exception state temporarily. Use PyErr_SetHandledException()
to restore or clear the exception state.
® Note
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when
code needs to save and restore the exception state temporarily. Use PyErr_GetHandledException()
to get the exception state.
® Note
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when
code needs to save and restore the exception state temporarily. Use PyErr_SetExcInfo() to restore or
clear the exception state.
® Note
This function is not normally used by code that wants to handle exceptions. Rather, it can be used when
code needs to save and restore the exception state temporarily. Use PyErr_GetExcInfo() to read the
exception state.
The function attempts to handle all pending signals, and then returns 0. However, if a Python signal handler
raises an exception, the error indicator is set and the function returns -1 immediately (such that other pending
signals may not have been handled yet: they will be on the next PyErr_CheckSignals() invocation).
If the function is called from a non-main thread, or under a non-main Python interpreter, it does nothing and
returns 0.
This function can be called by long-running C code that wants to be interruptible by user requests (such as by
pressing Ctrl-C).
® Note
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).
® Note
This function is async-signal-safe. It can be called without an attached thread state and from a C signal
handler.
This function can be called by C code that sets up its own signal handling and wants Python signal handlers
to be invoked as expected when an interruption is requested (for example when the user presses Ctrl-C to
interrupt an operation).
If the given signal isn’t handled by Python (it was set to signal.SIG_DFL or signal.SIG_IGN), it will be
ignored.
If signum is outside of the allowed range of signal numbers, -1 is returned. Otherwise, 0 is returned. The
error indicator is never changed by this function.
® Note
This function is async-signal-safe. It can be called without an attached thread state and from a C signal
handler.
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.
µ See also
UnicodeError.start
® Note
While passing a negative start does not raise an exception, the corresponding getters will not consider it as
a relative offset.
µ See also
UnicodeError.end
Changed in version 3.9: This function is now also available in the limited API.
void Py_LeaveRecursiveCall(void)
Part of the Stable ABI since version 3.9. Ends a Py_EnterRecursiveCall(). Must be called once for each
successful invocation of Py_EnterRecursiveCall().
Changed in version 3.9: This function is now also available in the limited API.
Properly implementing tp_repr for container types requires special recursion handling. In addition to protecting the
stack, tp_repr also needs to track objects to prevent cycles. The following two functions facilitate this functionality.
Effectively, these are the C equivalent to reprlib.recursive_repr().
C Name Notes
PyExc_EnvironmentError
PyExc_IOError
2
PyExc_WindowsError
SIX
UTILITIES
The functions in this chapter perform various utility tasks, ranging from helping C code be more portable across
platforms, using Python modules from C, and parsing function arguments and constructing Python values from C
values.
Á Warning
The C fork() call should only be made from the “main” thread (of the “main” interpreter). The same is
true for PyOS_BeforeFork().
Á Warning
The C fork() call should only be made from the “main” thread (of the “main” interpreter). The same is
true for PyOS_AfterFork_Parent().
67
The Python/C API, Release 3.14.0a7
Á Warning
The C fork() call should only be made from the “main” thread (of the “main” interpreter). The same is
true for PyOS_AfterFork_Child().
µ See also
void PyOS_AfterFork()
Part of the Stable ABI on platforms with fork(). Function to update some internal state after a process fork;
this should be called in the new process if the Python interpreter will continue to be used. If a new executable
is loaded into the new process, this function does not need to be called.
Deprecated since version 3.7: This function is superseded by PyOS_AfterFork_Child().
int PyOS_CheckStack()
Part of the Stable ABI on platforms with USE_STACKCHECK since version 3.7. Return true when the interpreter
runs out of stack space. This is a reliable check, but is only available when USE_STACKCHECK is defined
(currently on certain versions of Windows using the Microsoft Visual C++ compiler). USE_STACKCHECK will
be defined automatically; you should never change the definition in your own code.
typedef void (*PyOS_sighandler_t)(int)
Part of the Stable ABI.
PyOS_sighandler_t PyOS_getsig(int i)
Part of the Stable ABI. Return the current signal handler for signal i. This is a thin wrapper around either
sigaction() or signal(). Do not call those functions directly!
Á Warning
This function should not be called directly: use the PyConfig API with the
PyConfig_SetBytesString() function which ensures that Python is preinitialized.
This function must not be called before Python is preinitialized and so that the LC_CTYPE locale is properly
configured: see the Py_PreInitialize() function.
Decode a byte string from the filesystem encoding and error handler. If the error handler is surrogateescape er-
ror handler, undecodable bytes are decoded as characters in range U+DC80..U+DCFF; and if a byte sequence
68 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
can be decoded as a surrogate character, the bytes are escaped using the surrogateescape error handler instead
of decoding them.
Return a pointer to a newly allocated wide character string, use PyMem_RawFree() to free the memory. If
size is not NULL, write the number of wide characters excluding the null character into *size
Return NULL on decoding error or memory allocation error. If size is not NULL, *size is set to (size_t)-1
on memory error or set to (size_t)-2 on decoding error.
The filesystem encoding and error handler are selected by PyConfig_Read(): see filesystem_encoding
and filesystem_errors members of PyConfig .
Decoding errors should never happen, unless there is a bug in the C library.
Use the Py_EncodeLocale() function to encode the character string back to a byte string.
µ See also
Á Warning
This function must not be called before Python is preinitialized and so that the LC_CTYPE locale is properly
configured: see the Py_PreInitialize() function.
µ See also
Deprecated since version 3.13, will be removed in version 3.15: Clear sys.warnoptions and warnings.
filters instead.
70 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
If the interpreter is initialized, this function raises an auditing event sys.addaudithook with no arguments.
If any existing hooks raise an exception derived from Exception, the new hook will not be added and the
exception is cleared. As a result, callers cannot assume that their hook has been added unless they control all
existing hooks.
µ See also
Changed in version 3.3: This function used to fail immediately when the import lock was held by another
thread. In Python 3.3 though, the locking scheme switched to per-module locks for most purposes, so this
function’s special behaviour isn’t needed anymore.
Deprecated since version 3.13, will be removed in version 3.15: Use PyImport_ImportModule() instead.
PyObject *PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals, PyObject
*fromlist)
Return value: New reference. Import a module. This is best described by referring to the built-in Python
function __import__().
72 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
The return value is a new reference to the imported module or top-level package, or NULL with an exception
set on failure. Like for __import__(), the return value when a submodule of a package was requested is
normally the top-level package, unless a non-empty fromlist was given.
Failing imports remove incomplete module objects, like with 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. Import a module. This is best described
by referring to the built-in Python function __import__(), as the standard __import__() function calls
this function directly.
The return value is a new reference to the imported module or top-level package, or NULL with an exception
set on failure. Like for __import__(), the return value when a submodule of a package was requested is
normally the top-level package, unless a non-empty fromlist was given.
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 to PyImport_ImportModuleLevelObject(),
but the name is a UTF-8 encoded string instead of a Unicode object.
Changed in version 3.3: Negative values for level are no longer accepted.
PyObject *PyImport_Import(PyObject *name)
Return value: New reference. Part of the Stable ABI. This is a higher-level interface that calls the current
“import hook function” (with an explicit level of 0, meaning absolute import). It invokes the __import__()
function from the __builtins__ of the current globals. This means that the import is done using whatever
import hooks are installed in the current environment.
This function always uses absolute imports.
PyObject *PyImport_ReloadModule(PyObject *m)
Return value: New reference. Part of the Stable ABI. Reload a module. Return a new reference to the reloaded
module, or NULL with an exception set on failure (the module still exists in this case).
PyObject *PyImport_AddModuleRef(const char *name)
Return value: New reference. Part of the Stable ABI since version 3.13. Return the module object corresponding
to a module name.
The name argument may be of the form package.module. First check the modules dictionary if there’s one
there, and if not, create a new one and insert it in the modules dictionary.
Return a strong reference to the module on success. Return NULL with an exception set on failure.
The module name name is decoded from UTF-8.
This function does not load or import the module; if the module wasn’t already loaded, you will get an empty
module object. Use PyImport_ImportModule() or one of its variants to import a module. Package struc-
tures implied by a dotted name for name are not created if not already present.
Added in version 3.13.
PyObject *PyImport_AddModuleObject(PyObject *name)
Return value: Borrowed reference. Part of the Stable ABI since version 3.7. Similar to
PyImport_AddModuleRef(), but return a borrowed reference and name is a Python str object.
74 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
struct _frozen {
const char *name;
const unsigned char *code;
int size;
bool is_package;
};
Changed in version 3.11: The new is_package field indicates whether the module is a package or not. This
replaces setting the size field to a negative value.
const struct _frozen *PyImport_FrozenModules
This pointer is initialized to point to an array of _frozen records, terminated by one whose members are all
NULL or zero. When a frozen module is imported, it is searched in this table. Third-party code could play
tricks with this to provide a dynamically created collection of frozen modules.
int PyImport_AppendInittab(const char *name, PyObject *(*initfunc)(void))
Part of the Stable ABI. Add a single module to the existing table of built-in modules. This is a convenience
wrapper around PyImport_ExtendInittab(), returning -1 if the table could not be extended. The new
module can be imported by the name name, and uses the function initfunc as the initialization function called
on the first attempted import. This should be called before Py_Initialize().
struct _inittab
Structure describing a single entry in the list of built-in modules. Programs which embed Python may use an
array of these structures in conjunction with PyImport_ExtendInittab() to provide additional built-in
modules. The structure consists of two members:
const char *name
The module name, as an ASCII encoded string.
PyObject *(*initfunc)(void)
Initialization function for a module built into the interpreter.
int PyImport_ExtendInittab(struct _inittab *newtab)
Add a collection of modules to the table of built-in modules. The newtab array must end with a sentinel entry
which contains NULL for the name field; failure to provide the sentinel value can result in a memory fault.
Returns 0 on success or -1 if insufficient memory could be allocated to extend the internal table. In the event
of failure, no modules are added to the internal table. This must be called before Py_Initialize().
If Python is initialized multiple times, PyImport_AppendInittab() or PyImport_ExtendInittab()
must be called before each Python initialization.
PyObject *PyImport_ImportModuleAttr(PyObject *mod_name, PyObject *attr_name)
Return value: New reference. Import the module mod_name and get its attribute attr_name.
Names must be Python str objects.
Helper function combining PyImport_Import() and PyObject_GetAttr(). For example, it can raise
ImportError if the module is not found, and AttributeError if the attribute doesn’t exist.
Added in version 3.14.
PyObject *PyImport_ImportModuleAttrString(const char *mod_name, const char *attr_name)
Return value: New reference. Similar to PyImport_ImportModuleAttr(), but names are UTF-8 encoded
strings instead of Python str objects.
Added in version 3.14.
76 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
® Note
On Python 3.12 and older, the macro PY_SSIZE_T_CLEAN must be defined before including Python.h to use
all # variants of formats (s#, y#, etc.) explained below. This is not necessary on Python 3.13 and later.
These formats allow accessing an object as a contiguous chunk of memory. You don’t have to provide raw storage
for the returned unicode or bytes area.
Unless otherwise stated, buffers are not NUL-terminated.
® Note
This format does not accept bytes-like objects. If you want to accept filesystem paths and convert them to
C character strings, it is preferable to use the O& format with PyUnicode_FSConverter() as converter.
Changed in version 3.5: Previously, TypeError was raised when embedded null code points were encountered
in the Python string.
s* (str or bytes-like object) [Py_buffer]
This format accepts Unicode objects as well as bytes-like objects. It fills a Py_buffer structure provided by
the caller. In this case the resulting C string may contain embedded NUL bytes. Unicode objects are converted
to C strings using 'utf-8' encoding.
s# (str, read-only bytes-like object) [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 or None) [const char *]
Like s, but the Python object may also be None, in which case the C pointer is set to NULL. It is the same as
s? with the C pointer was initialized to NULL.
z* (str, bytes-like object or None) [Py_buffer]
Like s*, but the Python object may also be None, in which case the buf member of the Py_buffer structure
is set to NULL. It is the same as s*? with the buf member of the Py_buffer structure was initialized to NULL.
z# (str, read-only bytes-like object or None) [const char *, Py_ssize_t]
Like s#, but the Python object may also be None, in which case the C pointer is set to NULL. It is the same as
s#? with the C pointer was initialized to NULL.
y (read-only bytes-like object) [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.
Changed in version 3.5: Previously, TypeError was raised when embedded null bytes were encountered in
the bytes buffer.
78 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
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* (read-write bytes-like object) [Py_buffer]
This format accepts any object which implements the read-write buffer interface. It fills a Py_buffer
structure provided by the caller. The buffer may contain embedded null bytes. The caller have to call
PyBuffer_Release() when it is done with the buffer.
et# (str, bytes or bytearray) [const char *encoding, char **buffer, Py_ssize_t *buffer_length]
Same as es# except that byte string objects are passed through without recoding them. Instead, the imple-
mentation assumes that the byte string object uses the encoding passed in as parameter.
Changed in version 3.12: u, u#, Z, and Z# are removed because they used a legacy Py_UNICODE* representation.
Numbers
These formats allow representing Python numbers or single characters as C numbers. Formats that require
int, float or complex can also use the corresponding special methods __index__(), __float__() or
__complex__() to convert the Python object to the required type.
For signed integer formats, OverflowError is raised if the value is out of range for the C type. For unsigned integer
formats, no range checking is done — the most significant bits are silently truncated when the receiving field is too
small to receive the value.
b (int) [unsigned char]
Convert a nonnegative Python integer to an unsigned tiny integer, stored in a C unsigned char.
B (int) [unsigned char]
Convert a Python integer to a tiny integer without overflow checking, stored in a C unsigned char.
h (int) [short int]
Convert a Python integer to a C short int.
H (int) [unsigned short int]
Convert a Python integer to a C unsigned short int, without overflow checking.
i (int) [int]
Convert a Python integer to a plain C int.
I (int) [unsigned int]
Convert a Python integer to a C unsigned int, without overflow checking.
l (int) [long int]
Convert a Python integer to a C long int.
k (int) [unsigned long]
Convert a Python integer to a C unsigned long without overflow checking.
Changed in version 3.14.0a7 (unreleased): Use __index__() if available.
L (int) [long long]
Convert a Python integer to a C long long.
K (int) [unsigned long long]
Convert a Python integer to a C unsigned long long without overflow checking.
Changed in version 3.14.0a7 (unreleased): Use __index__() if available.
n (int) [Py_ssize_t]
Convert a Python integer to a C Py_ssize_t.
c (bytes or bytearray of length 1) [char]
Convert a Python byte, represented as a bytes or bytearray object of length 1, to a C char.
Changed in version 3.3: Allow bytearray objects.
C (str of length 1) [int]
Convert a Python character, represented as a str object of length 1, to a C int.
f (float) [float]
Convert a Python floating-point number to a C float.
d (float) [double]
Convert a Python floating-point number to a C double.
D (complex) [Py_complex]
Convert a Python complex number to a C Py_complex structure.
80 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
Other objects
O (object) [PyObject *]
Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual
object that was passed. A new strong reference to the object is not created (i.e. its reference count is not
increased). The pointer stored is not NULL.
O! (object) [typeobject, PyObject *]
Store a Python object in a C object pointer. This is similar to O, but takes two C arguments: the first is the
address of a Python type object, the second is the address of the C variable (of type PyObject*) into which
the object pointer is stored. If the Python object does not have the required type, TypeError is raised.
O& (object) [converter, address]
Convert a Python object to a C variable through a converter function. This takes two arguments: the first is
a function, the second is the address of a C variable (of arbitrary type), converted to void*. The converter
function in turn is called as follows:
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. If the converter returns Py_CLEANUP_SUPPORTED, it may get called a second time if
the argument parsing eventually fails, giving the converter a chance to release any memory that it had already
allocated. In this second call, the object parameter will be NULL; address will have the same value as in the
original call.
Examples of converters: PyUnicode_FSConverter() and PyUnicode_FSDecoder().
Changed in version 3.1: Py_CLEANUP_SUPPORTED was added.
p (bool) [int]
Tests the value passed in for truth (a boolean predicate) and converts the result to its equivalent C true/false
integer value. Sets the int to 1 if the expression was true and 0 if it was false. This accepts any valid Python
value. See truth for more information about how Python tests values for truth.
Added in version 3.3.
(items) (sequence) [matching-items]
The object must be a Python sequence (except str, bytes or bytearray) whose length is the number of
format units in items. The C arguments must correspond to the individual format units in items. Format units
for sequences may be nested.
If items contains format units which store a borrowed buffer (s, s#, z, z#, y, or y#) or a borrowed reference
(S, Y, U, O, or O!), the object must be a Python tuple. The converter for the O& format unit in items must not
store a borrowed buffer or a borrowed reference.
Changed in version 3.14.0a7 (unreleased): str and bytearray objects no longer accepted as a sequence.
Deprecated since version 3.14.0a7 (unreleased): Non-tuple sequences are deprecated if items contains format
units which store a borrowed buffer or a borrowed reference.
unit? (anything or None) [matching-variable(s)]
? modifies the behavior of the preceding format unit. The C variable(s) corresponding to that parameter should
be initialized to their default value — when the argument is None, PyArg_ParseTuple() does not touch the
contents of the corresponding C variable(s). If the argument is not None, it is parsed according to the specified
format unit.
Added in version 3.14.0a7 (unreleased).
A few other characters have a meaning in a format string. These may not occur inside nested parentheses. They are:
|
Indicates that the remaining arguments in the Python argument list are optional. The C variables corresponding
to optional arguments should be initialized to their default value — when an optional argument is not specified,
PyArg_ParseTuple() does not touch the contents of the corresponding C variable(s).
$
PyArg_ParseTupleAndKeywords() only: Indicates that the remaining arguments in the Python argument
list are keyword-only. Currently, all keyword-only arguments must also be optional arguments, so | must
always be specified before $ in the format string.
Added in version 3.3.
:
The list of format units ends here; the string after the colon is used as the function name in error messages (the
“associated value” of the exception that PyArg_ParseTuple() raises).
;
The list of format units ends here; the string after the semicolon is used as the error message instead of the
default error message. : and ; mutually exclude each other.
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)!
Additional arguments passed to these functions must be addresses of variables whose type is determined by the format
string; these are used to store values from the input tuple. There are a few cases, as described in the list of format units
above, where these parameters are used as input values; they should match what is specified for the corresponding
format unit in that case.
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.
API Functions
int PyArg_ParseTuple(PyObject *args, const char *format, ...)
Part of the Stable ABI. Parse the parameters of a function that takes only positional parameters into local
variables. Returns true on success; on failure, it returns false and raises the appropriate exception.
int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)
Part of the Stable ABI. Identical to PyArg_ParseTuple(), except that it accepts a va_list rather than a
variable number of arguments.
int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *const
*keywords, ...)
Part of the Stable ABI. Parse the parameters of a function that takes both positional and keyword parameters
into local variables. The keywords argument is a NULL-terminated array of keyword parameter names speci-
fied as null-terminated ASCII or UTF-8 encoded C strings. Empty names denote positional-only parameters.
Returns true on success; on failure, it returns false and raises the appropriate exception.
® Note
The keywords parameter declaration is char *const* in C and const char *const* in C++. This
can be overridden with the PY_CXX_CONST macro.
int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *const
*keywords, va_list vargs)
Part of the Stable ABI. Identical to PyArg_ParseTupleAndKeywords(), except that it accepts a va_list
rather than a variable number of arguments.
82 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
int PyArg_ValidateKeywordArguments(PyObject*)
Part of the Stable ABI. Ensure that the keys in the keywords argument dictionary are strings. This is only
needed if PyArg_ParseTupleAndKeywords() is not used, since the latter already does this check.
Added in version 3.2.
int PyArg_Parse(PyObject *args, const char *format, ...)
Part of the Stable ABI. Parse the parameter of a function that takes a single positional parameter into a local
variable. Returns true on success; on failure, it returns false and raises the appropriate exception.
Example:
int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
Part of the Stable ABI. A simpler form of parameter retrieval which does not use a format string to specify the
types of the arguments. Functions which use this method to retrieve their parameters should be declared as
METH_VARARGS in function or method tables. The tuple containing the actual parameters should be passed as
args; it must actually be a tuple. The length of the tuple must be at least min and no more than max; min and
max may be equal. Additional arguments must be passed to the function, each of which should be a pointer to
a PyObject* variable; these will be filled in with the values from args; they will contain borrowed references.
The variables which correspond to optional parameters not given by args will not be filled in; these should be
initialized by the caller. This function returns true on success and false if args is not a tuple or contains the
wrong number of elements; an exception will be set if there was a failure.
This is an example of the use of this function, taken from the sources for the _weakref helper module for
weak references:
static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
PyObject *object;
PyObject *callback = NULL;
PyObject *result = NULL;
PY_CXX_CONST
The value to be inserted, if any, before char *const* in the keywords parameter declaration of
PyArg_ParseTupleAndKeywords() and PyArg_VaParseTupleAndKeywords(). Default empty for C
and const for C++ (const char *const*). To override, define it to the desired value before including
Python.h.
Py_BuildValue() does not always build a tuple. It builds a tuple only if its format string contains two or
more format units. If the format string is empty, it returns None; if it contains exactly one format unit, it returns
whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the
format string.
When memory buffers are passed as parameters to supply data to build objects, as for the s and s# formats,
the required data is copied. Buffers provided by the caller are never referenced by the objects created by
Py_BuildValue(). In other words, if your code invokes malloc() and passes the allocated memory to
Py_BuildValue(), your code is responsible for calling free() for that memory once Py_BuildValue()
returns.
In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python
object type that the format unit will return; and the entry in [square] brackets is the type of the C value(s) to
be passed.
The characters space, tab, colon and comma are ignored in format strings (but not within format units such as
s#). This can be used to make long format strings a tad more readable.
s (str or None) [const char *]
Convert a null-terminated C string to a Python str object using 'utf-8' encoding. If the C string
pointer is NULL, None is used.
s# (str or None) [const char *, Py_ssize_t]
Convert a C string and its length to a Python str object using 'utf-8' encoding. If the C string pointer
is NULL, the length is ignored and None is returned.
y (bytes) [const char *]
This converts a C string to a Python bytes object. If the C string pointer is NULL, None is returned.
y# (bytes) [const char *, Py_ssize_t]
This converts a C string and its lengths to a Python object. If the C string pointer is NULL, None is
returned.
z (str or None) [const char *]
Same as s.
z# (str or None) [const char *, Py_ssize_t]
Same as s#.
u (str) [const wchar_t *]
Convert a null-terminated wchar_t buffer of Unicode (UTF-16 or UCS-4) data to a Python Unicode
object. If the Unicode buffer pointer is NULL, None is returned.
u# (str) [const wchar_t *, Py_ssize_t]
Convert a Unicode (UTF-16 or UCS-4) data buffer and its length to a Python Unicode object. If the
Unicode buffer pointer is NULL, the length is ignored and None is returned.
U (str or None) [const char *]
Same as s.
U# (str or None) [const char *, Py_ssize_t]
Same as s#.
i (int) [int]
Convert a plain C int to a Python integer object.
84 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
b (int) [char]
Convert a plain C char to a Python integer object.
h (int) [short int]
Convert a plain C short int to a Python integer object.
l (int) [long int]
Convert a C long int to a Python integer object.
B (int) [unsigned char]
Convert a C unsigned char to a Python integer object.
H (int) [unsigned short int]
Convert a C unsigned short int to a Python integer object.
I (int) [unsigned int]
Convert a C unsigned int to a Python integer object.
k (int) [unsigned long]
Convert a C unsigned long to a Python integer object.
L (int) [long long]
Convert a C long long to a Python integer object.
If there is an error in the format string, the SystemError exception is set and NULL returned.
PyObject *Py_VaBuildValue(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Identical to Py_BuildValue(), except that it accepts a
va_list rather than a variable number of arguments.
86 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
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.
If endptr is NULL, convert the whole string. Raise ValueError and return -1.0 if the string is not a valid
representation of a floating-point number.
If endptr is not NULL, convert as much of the string as possible and set *endptr to point to the first unconverted
character. If no initial segment of the string is the valid representation of a floating-point number, set *endptr
to point to the beginning of the string, raise ValueError, and return -1.0.
If s represents a value that is too large to store in a float (for example, "1e500" is such a string on many
platforms) then if overflow_exception is NULL return Py_INFINITY (with an appropriate sign) and don’t
set any exception. Otherwise, overflow_exception must point to a Python exception object; raise that
exception and return -1.0. In both cases, set *endptr to point to the first character after the converted value.
If any other error occurs during the conversion (for example an out-of-memory error), set the appropriate
Python exception and return -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 must be one of 'e', 'E', 'f', 'F', 'g', 'G' or 'r'. For 'r', the supplied precision must be
0 and is ignored. The 'r' format code specifies the standard repr() format.
flags can be zero or more of the values Py_DTSF_SIGN, Py_DTSF_ADD_DOT_0, or Py_DTSF_ALT, or-ed
together:
• Py_DTSF_SIGN means to always precede the returned string with a sign character, even if val is non-
negative.
• Py_DTSF_ADD_DOT_0 means to ensure that the returned string will not look like an integer.
• Py_DTSF_ALT means to apply “alternate” formatting rules. See the documentation for the
PyOS_snprintf() '#' specifier for details.
If ptype is non-NULL, then the value it points to will be set to one of Py_DTST_FINITE, Py_DTST_INFINITE,
or Py_DTST_NAN, signifying that val is a finite number, an infinite number, or not a number, respectively.
The return value is a pointer to buffer with the converted string or NULL if the conversion failed. The caller is
responsible for freeing the returned string by calling 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.
µ See also
88 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
6.9 Reflection
PyObject *PyEval_GetBuiltins(void)
Return value: Borrowed reference. Part of the Stable ABI. Deprecated since version 3.13: Use
PyEval_GetFrameBuiltins() instead.
Return a dictionary of the builtins in the current execution frame, or the interpreter of the thread state if no
frame is currently executing.
PyObject *PyEval_GetLocals(void)
Return value: Borrowed reference. Part of the Stable ABI. Deprecated since version 3.13: Use either
PyEval_GetFrameLocals() to obtain the same behaviour as calling locals() in Python code, or else
call PyFrame_GetLocals() on the result of PyEval_GetFrame() to access the f_locals attribute of
the currently executing frame.
Return a mapping providing access to the local variables in the current execution frame, or NULL if no frame
is currently executing.
Refer to locals() for details of the mapping returned at different scopes.
As this function returns a borrowed reference, the dictionary returned for optimized scopes is cached on the
frame object and will remain alive as long as the frame object does. Unlike PyEval_GetFrameLocals()
and locals(), subsequent calls to this function in the same frame will update the contents of the cached
dictionary to reflect changes in the state of the local variables rather than returning a new snapshot.
Changed in version 3.13: As part of PEP 667, PyFrame_GetLocals(), locals(), and FrameType.
f_locals no longer make use of the shared cache dictionary. Refer to the What’s New entry for additional
details.
PyObject *PyEval_GetGlobals(void)
Return value: Borrowed reference. Part of the Stable ABI. Deprecated since version 3.13: Use
PyEval_GetFrameGlobals() instead.
Return a dictionary of the global variables in the current execution frame, or NULL if no frame is currently
executing.
6.9. Reflection 89
The Python/C API, Release 3.14.0a7
PyFrameObject *PyEval_GetFrame(void)
Return value: Borrowed reference. Part of the Stable ABI. Return the attached thread state’s frame, which is
NULL if no frame is currently executing.
90 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
6.11.1 Types
type PyTime_t
A timestamp or duration in nanoseconds, represented as a signed 64-bit integer.
The reference point for timestamps depends on the clock used. For example, PyTime_Time() returns times-
tamps relative to the UNIX epoch.
The supported range is around [-292.3 years; +292.3 years]. Using the Unix epoch (January 1st, 1970) as
reference, the supported date range is around [1677-09-21; 2262-04-11]. The exact limits are exposed as
constants:
PyTime_t PyTime_MIN
Minimum value of PyTime_t.
PyTime_t PyTime_MAX
Maximum value of PyTime_t.
92 Chapter 6. Utilities
The Python/C API, Release 3.14.0a7
Open the /tmp/perf-$pid.map file, unless it’s already opened, and create a lock to ensure thread-safe writes
to the file (provided the writes are done through PyUnstable_WritePerfMapEntry()). Normally, there’s
no need to call this explicitly; just use PyUnstable_WritePerfMapEntry() and it will initialize the state
on first call.
Returns 0 on success, -1 on failure to create/open the perf map file, or -2 on failure to create a lock. Check
errno for more information about the cause of a failure.
Write one single entry to the /tmp/perf-$pid.map file. This function is thread safe. Here is what an
example entry looks like:
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.
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.
94 Chapter 6. Utilities
CHAPTER
SEVEN
The functions in this chapter interact with Python objects regardless of their type, or with wide classes of object types
(e.g. all numerical types, or all sequence types). When used on object types for which they do not apply, they will
raise a Python exception.
It is not possible to use these functions on objects that are not properly initialized, such as a list object that has been
created by PyList_New(), but whose items have not been set to some non-NULL value yet.
95
The Python/C API, Release 3.14.0a7
1 False
Py_CONSTANT_FALSE
2 True
Py_CONSTANT_TRUE
3 Ellipsis
Py_CONSTANT_ELLIPSIS
4 NotImplemented
Py_CONSTANT_NOT_IMPLEMENTED
5 0
Py_CONSTANT_ZERO
6 1
Py_CONSTANT_ONE
7 ''
Py_CONSTANT_EMPTY_STR
8 b''
Py_CONSTANT_EMPTY_BYTES
9 ()
Py_CONSTANT_EMPTY_TUPLE
Numeric values are only given for projects which cannot use the constant identifiers.
Added in version 3.13.
CPython implementation detail: In CPython, all of these constants are immortal.
PyObject *Py_GetConstantBorrowed(unsigned int constant_id)
Part of the Stable ABI since version 3.13. Similar to Py_GetConstant(), but return a borrowed reference.
This function is primarily intended for backwards compatibility: using Py_GetConstant() is recommended
for new code.
The reference is borrowed from the interpreter, and is valid until the interpreter finalization.
Added in version 3.13.
PyObject *Py_NotImplemented
The NotImplemented singleton, used to signal that an operation is not implemented for the given type com-
bination.
Py_RETURN_NOTIMPLEMENTED
Properly handle returning Py_NotImplemented from within a C function (that is, create a new strong refer-
ence 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().
® Note
Exceptions that occur when this calls __getattr__() and __getattribute__() methods aren’t
propagated, but instead given to sys.unraisablehook(). For proper error handling, use
PyObject_HasAttrWithError(), PyObject_GetOptionalAttr() or PyObject_GetAttr() in-
stead.
® Note
Exceptions that occur when this calls __getattr__() and __getattribute__() methods
or while creating the temporary str object are silently ignored. For proper error han-
dling, use PyObject_HasAttrStringWithError(), PyObject_GetOptionalAttrString() or
PyObject_GetAttrString() instead.
If the missing attribute should not be treated as a failure, you can use PyObject_GetOptionalAttr()
instead.
PyObject *PyObject_GetAttrString(PyObject *o, const char *attr_name)
Return value: New reference. Part of the Stable ABI. This is the same as PyObject_GetAttr(), but
attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.
If the missing attribute should not be treated as a failure, you can use
PyObject_GetOptionalAttrString() instead.
If the attribute is found, return 1 and set *result to a new strong reference to the attribute. If the attribute
is not found, return 0 and set *result to NULL; the AttributeError is silenced. If an error other than
AttributeError is raised, return -1 and set *result to NULL.
If v is NULL, the attribute is deleted. This behaviour is deprecated in favour of using PyObject_DelAttr(),
but there are currently no plans to remove it.
int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)
Part of the Stable ABI. This is the same as PyObject_SetAttr(), but attr_name is specified as a const
char* UTF-8 encoded bytes string, rather than a PyObject*.
If v is NULL, the attribute is deleted, but this feature is deprecated in favour of using
PyObject_DelAttrString().
The number of different attribute names passed to this function should be kept small, usually by us-
ing a statically allocated string as attr_name. For attribute names that aren’t known at compile time,
prefer calling PyUnicode_FromString() and PyObject_SetAttr() directly. For more details, see
PyUnicode_InternFromString(), which may be used internally to create a key object.
This function may also be called to get the __dict__ of the object o. Pass NULL for context when call-
ing it. Since this function may need to allocate memory for the dictionary, it may be more efficient to call
PyObject_GetAttr() when accessing an attribute on the object.
® Note
If o1 and o2 are the same object, PyObject_RichCompareBool() will always return 1 for Py_EQ and 0 for
Py_NE.
format_spec may be NULL. In this case the call is equivalent to format(obj). Returns the formatted string
on success, NULL on failure.
PyObject *PyObject_Repr(PyObject *o)
Return value: New reference. Part of the Stable ABI. Compute a string representation of object o. Returns the
string representation on success, NULL on failure. This is the equivalent of the Python expression repr(o).
Called by the repr() built-in function.
Changed in version 3.4: This function now includes a debug assertion to help ensure that it does not silently
discard an active exception.
PyObject *PyObject_ASCII(PyObject *o)
Return value: New reference. Part of the Stable ABI. As PyObject_Repr(), compute a string representation
of object o, but escape the non-ASCII characters in the string returned by PyObject_Repr() with \x, \u or
\U escapes. This generates a string similar to that returned by PyObject_Repr() in Python 2. Called by the
ascii() built-in function.
Changed in version 3.4: This function now includes a debug assertion to help ensure that it does not silently
discard an active exception.
PyObject *PyObject_Bytes(PyObject *o)
Return value: New reference. Part of the Stable ABI. Compute a bytes representation of object o. NULL is
returned on failure and a bytes object on success. This is equivalent to the Python expression bytes(o), when
o is not an integer. Unlike bytes(o), a TypeError is raised when o is an integer instead of a zero-initialized
bytes object.
int PyObject_IsSubclass(PyObject *derived, PyObject *cls)
Part of the Stable ABI. Return 1 if the class derived is identical to or derived from the class cls, otherwise
return 0. In case of an error, return -1.
If cls is a tuple, the check will be done against every entry in cls. The result will be 1 when at least one of the
checks returns 1, otherwise it will be 0.
If cls has a __subclasscheck__() method, it will be called to determine the subclass status as described
in PEP 3119. Otherwise, derived is a subclass of cls if it is a direct or indirect subclass, i.e. contained in
cls.__mro__.
Normally only class objects, i.e. instances of type or a derived class, are considered classes. However, objects
can override this by having a __bases__ attribute (which must be a tuple of base classes).
int PyObject_IsInstance(PyObject *inst, PyObject *cls)
Part of the Stable ABI. Return 1 if inst is an instance of the class cls or a subclass of cls, or 0 if not. On error,
returns -1 and sets an exception.
If cls is a tuple, the check will be done against every entry in cls. The result will be 1 when at least one of the
checks returns 1, otherwise it will be 0.
If cls has a __instancecheck__() method, it will be called to determine the subclass status as described in
PEP 3119. Otherwise, inst is an instance of cls if its class is a subclass of cls.
An instance inst can override what is considered its class by having a __class__ attribute.
An object cls can override if it is considered a class, and what its base classes are, by having a __bases__
attribute (which must be a tuple of base classes).
Py_hash_t PyObject_Hash(PyObject *o)
Part of the Stable ABI. Compute and return the hash value of an object o. On failure, return -1. This is the
equivalent of the Python expression hash(o).
Changed in version 3.2: The return type is now Py_hash_t. This is a signed integer the same size as
Py_ssize_t.
Py_hash_t PyObject_HashNotImplemented(PyObject *o)
Part of the Stable ABI. Set a TypeError indicating that type(o) is not hashable and return -1. This function
receives special treatment when stored in a tp_hash slot, allowing a type to explicitly indicate to the interpreter
that it is not hashable.
int PyObject_IsTrue(PyObject *o)
Part of the Stable ABI. Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent
to the Python expression not not o. On failure, return -1.
int PyObject_Not(PyObject *o)
Part of the Stable ABI. Returns 0 if the object o is considered to be true, and 1 otherwise. This is equivalent
to the Python expression not o. On failure, return -1.
PyObject *PyObject_Type(PyObject *o)
Return value: New reference. Part of the Stable ABI. When o is non-NULL, returns a type object correspond-
ing to the object type of object o. On failure, raises SystemError and returns NULL. This is equivalent to
the Python expression type(o). This function creates a new strong reference to the return value. There’s
really no reason to use this function instead of the Py_TYPE() function, which returns a pointer of type
PyTypeObject*, except when a new strong reference is needed.
Enable deferred reference counting on obj, if supported by the runtime. In the free-threaded build, this allows
the interpreter to avoid reference count adjustments to obj, which may improve multi-threaded performance.
The tradeoff is that obj will only be deallocated by the tracing garbage collector.
This function returns 1 if deferred reference counting is enabled on obj (including when it was enabled before
the call), and 0 if deferred reference counting is not supported or if the hint was ignored by the runtime. This
function is thread-safe, and cannot fail.
This function does nothing on builds with the GIL enabled, which do not support deferred reference counting.
This also does nothing if obj is not an object tracked by the garbage collector (see gc.is_tracked() and
PyObject_GC_IsTracked()).
This function is intended to be used soon after obj is created, by the code that creates it.
Added in version 3.14.
This function returns non-zero if obj is immortal, and zero otherwise. This function cannot fail.
® Note
Objects that are immortal in one CPython version are not guaranteed to be immortal in another.
Increments the reference count of obj if it is not zero. Returns 1 if the object’s reference count was successfully
incremented. Otherwise, this function returns 0.
PyUnstable_EnableTryIncRef() must have been called earlier on obj or this function may spuriously
return 0 in the free threading build.
This function is logically equivalent to the following C code, except that it behaves atomically in the free
threading build:
if (Py_REFCNT(op) > 0) {
Py_INCREF(op);
return 1;
}
return 0;
This is intended as a building block for managing weak references without the overhead of a Python weak
reference object.
Typically, correct use of this function requires support from obj’s deallocator (tp_dealloc). For example,
the following sketch could be adapted to implement a “weakmap” that works like a WeakValueDictionary
for a specific type:
PyMutex mutex;
PyObject *
add_entry(weakmap_key_type *key, PyObject *value)
{
PyUnstable_EnableTryIncRef(value);
weakmap_type weakmap = ...;
PyMutex_Lock(&mutex);
weakmap_add_entry(weakmap, key, value);
PyMutex_Unlock(&mutex);
Py_RETURN_NONE;
}
PyObject *
(continues on next page)
...
PyMutex_Unlock(&mutex);
}
Enables subsequent uses of PyUnstable_TryIncRef() on obj. The caller must hold a strong reference to
obj when calling this.
Added in version 3.14.
A call is made using a tuple for the positional arguments and a dict for the keyword arguments, similarly to
callable(*args, **kwargs) in Python code. args must be non-NULL (use an empty tuple if there are no
arguments) but kwargs may be NULL if there are no keyword arguments.
This convention is not only used by tp_call: tp_new and tp_init also pass arguments this way.
Á Warning
A class supporting vectorcall must also implement tp_call with the same semantics.
Changed in version 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.
A class should not implement vectorcall if that would be slower than tp_call. For example, if the callee needs to
convert the arguments to an args tuple and kwargs dict anyway, then there is no point in implementing vectorcall.
Classes can implement the vectorcall protocol by enabling the Py_TPFLAGS_HAVE_VECTORCALL flag and setting
tp_vectorcall_offset to the offset inside the object structure where a vectorcallfunc appears. This is a pointer
to a function with the following signature:
typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject
*kwnames)
Part of the Stable ABI since version 3.12.
• callable is the object being called.
• args is a C array consisting of the positional arguments followed by the
values of the keyword arguments. This can be NULL if there are no arguments.
• nargsf is the number of positional arguments plus possibly the
PY_VECTORCALL_ARGUMENTS_OFFSET flag. To get the actual number of positional arguments from
nargsf, use PyVectorcall_NARGS().
• kwnames is a tuple containing the names of the keyword arguments;
in other words, the keys of the kwargs dict. These names must be strings (instances of str or a subclass)
and they must be unique. If there are no keyword arguments, then kwnames can instead be NULL.
PY_VECTORCALL_ARGUMENTS_OFFSET
Part of the Stable ABI since version 3.12. If this flag is set in a vectorcall nargsf argument, the callee is allowed
to temporarily change args[-1]. In other words, args points to argument 1 (not 0) in the allocated vector.
The callee must restore the value of args[-1] before returning.
For PyObject_VectorcallMethod(), this flag means instead that args[0] may be changed.
Whenever they can do so cheaply (without additional allocation), callers are encouraged to use
PY_VECTORCALL_ARGUMENTS_OFFSET . Doing so will allow callables such as bound methods to make their
onward calls (which include a prepended self argument) very efficiently.
Added in version 3.8.
To call an object that implements vectorcall, use a call API function as with any other callable.
PyObject_Vectorcall() will usually be most efficient.
Recursion Control
When using tp_call, callees do not need to worry about recursion: CPython uses Py_EnterRecursiveCall() and
Py_LeaveRecursiveCall() for calls made using tp_call.
For efficiency, this is not the case for calls done using vectorcall: the callee should use Py_EnterRecursiveCall and
Py_LeaveRecursiveCall if needed.
However, the function PyVectorcall_NARGS should be used to allow for future extensions.
Added in version 3.8.
vectorcallfunc PyVectorcall_Function(PyObject *op)
If op does not support the vectorcall protocol (either because the type does not or because the specific instance
does not), return NULL. Otherwise, return the vectorcall function pointer stored in op. This function never
raises an exception.
This is mostly useful to check whether or not op supports vectorcall, which can be done by checking
PyVectorcall_Function(op) != NULL.
Added in version 3.9.
PyObject *PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict)
Part of the Stable ABI since version 3.12. Call callable’s vectorcallfunc with positional and keyword
arguments given in a tuple and dict, respectively.
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.
If the object has the Py_TPFLAGS_METHOD_DESCRIPTOR feature, this will call the unbound method object
with the full args vector as arguments.
Return the result of the call on success, or raise an exception and return NULL on failure.
Added in version 3.9.
a floating-point value when passed two integers. The operation is done in-place when o1 supports it. This is
the equivalent of the Python statement o1 /= o2.
PyObject *PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2)
Return value: New reference. Part of the Stable ABI. Returns the remainder of dividing o1 by o2, or NULL on
failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1
%= o2.
Changed in version 3.10: The result always has exact type int. Previously, the result could have been an
instance of a subclass of int.
PyObject *PyNumber_ToBase(PyObject *n, int base)
Return value: New reference. Part of the Stable ABI. Returns the integer n converted to base base as a string.
The base argument must be one of 2, 8, 10, or 16. For base 2, 8, or 16, the returned string is prefixed with a base
marker of '0b', '0o', or '0x', respectively. If n is not a Python int, it is converted with PyNumber_Index()
first.
Note, if a list gets resized, the reallocation may relocate the items array. So, only use the underlying array
pointer in contexts where the sequence cannot change.
PyObject *PySequence_ITEM(PyObject *o, Py_ssize_t i)
Return value: New reference. Return the ith element of o or NULL on failure. Faster form of
PySequence_GetItem() but without checking that PySequence_Check() on o is true and without ad-
justment for negative indices.
® Note
Exceptions which occur when this calls __getitem__() method are silently ignored. For
proper error handling, use PyMapping_HasKeyWithError(), PyMapping_GetOptionalItem() or
PyObject_GetItem() instead.
® Note
Exceptions that occur when this calls __getitem__() method or while creating the temporary str ob-
ject are silently ignored. For proper error handling, use PyMapping_HasKeyStringWithError(),
PyMapping_GetOptionalItemString() or PyMapping_GetItemString() instead.
In both cases, PyBuffer_Release() must be called when the buffer isn’t needed anymore. Failure to do so could
lead to various issues such as resource leaks.
Added in version 3.12: The buffer protocol is now accessible in Python, see python-buffer-protocol and memoryview.
type Py_buffer
Part of the Stable ABI (including all members) since version 3.11.
void *buf
A pointer to the start of the logical structure described by the buffer fields. This can be any location
within the underlying physical memory block of the exporter. For example, with negative strides the
value may point to the end of the memory block.
For contiguous arrays, the value points to the beginning of the memory block.
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.
As a special case, for temporary buffers that are wrapped by PyMemoryView_FromBuffer() or
PyBuffer_FillInfo() this field is NULL. In general, exporting objects MUST NOT use this scheme.
Py_ssize_t len
product(shape) * itemsize. For contiguous arrays, this is the length of the underlying memory
block. For non-contiguous arrays, it is the length that the logical structure would have if it were copied
to a contiguous representation.
Accessing ((char *)buf)[0] up to ((char *)buf)[len-1] is only valid if the buffer has been
obtained by a request that guarantees contiguity. In most cases such a request will be PyBUF_SIMPLE
or PyBUF_WRITABLE.
int readonly
An indicator of whether the buffer is read-only. This field is controlled by the PyBUF_WRITABLE flag.
Py_ssize_t itemsize
Item size in bytes of a single element. Same as the value of struct.calcsize() called on non-NULL
format values.
Important exception: If a consumer requests a buffer without the PyBUF_FORMAT flag, format will be
set to NULL, but itemsize still has the value for the original format.
If shape is present, the equality product(shape) * itemsize == len still holds and the consumer
can use itemsize to navigate the buffer.
If shape is NULL as a result of a PyBUF_SIMPLE or a PyBUF_WRITABLE request, the consumer must
disregard itemsize and assume itemsize == 1.
char *format
A NULL terminated string in struct module style syntax describing the contents of a single item. If
this is NULL, "B" (unsigned bytes) is assumed.
This field is controlled by the PyBUF_FORMAT flag.
int ndim
The number of dimensions the memory represents as an n-dimensional array. If it is 0, buf points to a
single item representing a scalar. In this case, shape, strides and suboffsets MUST be NULL. The
maximum number of dimensions is given by PyBUF_MAX_NDIM .
Py_ssize_t *shape
An array of Py_ssize_t of length ndim indicating the shape of the memory as an n-dimensional array.
Note that shape[0] * ... * shape[ndim-1] * itemsize MUST be equal to len.
Shape values are restricted to shape[n] >= 0. The case shape[n] == 0 requires special attention.
See complex arrays for further information.
The shape array is read-only for the consumer.
Py_ssize_t *strides
An array of Py_ssize_t of length ndim giving the number of bytes to skip to get to a new element in
each dimension.
Stride values can be any integer. For regular arrays, strides are usually positive, but a consumer MUST
be able to handle the case strides[n] <= 0. See complex arrays for further information.
The strides array is read-only for the consumer.
Py_ssize_t *suboffsets
An array of Py_ssize_t of length ndim. If suboffsets[n] >= 0, the values stored along the nth
dimension are pointers and the suboffset value dictates how many bytes to add to each pointer after de-
referencing. A suboffset value that is negative indicates that no de-referencing should occur (striding in
a contiguous memory block).
If all suboffsets are negative (i.e. no de-referencing is needed), then this field must be NULL (the default
value).
This type of array representation is used by the Python Imaging Library (PIL). See complex arrays for
further information how to access elements of such an array.
The suboffsets array is read-only for the consumer.
void *internal
This is for use internally by the exporting object. For example, this might be re-cast as an integer by the
exporter and used to store flags about whether or not the shape, strides, and suboffsets arrays must be
freed when the buffer is released. The consumer MUST NOT alter this value.
Constants:
PyBUF_MAX_NDIM
The maximum number of dimensions the memory represents. Exporters MUST respect this limit, consumers
of multi-dimensional buffers SHOULD be able to handle up to PyBUF_MAX_NDIM dimensions. Currently set
to 64.
request-independent fields
The following fields are not influenced by flags and must always be filled in with the correct values: obj, buf , len,
itemsize, ndim.
readonly, format
PyBUF_WRITABLE
Controls the readonly field. If set, the exporter MUST provide a writable buffer or else report
failure. Otherwise, the exporter MAY provide either a read-only or writable buffer, but the choice
MUST be consistent for all consumers. For example, PyBUF_SIMPLE | PyBUF_WRITABLE can
be used to request a simple writable buffer.
PyBUF_FORMAT
Controls the format field. If set, this field MUST be filled in correctly. Otherwise, this field
MUST be NULL.
PyBUF_WRITABLE can be |’d to any of the flags in the next section. Since PyBUF_SIMPLE is defined as 0,
PyBUF_WRITABLE can be used as a stand-alone flag to request a simple writable buffer.
PyBUF_FORMAT must be |’d to any of the flags except PyBUF_SIMPLE, because the latter already implies format B
(unsigned bytes). PyBUF_FORMAT cannot be used on its own.
contiguity requests
C or Fortran contiguity can be explicitly requested, with and without stride information. Without stride information,
the buffer must be C-contiguous.
compound requests
All possible requests are fully defined by some combination of the flags in the previous section. For convenience, the
buffer protocol provides frequently used combinations as single flags.
In the following table U stands for undefined contiguity. The consumer would have to call
PyBuffer_IsContiguous() to determine contiguity.
As noted above, buf can point to any location within the actual memory block. An exporter can check the validity
of a buffer with this function:
if ndim <= 0:
return ndim == 0 and not shape and not strides
if 0 in shape:
return True
EIGHT
The functions in this chapter are specific to certain Python object types. Passing them an object of the wrong type is
not a good idea; if you receive an object from a Python program and you are not sure that it has the right type, you
must perform a type check first; for example, to check that an object is a dictionary, use PyDict_Check(). The
chapter is structured like the “family tree” of Python object types.
Á Warning
While the functions described in this chapter carefully check the type of the objects which are passed in, many
of them do not check for NULL being passed instead of a valid object. Allowing NULL to be passed in can cause
memory access violations and immediate termination of the interpreter.
123
The Python/C API, Release 3.14.0a7
® Note
If some of the base classes implements the GC protocol and the provided type does not include the
Py_TPFLAGS_HAVE_GC in its flags, then the GC protocol will be automatically implemented from its
parents. On the contrary, if the type being created does include Py_TPFLAGS_HAVE_GC in its flags then
it must implement the GC protocol itself by at least implementing the tp_traverse handle.
This function is usually used to get the module in which a method is defined. Note that in such a method,
PyType_GetModule(Py_TYPE(self)) may not return the intended result. Py_TYPE(self) may be a
subclass of the intended class, and subclasses are not necessarily defined in the same module as their superclass.
See PyCMethod to get the class that defines the method. See PyType_GetModuleByDef() for cases when
PyCMethod cannot be used.
The metaclass metaclass is used to construct the resulting type object. When metaclass is NULL, the metaclass
is derived from bases (or Py_tp_base[s] slots if bases is NULL, see below).
Metaclasses that override tp_new are not supported, except if tp_new is NULL.
The bases argument can be used to specify base classes; it can either be only one class or a tuple of classes. If
bases is NULL, the Py_tp_bases slot is used instead. If that also is NULL, the Py_tp_base slot is used instead. If
that also is NULL, the new type derives from object.
The module argument can be used to record the module in which the new class is defined. It must be a
module object or NULL. If not NULL, the module is associated with the new type and can later be retrieved
with PyType_GetModule(). The associated module is not inherited by subclasses; it must be specified for
each class individually.
This function calls PyType_Ready() on the new type.
Note that this function does not fully match the behavior of calling type() or using the class statement.
With user-provided base types or metaclasses, prefer calling type (or the metaclass) over PyType_From*
functions. Specifically:
• __new__() is not called on the new class (and it must be set to type.__new__).
• __init__() is not called on the new class.
• __init_subclass__() is not called on any bases.
• __set_name__() is not called on new descriptors.
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.
Changed in version 3.10: The function now accepts a single class as the bases argument and NULL as the
tp_doc slot.
Changed in version 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.
Changed in version 3.14: Creating classes whose metaclass overrides tp_new is 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).
Changed in version 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.
Changed in version 3.14: Creating classes whose metaclass overrides tp_new is no longer allowed.
int PyType_Freeze(PyTypeObject *type)
Part of the Stable ABI since version 3.14. Make a type immutable: set the Py_TPFLAGS_IMMUTABLETYPE
flag.
All base classes of type must be immutable.
On success, return 0. On error, set an exception and return -1.
The type must not be used before it’s made immutable. For example, type instances must not be created before
the type is made immutable.
Added in version 3.14.
type PyType_Spec
Part of the Stable ABI (including all members). Structure defining a type’s behavior.
const char *name
Name of the type, used to set PyTypeObject.tp_name.
int basicsize
If positive, specifies the size of the instance in bytes. It is used to set PyTypeObject.tp_basicsize.
If zero, specifies that tp_basicsize should be inherited.
If negative, the absolute value specifies how much space instances of the class need in addition to the
superclass. Use PyObject_GetTypeData() to get a pointer to subclass-specific memory reserved
this way. For negative basicsize, Python will insert padding when needed to meet tp_basicsize’s
alignment requirements.
Changed in version 3.12: Previously, this field could not be negative.
int itemsize
Size of one element of a variable-size type, in bytes. Used to set PyTypeObject.tp_itemsize. See
tp_itemsize documentation for caveats.
If zero, tp_itemsize is inherited. Extending arbitrary variable-sized classes is dangerous, since some
types use a fixed offset for variable-sized memory, which can then overlap fixed-sized memory used by a
subclass. To help prevent mistakes, inheriting itemsize is only possible in the following situations:
• The base is not variable-sized (its tp_itemsize).
• The requested PyType_Spec.basicsize is positive, suggesting that the memory layout of the
base class is known.
• The requested PyType_Spec.basicsize is zero, suggesting that the subclass does not access the
instance’s memory directly.
• With the Py_TPFLAGS_ITEMS_AT_END flag.
unsigned int flags
Type flags, used to set PyTypeObject.tp_flags.
If the Py_TPFLAGS_HEAPTYPE flag is not set, PyType_FromSpecWithBases() sets it automatically.
PyType_Slot *slots
Array of PyType_Slot structures. Terminated by the special slot value {0, NULL}.
Each slot ID should be specified at most once.
type PyType_Slot
Part of the Stable ABI (including all members). Structure defining optional functionality of a type, containing
a slot ID and a value pointer.
int slot
A slot ID.
Slot IDs are named like the field names of the structures PyTypeObject, PyNumberMethods,
PySequenceMethods, PyMappingMethods and PyAsyncMethods with an added Py_ prefix. For
example, use:
• Py_tp_dealloc to set PyTypeObject.tp_dealloc
• Py_nb_add to set PyNumberMethods.nb_add
• Py_sq_length to set PySequenceMethods.sq_length
An additional slot is supported that does not correspond to a PyTypeObject struct field:
• Py_tp_token
The following “offset” fields cannot be set using PyType_Slot:
• tp_weaklistoffset (use Py_TPFLAGS_MANAGED_WEAKREF instead if possible)
• tp_dictoffset (use Py_TPFLAGS_MANAGED_DICT instead if possible)
• tp_vectorcall_offset (use "__vectorcalloffset__" in PyMemberDef)
If it is not possible to switch to a MANAGED flag (for example, for vectorcall or to support Python older
than 3.12), specify the offset in Py_tp_members. See PyMemberDef documentation for details.
The following internal fields cannot be set at all when creating a heap type:
• tp_dict, tp_mro, tp_cache, tp_subclasses, and tp_weaklist.
Setting Py_tp_bases or Py_tp_base may be problematic on some platforms. To avoid issues, use the
bases argument of PyType_FromSpecWithBases() instead.
Changed in version 3.9: Slots in PyBufferProcs may be set in the unlimited API.
Changed in version 3.11: bf_getbuffer and bf_releasebuffer are now available under the limited
API.
Changed in version 3.14: The field tp_vectorcall can now set using Py_tp_vectorcall. See the
field’s documentation for details.
void *pfunc
The desired value of the slot. In most cases, this is a pointer to a function.
pfunc values may not be NULL, except for the following slots:
• Py_tp_doc
• Py_tp_token (for clarity, prefer Py_TP_USE_SPEC rather than NULL)
Py_tp_token
A slot that records a static memory layout ID for a class.
If the PyType_Spec of the class is statically allocated, the token can be set to the spec using the special value
Py_TP_USE_SPEC :
It can also be set to an arbitrary pointer, but you must ensure that:
• The pointer outlives the class, so it’s not reused for something else while the class exists.
• It “belongs” to the extension module where the class lives, so it will not clash with other extensions.
Use PyType_GetBaseByToken() to check if a class’s superclass has a given token – that is, check whether
the memory layout is compatible.
To get the token for a given class (without considering superclasses), use PyType_GetSlot() with
Py_tp_token.
type PyLongObject
Part of the Limited API (as an opaque struct). This subtype of PyObject represents a Python integer object.
PyTypeObject PyLong_Type
Part of the Stable ABI. This instance of PyTypeObject represents the Python integer type. This is the same
object as int in the Python layer.
int PyLong_Check(PyObject *p)
Return true if its argument is a PyLongObject or a subtype of PyLongObject. This function always suc-
ceeds.
int PyLong_CheckExact(PyObject *p)
Return true if its argument is a PyLongObject, but not a subtype of PyLongObject. This function always
succeeds.
PyObject *PyLong_FromLong(long v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from v, or NULL on
failure.
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_FromSsize_t(Py_ssize_t v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C
Py_ssize_t, or NULL on failure.
PyObject *PyLong_FromSize_t(size_t v)
Return value: New reference. Part of the Stable ABI. Return a new PyLongObject object from a C size_t,
or NULL on failure.
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.
µ See also
Raise OverflowError if the value of obj is out of range for a long long.
Returns -1 on error. Use PyErr_Occurred() to disambiguate.
Changed in version 3.8: Use __index__() if available.
Changed in version 3.10: This function will no longer use __int__().
If the value of obj is greater than LLONG_MAX or less than LLONG_MIN, set *overflow to 1 or -1, respectively,
and return -1; otherwise, set *overflow to 0. If any other exception occurs set *overflow to 0 and return -1 as
usual.
Returns -1 on error. Use PyErr_Occurred() to disambiguate.
Added in version 3.2.
Changed in version 3.8: Use __index__() if available.
Changed in version 3.10: This function will no longer use __int__().
Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
Part of the Stable ABI. Return a C Py_ssize_t representation of pylong. pylong must be an instance of
PyLongObject.
Raise OverflowError if the value of pylong is out of range for a Py_ssize_t.
Returns -1 on error. Use PyErr_Occurred() to disambiguate.
unsigned long PyLong_AsUnsignedLong(PyObject *pylong)
Part of the Stable ABI. Return a C unsigned long representation of pylong. pylong must be an instance of
PyLongObject.
Raise OverflowError if the value of pylong is out of range for a unsigned long.
Returns (unsigned long)-1 on error. Use PyErr_Occurred() to disambiguate.
size_t PyLong_AsSize_t(PyObject *pylong)
Part of the Stable ABI. Return a C size_t representation of pylong. pylong must be an instance of
PyLongObject.
Raise OverflowError if the value of pylong is out of range for a size_t.
Returns (size_t)-1 on error. Use PyErr_Occurred() to disambiguate.
unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)
Part of the Stable ABI. Return a C unsigned long long representation of pylong. pylong must be an
instance of PyLongObject.
Raise OverflowError if the value of pylong is out of range for an unsigned long long.
Returns (unsigned long long)-1 on error. Use PyErr_Occurred() to disambiguate.
Changed in version 3.1: A negative pylong now raises OverflowError, not TypeError.
unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)
Part of the Stable ABI. Return a C unsigned long representation of obj. If obj is not an instance of
PyLongObject, first call its __index__() method (if present) to convert it to a PyLongObject.
If the value of obj is out of range for an unsigned long, return the reduction of that value modulo
ULONG_MAX + 1.
If the value of obj is out of range for an unsigned long long, return the reduction of that value modulo
ULLONG_MAX + 1.
® Note
Overflow is not considered an error. If the returned value is larger than n_bytes, most significant bits were
discarded.
int32_t value;
Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, &value, sizeof(value), -1);
if (bytes < 0) {
// Failed. A Python exception was set with the reason.
return NULL;
}
else if (bytes <= (Py_ssize_t)sizeof(value)) {
// Success!
}
else {
// Overflow occurred, but 'value' contains the truncated
// lowest bits of pylong.
}
Passing zero to n_bytes will return the size of a buffer that would be large enough to hold the value. This may
be larger than technically necessary, but not unreasonably so. If n_bytes=0, buffer may be NULL.
® Note
Passing n_bytes=0 to this function is not an accurate way to determine the bit length of the value.
To get at the entire Python value of an unknown size, the function can be called twice: first to determine the
buffer size, then to fill it:
flags is either -1 (Py_ASNATIVEBYTES_DEFAULTS) to select defaults that behave most like a C cast, or a
combination of the other flags in the table below. Note that -1 cannot be combined with other flags.
Currently, -1 corresponds to Py_ASNATIVEBYTES_NATIVE_ENDIAN |
Py_ASNATIVEBYTES_UNSIGNED_BUFFER.
Flag Value
-1
Py_ASNATIVEBYTES_DEFAULTS
0
Py_ASNATIVEBYTES_BIG_ENDIAN
1
Py_ASNATIVEBYTES_LITTLE_ENDIAN
3
Py_ASNATIVEBYTES_NATIVE_ENDIAN
4
Py_ASNATIVEBYTES_UNSIGNED_BUFFER
8
Py_ASNATIVEBYTES_REJECT_NEGATIVE
16
Py_ASNATIVEBYTES_ALLOW_INDEX
Specifying Py_ASNATIVEBYTES_NATIVE_ENDIAN will override any other endian flags. Passing 2 is reserved.
By default, sufficient buffer will be requested to include a sign bit. For example, when converting 128 with
n_bytes=1, the function will return 2 (or more) in order to store a zero sign bit.
If Py_ASNATIVEBYTES_UNSIGNED_BUFFER is specified, a zero sign bit will be omitted from size calcula-
tions. This allows, for example, 128 to fit in a single-byte buffer. If the destination buffer is later treated as
signed, a positive input value may become negative. Note that the flag does not affect handling of negative
values: for those, space for a sign bit is always requested.
Specifying Py_ASNATIVEBYTES_REJECT_NEGATIVE causes an exception to be set if pylong is negative.
Without this flag, negative values will be copied provided there is enough space for at least one sign bit, re-
gardless of whether Py_ASNATIVEBYTES_UNSIGNED_BUFFER was specified.
If Py_ASNATIVEBYTES_ALLOW_INDEX is specified and a non-integer value is passed, its __index__()
method will be called first. This may result in Python code executing and other threads being allowed to run,
which could cause changes to other objects or values in use. When flags is -1, this option is not set, and
non-integer values will raise TypeError.
® Note
With the default flags (-1, or UNSIGNED_BUFFER without REJECT_NEGATIVE), multiple Python inte-
gers can map to a single value without overflow. For example, both 255 and -1 fit a single-byte buffer and
set all its bits. This matches typical C cast behavior.
Export API
Added in version 3.14.
struct PyLongLayout
Layout of an array of “digits” (“limbs” in the GMP terminology), used to represent absolute value for arbitrary
precision integers.
Use PyLong_GetNativeLayout() to get the native layout of Python int objects, used internally for integers
with “big enough” absolute value.
See also sys.int_info which exposes similar information in Python.
uint8_t bits_per_digit
Bits per digit. For example, a 15 bit digit means that bits 0-14 contain meaningful information.
uint8_t digit_size
Digit size in bytes. For example, a 15 bit digit will require at least 2 bytes.
int8_t digits_order
Digits order:
• 1 for most significant digit first
• -1 for least significant digit first
int8_t digit_endianness
Digit endianness:
• 1 for most significant byte first (big endian)
• -1 for least significant byte first (little endian)
const PyLongLayout *PyLong_GetNativeLayout(void)
Get the native layout of Python int objects.
See the PyLongLayout structure.
The function must not be called before Python initialization nor after Python finalization. The returned layout
is valid until Python is finalized. The layout is the same for all Python sub-interpreters in a process, and so it
can be cached.
struct PyLongExport
Export of a Python int object.
There are two cases:
• If digits is NULL, only use the value member.
• If digits is not NULL, use negative, ndigits and digits members.
int64_t value
The native integer value of the exported int object. Only valid if digits is NULL.
uint8_t negative
1 if the number is negative, 0 otherwise. Only valid if digits is not NULL.
Py_ssize_t ndigits
Number of digits in digits array. Only valid if digits is not NULL.
const void *digits
Read-only array of unsigned digits. Can be NULL.
int PyLong_Export(PyObject *obj, PyLongExport *export_long)
Export a Python int object.
export_long must point to a PyLongExport structure allocated by the caller. It must not be NULL.
On success, fill in *export_long and return 0. On error, set an exception and return -1.
PyLong_FreeExport() must be called when the export is no longer needed.
CPython implementation detail: This function always succeeds if obj is a Python int object or
a subclass.
void PyLong_FreeExport(PyLongExport *export_long)
Release the export export_long created by PyLong_Export().
CPython implementation detail: Calling PyLong_FreeExport() is optional if export_long->digits is
NULL.
PyLongWriter API
The PyLongWriter API can be used to import an integer.
Added in version 3.14.
struct PyLongWriter
A Python int writer instance.
The instance must be destroyed by PyLongWriter_Finish() or PyLongWriter_Discard().
PyLongWriter *PyLongWriter_Create(int negative, Py_ssize_t ndigits, void **digits)
Create a PyLongWriter.
On success, allocate *digits and return a writer. On error, set an exception and return NULL.
negative is 1 if the number is negative, or 0 otherwise.
ndigits is the number of digits in the digits array. It must be greater than 0.
digits must not be NULL.
After a successful call to this function, the caller should fill in the array of digits digits and
then call PyLongWriter_Finish() to get a Python int. The layout of digits is described by
PyLong_GetNativeLayout().
Digits must be in the range [0; (1 << bits_per_digit) - 1] (where the bits_per_digit is the num-
ber of bits per digit). Any unused most significant digits must be set to 0.
Alternately, call PyLongWriter_Discard() to destroy the writer instance without creating an int object.
PyObject *PyLongWriter_Finish(PyLongWriter *writer)
Return value: New reference. Finish a PyLongWriter created by PyLongWriter_Create().
On success, return a Python int object. On error, set an exception and return NULL.
The function takes care of normalizing the digits and converts the object to a compact integer if needed.
The writer instance and the digits array are invalid after the call.
PyObject *PyFloat_FromDouble(double v)
Return value: New reference. Part of the Stable ABI. Create a PyFloatObject object from v, or NULL on
failure.
double PyFloat_AsDouble(PyObject *pyfloat)
Part of the Stable ABI. Return a C double representation of the contents of pyfloat. If pyfloat is not a Python
floating-point object but has a __float__() method, this method will first be called to convert pyfloat into
a float. If __float__() is not defined then it falls back to __index__(). This method returns -1.0 upon
failure, so one should call PyErr_Occurred() to check for errors.
Changed in version 3.8: Use __index__() if available.
double PyFloat_AS_DOUBLE(PyObject *pyfloat)
Return a C double representation of the contents of pyfloat, but without error checking.
PyObject *PyFloat_GetInfo(void)
Return value: New reference. Part of the Stable ABI. Return a structseq instance which contains information
about the precision, minimum and maximum values of a float. It’s a thin wrapper around the header file
float.h.
double PyFloat_GetMax()
Part of the Stable ABI. Return the maximum representable finite float DBL_MAX as C double.
double PyFloat_GetMin()
Part of the Stable ABI. Return the minimum normalized positive float DBL_MIN as C double.
Pack functions
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.
Return value: 0 if all is OK, -1 if error (and an exception is set, most likely OverflowError).
There are two problems on non-IEEE platforms:
• What this does is undefined if x is a NaN or infinity.
• -0.0 and +0.0 produce the same bytes string.
int PyFloat_Pack2(double x, unsigned char *p, int le)
Pack a C double as the IEEE 754 binary16 half-precision format.
int PyFloat_Pack4(double x, unsigned char *p, int le)
Pack a C double as the IEEE 754 binary32 single precision format.
Unpack functions
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.
Return value: The unpacked double. On error, this is -1.0 and PyErr_Occurred() is true (and an exception is
set, most likely OverflowError).
Note that on a non-IEEE platform this will refuse to unpack a bytes string that represents a NaN or infinity.
double PyFloat_Unpack2(const unsigned char *p, int le)
Unpack the IEEE 754 binary16 half-precision format as a C double.
double PyFloat_Unpack4(const unsigned char *p, int le)
Unpack the IEEE 754 binary32 single precision format as a C double.
double PyFloat_Unpack8(const unsigned char *p, int le)
Unpack the IEEE 754 binary64 double precision format as a C double.
typedef struct {
double real;
double imag;
} Py_complex;
An unrecognized format character causes all the rest of the format string to be copied as-is to the result object,
and any extra arguments discarded.
PyObject *PyBytes_FromFormatV(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Identical to PyBytes_FromFormat() except that it
takes exactly two arguments.
PyObject *PyBytes_FromObject(PyObject *o)
Return value: New reference. Part of the Stable ABI. Return the bytes representation of object o that implements
the buffer protocol.
Py_ssize_t PyBytes_Size(PyObject *o)
Part of the Stable ABI. Return the length of the bytes in bytes object o.
Py_ssize_t PyBytes_GET_SIZE(PyObject *o)
Similar to PyBytes_Size(), but without error checking.
char *PyBytes_AsString(PyObject *o)
Part of the Stable ABI. Return a pointer to the contents of o. The pointer refers to the internal buffer of o,
which consists of len(o) + 1 bytes. The last byte in the buffer is always null, regardless of whether there
are any other null bytes. The data must not be modified in any way, unless the object was just created using
PyBytes_FromStringAndSize(NULL, size). It must not be deallocated. If o is not a bytes object at all,
PyBytes_AsString() returns NULL and raises TypeError.
1 For integer specifiers (d, u, ld, lu, zd, zu, i, x): the 0-conversion flag has effect even when a precision is given.
Macros
These macros trade safety for speed and they don’t check pointers.
char *PyByteArray_AS_STRING(PyObject *bytearray)
Similar to PyByteArray_AsString(), but without error checking.
Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray)
Similar to PyByteArray_Size(), but without error checking.
® Note
The Py_UNICODE representation has been removed since Python 3.12 with deprecated APIs. See PEP 623 for
more information.
Unicode Type
These are the basic Unicode object types used for the Unicode implementation in Python:
PyTypeObject PyUnicode_Type
Part of the Stable ABI. This instance of PyTypeObject represents the Python Unicode type. It is exposed to
Python code as str.
type Py_UCS4
type Py_UCS2
type Py_UCS1
Part of the Stable ABI. These types are typedefs for unsigned integer types wide enough to contain characters
of 32 bits, 16 bits and 8 bits, respectively. When dealing with single Unicode characters, use Py_UCS4.
Added in version 3.3.
type PyASCIIObject
type PyCompactUnicodeObject
type PyUnicodeObject
These subtypes of PyObject represent a Python Unicode object. In almost all cases, they shouldn’t be used
directly, since all API functions that deal with Unicode objects take and return PyObject pointers.
Added in version 3.3.
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.
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 char-
acter access. No checks are performed if the canonical representation has the correct character size; use
PyUnicode_KIND() to select the right function.
The function performs no checks for any of its requirements, and is intended for usage in loops.
Unicode provides many different character properties. The most often needed ones are available through these macros
which are mapped to C functions depending on the Python configuration.
int Py_UNICODE_ISSPACE(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a whitespace character.
int Py_UNICODE_ISLOWER(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a lowercase character.
int Py_UNICODE_ISUPPER(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is an uppercase character.
int Py_UNICODE_ISTITLE(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a titlecase character.
int Py_UNICODE_ISLINEBREAK(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a linebreak character.
int Py_UNICODE_ISDECIMAL(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a decimal character.
int Py_UNICODE_ISDIGIT(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a digit character.
int Py_UNICODE_ISNUMERIC(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is a numeric character.
int Py_UNICODE_ISALPHA(Py_UCS4 ch)
Return 1 or 0 depending on whether ch is an alphabetic character.
To create Unicode objects and access their basic sequence properties, use these APIs:
PyObject *PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
Return value: New reference. Create a new Unicode object. maxchar should be the true maximum code point
to be placed in the string. As an approximation, it can be rounded up to the nearest value in the sequence 127,
255, 65535, 1114111.
On error, set an exception and return NULL.
After creation, the string can be filled by PyUnicode_WriteChar(), PyUnicode_CopyCharacters(),
PyUnicode_Fill(), PyUnicode_WRITE() or similar. Since strings are supposed to be immutable, take
care to not “use” the result while it is being modified. In particular, before it’s filled with its final contents, a
string:
• must not be hashed,
• must not be converted to UTF-8, or another non-“canonical” representation,
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:
® Note
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).
® Note
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).
added.
Changed in version 3.12: Support for conversion specifiers o and X. Support for length modifiers j and t.
Length modifiers are now applied to all integer conversions. Length modifier l is now applied to conversion
specifiers s and V. Support for variable width and precision *. Support for flag -.
An unrecognized format character now sets a SystemError. In previous versions it caused all the rest of the
format string to be copied as-is to the result string, and any extra arguments discarded.
Changed in version 3.13: Support for %T, %#T, %N and %#N formats added.
PyObject *PyUnicode_FromFormatV(const char *format, va_list vargs)
Return value: New reference. Part of the Stable ABI. Identical to PyUnicode_FromFormat() except that it
takes exactly two arguments.
PyObject *PyUnicode_FromObject(PyObject *obj)
Return value: New reference. Part of the Stable ABI. Copy an instance of a Unicode subtype to a new true
Unicode object if necessary. If obj is already a true Unicode object (not a subtype), return a new strong reference
to the object.
Objects other than Unicode or its subtypes will cause a TypeError.
PyObject *PyUnicode_FromOrdinal(int ordinal)
Return value: New reference. Part of the Stable ABI. Create a Unicode Object from the given Unicode code
point ordinal.
The ordinal must be in range(0x110000). A ValueError is raised in the case it is not.
PyObject *PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)
Return value: New reference. Part of the Stable ABI. Decode an encoded object obj to a Unicode object.
bytes, bytearray and other bytes-like objects are decoded according to the given encoding and using the
error handling defined by errors. Both can be NULL to have the interface use the default values (see Built-in
Codecs for details).
All other objects, including Unicode objects, cause a TypeError to be set.
The API returns NULL if there was an error. The caller is responsible for decref’ing the returned objects.
void PyUnicode_Append(PyObject **p_left, PyObject *right)
Part of the Stable ABI. Append the string right to the end of p_left. p_left must point to a strong reference to a
Unicode object; PyUnicode_Append() releases (“steals”) this reference.
On error, set *p_left to NULL and set an exception.
On success, set *p_left to a new strong reference to the result.
void PyUnicode_AppendAndDel(PyObject **p_left, PyObject *right)
Part of the Stable ABI. The function is similar to PyUnicode_Append(), with the only difference being that
it decrements the reference count of right by one.
const char *PyUnicode_GetDefaultEncoding(void)
Part of the Stable ABI. Return the name of the default string encoding, "utf-8". See sys.
getdefaultencoding().
The returned string does not need to be freed, and is valid until interpreter shutdown.
Py_ssize_t PyUnicode_GetLength(PyObject *unicode)
Part of the Stable ABI since version 3.7. Return the length of the Unicode object, in code points.
On error, set an exception and return -1.
Added in version 3.3.
This function checks that unicode is a Unicode object, that the index is not out of bounds, and that the object’s
reference count is one). See PyUnicode_WRITE() for a version that skips these checks, making them your
responsibility.
The string must not have been “used” yet. See PyUnicode_New() for details.
Added in version 3.3.
Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
Part of the Stable ABI since version 3.7. Read a character from a string. This function checks that unicode is a
Unicode object and the index is not out of bounds, in contrast to PyUnicode_READ_CHAR(), which performs
no error checking.
Return character on success, -1 on error with an exception set.
Added in version 3.3.
PyObject *PyUnicode_Substring(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
Return value: New reference. Part of the Stable ABI since version 3.7. Return a substring of unicode, from
character index start (included) to character index end (excluded). Negative indices are not supported. On
error, set an exception and return NULL.
Added in version 3.3.
Py_UCS4 *PyUnicode_AsUCS4(PyObject *unicode, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)
Part of the Stable ABI since version 3.7. Copy the string unicode into a UCS4 buffer, including a null character,
if copy_null is set. Returns NULL and sets an exception on error (in particular, a SystemError if buflen is
smaller than the length of unicode). buffer is returned on success.
Added in version 3.3.
Locale Encoding
The current locale encoding can be used to decode text from the operating system.
PyObject *PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t length, const char *errors)
Return value: New reference. Part of the Stable ABI since version 3.7. Decode a string from UTF-8 on Android
and VxWorks, or from the current locale encoding on other platforms. The supported error handlers are
"strict" and "surrogateescape" (PEP 383). The decoder uses "strict" error handler if errors is
NULL. str must end with a null character but cannot contain embedded null characters.
Use PyUnicode_DecodeFSDefaultAndSize() to decode a string from the filesystem encoding and error
handler.
This function ignores the Python UTF-8 Mode.
µ See also
µ See also
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:
µ See also
µ See also
wchar_t Support
Built-in Codecs
Python provides a set of built-in codecs which are written in C for speed. All of these codecs are directly usable via
the following functions.
Many of the following APIs take two arguments encoding and errors, and they have the same semantics as the ones
of the built-in str() string object constructor.
Setting encoding to NULL causes the default encoding to be used which is UTF-8. The file system calls should
use PyUnicode_FSConverter() for encoding file names. This uses the filesystem encoding and error handler
internally.
Error handling is set by errors which may also be set to NULL meaning to use the default handling defined for the
codec. Default error handling for all built-in codecs is “strict” (ValueError is raised).
The codecs all use a similar interface. Only deviations from the following generic ones are documented for simplicity.
Generic Codecs
UTF-8 Codecs
Á Warning
This function does not have any special behavior for null characters embedded within unicode. As a re-
sult, strings containing null characters will remain in the returned string, which some C functions might
interpret as the end of the string, leading to truncation. If truncation is an issue, it is recommended to use
PyUnicode_AsUTF8AndSize() instead.
UTF-32 Codecs
If *byteorder is zero, and the first four bytes of the input data are a byte order mark (BOM), the decoder
switches to this byte order and the BOM is not copied into the resulting Unicode string. If *byteorder is -1
or 1, any byte order mark is copied to the output.
After completion, *byteorder is set to the current byte order at the end of input data.
If byteorder is NULL, the codec starts in native order mode.
Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeUTF32Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Return value:New reference. Part of the Stable ABI. If consumed is NULL, behave like
PyUnicode_DecodeUTF32(). If consumed is not NULL, PyUnicode_DecodeUTF32Stateful() will not
treat trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible by four) as an error.
Those bytes will not be decoded and the number of bytes that have been decoded will be stored in consumed.
PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Return a Python byte string using the UTF-32 encoding
in native byte order. The string always starts with a BOM mark. Error handling is “strict”. Return NULL if an
exception was raised by the codec.
UTF-16 Codecs
If *byteorder is zero, and the first two bytes of the input data are a byte order mark (BOM), the decoder
switches to this byte order and the BOM is not copied into the resulting Unicode string. If *byteorder is
-1 or 1, any byte order mark is copied to the output (where it will result in either a \ufeff or a \ufffe
character).
After completion, *byteorder is set to the current byte order at the end of input data.
If byteorder is NULL, the codec starts in native order mode.
Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeUTF16Stateful(const char *str, Py_ssize_t size, const char *errors, int
*byteorder, Py_ssize_t *consumed)
Return value:New reference. Part of the Stable ABI. If consumed is NULL, behave like
PyUnicode_DecodeUTF16(). If consumed is not NULL, PyUnicode_DecodeUTF16Stateful() will not
treat trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a split surrogate pair) as
an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in
consumed.
PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
Return value: New reference. Part of the Stable ABI. Return a Python byte string using the UTF-16 encoding
in native byte order. The string always starts with a BOM mark. Error handling is “strict”. Return NULL if an
exception was raised by the codec.
UTF-7 Codecs
Unicode-Escape Codecs
Raw-Unicode-Escape Codecs
Latin-1 Codecs
These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted
by the codecs during encoding.
PyObject *PyUnicode_DecodeLatin1(const char *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. Encode a Unicode object using Latin-1 and return the
result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.
ASCII Codecs
These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors.
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. Encode a Unicode object using ASCII and return the
result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.
This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to
obtain most of the standard codecs included in the encodings package). The codec uses mappings to encode and
decode characters. The mapping objects provided must support the __getitem__() mapping interface; dictionaries
and sequences work well.
These are the mapping codec APIs:
PyObject *PyUnicode_DecodeCharmap(const char *str, Py_ssize_t length, PyObject *mapping, const char
*errors)
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.
If mapping is NULL, Latin-1 decoding will be applied. Else mapping must map bytes ordinals (integers in the
range from 0 to 255) to Unicode strings, integers (which are then interpreted as Unicode ordinals) or None.
Unmapped data bytes – ones which cause a LookupError, as well as ones which get mapped to None, 0xFFFE
or '\ufffe', are treated as undefined mappings and cause an error.
PyObject *PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)
Return value: New reference. Part of the Stable ABI. Encode a Unicode object using the given mapping object
and return the result as a bytes object. Error handling is “strict”. Return NULL if an exception was raised by
the codec.
The mapping object must map Unicode ordinal integers to bytes objects, integers in the range from 0 to 255
or None. Unmapped character ordinals (ones which cause a LookupError) as well as mapped to None are
treated as “undefined mapping” and cause an error.
The following codec API is special in that maps Unicode to Unicode.
PyObject *PyUnicode_Translate(PyObject *unicode, PyObject *table, const char *errors)
Return value: New reference. Part of the Stable ABI. Translate a string by applying a character mapping table
to it and return the resulting Unicode object. Return NULL if an exception was raised by the codec.
The mapping table must map Unicode ordinal integers to Unicode ordinal integers or None (causing deletion
of the character).
Mapping tables need only provide the __getitem__() interface; dictionaries and sequences work well. Un-
mapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is.
errors has the usual meaning for codecs. It may be NULL which indicates to use the default error handling.
These are the MBCS codec APIs. They are currently only available on Windows and use the Win32 MBCS converters
to implement the conversions. Note that MBCS (or DBCS) is a class of encodings, not just one. The target encoding
is defined by the user settings on the machine running the codec.
PyObject *PyUnicode_DecodeMBCS(const char *str, Py_ssize_t size, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Create a Unicode object
by decoding size bytes of the MBCS encoded string str. Return NULL if an exception was raised by the codec.
PyObject *PyUnicode_DecodeMBCSStateful(const char *str, Py_ssize_t size, const char *errors, Py_ssize_t
*consumed)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. If consumed is NULL, behave
like PyUnicode_DecodeMBCS(). If consumed is not NULL, PyUnicode_DecodeMBCSStateful() will
not decode trailing lead byte and the number of bytes that have been decoded will be stored in consumed.
PyObject *PyUnicode_DecodeCodePageStateful(int code_page, const char *str, Py_ssize_t size, const char
*errors, Py_ssize_t *consumed)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Similar to
PyUnicode_DecodeMBCSStateful(), except uses the code page specified by code_page.
PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Encode a Unicode object
using MBCS and return the result as Python bytes object. Error handling is “strict”. Return NULL if an
exception was raised by the codec.
PyObject *PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)
Return value: New reference. Part of the Stable ABI on Windows since version 3.7. Encode the Unicode object
using the specified code page and return a Python bytes object. Return NULL if an exception was raised by the
codec. Use CP_ACP code page to get the MBCS encoder.
Added in version 3.3.
µ See also
µ See also
PyUnicodeWriter
The PyUnicodeWriter API can be used to create a Python str object.
Added in version 3.14.
type PyUnicodeWriter
A Unicode writer instance.
The instance must be destroyed by PyUnicodeWriter_Finish() on success, or
PyUnicodeWriter_Discard() on error.
PyUnicodeWriter *PyUnicodeWriter_Create(Py_ssize_t length)
Create a Unicode writer instance.
length must be greater than or equal to 0.
If length is greater than 0, preallocate an internal buffer of length characters.
Set an exception and return NULL on error.
PyObject *PyUnicodeWriter_Finish(PyUnicodeWriter *writer)
Return the final Python str object and destroy the writer instance.
Set an exception and return NULL on error.
The writer instance is invalid after this call.
void PyUnicodeWriter_Discard(PyUnicodeWriter *writer)
Discard the internal Unicode buffer and destroy the writer instance.
If writer is NULL, no operation is performed.
The writer instance is invalid after this call.
int PyUnicodeWriter_WriteChar(PyUnicodeWriter *writer, Py_UCS4 ch)
Write the single Unicode character ch into writer.
On success, return 0. On error, set an exception, leave the writer unchanged, and return -1.
int PyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer, const char *str, Py_ssize_t size)
Decode the string str from UTF-8 in strict mode and write the output into writer.
size is the string length in bytes. If size is equal to -1, call strlen(str) to get the string length.
On success, return 0. On error, set an exception, leave the writer unchanged, and return -1.
See also PyUnicodeWriter_DecodeUTF8Stateful().
int PyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer, const wchar_t *str, Py_ssize_t size)
Writer the wide string str into writer.
size is a number of wide characters. If size is equal to -1, call wcslen(str) to get the string length.
On success, return 0. On error, set an exception, leave the writer unchanged, and return -1.
int PyUnicodeWriter_WriteUCS4(PyUnicodeWriter *writer, Py_UCS4 *str, Py_ssize_t size)
Writer the UCS4 string str into writer.
size is a number of UCS4 characters.
On success, return 0. On error, set an exception, leave the writer unchanged, and return -1.
int PyUnicodeWriter_WriteStr(PyUnicodeWriter *writer, PyObject *obj)
Call PyObject_Str() on obj and write the output into writer.
On success, return 0. On error, set an exception, leave the writer unchanged, and return -1.
int PyUnicodeWriter_WriteRepr(PyUnicodeWriter *writer, PyObject *obj)
Call PyObject_Repr() on obj and write the output into writer.
On success, return 0. On error, set an exception, leave the writer unchanged, and return -1.
Deprecated API
The following API is deprecated.
type Py_UNICODE
This is a typedef of wchar_t, which is a 16-bit type or 32-bit type depending on the platform. Please use
wchar_t directly instead.
Changed in version 3.3: In previous versions, this was a 16-bit type or a 32-bit type depending on whether you
selected a “narrow” or “wide” Unicode version of Python at build time.
Deprecated since version 3.13, will be removed in version 3.15.
int PyUnicode_READY(PyObject *unicode)
Do nothing and return 0. This API is kept only for backward compatibility, but there are no plans to remove
it.
Added in version 3.3.
Deprecated since version 3.10: This API does nothing since Python 3.12. Previously, this needed to be called
for each string created using the old API (PyUnicode_FromUnicode() or similar).
unsigned int PyUnicode_IS_READY(PyObject *unicode)
Do nothing and return 1. This API is kept only for backward compatibility, but there are no plans to remove
it.
Added in version 3.3.
Deprecated since version 3.14: This API does nothing since Python 3.12. Previously, this could be called to
check if PyUnicode_READY() is necessary.
PyTypeObject PyTuple_Type
Part of the Stable ABI. This instance of PyTypeObject represents the Python tuple type; it is the same object
as tuple in the Python layer.
int PyTuple_Check(PyObject *p)
Return true if p is a tuple object or an instance of a subtype of the tuple type. This function always succeeds.
int PyTuple_CheckExact(PyObject *p)
Return true if p is a tuple object, but not an instance of a subtype of the tuple type. This function always
succeeds.
PyObject *PyTuple_New(Py_ssize_t len)
Return value: New reference. Part of the Stable ABI. Return a new tuple object of size len, or NULL with an
exception set on failure.
PyObject *PyTuple_Pack(Py_ssize_t n, ...)
Return value: New reference. Part of the Stable ABI. Return a new tuple object of size n, or NULL with an
exception set on failure. The tuple values are initialized to the subsequent n C arguments pointing to Python
objects. PyTuple_Pack(2, a, b) is equivalent to Py_BuildValue("(OO)", a, b).
Py_ssize_t PyTuple_Size(PyObject *p)
Part of the Stable ABI. Take a pointer to a tuple object, and return the size of that tuple. On error, return -1
and with an exception set.
Py_ssize_t PyTuple_GET_SIZE(PyObject *p)
Like PyTuple_Size(), but without error checking.
PyObject *PyTuple_GetItem(PyObject *p, Py_ssize_t pos)
Return value: Borrowed reference. Part of the Stable ABI. Return the object at position pos in the tuple pointed
to by p. If pos is negative or out of bounds, return NULL and set an IndexError exception.
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. Like PyTuple_GetItem(), but does no checking of its arguments.
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 with an exception set 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. Insert a reference to object o at position pos of the tuple pointed to by p. Return 0 on
success. If pos is out of bounds, return -1 and set an IndexError exception.
® Note
This function “steals” a reference to o and discards a reference to an item already in the tuple at the affected
position.
® Note
This function “steals” a reference to o, and, unlike PyTuple_SetItem(), does not discard a reference to
any item that is being replaced; any reference in the tuple at position pos will be leaked.
Á Warning
This macro should only be used on tuples that are newly created. Using this macro on a tuple that is already
in use (or in other words, has a refcount > 1) could lead to undefined behavior.
® Note
® Note
If len is greater than zero, the returned list object’s items are set to NULL. Thus you cannot use abstract API
functions such as PySequence_SetItem() or expose the object to Python code before setting all items
to a real object with PyList_SetItem() or PyList_SET_ITEM(). The following APIs are safe APIs
before the list is fully initialized: PyList_SetItem() and PyList_SET_ITEM().
® Note
This function “steals” a reference to item and discards a reference to an item already in the list at the affected
position.
® Note
This macro “steals” a reference to item, and, unlike PyList_SetItem(), does not discard a reference to
any item that is being replaced; any reference in list at position i will be leaked.
® Note
Exceptions that occur while this calls __hash__() and __eq__() methods are silently ignored. Prefer
the PyDict_GetItemWithError() function instead.
Changed in version 3.10: Calling this API without an attached thread state had been allowed for historical
reason. It is no longer allowed.
PyObject *PyDict_GetItemWithError(PyObject *p, PyObject *key)
Return value: Borrowed reference. Part of the Stable ABI. Variant of PyDict_GetItem() that does not
suppress exceptions. Return NULL with an exception set if an exception occurred. Return NULL without an
exception set if the key wasn’t present.
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*.
® Note
Exceptions that occur while this calls __hash__() and __eq__() methods or while creating the tem-
porary str object are silently ignored. Prefer using the PyDict_GetItemWithError() function with
your own PyUnicode_FromString() key instead.
• If the key is missing, set *result to NULL if result is not NULL, and return 0.
• On error, raise an exception and return -1.
Similar to dict.pop(), but without the default value and not raising KeyError if the key missing.
Added in version 3.13.
int PyDict_PopString(PyObject *p, const char *key, PyObject **result)
Similar to PyDict_Pop(), but key is specified as a const char* UTF-8 encoded bytes string, rather than
a PyObject*.
The dictionary p should not be mutated during iteration. It is safe to modify the values of the keys as you
iterate over the dictionary, but only so long as the set of keys does not change. For example:
The function is not thread-safe in the free-threaded build without external synchronization. You can use
Py_BEGIN_CRITICAL_SECTION to lock the dictionary while iterating over it:
Py_BEGIN_CRITICAL_SECTION(self->dict);
while (PyDict_Next(self->dict, &pos, &key, &value)) {
...
}
Py_END_CRITICAL_SECTION();
PyDict_EVENT_CLONED occurs when dict was previously empty and another dict is merged into it. To main-
tain efficiency of this operation, per-key PyDict_EVENT_ADDED events are not issued in this case; instead a
single PyDict_EVENT_CLONED is issued, and key will be the source dictionary.
The callback may inspect but must not modify dict; doing so could have unpredictable effects, including infinite
recursion. Do not trigger Python code execution in the callback, as it could modify the dict as a side effect.
If event is PyDict_EVENT_DEALLOCATED, taking a new reference in the callback to the about-to-be-destroyed
dictionary will resurrect it and prevent it from being freed at this time. When the resurrected object is destroyed
later, any watcher callbacks active at that time will be called again.
Callbacks occur before the notified modification to dict takes place, so the prior state of dict can be inspected.
If the callback sets an exception, it must return -1; this exception will be printed as an unraisable exception
using PyErr_WriteUnraisable(). Otherwise it should return 0.
There may already be a pending exception set on entry to the callback. In this case, the callback should return 0
with the same exception still set. This means the callback may not call any other API that can set an exception
unless it saves and clears the exception state first, and restores it before returning.
Added in version 3.12.
Return the position of the first free (closure) variable in a code object.
Changed in version 3.13: Renamed from PyCode_GetFirstFree as part of Unstable C API. The old name
is deprecated, but will remain available until the signature changes again.
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.
Changed in version 3.11: Added qualname and exceptiontable parameters.
Changed in version 3.12: Renamed from PyCode_New as part of Unstable C API. The old name is deprecated,
but will remain available until the signature changes again.
PyCodeObject *PyUnstable_Code_NewWithPosOnlyArgs(int argcount, int posonlyargcount, int
kwonlyargcount, int nlocals, int stacksize, int flags,
PyObject *code, PyObject *consts, PyObject
*names, PyObject *varnames, PyObject *freevars,
PyObject *cellvars, PyObject *filename, PyObject
*name, PyObject *qualname, int firstlineno,
PyObject *linetable, PyObject *exceptiontable)
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
Changed in version 3.12: Renamed to PyUnstable_Eval_RequestCodeExtraIndex. The old private
name is deprecated, but will be available until the API changes.
int PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
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
Changed in version 3.12: Renamed to PyUnstable_Code_GetExtra. The old private name is deprecated,
but will be available until the API changes.
int PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
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
Changed in version 3.12: Renamed to PyUnstable_Code_SetExtra. The old private name is deprecated,
but will be available until the API changes.
Á Warning
Since Python streams have their own buffering layer, mixing them with OS-level file descriptors can pro-
duce various issues (such as unexpected ordering of data).
Initializing C modules
Modules objects are usually created from extension modules (shared libraries which export an initialization function),
or compiled-in modules (where the initialization function is added using PyImport_AppendInittab()). See
building or extending-with-embedding for details.
The initialization function can either pass a module definition instance to PyModule_Create(), and return the
resulting module object, or request “multi-phase initialization” by returning the definition struct itself.
type PyModuleDef
Part of the Stable ABI (including all members). The module definition struct, which holds all information
needed to create a module object. There is usually only one statically initialized variable of this type for each
module.
PyModuleDef_Base m_base
Always initialize this member to PyModuleDef_HEAD_INIT.
const char *m_name
Name for the new module.
const char *m_doc
Docstring for the module; usually a docstring variable created with PyDoc_STRVAR is used.
Py_ssize_t m_size
Module state may be kept in a per-module memory area that can be retrieved with
PyModule_GetState(), rather than in static globals. This makes modules safe for use in mul-
tiple sub-interpreters.
This memory area is allocated based on m_size on module creation, and freed when the module object is
deallocated, after the m_free function has been called, if present.
Setting m_size to -1 means that the module does not support sub-interpreters, because it has global
state.
Setting it to a non-negative value means that the module can be re-initialized and specifies the additional
amount of memory it requires for its state. Non-negative m_size is required for multi-phase initializa-
tion.
See PEP 3121 for more details.
PyMethodDef *m_methods
A pointer to a table of module-level functions, described by PyMethodDef values. Can be NULL if no
functions are present.
PyModuleDef_Slot *m_slots
An array of slot definitions for multi-phase initialization, terminated by a {0, NULL} entry. When using
single-phase initialization, m_slots must be NULL.
Changed in version 3.5: Prior to version 3.5, this member was always set to NULL, and was defined as:
inquiry m_reload
traverseproc m_traverse
A traversal function to call during GC traversal of the module object, or NULL if not needed.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Changed in version 3.9: No longer called before the module state is allocated.
inquiry m_clear
A clear function to call during GC clearing of the module object, or NULL if not needed.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Like PyTypeObject.tp_clear, this function is not always called before a module is deallocated. For
example, when reference counting is enough to determine that an object is no longer used, the cyclic
garbage collector is not involved and m_free is called directly.
Changed in version 3.9: No longer called before the module state is allocated.
freefunc m_free
A function to call during deallocation of the module object, or NULL if not needed.
This function is not called if the module state was requested but is not allocated yet. This is the case
immediately after the module is created and before the module is executed (Py_mod_exec function).
More precisely, this function is not called if m_size is greater than 0 and the module state (as returned
by PyModule_GetState()) is NULL.
Changed in version 3.9: No longer called before the module state is allocated.
Single-phase initialization
The module initialization function may create and return the module object directly. This is referred to as “single-
phase initialization”, and uses one of the following two module creation functions:
PyObject *PyModule_Create(PyModuleDef *def)
Return value: New reference. Create a new module object, given the definition in def. This behaves like
PyModule_Create2() with module_api_version set to PYTHON_API_VERSION.
® Note
Most uses of this function should be using PyModule_Create() instead; only use this if you are sure you
need it.
Before it is returned from in the initialization function, the resulting module object is typically populated using
functions like PyModule_AddObjectRef().
Multi-phase initialization
An alternate way to specify extensions is to request “multi-phase initialization”. Extension modules created this way
behave more like Python modules: the initialization is split between the creation phase, when the module object is
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()).
All modules created using multi-phase initialization are expected to support sub-interpreters. Making sure multiple
modules are independent is typically enough to achieve this.
To request multi-phase initialization, the initialization function (PyInit_modulename) returns a PyModuleDef in-
stance with non-empty m_slots. Before it is returned, the PyModuleDef instance must be initialized with the
following function:
PyObject *PyModuleDef_Init(PyModuleDef *def)
Return value: Borrowed reference. Part of the Stable ABI since version 3.5. Ensures a module definition is a
properly initialized Python object that correctly reports its type and reference count.
Returns def cast to PyObject*, or NULL if an error occurred.
Added in version 3.5.
The m_slots member of the module definition must point to an array of PyModuleDef_Slot structures:
type PyModuleDef_Slot
int slot
A slot ID, chosen from the available values explained below.
void *value
Value of the slot, whose meaning depends on the slot ID.
Added in version 3.5.
The m_slots array must be terminated by a slot with id 0.
The available slot types are:
Py_mod_create
Specifies a function that is called to create the module object itself. The value pointer of this slot must point
to a function of the signature:
PyObject *create_module(PyObject *spec, PyModuleDef *def)
The function receives a ModuleSpec instance, as defined in PEP 451, and the module definition. It should
return a new module object, or set an error and return NULL.
This function should be kept minimal. In particular, it should not call arbitrary Python code, as trying to import
the same module again may result in an infinite loop.
Multiple Py_mod_create slots may not be specified in one module definition.
If Py_mod_create is not specified, the import machinery will create a normal module object using
PyModule_New(). The name is taken from spec, not the definition, to allow extension modules to dynami-
cally adjust to their place in the module hierarchy and be imported under different names through symlinks,
all while sharing a single module definition.
There is no requirement for the returned object to be an instance of PyModule_Type. Any type can be used,
as long as it supports setting and getting import-related attributes. However, only PyModule_Type instances
may be returned if the PyModuleDef has non-NULL m_traverse, m_clear, m_free; non-zero m_size; or
slots other than Py_mod_create.
Py_mod_exec
Specifies a function that is called to execute the module. This is equivalent to executing the code of a Python
module: typically, this function adds classes and constants to the module. The signature of the function is:
int exec_module(PyObject *module)
If multiple Py_mod_exec slots are specified, they are processed in the order they appear in the m_slots array.
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_SUPPORTED.
The following functions are called under the hood when using multi-phase initialization. They can be used di-
rectly, for example when creating module objects dynamically. Note that both PyModule_FromDefAndSpec and
PyModule_ExecDef must be called to fully initialize a module.
® Note
Most uses of this function should be using PyModule_FromDefAndSpec() instead; only use this if you
are sure you need it.
Support functions
The module initialization function (if using single phase initialization) or a function called from a module execution
slot (if using multi-phase initialization), can use the following functions to help initialize the module state:
int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
Part of the Stable ABI since version 3.10. Add an object to module as name. This is a convenience function
which can be used from the module’s initialization function.
On success, return 0. On error, raise an exception and return -1.
Example usage:
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
if (obj == NULL) {
return -1;
}
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_DECREF(obj);
return res;
}
To be convenient, the function accepts NULL value with an exception set. In this case, return -1 and just leave
the raised exception unchanged.
The example can also be written without checking explicitly if obj is NULL:
static int
add_spam(PyObject *module, int value)
{
PyObject *obj = PyLong_FromLong(value);
int res = PyModule_AddObjectRef(module, "spam", obj);
Py_XDECREF(obj);
return res;
}
Note that Py_XDECREF() should be used instead of Py_DECREF() in this case, since obj can be NULL.
The number of different name strings passed to this function should be kept small, usually by
only using statically allocated strings as name. For names that aren’t known at compile time, pre-
fer calling PyUnicode_FromString() and PyObject_SetAttr() directly. For more details, see
PyUnicode_InternFromString(), which may be used internally to create a key object.
® Note
Unlike other functions that steal references, PyModule_AddObject() only releases the reference to value
on success.
This means that its return value must be checked, and calling code must Py_XDECREF() value manually
on error.
Example usage:
PyModule_AddIntMacro(module, macro)
Add an int constant to module. The name and the value are taken from macro. For example
PyModule_AddIntMacro(module, AF_INET) adds the int constant AF_INET with the value of AF_INET
to module. Return -1 with an exception set on error, 0 on success.
PyModule_AddStringMacro(module, macro)
Add a string constant to module.
int PyModule_AddType(PyObject *module, PyTypeObject *type)
Part of the Stable ABI since version 3.10. Add a type object to module. The type object is finalized by calling
internally PyType_Ready(). The name of the type object is taken from the last component of tp_name after
dot. Return -1 with an exception set on error, 0 on success.
Added in version 3.9.
int PyUnstable_Module_SetGIL(PyObject *module, void *gil)
Indicate that module does or does not support running without the global interpreter lock (GIL), using one
of the values from Py_mod_gil. It must be called during module’s initialization function. If this function is
not called during module initialization, the import machinery assumes the module does not support running
without the GIL. This function is only available in Python builds configured with --disable-gil. Return
-1 with an exception set on error, 0 on success.
Module lookup
Single-phase initialization creates singleton modules that can be looked up in the context of the current interpreter.
This allows the module object to be retrieved later with only a reference to the module definition.
These functions will not work on modules created using multi-phase initialization, since multiple such modules can
be created from a single definition.
PyObject *PyState_FindModule(PyModuleDef *def)
Return value: Borrowed reference. Part of the Stable ABI. Returns the module object that was created from def
for the current interpreter. This method requires that the module object has been attached to the interpreter
state with PyState_AddModule() beforehand. In case the corresponding module object is not found or has
not been attached to the interpreter state yet, it returns NULL.
int PyState_AddModule(PyObject *module, PyModuleDef *def)
Part of the Stable ABI since version 3.3. Attaches the module object passed to the function to the interpreter
state. This allows the module object to be accessible via PyState_FindModule().
Only effective on modules created using single-phase initialization.
Python calls PyState_AddModule automatically after importing a module, so it is unnecessary (but harm-
less) to call it from module initialization code. An explicit call is needed only if the module’s own init code
subsequently calls PyState_FindModule. The function is mainly intended for implementing alternative im-
port mechanisms (either by calling it directly, or by referring to its implementation for details of the required
state updates).
The caller must have an attached thread state.
Return -1 with an exception set on error, 0 on success.
Added in version 3.3.
int PyState_RemoveModule(PyModuleDef *def)
Part of the Stable ABI since version 3.3. Removes the module object created from def from the interpreter
state. Return -1 with an exception set on error, 0 on success.
The caller must have an attached thread state.
Added in version 3.3.
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. Usable replacement for PySlice_GetIndices(). Retrieve the start, stop, and step
indices from the slice object slice assuming a sequence of length length, and store the length of the slice in
slicelength. Out of bounds indices are clipped in a manner consistent with the handling of normal slices.
Return 0 on success and -1 on error with an exception set.
® Note
This function is considered not safe for resizable sequences. Its invocation should be replaced by a combi-
nation of PySlice_Unpack() and PySlice_AdjustIndices() where
if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength)
,→< 0) {
// return error
}
is replaced by
if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {
// return error
}
slicelength = PySlice_AdjustIndices(length, &start, &stop, step);
Changed in version 3.2: The parameter type for the slice parameter was PySliceObject* before.
Changed in version 3.6.1: If Py_LIMITED_API is not set or set to the value between 0x03050400 and
0x03060000 (not including) or 0x03060100 or higher PySlice_GetIndicesEx() is implemented as a
macro using PySlice_Unpack() and PySlice_AdjustIndices(). Arguments start, stop and step are
evaluated more than once.
Deprecated since version 3.6.1: If Py_LIMITED_API is set to the value less than 0x03050400 or between
0x03060000 and 0x03060100 (not including) PySlice_GetIndicesEx() is a deprecated function.
Ellipsis Object
PyTypeObject PyEllipsis_Type
Part of the Stable ABI. The type of Python Ellipsis object. Same as types.EllipsisType in the Python
layer.
PyObject *Py_Ellipsis
The Python Ellipsis object. This object has no methods. Like Py_None, it is an immortal singleton object.
Changed in version 3.12: Py_Ellipsis is immortal.
® Note
This function returns a borrowed reference to the referenced object. This means that you should always
call Py_INCREF() on the object except when it cannot be destroyed before the last usage of the borrowed
reference.
Deprecated since version 3.13, will be removed in version 3.15: Use PyWeakref_GetRef() instead.
PyObject *PyWeakref_GET_OBJECT(PyObject *ref)
Return value: Borrowed reference. Similar to PyWeakref_GetObject(), but does no error checking.
Deprecated since version 3.13, will be removed in version 3.15: Use PyWeakref_GetRef() instead.
int PyWeakref_IsDead(PyObject *ref)
Test if the weak reference ref is dead. Returns 1 if the reference is dead, 0 if it is alive, and -1 with an error
set if ref is not a weak reference object.
Added in version 3.14.
void PyObject_ClearWeakRefs(PyObject *object)
Part of the Stable ABI. This function is called by the tp_dealloc handler to clear weak references.
This iterates through the weak references for object and calls callbacks for those references which have one. It
returns when all callbacks have been attempted.
void PyUnstable_Object_ClearWeakRefsNoCallbacks(PyObject *object)
8.6.8 Capsules
Refer to using-capsules for more information on using these objects.
Added in version 3.1.
type PyCapsule
This subtype of PyObject represents an opaque value, useful for C extension modules who need to pass an
opaque value (as a void* pointer) through Python code to other C code. It is often used to make a C function
pointer defined in one module available to other modules, so the regular import mechanism can be used to
access C APIs defined in dynamically loaded modules.
type PyCapsule_Destructor
Part of the Stable ABI. The type of a destructor callback for a capsule. Defined as:
It is legal for a capsule to have a NULL context. This makes a NULL return code somewhat ambiguous; use
PyCapsule_IsValid() or PyErr_Occurred() to disambiguate.
PyTypeObject PyFrame_Type
The type of frame objects. It is the same object as types.FrameType in the Python layer.
Changed in version 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.
Changed in version 3.11: Previously, this function was only available after including <frameobject.h>.
PyFrameObject *PyFrame_GetBack(PyFrameObject *frame)
Return value: New reference. Get the frame next outer frame.
Return a strong reference, or NULL if frame has no outer frame.
Added in version 3.9.
PyObject *PyFrame_GetBuiltins(PyFrameObject *frame)
Return value: New reference. Get the frame’s f_builtins attribute.
Return a strong reference. The result cannot be NULL.
Added in version 3.11.
PyCodeObject *PyFrame_GetCode(PyFrameObject *frame)
Return value: New reference. Part of the Stable ABI since version 3.10. Get the frame code.
Return a strong reference.
The result (frame code) cannot be NULL.
Added in version 3.9.
PyObject *PyFrame_GetGenerator(PyFrameObject *frame)
Return value: New reference. Get the generator, coroutine, or async generator that owns this frame, or NULL if
this frame is not owned by a generator. Does not raise an exception, even if the return value is NULL.
Return a strong reference, or NULL.
Added in version 3.11.
PyObject *PyFrame_GetGlobals(PyFrameObject *frame)
Return value: New reference. Get the frame’s f_globals attribute.
Return a strong reference. The result cannot be NULL.
Added in version 3.11.
int PyFrame_GetLasti(PyFrameObject *frame)
Get the frame’s f_lasti attribute.
Returns -1 if frame.f_lasti is None.
Added in version 3.11.
PyObject *PyFrame_GetVar(PyFrameObject *frame, PyObject *name)
Return value: New reference. Get the variable name of frame.
• Return a strong reference to the variable value on success.
• Raise NameError and return NULL if the variable does not exist.
• Raise an exception and return NULL on error.
name type must be a str.
Added in version 3.12.
Internal Frames
Unless using PEP 523, you will not need this.
struct _PyInterpreterFrame
The interpreter’s internal frame representation.
Added in version 3.11.
PyObject *PyUnstable_InterpreterFrame_GetCode(struct _PyInterpreterFrame *frame);
® Note
In Python 3.7.1 the signatures of all context variables C APIs were changed to use PyObject pointers instead
of PyContext, PyContextVar, and PyContextToken, e.g.:
// in 3.7.0:
PyContext *PyContext_New(void);
// in 3.7.1+:
PyObject *PyContext_New(void);
This section details the public C API for the contextvars module.
type PyContext
The C structure used to represent a contextvars.Context object.
type PyContextVar
The C structure used to represent a contextvars.ContextVar object.
type PyContextToken
The C structure used to represent a contextvars.Token object.
PyTypeObject PyContext_Type
The type object representing the context type.
PyTypeObject PyContextVar_Type
The type object representing the context variable type.
PyTypeObject PyContextToken_Type
The type object representing the context variable token type.
Type-check macros:
int PyContext_CheckExact(PyObject *o)
Return true if o is of type PyContext_Type. o must not be NULL. This function always succeeds.
int PyContextVar_CheckExact(PyObject *o)
Return true if o is of type PyContextVar_Type. o must not be NULL. This function always succeeds.
int PyContextToken_CheckExact(PyObject *o)
Return true if o is of type PyContextToken_Type. o must not be NULL. This function always succeeds.
Context object management functions:
PyObject *PyContext_New(void)
Return value: New reference. Create a new empty context object. Returns NULL if an error has occurred.
PyObject *PyContext_Copy(PyObject *ctx)
Return value: New reference. Create a shallow copy of the passed ctx context object. Returns NULL if an error
has occurred.
PyObject *PyContext_CopyCurrent(void)
Return value: New reference. Create a shallow copy of the current thread context. Returns NULL if an error
has occurred.
If the callback returns with an exception set, it must return -1; this exception will be printed as an unraisable
exception using PyErr_FormatUnraisable(). Otherwise it should return 0.
There may already be a pending exception set on entry to the callback. In this case, the callback should return 0
with the same exception still set. This means the callback may not call any other API that can set an exception
unless it saves and clears the exception state first, and restores it before returning.
Added in version 3.14.
Context variable functions:
PyObject *PyContextVar_New(const char *name, PyObject *def)
Return value: New reference. Create a new ContextVar object. The name parameter is used for introspection
and debug purposes. The def parameter specifies a default value for the context variable, or NULL for no default.
If an error has occurred, this function returns NULL.
int PyContextVar_Get(PyObject *var, PyObject *default_value, PyObject **value)
Get the value of a context variable. Returns -1 if an error has occurred during lookup, and 0 if no error
occurred, whether or not a value was found.
If the context variable was found, value will be a pointer to it. If the context variable was not found, value will
point to:
• default_value, if not NULL;
• the default value of var, if not NULL;
• NULL
Except for NULL, the function returns a new reference.
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.
...
static PyMethodDef my_obj_methods[] = {
// Other methods.
...
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}
...
}
µ See also
NINE
See Python Initialization Configuration for details on how to configure the interpreter prior to initialization.
213
The Python/C API, Release 3.14.0a7
– Py_GetCopyright()
– Py_GetPlatform()
– Py_GetVersion()
– Py_IsInitialized()
• Utilities:
– Py_DecodeLocale()
– the status reporting and utility functions covered in Python Initialization Configuration
• Memory allocators:
– PyMem_RawMalloc()
– PyMem_RawRealloc()
– PyMem_RawCalloc()
– PyMem_RawFree()
• Synchronization:
– PyMutex_Lock()
– PyMutex_Unlock()
® Note
Despite their apparent similarity to some of the functions listed above, the following functions should not be
called before the interpreter has been initialized: Py_EncodeLocale(), Py_GetPath(), Py_GetPrefix(),
Py_GetExecPrefix(), Py_GetProgramFullPath(), Py_GetPythonHome(), Py_GetProgramName(),
PyEval_InitThreads(), and Py_RunMain().
int Py_DontWriteBytecodeFlag
This API is kept for backward compatibility: setting PyConfig.write_bytecode should be used instead,
see Python Initialization Configuration.
If set to non-zero, Python won’t try to write .pyc files on the import of source modules.
Set by the -B option and the PYTHONDONTWRITEBYTECODE environment variable.
Deprecated since version 3.12, will be removed in version 3.15.
int Py_FrozenFlag
This API is kept for backward compatibility: setting PyConfig.pathconfig_warnings should be used
instead, see Python Initialization Configuration.
Suppress error messages when calculating the module search path in Py_GetPath().
Private flag used by _freeze_module and frozenmain programs.
Deprecated since version 3.12, will be removed in version 3.15.
int Py_HashRandomizationFlag
This API is kept for backward compatibility: setting PyConfig.hash_seed and PyConfig.
use_hash_seed should be used instead, see Python Initialization Configuration.
® Note
On Windows, changes the console mode from O_TEXT to O_BINARY, which will also affect non-Python
uses of the console using the C Runtime.
int Py_IsFinalizing()
Part of the Stable ABI since version 3.13. Return true (non-zero) if the main Python interpreter is shutting
down. Return false (zero) otherwise.
Added in version 3.13.
int Py_FinalizeEx()
Part of the Stable ABI since version 3.6. Undo all initializations made by Py_Initialize() and subsequent
use of Python/C API functions, and destroy all sub-interpreters (see Py_NewInterpreter() below) that
were created and not yet destroyed since the last call to Py_Initialize(). This is a no-op when called for
a second time (without calling Py_Initialize() again first).
Since this is the reverse of Py_Initialize(), it should be called in the same thread with the same interpreter
active. That means the main thread and the main interpreter. This should never be called while Py_RunMain()
is running.
Normally the return value is 0. If there were errors during finalization (flushing buffered data), -1 is returned.
Note that Python will do a best effort at freeing all memory allocated by the Python interpreter. Therefore,
any C-Extension should make sure to correctly clean up all of the preveiously allocated PyObjects before using
them in subsequent calls to Py_Initialize(). Otherwise it could introduce vulnerabilities and incorrect
behavior.
This function is provided for a number of reasons. An embedding application might want to restart Python
without having to restart the application itself. An application that has loaded the Python interpreter from a
dynamically loadable library (or DLL) might want to free all memory allocated by Python before unloading the
DLL. During a hunt for memory leaks in an application a developer might want to free all memory allocated
by Python before exiting from the application.
Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may
cause destructors (__del__() methods) to fail when they depend on other objects (even functions) or mod-
ules. 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. Interned strings will all be deallocated regardless of their
reference count. Some memory allocated by extension modules may not be freed. Some extensions may not
work properly if their initialization routine is called more than once; this can happen if an application calls
Py_Initialize() and Py_FinalizeEx() more than once. Py_FinalizeEx() must not be called recur-
sively from within itself. Therefore, it must not be called by any code that may be run as part of the interpreter
shutdown process, such as atexit handlers, object finalizers, or any code that may be run while flushing the
stdout and stderr files.
Raises an auditing event cpython._PySys_ClearAuditHooks with no arguments.
Added in version 3.6.
void Py_Finalize()
Part of the Stable ABI. This is a backwards-compatible version of Py_FinalizeEx() that disregards the
return value.
int Py_BytesMain(int argc, char **argv)
Part of the Stable ABI since version 3.8. Similar to Py_Main() but argv is an array of bytes strings, allowing
the calling application to delegate the text decoding step to the CPython runtime.
Added in version 3.8.
int Py_Main(int argc, wchar_t **argv)
Part of the Stable ABI. The main program for the standard interpreter, encapsulating a full initializa-
tion/finalization cycle, as well as additional behaviour to implement reading configurations settings from the
environment and command line, and then executing __main__ in accordance with using-on-cmdline.
This is made available for programs which wish to support the full CPython command line interface, rather
than just embedding a Python runtime in a larger application.
The argc and argv parameters are similar to those which are passed to a C program’s main() function, except
that the argv entries are first converted to wchar_t using Py_DecodeLocale(). It is also important to note
that the argument list entries may be modified to point to strings other than those passed in (however, the
contents of the strings pointed to by the argument list are not modified).
The return value will be 0 if the interpreter exits normally (i.e., without an exception), 1 if the interpreter exits
due to an exception, or 2 if the argument list does not represent a valid Python command line.
Note that if an otherwise unhandled SystemExit is raised, this function will not return 1, but exit the process,
as long as Py_InspectFlag is not set. If Py_InspectFlag is set, execution will drop into the interactive
Python prompt, at which point a second otherwise unhandled SystemExit will still exit the process, while
any other means of exiting will set the return value as described above.
In terms of the CPython runtime configuration APIs documented in the runtime configuration section (and
without accounting for error handling), Py_Main is approximately equivalent to:
PyConfig config;
PyConfig_InitPythonConfig(&config);
PyConfig_SetArgv(&config, argc, argv);
Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
Py_RunMain();
In normal usage, an embedding application will call this function instead of calling Py_Initialize(),
Py_InitializeEx() or Py_InitializeFromConfig() directly, and all settings will be applied as de-
scribed elsewhere in this documentation. If this function is instead called after a preceding runtime initial-
ization API call, then exactly which environmental and command line configuration settings will be updated
is version dependent (as it depends on which settings correctly support being modified after they have already
been set once when the runtime was first initialized).
int Py_RunMain(void)
Executes the main module in a fully configured CPython runtime.
Executes the command (PyConfig.run_command), the script (PyConfig.run_filename) or the module
(PyConfig.run_module) specified on the command line or in the configuration. If none of these values are
set, runs the interactive Python prompt (REPL) using the __main__ module’s global namespace.
If PyConfig.inspect is not set (the default), the return value will be 0 if the interpreter exits normally (that
is, without raising an exception), or 1 if the interpreter exits due to an exception. If an otherwise unhandled
SystemExit is raised, the function will immediately exit the process instead of returning 1.
If PyConfig.inspect is set (such as when the -i option is used), rather than returning when the interpreter
exits, execution will instead resume in an interactive Python prompt (REPL) using the __main__ module’s
global namespace. If the interpreter exited with an exception, it is immediately raised in the REPL session.
The function return value is then determined by the way the REPL session terminates: returning 0 if the session
terminates without raising an unhandled exception, exiting immediately for an unhandled SystemExit, and
returning 1 for any other unhandled exception.
This function always finalizes the Python interpreter regardless of whether it returns a value or immediately
exits the process due to an unhandled SystemExit exception.
See Python Configuration for an example of a customized Python that always runs in isolated mode using
Py_RunMain().
Register an atexit callback for the target interpreter interp. This is similar to Py_AtExit(), but takes an
explicit interpreter and data pointer for the callback.
are another platform, and Intel machines running Linux are yet another platform. Different major revisions of
the same operating system generally also form different platforms. Non-Unix operating systems are a different
story; the installation strategies on those systems are so different that the prefix and exec-prefix are meaning-
less, and set to the empty string. Note that compiled Python bytecode files are platform independent (but not
independent from the Python version by which they were compiled!).
System administrators will know how to configure the mount or automount programs to share /usr/local
between platforms while having /usr/local/plat be a different filesystem for each platform.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Changed in version 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Use
PyConfig_Get("base_exec_prefix") (sys.base_exec_prefix) instead. Use
PyConfig_Get("exec_prefix") (sys.exec_prefix) if virtual environments need to be handled.
wchar_t *Py_GetProgramFullPath()
Part of the Stable ABI. Return the full program name of the Python executable; this is computed as a side-effect
of deriving the default module search path from the program name (set by PyConfig.program_name). The
returned string points into static storage; the caller should not modify its value. The value is available to Python
code as sys.executable.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Changed in version 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Use PyConfig_Get("executable")
(sys.executable) instead.
wchar_t *Py_GetPath()
Part of the Stable ABI. Return the default module search path; this is computed from the program name (set
by PyConfig.program_name) and some environment variables. The returned string consists of a series of
directory names separated by a platform dependent delimiter character. The delimiter character is ':' on
Unix and macOS, ';' on Windows. The returned string points into static storage; the caller should not modify
its value. The list sys.path is initialized with this value on interpreter startup; it can be (and usually is)
modified later to change the search path for loading modules.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Changed in version 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Use
PyConfig_Get("module_search_paths") (sys.path) instead.
The first word (up to the first space character) is the current Python version; the first characters are the major
and minor version separated by a period. The returned string points into static storage; the caller should not
modify its value. The value is available to Python code as sys.version.
See also the Py_Version constant.
const char *Py_GetPlatform()
Part of the Stable ABI. Return the platform identifier for the current platform. On Unix, this is formed from
the “official” name of the operating system, converted to lower case, followed by the major revision number;
e.g., for Solaris 2.x, which is also known as SunOS 5.x, the value is 'sunos5'. On macOS, it is 'darwin'.
On Windows, it is 'win'. The returned string points into static storage; the caller should not modify its value.
The value is available to Python code as sys.platform.
The returned string points into static storage; the caller should not modify its value. The value is available to
Python code as sys.copyright.
const char *Py_GetCompiler()
Part of the Stable ABI. Return an indication of the compiler used to build the current Python version, in square
brackets, for example:
"[GCC 2.7.2.2]"
The returned string points into static storage; the caller should not modify its value. The value is available to
Python code as part of the variable sys.version.
const char *Py_GetBuildInfo()
Part of the Stable ABI. Return information about the sequence number and build date and time of the current
Python interpreter instance, for example
The returned string points into static storage; the caller should not modify its value. The value is available to
Python code as part of the variable sys.version.
void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Part of the Stable ABI. This API is kept for backward compatibility: setting PyConfig.argv , PyConfig.
parse_argv and PyConfig.safe_path should be used instead, see Python Initialization Configuration.
Set sys.argv based on argc and argv. These parameters are similar to those passed to the program’s
main() function with the difference that the first entry should refer to the script file to be executed rather
than the executable hosting the Python interpreter. If there isn’t a script that will be run, the first entry in
argv can be an empty string. If this function fails to initialize sys.argv, a fatal condition is signalled using
Py_FatalError().
If updatepath is zero, this is all the function does. If updatepath is non-zero, the function also modifies sys.
path according to the following algorithm:
• If the name of an existing script is passed in argv[0], the absolute path of the directory where the script
is located is prepended to sys.path.
• Otherwise (that is, if argc is 0 or argv[0] doesn’t point to an existing file name), an empty string is
prepended to sys.path, which is the same as prepending the current working directory (".").
Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.
See also PyConfig.orig_argv and PyConfig.argv members of the Python Initialization Configuration.
® Note
It is recommended that applications embedding the Python interpreter for purposes other than executing a
single script pass 0 as updatepath, and update sys.path themselves if desired. See CVE 2008-5983.
On versions before 3.1.3, you can achieve the same effect by manually popping the first sys.path element
after having called PySys_SetArgv(), for example using:
PyRun_SimpleString("import sys; sys.path.pop(0)\n");
This function works like PySys_SetArgvEx() with updatepath set to 1 unless the python interpreter was
started with the -I.
Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.
See also PyConfig.orig_argv and PyConfig.argv members of the Python Initialization Configuration.
Changed in version 3.4: The updatepath value depends on -I.
Deprecated since version 3.11, will be removed in version 3.15.
void Py_SetPythonHome(const wchar_t *home)
Part of the Stable ABI. This API is kept for backward compatibility: setting PyConfig.home should be used
instead, see Python Initialization Configuration.
Set the default “home” directory, that is, the location of the standard Python libraries. See PYTHONHOME for
the meaning of the argument string.
The argument should point to a zero-terminated character string in static storage whose contents will not change
for the duration of the program’s execution. No code in the Python interpreter will change the contents of this
storage.
Use Py_DecodeLocale() to decode a bytes string to get a wchar_t* string.
Deprecated since version 3.11, will be removed in version 3.15.
wchar_t *Py_GetPythonHome()
Part of the Stable ABI. Return the default “home”, that is, the value set by PyConfig.home, or the value of
the PYTHONHOME environment variable if it is set.
This function should not be called before Py_Initialize(), otherwise it returns NULL.
Changed in version 3.10: It now returns NULL if called before Py_Initialize().
Deprecated since version 3.13, will be removed in version 3.15: Use PyConfig_Get("home") or the
PYTHONHOME environment variable instead.
Py_BEGIN_ALLOW_THREADS
... Do some blocking I/O operation ...
Py_END_ALLOW_THREADS
The Py_BEGIN_ALLOW_THREADS macro opens a new block and declares a hidden local variable; the
Py_END_ALLOW_THREADS macro closes the block.
PyThreadState *_save;
_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
PyEval_RestoreThread(_save);
® Note
Calling system I/O functions is the most common use case for detaching the thread state, but it can also be useful
before calling long-running computations which don’t need access to Python objects, such as compression or
cryptographic functions operating over memory buffers. For example, the standard zlib and hashlib modules
detach the thread state when compressing or hashing data.
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
Note that the PyGILState_* functions assume there is only one global interpreter (created automatically by
Py_Initialize()). Python supports the creation of additional interpreters (using Py_NewInterpreter()),
but mixing multiple interpreters and the PyGILState_* API is unsupported.
cooperating threads. Threads belonging to the same interpreter share their module administration and a few
other internal items. There are no public members in this structure.
Threads belonging to different interpreters initially share nothing, except process state like available memory,
open file descriptors and such. The global interpreter lock is also shared by all threads, regardless of to which
interpreter they belong.
type PyThreadState
Part of the Limited API (as an opaque struct). 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. Deprecated function which does nothing.
In Python 3.6 and older, this function created the GIL if it didn’t exist.
Changed in version 3.9: The function now does nothing.
Changed in version 3.7: This function is now called by Py_Initialize(), so you don’t have to call it yourself
anymore.
Changed in version 3.2: This function cannot be called before Py_Initialize() anymore.
Deprecated since version 3.9.
PyThreadState *PyEval_SaveThread()
Part of the Stable ABI. Detach the attached thread state and return it. The thread will have no thread state upon
returning.
void PyEval_RestoreThread(PyThreadState *tstate)
Part of the Stable ABI. Set the attached thread state to tstate. The passed thread state should not be attached,
otherwise deadlock ensues. tstate will be attached upon returning.
® Note
Calling this function from a thread when the runtime is finalizing will hang the thread until the program
exits, even if the thread was not created by Python. Refer to Cautions regarding runtime finalization for
more details.
Changed in version 3.14: Hangs the current thread, rather than terminating it, if called while the interpreter is
finalizing.
PyThreadState *PyThreadState_Get()
Part of the Stable ABI. Return the attached thread state. If the thread has no attached thread state, (such as
when inside of Py_BEGIN_ALLOW_THREADS block), then this issues a fatal error (so that the caller needn’t
check for NULL).
See also PyThreadState_GetUnchecked().
PyThreadState *PyThreadState_GetUnchecked()
Similar to PyThreadState_Get(), but don’t kill the process with a fatal error if it is NULL. The caller is
responsible to check if the result is NULL.
Added in version 3.13: In Python 3.5 to 3.12, the function was private and known as
_PyThreadState_UncheckedGet().
This function is safe to call without an attached thread state; it will simply return NULL indicating that there
was no prior thread state.
The following functions use thread-local storage, and are not compatible with sub-interpreters:
PyGILState_STATE PyGILState_Ensure()
Part of the Stable ABI. Ensure that the current thread is ready to call the Python C API regardless of the
current state of Python, or of the attached thread state. This may be called as many times as desired by a
thread as long as each call is matched with a call to PyGILState_Release(). In general, other thread-
related APIs may be used between PyGILState_Ensure() and PyGILState_Release() calls as long
as the thread state is restored to its previous state before the Release(). For example, normal usage of the
Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros is acceptable.
The return value is an opaque “handle” to the attached thread state when PyGILState_Ensure() was called,
and must be passed to PyGILState_Release() to ensure Python is left in the same state. Even though
recursive calls are allowed, these handles cannot be shared - each unique call to PyGILState_Ensure()
must save the handle for its call to PyGILState_Release().
When the function returns, there will be an attached thread state and the thread will be able to call arbitrary
Python code. Failure is a fatal error.
® Note
Calling this function from a thread when the runtime is finalizing will hang the thread until the program
exits, even if the thread was not created by Python. Refer to Cautions regarding runtime finalization for
more details.
Changed in version 3.14: Hangs the current thread, rather than terminating it, if called while the interpreter is
finalizing.
void PyGILState_Release(PyGILState_STATE)
Part of the Stable ABI. Release any resources previously acquired. After this call, Python’s state will be the same
as it was prior to the corresponding PyGILState_Ensure() call (but generally this state will be unknown to
the caller, hence the use of the GILState API).
Every call to PyGILState_Ensure() must be matched by a call to PyGILState_Release() on the same
thread.
PyThreadState *PyGILState_GetThisThreadState()
Part of the Stable ABI. Get the attached thread state for this thread. May return NULL if no GILState API
has been used on the current thread. Note that the main thread always has such a thread-state, even if no
auto-thread-state call has been made on the main thread. This is mainly a helper/diagnostic function.
int PyGILState_Check()
Return 1 if the current thread is holding the GIL and 0 otherwise. This function can be called from any thread
at any time. Only if it has had its Python thread state initialized and currently is holding the GIL will it return
1. This is mainly a helper/diagnostic function. It can be useful for example in callback contexts or memory
allocation functions when knowing that the GIL is locked can allow the caller to perform sensitive actions or
otherwise behave differently.
Added in version 3.4.
The following macros are normally used without a trailing semicolon; look for example usage in the Python source
distribution.
Py_BEGIN_ALLOW_THREADS
Part of the Stable ABI. This macro expands to { PyThreadState *_save; _save =
PyEval_SaveThread();. Note that it contains an opening brace; it must be matched with a follow-
ing Py_END_ALLOW_THREADS macro. See above for further discussion of this macro.
Py_END_ALLOW_THREADS
Part of the Stable ABI. This macro expands to PyEval_RestoreThread(_save); }. Note that it contains
a closing brace; it must be matched with an earlier Py_BEGIN_ALLOW_THREADS macro. See above for further
discussion of this macro.
Py_BLOCK_THREADS
Part of the Stable ABI. This macro expands to PyEval_RestoreThread(_save);: it is equivalent to
Py_END_ALLOW_THREADS without the closing brace.
Py_UNBLOCK_THREADS
Part of the Stable ABI. This macro expands to _save = PyEval_SaveThread();: it is equivalent to
Py_BEGIN_ALLOW_THREADS without the opening brace and variable declaration.
Return a strong reference to the __main__ module object for the given interpreter.
The caller must have an attached thread state.
® Note
Calling this function from a thread when the runtime is finalizing will hang the thread until the program
exits, even if the thread was not created by Python. Refer to Cautions regarding runtime finalization for
more details.
int gil
This determines the operation of the GIL for the sub-interpreter. It may be one of the following:
PyInterpreterConfig_DEFAULT_GIL
Use the default selection (PyInterpreterConfig_SHARED_GIL).
PyInterpreterConfig_SHARED_GIL
Use (share) the main interpreter’s GIL.
PyInterpreterConfig_OWN_GIL
Use the sub-interpreter’s own GIL.
If this is PyInterpreterConfig_OWN_GIL then PyInterpreterConfig.use_main_obmalloc
must be 0.
PyStatus Py_NewInterpreterFromConfig(PyThreadState **tstate_p, const PyInterpreterConfig *config)
Create a new sub-interpreter. This is an (almost) totally separate environment for the execution of Python
code. In particular, the new interpreter has separate, independent versions of all imported modules, including
the fundamental modules builtins, __main__ and sys. The table of loaded modules (sys.modules) and
the module search path (sys.path) are also separate. The new environment has no sys.argv variable. It
has new standard I/O stream file objects sys.stdin, sys.stdout and sys.stderr (however these refer
to the same underlying file descriptors).
The given config controls the options with which the interpreter is initialized.
Upon success, tstate_p will be set to the first thread state created in the new sub-interpreter. This thread state
is attached. 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 attached thread state, which might not exist.
Like all other Python/C API functions, an attached thread state must be present before calling this function,
but it might be detached upon returning. On success, the returned thread state will be attached. If the sub-
interpreter is created with its own GIL then the attached thread state of the calling interpreter will be detached.
When the function returns, the new interpreter’s thread state will be attached to the current thread and the
previous interpreter’s attached thread state will remain detached.
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,
.allow_exec = 0,
.allow_threads = 1,
.allow_daemon_threads = 0,
.check_multi_interp_extensions = 1,
.gil = PyInterpreterConfig_OWN_GIL,
};
PyThreadState *tstate = NULL;
PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
Note that the config is used only briefly and does not get modified. During initialization the config’s values are
converted into various PyInterpreterState values. A read-only copy of the config may be stored internally
on the PyInterpreterState.
Extension modules are shared between (sub-)interpreters as follows:
to insert objects created in one sub-interpreter into a namespace of another (sub-)interpreter; this should be avoided
if possible.
Special care should be taken to avoid sharing user-defined functions, methods, instances or classes between sub-
interpreters, since import operations executed by such objects may affect the wrong (sub-)interpreter’s dictionary of
loaded modules. It is equally important to avoid sharing objects from which the above are reachable.
Also note that combining this functionality with PyGILState_* APIs is delicate, because these APIs assume a bijec-
tion between Python thread states and OS-level threads, an assumption broken by the presence of sub-interpreters. It
is highly recommended that you don’t switch sub-interpreters between a pair of matching PyGILState_Ensure()
and PyGILState_Release() calls. Furthermore, extensions (such as ctypes) using these APIs to allow calling
of Python code from non-Python created threads will probably be broken when using sub-interpreters.
Á Warning
This is a low-level function, only useful for very special cases. There is no guarantee that func will be
called as quick as possible. If the main thread is busy executing a system call, func won’t be called before
the system call returns. This function is generally not suitable for calling Python code from arbitrary C
threads. Instead, use the PyGILState API.
allows trace functions to be installed per-thread, and the basic events reported to the trace function are the same as
had been reported to the Python-level trace functions in previous versions.
typedef int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
The type of the trace function registered using PyEval_SetProfile() and PyEval_SetTrace().
The first parameter is the object passed to the registration function as obj, frame is the frame ob-
ject to which the event pertains, what is one of the constants PyTrace_CALL, PyTrace_EXCEPTION ,
PyTrace_LINE, PyTrace_RETURN , PyTrace_C_CALL, PyTrace_C_EXCEPTION , PyTrace_C_RETURN ,
or PyTrace_OPCODE, and arg depends on the value of what:
int PyTrace_CALL
The value of the what parameter to a Py_tracefunc function when a new call to a function or method is
being reported, or a new entry into a generator. Note that the creation of the iterator for a generator function
is not reported as there is no control transfer to the Python bytecode in the corresponding frame.
int PyTrace_EXCEPTION
The value of the what parameter to a Py_tracefunc function when an exception has been raised. The
callback function is called with this value for what when after any bytecode is processed after which the
exception becomes set within the frame being executed. The effect of this is that as exception propagation
causes the Python stack to unwind, the callback is called upon return to each frame as the exception propagates.
Only trace functions receives these events; they are not needed by the profiler.
int PyTrace_LINE
The value passed as the what parameter to a Py_tracefunc function (but not a profiling function) when a
line-number event is being reported. It may be disabled for a frame by setting f_trace_lines to 0 on that
frame.
int PyTrace_RETURN
The value for the what parameter to Py_tracefunc functions when a call is about to return.
int PyTrace_C_CALL
The value for the what parameter to Py_tracefunc functions when a C function is about to be called.
int PyTrace_C_EXCEPTION
The value for the what parameter to Py_tracefunc functions when a C function has raised an exception.
int PyTrace_C_RETURN
The value for the what parameter to Py_tracefunc functions when a C function has returned.
int PyTrace_OPCODE
The value for the what parameter to Py_tracefunc functions (but not profiling functions) when a new op-
code is about to be executed. This event is not emitted by default: it must be explicitly requested by setting
f_trace_opcodes to 1 on the frame.
® Note
None of these API functions handle memory management on behalf of the void* values. You need to allocate
and deallocate them yourself. If the void* values happen to be PyObject*, these functions don’t do refcount
operations on them either.
µ See also
type Py_tss_t
This data structure represents the state of a thread key, the definition of which may depend on the underlying
TLS implementation, and it has an internal field representing the key’s initialization state. There are no public
members in this structure.
When Py_LIMITED_API is not defined, static allocation of this type by Py_tss_NEEDS_INIT is allowed.
Py_tss_NEEDS_INIT
This macro expands to the initializer for Py_tss_t variables. Note that this macro won’t be defined with
Py_LIMITED_API.
Dynamic Allocation
Dynamic allocation of the Py_tss_t, required in extension modules built with Py_LIMITED_API, where static
allocation of this type is not possible due to its implementation being opaque at build time.
Py_tss_t *PyThread_tss_alloc()
Part of the Stable ABI since version 3.7. Return a value which is the same state as a value initialized with
Py_tss_NEEDS_INIT , or NULL in the case of dynamic allocation failure.
® Note
A freed key becomes a dangling pointer. You should reset the key to NULL.
Methods
The parameter key of these functions must not be NULL. Moreover, the behaviors of PyThread_tss_set()
and PyThread_tss_get() are undefined if the given Py_tss_t has not been initialized by
PyThread_tss_create().
® Note
This version of the API does not support platforms where the native TLS key is defined in a way that cannot be
safely cast to int. On such platforms, PyThread_create_key() will return immediately with a failure status,
and the other TLS functions will all be no-ops on such platforms.
Due to the compatibility problem noted above, this version of the API should not be used in new code.
int PyThread_create_key()
Part of the Stable ABI.
void PyThread_delete_key(int key)
Part of the Stable ABI.
int PyThread_set_key_value(int key, void *value)
Part of the Stable ABI.
void *PyThread_get_key_value(int key)
Part of the Stable ABI.
void PyThread_delete_key_value(int key)
Part of the Stable ABI.
void PyThread_ReInitTLS()
Part of the Stable ABI.
Instances of PyMutex should not be copied or moved. Both the contents and address of a PyMutex are
meaningful, and it must remain at a fixed, writable location in memory.
® Note
A PyMutex currently occupies one byte, but the size should be considered unstable. The size may change
in future Python releases without a deprecation period.
® Note
Operations that need to lock two objects at once must use Py_BEGIN_CRITICAL_SECTION2. You cannot use
nested critical sections to lock more than one object at once, because the inner critical section may suspend the
outer critical sections. This API does not provide a way to lock more than two objects at once.
Example usage:
static PyObject *
set_field(MyObject *self, PyObject *value)
{
Py_BEGIN_CRITICAL_SECTION(self);
Py_SETREF(self->field, Py_XNewRef(value));
Py_END_CRITICAL_SECTION();
Py_RETURN_NONE;
}
In the above example, Py_SETREF calls Py_DECREF , which can call arbitrary code through an object’s dealloca-
tion function. The critical section API avoids potential deadlocks due to reentrancy and lock ordering by allow-
ing the runtime to temporarily suspend the critical section if the code triggered by the finalizer blocks and calls
PyEval_SaveThread().
Py_BEGIN_CRITICAL_SECTION(op)
Acquires the per-object lock for the object op and begins a critical section.
In the free-threaded build, this macro expands to:
{
PyCriticalSection _py_cs;
PyCriticalSection_Begin(&_py_cs, (PyObject*)(op))
PyCriticalSection_End(&_py_cs);
}
Py_BEGIN_CRITICAL_SECTION2(a, b)
Acquires the per-objects locks for the objects a and b and begins a critical section. The locks are acquired in
a consistent order (lowest address first) to avoid lock ordering deadlocks.
In the free-threaded build, this macro expands to:
{
PyCriticalSection2 _py_cs2;
PyCriticalSection2_Begin(&_py_cs2, (PyObject*)(a), (PyObject*)(b))
PyCriticalSection2_End(&_py_cs2);
}
TEN
µ See also
10.1.1 Example
Example of customized Python always running with the Python Development Mode enabled; return -1 on error:
int init_python(void)
{
PyInitConfig *config = PyInitConfig_Create();
if (config == NULL) {
printf("PYTHON INIT ERROR: memory allocation failed\n");
return -1;
}
error:
{
// Display the error message.
//
// This uncommon braces style is used, because you cannot make
// goto targets point to variable declarations.
const char *err_msg;
(continues on next page)
243
The Python/C API, Release 3.14.0a7
10.1.6 Module
int PyInitConfig_AddModule(PyInitConfig *config, const char *name, PyObject *(*initfunc)(void))
Add a built-in extension module to the table of built-in modules.
The new module can be imported by the name name, and uses the function initfunc as the initialization function
called on the first attempted import.
• Return 0 on success.
• Set an error in config and return -1 on error.
If Python is initialized multiple times, PyInitConfig_AddModule() must be called at each Python initial-
ization.
Similar to the PyImport_AppendInittab() function.
Visibility:
• Public: Can by get by PyConfig_Get() and set by PyConfig_Set().
• Read-only: Can by get by PyConfig_Get(), but cannot be set by PyConfig_Set().
• The Isolated Configuration can be used to embed Python into an application. It isolates Python from the system.
For example, environment variables are ignored, the LC_CTYPE locale is left unchanged and no signal handler
is registered.
The Py_RunMain() function can be used to write a customized Python program.
See also Initialization, Finalization, and Threads.
µ See also
10.4.1 Example
Example of customized Python always running in isolated mode:
PyConfig config;
PyConfig_InitPythonConfig(&config);
config.isolated = 1;
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.4.2 PyWideStringList
type PyWideStringList
List of wchar_t* strings.
If length is non-zero, items must be non-NULL and all strings must be non-NULL.
Methods:
10.4.3 PyStatus
type PyStatus
Structure to store an initialization function status: success, error or exit.
For an error, it can store the C function name which created the error.
Structure fields:
int exitcode
Exit code. Argument passed to exit().
const char *err_msg
Error message.
const char *func
Name of the function which created an error, can be NULL.
Functions to create a status:
PyStatus PyStatus_Ok(void)
Success.
PyStatus PyStatus_Error(const char *err_msg)
Initialization error with a message.
err_msg must not be NULL.
PyStatus PyStatus_NoMemory(void)
Memory allocation failure (out of memory).
PyStatus PyStatus_Exit(int exitcode)
Exit Python with the specified exit code.
Functions to handle a status:
int PyStatus_Exception(PyStatus status)
Is the status an error or an exit? If true, the exception must be handled; by calling
Py_ExitStatusException() for example.
® Note
Internally, Python uses macros which set PyStatus.func, whereas functions to create a status set func to
NULL.
Example:
10.4.4 PyPreConfig
type PyPreConfig
Structure used to preinitialize Python.
Function to initialize a preconfiguration:
void PyPreConfig_InitPythonConfig(PyPreConfig *preconfig)
Initialize the preconfiguration with Python Configuration.
void PyPreConfig_InitIsolatedConfig(PyPreConfig *preconfig)
Initialize the preconfiguration with Isolated Configuration.
Structure fields:
int allocator
Name of the Python memory allocators:
• PYMEM_ALLOCATOR_NOT_SET (0): don’t change memory allocators (use defaults).
• PYMEM_ALLOCATOR_DEFAULT (1): default memory allocators.
• PYMEM_ALLOCATOR_DEBUG (2): default memory allocators with debug hooks.
• PYMEM_ALLOCATOR_MALLOC (3): use malloc() of the C library.
• PYMEM_ALLOCATOR_MALLOC_DEBUG (4): force usage of malloc() with debug hooks.
int parse_argv
If non-zero, Py_PreInitializeFromArgs() and Py_PreInitializeFromBytesArgs() parse
their argv argument the same way the regular Python parses command line arguments: see Command
Line Arguments.
Default: 1 in Python config, 0 in isolated config.
int use_environment
Use environment variables? See PyConfig.use_environment.
Default: 1 in Python config and 0 in isolated config.
int utf8_mode
If non-zero, enable the Python UTF-8 Mode.
Set to 0 or 1 by the -X utf8 command line option and the PYTHONUTF8 environment variable.
Also set to 1 if the LC_CTYPE locale is C or POSIX.
Default: -1 in Python config and 0 in isolated config.
Python memory allocation functions like PyMem_RawMalloc() must not be used before the Python preinitialization,
whereas calling directly malloc() and free() is always safe. Py_DecodeLocale() must not be called before
the Python preinitialization.
Example using the preinitialization to enable the Python UTF-8 Mode:
PyStatus status;
PyPreConfig preconfig;
PyPreConfig_InitPythonConfig(&preconfig);
preconfig.utf8_mode = 1;
status = Py_PreInitialize(&preconfig);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
Py_Initialize();
/* ... use Python API here ... */
Py_Finalize();
10.4.6 PyConfig
type PyConfig
Structure containing most parameters to configure Python.
When done, the PyConfig_Clear() function must be used to release the configuration memory.
Structure methods:
void PyConfig_InitPythonConfig(PyConfig *config)
Initialize configuration with the Python Configuration.
void PyConfig_InitIsolatedConfig(PyConfig *config)
Initialize configuration with the Isolated Configuration.
PyStatus PyConfig_SetString(PyConfig *config, wchar_t *const *config_str, const wchar_t *str)
Copy the wide character string str into *config_str.
Preinitialize Python if needed.
PyStatus PyConfig_SetBytesString(PyConfig *config, wchar_t *const *config_str, const char *str)
Decode str using Py_DecodeLocale() and set the result into *config_str.
Preinitialize Python if needed.
PyStatus PyConfig_SetArgv(PyConfig *config, int argc, wchar_t *const *argv)
Set command line arguments (argv member of config) from the argv list of wide character strings.
Preinitialize Python if needed.
PyStatus PyConfig_SetBytesArgv(PyConfig *config, int argc, char *const *argv)
Set command line arguments (argv member of config) from the argv list of bytes strings. Decode bytes
using Py_DecodeLocale().
Preinitialize Python if needed.
PyStatus PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length,
wchar_t **items)
Set the list of wide strings list to length and items.
Preinitialize Python if needed.
PyStatus PyConfig_Read(PyConfig *config)
Read all Python configuration.
Fields which are already initialized are left unchanged.
Fields for path configuration are no longer calculated or modified when calling this function, as of Python
3.11.
The PyConfig_Read() function only parses PyConfig.argv arguments once: PyConfig.
parse_argv is set to 2 after arguments are parsed. Since Python arguments are stripped from
PyConfig.argv , parsing arguments twice would parse the application options as Python options.
wchar_t *check_hash_pycs_mode
Control the validation behavior of hash-based .pyc files: value of the --check-hash-based-pycs
command line option.
Valid values:
• L"always": Hash the source file for invalidation regardless of value of the ‘check_source’ flag.
• L"never": Assume that hash-based pycs always are valid.
• L"default": The ‘check_source’ flag in hash-based pycs determines invalidation.
Default: L"default".
See also PEP 552 “Deterministic pycs”.
int configure_c_stdio
If non-zero, configure C standard streams:
• On Windows, set the binary mode (O_BINARY) on stdin, stdout and stderr.
• If buffered_stdio equals zero, disable buffering of stdin, stdout and stderr streams.
• If interactive is non-zero, enable stream buffering on stdin and stdout (only stdout on Windows).
Default: 1 in Python config, 0 in isolated config.
int dev_mode
If non-zero, enable the Python Development Mode.
Set to 1 by the -X dev option and the PYTHONDEVMODE environment variable.
Default: -1 in Python mode, 0 in isolated mode.
int dump_refs
Dump Python references?
If non-zero, dump all objects which are still alive at exit.
Set to 1 by the PYTHONDUMPREFS environment variable.
Needs a special build of Python with the Py_TRACE_REFS macro defined: see the configure
--with-trace-refs option.
Default: 0.
wchar_t *dump_refs_file
Filename where to dump Python references.
Set by the PYTHONDUMPREFSFILE environment variable.
Default: NULL.
Added in version 3.11.
wchar_t *exec_prefix
The site-specific directory prefix where the platform-dependent Python files are installed: sys.
exec_prefix.
Default: NULL.
Part of the Python Path Configuration output.
See also PyConfig.base_exec_prefix.
wchar_t *executable
The absolute path of the executable binary for the Python interpreter: sys.executable.
Default: NULL.
Part of the Python Path Configuration output.
int use_hash_seed
Randomized hash function seed.
If use_hash_seed is zero, a seed is chosen randomly at Python startup, and hash_seed is ignored.
Set by the PYTHONHASHSEED environment variable.
Default use_hash_seed value: -1 in Python mode, 0 in isolated mode.
wchar_t *home
Set the default Python “home” directory, that is, the location of the standard Python libraries (see
PYTHONHOME).
int isolated
If greater than 0, enable isolated mode:
• Set safe_path to 1: don’t prepend a potentially unsafe path to sys.path at Python startup, such
as the current directory, the script’s directory or an empty string.
• Set use_environment to 0: ignore PYTHON environment variables.
• Set user_site_directory to 0: don’t add the user site directory to sys.path.
• Python REPL doesn’t import readline nor enable default readline configuration on interactive
prompts.
Set to 1 by the -I command line option.
Default: 0 in Python mode, 1 in isolated mode.
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.
int module_search_paths_set
Module search paths: sys.path.
If module_search_paths_set is equal to 0, Py_InitializeFromConfig() will replace
module_search_paths and sets module_search_paths_set to 1.
Default: empty list (module_search_paths) and 0 (module_search_paths_set).
Part of the Python Path Configuration output.
int optimization_level
Compilation optimization level:
• 0: Peephole optimizer, set __debug__ to True.
• 1: Level 0, remove assertions, set __debug__ to False.
• 2: Level 1, strip docstrings.
Incremented by the -O command line option. Set to the PYTHONOPTIMIZE environment variable value.
Default: 0.
PyWideStringList orig_argv
The list of the original command line arguments passed to the Python executable: sys.orig_argv.
If orig_argv list is empty and argv is not a list only containing an empty string, PyConfig_Read()
copies argv into orig_argv before modifying argv (if parse_argv is non-zero).
See also the argv member and the Py_GetArgcArgv() function.
Default: empty list.
Added in version 3.10.
int parse_argv
Parse command line arguments?
If equals to 1, parse argv the same way the regular Python parses command line arguments, and strip
Python arguments from argv .
The PyConfig_Read() function only parses PyConfig.argv arguments once: PyConfig.
parse_argv is set to 2 after arguments are parsed. Since Python arguments are stripped from
PyConfig.argv , parsing arguments twice would parse the application options as Python options.
int parser_debug
Parser debug mode. If greater than 0, turn on parser debugging output (for expert only, depending on
compilation options).
Incremented by the -d command line option. Set to the PYTHONDEBUG environment variable value.
Needs a debug build of Python (the Py_DEBUG macro must be defined).
Default: 0.
int pathconfig_warnings
If non-zero, calculation of path configuration is allowed to log warnings into stderr. If equals to 0,
suppress these warnings.
Default: 1 in Python mode, 0 in isolated mode.
Part of the Python Path Configuration input.
Changed in version 3.11: Now also applies on Windows.
wchar_t *prefix
The site-specific directory prefix where the platform independent Python files are installed: sys.
prefix.
Default: NULL.
Part of the Python Path Configuration output.
See also PyConfig.base_prefix.
wchar_t *program_name
Program name used to initialize executable and in early error messages during Python initialization.
• On macOS, use PYTHONEXECUTABLE environment variable if set.
• If the WITH_NEXT_FRAMEWORK macro is defined, use __PYVENV_LAUNCHER__ environment vari-
able if set.
• Use argv[0] of argv if available and non-empty.
• Otherwise, use L"python" on Windows, or L"python3" on other platforms.
Default: NULL.
Part of the Python Path Configuration input.
wchar_t *pycache_prefix
Directory where cached .pyc files are written: sys.pycache_prefix.
Set by the -X pycache_prefix=PATH command line option and the PYTHONPYCACHEPREFIX envi-
ronment variable. The command-line option takes precedence.
If NULL, sys.pycache_prefix is set to None.
Default: NULL.
int quiet
Quiet mode. If greater than 0, don’t display the copyright and version at Python startup in interactive
mode.
Incremented by the -q command line option.
Default: 0.
wchar_t *run_command
Value of the -c command line option.
Used by Py_RunMain().
Default: NULL.
wchar_t *run_filename
Filename passed on the command line: trailing command line argument without -c or -m. It is used by
the Py_RunMain() function.
For example, it is set to script.py by the python3 script.py arg command line.
See also the PyConfig.skip_source_first_line option.
Default: NULL.
wchar_t *run_module
Value of the -m command line option.
Used by Py_RunMain().
Default: NULL.
wchar_t *run_presite
package.module path to module that should be imported before site.py is run.
Set by the -X presite=package.module command-line option and the PYTHON_PRESITE environ-
ment variable. The command-line option takes precedence.
Needs a debug build of Python (the Py_DEBUG macro must be defined).
Default: NULL.
int show_ref_count
Show total reference count at exit (excluding immortal objects)?
Set to 1 by -X showrefcount command line option.
Needs a debug build of Python (the Py_REF_DEBUG macro must be defined).
Default: 0.
int site_import
Import the site module at startup?
If equal to zero, disable the import of the module site and the site-dependent manipulations of sys.path
that it entails.
Also disable these manipulations if the site module is explicitly imported later (call site.main() if
you want them to be triggered).
Set to 0 by the -S command line option.
sys.flags.no_site is set to the inverted value of site_import.
Default: 1.
int skip_source_first_line
If non-zero, skip the first line of the PyConfig.run_filename source.
It allows the usage of non-Unix forms of #!cmd. This is intended for a DOS specific hack only.
Set to 1 by the -x command line option.
Default: 0.
wchar_t *stdio_encoding
wchar_t *stdio_errors
Encoding and encoding errors of sys.stdin, sys.stdout and sys.stderr (but sys.stderr al-
ways uses "backslashreplace" error handler).
Use the PYTHONIOENCODING environment variable if it is non-empty.
Default encoding:
• "UTF-8" if PyPreConfig.utf8_mode is non-zero.
• Otherwise, use the locale encoding.
Default error handler:
• On Windows: use "surrogateescape".
• "surrogateescape" if PyPreConfig.utf8_mode is non-zero, or if the LC_CTYPE locale is
“C” or “POSIX”.
• "strict" otherwise.
See also PyConfig.legacy_windows_stdio.
int tracemalloc
Enable tracemalloc?
If non-zero, call tracemalloc.start() at startup.
Set by -X tracemalloc=N command line option and by the PYTHONTRACEMALLOC environment vari-
able.
Default: -1 in Python mode, 0 in isolated mode.
int perf_profiling
Enable the Linux perf profiler support?
If equals to 1, enable support for the Linux perf profiler.
If equals to 2, enable support for the Linux perf profiler with DWARF JIT support.
Set to 1 by -X perf command-line option and the PYTHONPERFSUPPORT environment variable.
Set to 2 by the -X perf_jit command-line option and the PYTHON_PERF_JIT_SUPPORT environ-
ment variable.
Default: -1.
µ See also
int verbose
Verbose mode. If greater than 0, print a message each time a module is imported, showing the place
(filename or built-in module) from which it is loaded.
If greater than or equal to 2, print a message for each file that is checked for when searching for a module.
Also provides information on module cleanup at exit.
Incremented by the -v command line option.
Set by the PYTHONVERBOSE environment variable value.
Default: 0.
PyWideStringList warnoptions
Options of the warnings module to build warnings filters, lowest to highest priority: sys.
warnoptions.
The warnings module adds sys.warnoptions in the reverse order: the last PyConfig.
warnoptions item becomes the first item of warnings.filters which is checked first (highest pri-
ority).
The -W command line options adds its value to warnoptions, it can be used multiple times.
The PYTHONWARNINGS environment variable can also be used to add warning options. Multiple options
can be specified, separated by commas (,).
Default: empty list.
int write_bytecode
If equal to 0, Python won’t try to write .pyc files on the import of source modules.
Set to 0 by the -B command line option and the PYTHONDONTWRITEBYTECODE environment variable.
sys.dont_write_bytecode is initialized to the inverted value of write_bytecode.
Default: 1.
PyWideStringList xoptions
Values of the -X command line options: sys._xoptions.
Default: empty list.
int _pystats
If non-zero, write performance statistics at Python exit.
Need a special build with the Py_STATS macro: see --enable-pystats.
Default: 0.
If parse_argv is non-zero, argv arguments are parsed the same way the regular Python parses command line
arguments, and Python arguments are stripped from argv .
The xoptions options are parsed to set other options: see the -X command line option.
Changed in version 3.9: The show_alloc_count field has been removed.
void init_python(void)
{
PyStatus status;
PyConfig config;
PyConfig_InitPythonConfig(&config);
status = Py_InitializeFromConfig(&config);
if (PyStatus_Exception(status)) {
goto exception;
}
PyConfig_Clear(&config);
return;
exception:
PyConfig_Clear(&config);
Py_ExitStatusException(status);
}
More complete example modifying the default configuration, read the configuration, and then override some param-
eters. 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:
PyConfig config;
PyConfig_InitPythonConfig(&config);
status = Py_InitializeFromConfig(&config);
done:
PyConfig_Clear(&config);
return status;
}
– PyConfig.pathconfig_warnings
– PyConfig.program_name
– PyConfig.pythonpath_env
– current working directory: to get absolute paths
– PATH environment variable to get the program full path (from PyConfig.program_name)
– __PYVENV_LAUNCHER__ environment variable
– (Windows only) Application paths in the registry under “SoftwarePythonPythonCoreX.YPythonPath” of
HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE (where X.Y is the Python version).
• Path configuration output fields:
– PyConfig.base_exec_prefix
– PyConfig.base_executable
– PyConfig.base_prefix
– PyConfig.exec_prefix
– PyConfig.executable
– PyConfig.module_search_paths_set, PyConfig.module_search_paths
– PyConfig.prefix
If at least one “output field” is not set, Python calculates the path configuration to fill unset
fields. If module_search_paths_set is equal to 0, module_search_paths is overridden and
module_search_paths_set is set to 1.
It is possible to completely ignore the function calculating the default path configuration by setting explic-
itly all path configuration output fields listed above. A string is considered as set even if it is non-empty.
module_search_paths is considered as set if module_search_paths_set is set to 1. In this case,
module_search_paths will be used without modification.
Set pathconfig_warnings to 0 to suppress warnings when calculating the path configuration (Unix only, Windows
does not log any warning).
If base_prefix or base_exec_prefix fields are not set, they inherit their value from prefix and exec_prefix
respectively.
Py_RunMain() and Py_Main() modify sys.path:
• If run_filename is set and is a directory which contains a __main__.py script, prepend run_filename
to sys.path.
• If isolated is zero:
– If run_module is set, prepend the current directory to sys.path. Do nothing if the current directory
cannot be read.
– If run_filename is set, prepend the directory of the filename to sys.path.
– Otherwise, prepend an empty string to sys.path.
If site_import is non-zero, sys.path can be modified by the site module. If user_site_directory is
non-zero and the user’s site-package directory exists, the site module appends the user’s site-package directory to
sys.path.
• Set isolated to 1.
• Set use_environment to 0.
• Set site_import to 0.
• Set safe_path to 1.
If home is not set and a pyvenv.cfg file is present in the same directory as executable, or its parent, prefix
and exec_prefix are set that location. When this happens, base_prefix and base_exec_prefix still keep
their value, pointing to the base installation. See sys-path-init-virtual-environments for more information.
The __PYVENV_LAUNCHER__ environment variable is used to set PyConfig.base_executable.
Changed in version 3.14: prefix, and exec_prefix, are now set to the pyvenv.cfg directory. This was previ-
ously done by site, therefore affected by -S.
10.5 Py_GetArgcArgv()
void Py_GetArgcArgv(int *argc, wchar_t ***argv)
Get the original command line arguments, before Python modified them.
See also PyConfig.orig_argv member.
ELEVEN
MEMORY MANAGEMENT
11.1 Overview
Memory management in Python involves a private heap containing all Python objects and data structures. The
management of this private heap is ensured internally by the Python memory manager. The Python memory manager
has different components which deal with various dynamic storage management aspects, like sharing, segmentation,
preallocation or caching.
At the lowest level, a raw memory allocator ensures that there is enough room in the private heap for storing all
Python-related data by interacting with the memory manager of the operating system. On top of the raw memory
allocator, several object-specific allocators operate on the same heap and implement distinct memory management
policies adapted to the peculiarities of every object type. For example, integer objects are managed differently within
the heap than strings, tuples or dictionaries because integers imply different storage requirements and speed/space
tradeoffs. The Python memory manager thus delegates some of the work to the object-specific allocators, but ensures
that the latter operate within the bounds of the private heap.
It is important to understand that the management of the Python heap is performed by the interpreter itself and that
the user has no control over it, even if they regularly manipulate object pointers to memory blocks inside that heap.
The allocation of heap space for Python objects and other internal buffers is performed on demand by the Python
memory manager through the Python/C API functions listed in this document.
To avoid memory corruption, extension writers should never try to operate on Python objects with the functions
exported by the C library: malloc(), calloc(), realloc() and free(). This will result in mixed calls be-
tween the C allocator and the Python memory manager with fatal consequences, because they implement different
algorithms and operate on different heaps. However, one may safely allocate and release memory blocks with the C
library allocator for individual purposes, as shown in the following example:
PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyBytes_FromString(buf);
free(buf); /* malloc'ed */
return res;
In this example, the memory request for the I/O buffer is handled by the C library allocator. The Python memory
manager is involved only in the allocation of the bytes object returned as a result.
In most situations, however, it is recommended to allocate memory from the Python heap specifically because the
latter is under control of the Python memory manager. For example, this is required when the interpreter is extended
with new object types written in C. Another reason for using the Python heap is the desire to inform the Python
memory manager about the memory needs of the extension module. Even when the requested memory is used
exclusively for internal, highly specific purposes, delegating all memory requests to the Python memory manager
causes the interpreter to have a more accurate image of its memory footprint as a whole. Consequently, under certain
circumstances, the Python memory manager may or may not trigger appropriate actions, like garbage collection,
271
The Python/C API, Release 3.14.0a7
memory compaction or other preventive procedures. Note that by using the C library allocator as shown in the
previous example, the allocated memory for the I/O buffer escapes completely the Python memory manager.
µ See also
The PYTHONMALLOC environment variable can be used to configure the memory allocators used by Python.
The PYTHONMALLOCSTATS environment variable can be used to print statistics of the pymalloc memory allocator
every time a new pymalloc object arena is created, and on shutdown.
® Note
The free-threaded build requires that only Python objects are allocated using the “object” domain and that all
Python objects are allocated using that domain. This differs from the prior Python versions, where this was only
a best practice and not a hard requirement.
For example, buffers (non-Python objects) should be allocated using PyMem_Malloc(), PyMem_RawMalloc(),
or malloc(), but not PyObject_Malloc().
See Memory Allocation APIs.
If the request fails, PyMem_RawRealloc() returns NULL and p remains a valid pointer to the previous memory
area.
void PyMem_RawFree(void *p)
Part of the Stable ABI since version 3.13. Frees the memory block pointed to by p, which must have been
returned by a previous call to PyMem_RawMalloc(), PyMem_RawRealloc() or PyMem_RawCalloc().
Otherwise, or if PyMem_RawFree(p) has been called before, undefined behavior occurs.
If p is NULL, no operation is performed.
Á Warning
Changed in version 3.6: The default allocator is now pymalloc instead of system malloc().
void *PyMem_Malloc(size_t n)
Part of the Stable ABI. Allocates n bytes and returns a pointer of type void* to the allocated memory, or
NULL if the request fails.
Requesting zero bytes returns a distinct non-NULL pointer if possible, as if PyMem_Malloc(1) had been called
instead. The memory will not have been initialized in any way.
void *PyMem_Calloc(size_t nelem, size_t elsize)
Part of the Stable ABI since version 3.7. Allocates nelem elements each whose size in bytes is elsize and returns
a pointer of type void* to the allocated memory, or NULL if the request fails. The memory is initialized to
zeros.
Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if
PyMem_Calloc(1, 1) had been called instead.
® Note
There is no guarantee that the memory returned by these allocators can be successfully cast to a Python object
when intercepting the allocating functions in this domain by the methods described in the Customize Memory
Allocators section.
Á Warning
void *PyObject_Malloc(size_t n)
Part of the Stable ABI. Allocates n bytes and returns a pointer of type void* to the allocated memory, or
NULL if the request fails.
Requesting zero bytes returns a distinct non-NULL pointer if possible, as if PyObject_Malloc(1) had been
called instead. The memory will not have been initialized in any way.
void *PyObject_Calloc(size_t nelem, size_t elsize)
Part of the Stable ABI since version 3.7. Allocates nelem elements each whose size in bytes is elsize and returns
a pointer of type void* to the allocated memory, or NULL if the request fails. The memory is initialized to
zeros.
Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if
PyObject_Calloc(1, 1) had been called instead.
If the request fails, PyObject_Realloc() returns NULL and p remains a valid pointer to the previous memory
area.
void PyObject_Free(void *p)
Part of the Stable ABI. Frees the memory block pointed to by p, which must have been returned by a pre-
vious call to PyObject_Malloc(), PyObject_Realloc() or PyObject_Calloc(). Otherwise, or if
PyObject_Free(p) has been called before, undefined behavior occurs.
Legend:
Field Meaning
void *ctx user context passed as first argument
void* malloc(void *ctx, size_t size) allocate a memory block
void* calloc(void *ctx, size_t nelem, size_t allocate a memory block initialized with
elsize) zeros
void* realloc(void *ctx, void *ptr, size_t allocate or resize a memory block
new_size)
void free(void *ctx, void *ptr) free a memory block
Changed in version 3.5: The PyMemAllocator structure was renamed to PyMemAllocatorEx and a new
calloc field was added.
type PyMemAllocatorDomain
Enum used to identify an allocator domain. Domains:
PYMEM_DOMAIN_RAW
Functions:
• PyMem_RawMalloc()
• PyMem_RawRealloc()
• PyMem_RawCalloc()
• PyMem_RawFree()
PYMEM_DOMAIN_MEM
Functions:
• PyMem_Malloc(),
• PyMem_Realloc()
• PyMem_Calloc()
• PyMem_Free()
PYMEM_DOMAIN_OBJ
Functions:
• PyObject_Malloc()
• PyObject_Realloc()
• PyObject_Calloc()
• PyObject_Free()
void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Get the memory block allocator of the specified domain.
void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
Set the memory block allocator of the specified domain.
The new allocator must return a distinct non-NULL pointer when requesting zero bytes.
For the PYMEM_DOMAIN_RAW domain, the allocator must be thread-safe: a thread state is not attached when
the allocator is called.
For the remaining domains, the allocator must also be thread-safe: the allocator may be called in different
interpreters that do not share a GIL.
If the new allocator is not a hook (does not call the previous allocator), the PyMem_SetupDebugHooks()
function must be called to reinstall the debug hooks on top on the new allocator.
See also PyPreConfig.allocator and Preinitialize Python with PyPreConfig.
Á Warning
These debug hooks fill dynamically allocated memory blocks with special, recognizable bit patterns. Newly
allocated memory is filled with the byte 0xCD (PYMEM_CLEANBYTE), freed memory is filled with the byte
0xDD (PYMEM_DEADBYTE). Memory blocks are surrounded by “forbidden bytes” filled with the byte 0xFD
(PYMEM_FORBIDDENBYTE). Strings of these bytes are unlikely to be valid addresses, floats, or ASCII strings.
Runtime checks:
• Detect API violations. For example, detect if PyObject_Free() is called on a memory block allocated by
PyMem_Malloc().
• Check that there is an attached thread state when allocator functions of PYMEM_DOMAIN_OBJ (ex:
PyObject_Malloc()) and PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) domains are called.
On error, the debug hooks use the tracemalloc module to get the traceback where a memory block was allocated.
The traceback is only displayed if tracemalloc is tracing Python memory allocations and the memory block was
traced.
Let S = sizeof(size_t). 2*S bytes are added at each end of each block of N bytes requested. The memory layout
is like so, where p represents the address returned by a malloc-like or realloc-like function (p[i:j] means the slice
of bytes from *(p+i) inclusive up to *(p+j) exclusive; note that the treatment of negative indices differs from a
Python slice):
p[-2*S:-S]
Number of bytes originally asked for. This is a size_t, big-endian (easier to read in a memory dump).
p[-S]
API identifier (ASCII character):
• 'r' for PYMEM_DOMAIN_RAW .
• 'm' for PYMEM_DOMAIN_MEM .
• 'o' for PYMEM_DOMAIN_OBJ .
p[-S+1:0]
Copies of PYMEM_FORBIDDENBYTE. Used to catch under- writes and reads.
p[0:N]
The requested memory, filled with copies of PYMEM_CLEANBYTE, used to catch reference to uninitial-
ized memory. When a realloc-like function is called requesting a larger memory block, the new excess bytes
are also filled with PYMEM_CLEANBYTE. When a free-like function is called, these are overwritten with
PYMEM_DEADBYTE, to catch reference to freed memory. When a realloc- like function is called requesting
a smaller memory block, the excess old bytes are also filled with PYMEM_DEADBYTE.
p[N:N+S]
Copies of PYMEM_FORBIDDENBYTE. Used to catch over- writes and reads.
p[N+S:N+2*S]
Only used if the PYMEM_DEBUG_SERIALNO macro is defined (not defined by default).
A serial number, incremented by 1 on each call to a malloc-like or realloc-like function. Big-endian size_t.
If “bad memory” is detected later, the serial number gives an excellent way to set a breakpoint on the next run,
to capture the instant at which this block was passed out. The static function bumpserialno() in obmalloc.c is
the only place the serial number is incremented, and exists so you can set such a breakpoint easily.
A realloc-like or free-like function first checks that the PYMEM_FORBIDDENBYTE bytes at each end are intact.
If they’ve been altered, diagnostic output is written to stderr, and the program is aborted via Py_FatalError(). The
other main failure mode is provoking a memory error when a program reads up one of the special bit patterns and
tries to use it as an address. If you get in a debugger then and look at the object, you’re likely to see that it’s entirely
filled with PYMEM_DEADBYTE (meaning freed memory is getting used) or PYMEM_CLEANBYTE (meaning
uninitialized memory is getting used).
Changed in version 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 there is an attached thread state when functions of PYMEM_DOMAIN_OBJ and
PYMEM_DOMAIN_MEM domains are called.
Changed in version 3.8: Byte patterns 0xCB (PYMEM_CLEANBYTE), 0xDB (PYMEM_DEADBYTE) and 0xFB
(PYMEM_FORBIDDENBYTE) have been replaced with 0xCD, 0xDD and 0xFD to use the same values than Windows
CRT debug malloc() and free().
Field Meaning
void *ctx user context passed as first argument
void* alloc(void *ctx, size_t size) allocate an arena of size bytes
void free(void *ctx, void *ptr, size_t size) free an arena
11.12 Examples
Here is the example from section Overview, rewritten so that the I/O buffer is allocated from the Python heap by
using the first function set:
PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;
PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
if (buf == NULL)
return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_New */
return res;
Note that in the two examples above, the buffer is always manipulated via functions belonging to the same set. Indeed,
it is required to use the same memory API family for a given memory block, so that the risk of mixing different
allocators is reduced to a minimum. The following code sequence contains two errors, one of which is labeled as
fatal because it mixes two different allocators operating on different heaps.
In addition to the functions aimed at handling raw memory blocks from the Python heap, objects in Python are
allocated and released with PyObject_New , PyObject_NewVar and PyObject_Free().
These will be explained in the next chapter on defining and implementing new object types in C.
TWELVE
This chapter describes the functions, types, and macros used when defining new object types.
281
The Python/C API, Release 3.14.0a7
µ See also
PyModule_Create()
To allocate and create extension modules.
type PyVarObject
Part of the Limited API. (Only some members are part of the stable ABI.) This is an extension of PyObject
that adds the ob_size field. This is only used for objects that have some notion of length. This type does not
often appear in the Python/C API. Access to the members must be done by using the macros Py_REFCNT ,
Py_TYPE, and Py_SIZE.
PyObject_HEAD
This is a macro used when declaring new types which represent objects without a varying length. The PyOb-
ject_HEAD macro expands to:
PyObject ob_base;
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.
The function signature is:
type PyCFunctionWithKeywords
Part of the Stable ABI. Type of the functions used to implement Python callables in C with signature
METH_VARARGS | METH_KEYWORDS. The function signature is:
type PyCFunctionFast
Part of the Stable ABI since version 3.13. Type of the functions used to implement Python callables in C with
signature METH_FASTCALL. The function signature is:
type PyCFunctionFastWithKeywords
Part of the Stable ABI since version 3.13. Type of the functions used to implement Python callables in C with
signature METH_FASTCALL | METH_KEYWORDS. The function signature is:
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.
There are these calling conventions:
METH_VARARGS
This is the typical calling convention, where the methods have the type PyCFunction. The function expects
two PyObject* values. The first one is the self object for methods; for module functions, it is the module
object. The second parameter (often called args) is a tuple object representing all arguments. This parameter
is typically processed using PyArg_ParseTuple() or PyArg_UnpackTuple().
METH_KEYWORDS
Can only be used in certain combinations with other flags: METH_VARARGS | METH_KEYWORDS,
METH_FASTCALL | METH_KEYWORDS and METH_METHOD | METH_FASTCALL | METH_KEYWORDS.
METH_VARARGS | METH_KEYWORDS
Methods with these flags must be of type PyCFunctionWithKeywords. The function expects three parame-
ters: self, args, kwargs where kwargs is a dictionary of all the keyword arguments or possibly NULL if there are
no keyword arguments. The parameters are typically processed using PyArg_ParseTupleAndKeywords().
METH_FASTCALL
Fast calling convention supporting only positional arguments. The methods have the type PyCFunctionFast.
The first parameter is self, the second parameter is a C array of PyObject* values indicating the arguments
and the third parameter is the number of arguments (the length of the array).
Added in version 3.7.
Changed in version 3.10: METH_FASTCALL is now part of the stable ABI.
METH_FASTCALL | METH_KEYWORDS
Extension of METH_FASTCALL supporting also keyword arguments, with methods of type
PyCFunctionFastWithKeywords. Keyword arguments are passed the same way as in the vectorcall
protocol: there is an additional fourth PyObject* parameter which is a tuple representing the names of the
keyword arguments (which are guaranteed to be strings) or possibly NULL if there are no keywords. The
values of the keyword arguments are stored in the args array, after the positional arguments.
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).
The method needs to be of type PyCMethod, the same as for METH_FASTCALL | METH_KEYWORDS with
defining_class argument added after self.
METH_NOARGS flag. They need to be of type PyCFunction. The first parameter is typically named self and
will hold a reference to the module or object instance. In all cases the second parameter will be NULL.
The function must have 2 parameters. Since the second parameter is unused, Py_UNUSED can be used to
prevent a compiler warning.
METH_O
Methods with a single object argument can be listed with the METH_O flag, instead of invoking
PyArg_ParseTuple() with a "O" argument. They have the type PyCFunction, with the self parameter,
and a PyObject* parameter representing the single argument.
These two constants are not used to indicate the calling convention but the binding when use with methods of classes.
These may not be used for functions defined for modules. At most one of these flags may be set for any given method.
METH_CLASS
The method will be passed the type object as the first parameter rather than an instance of the type. This is
used to create class methods, similar to what is created when using the classmethod() built-in function.
METH_STATIC
The method will be passed NULL as the first parameter rather than an instance of the type. This is used to
create static methods, similar to what is created when using the staticmethod() built-in function.
One other constant controls whether a method is loaded in place of another definition with the same method name.
METH_COEXIST
The method will be loaded in place of existing definitions. Without METH_COEXIST, the default is to skip
repeated definitions. Since slot wrappers are loaded before the method table, the existence of a sq_contains
slot, for example, would generate a wrapped method named __contains__() and preclude the loading of
a corresponding PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in
place of the wrapper object and will co-exist with the slot. This is helpful because calls to PyCFunctions are
optimized more than wrapper object calls.
PyObject *PyCMethod_New(PyMethodDef *ml, PyObject *self, PyObject *module, PyTypeObject *cls)
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.
µ See also
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).
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 def-
inition for the special member "__vectorcalloffset__", corresponding to tp_vectorcall_offset
in type objects. This member must be defined with Py_T_PYSSIZET, and either Py_READONLY or
Py_READONLY | Py_RELATIVE_OFFSET. For example:
Member flags
The following flags can be used with PyMemberDef.flags:
Py_READONLY
Not writable.
Py_AUDIT_READ
Emit an object.__getattr__ audit event before reading.
Py_RELATIVE_OFFSET
Indicates that the offset of this PyMemberDef entry indicates an offset from the subclass-specific data, rather
than from PyObject.
Can only be used as part of Py_tp_members slot when creating a class using negative basicsize. It is
mandatory in that case.
This flag is only used in PyType_Slot. When setting tp_members during class creation, Python clears it
and sets PyMemberDef.offset to the offset from the PyObject struct.
Changed in version 3.10: The RESTRICTED, READ_RESTRICTED and WRITE_RESTRICTED macros available
with #include "structmember.h" are deprecated. READ_RESTRICTED and RESTRICTED are equivalent to
Py_AUDIT_READ; WRITE_RESTRICTED does nothing.
Changed in version 3.12: The READONLY macro was renamed to Py_READONLY . The PY_AUDIT_READ macro was
renamed with the Py_ prefix. The new names are now always available. Previously, these required #include
"structmember.h". The header is still available and it provides the old names.
Member types
PyMemberDef.type can be one of the following macros corresponding to various C types. When the member is
accessed in Python, it will be converted to the equivalent Python type. When it is set from Python, it will be converted
back to the C type. If that is not possible, an exception such as TypeError or ValueError is raised.
Unless marked (D), attributes defined this way cannot be deleted using e.g. del or delattr().
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
Added in version 3.12: In previous versions, the macros were only available with #include "structmember.h"
and were named without the Py_ prefix (e.g. as T_INT). The header is still available and contains the old names,
along with the following deprecated types:
T_OBJECT
Like Py_T_OBJECT_EX, but NULL is converted to None. This results in surprising behavior in Python: deleting
the attribute effectively sets it to None.
T_NONE
Always None. Must be used with Py_READONLY .
In addition to the following quick reference, the Examples section provides at-a-glance insight into the meaning and
use of PyTypeObject.
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 Columns:
bf_getbuffer getbufferproc()
bf_releasebuffer releasebufferproc()
slot typedefs
PyTypeObject *
Py_ssize_t
newfunc PyObject *
PyTypeObject *
PyObject *
PyObject *
initproc int
PyObject *
PyObject *
PyObject *
PyObject *
const char *
setattrfunc int
PyObject *
const char *
PyObject *
getattrofunc PyObject *
PyObject *
PyObject *
setattrofunc int
PyObject *
PyObject *
PyObject *
descrgetfunc PyObject *
PyObject *
PyObject *
PyObject *
descrsetfunc int
PyObject *
PyObject *
294 PyObject * Chapter 12. Object Implementation Support
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;
destructor tp_finalize;
vectorcallfunc tp_vectorcall;
Py_ssize_t PyObject.ob_refcnt
Part of the Stable ABI. This is the type object’s reference count, initialized to 1 by the PyObject_HEAD_INIT
macro. Note that for statically allocated type objects, the type’s instances (objects whose ob_type points back
to the type) do not count as references. But for dynamically allocated type objects, the instances do count as
references.
Inheritance:
This field is not inherited by subtypes.
PyTypeObject *PyObject.ob_type
Part of the Stable ABI. This is the type’s type, in other words its metatype. It is initialized by the argument to the
PyObject_HEAD_INIT macro, and its value should normally be &PyType_Type. However, for dynamically
loadable extension modules that must be usable on Windows (at least), the compiler complains that this is not
a valid initializer. Therefore, the convention is to pass NULL to the PyObject_HEAD_INIT macro and to
initialize this field explicitly at the start of the module’s initialization function, before doing anything else. This
is typically done like this:
Foo_Type.ob_type = &PyType_Type;
This should be done before any instances of the type are created. PyType_Ready() checks if ob_type is
NULL, and if so, initializes it to the ob_type field of the base class. PyType_Ready() will not change this
field if it is non-zero.
Inheritance:
This field is inherited by subtypes.
For dynamically allocated type objects, this should just be the type name, and the module name explicitly stored
in the type dict as the value for key '__module__'.
For statically allocated type objects, the tp_name field should contain a dot. Everything before the last dot
is made accessible as the __module__ attribute, and everything after the last dot is made accessible as the
__name__ attribute.
If no dot is present, the entire tp_name field is made accessible as the __name__ attribute, and the
__module__ attribute is undefined (unless explicitly set in the dictionary, as explained above). This means
your type will be impossible to pickle. Additionally, it will not be listed in module documentations created
with pydoc.
This field must not be NULL. It is the only required field in PyTypeObject() (other than potentially
tp_itemsize).
Inheritance:
This field is not inherited by subtypes.
Py_ssize_t PyTypeObject.tp_basicsize
Py_ssize_t PyTypeObject.tp_itemsize
These fields allow calculating the size in bytes of instances of the type.
There are two kinds of types: types with fixed-length instances have a zero tp_itemsize field, types
with variable-length instances have a non-zero tp_itemsize field. For a type with fixed-length instances,
all instances have the same size, given in tp_basicsize. (Exceptions to this rule can be made using
PyUnstable_Object_GC_NewWithExtraData().)
For a type with variable-length instances, the instances must have an ob_size field, and the instance size is
tp_basicsize plus N times tp_itemsize, where N is the “length” of the object.
Functions like PyObject_NewVar() will take the value of N as an argument, and store in the instance’s
ob_size field. Note that the ob_size field may later be used for other purposes. For example, int instances
use the bits of ob_size in an implementation-defined way; the underlying storage and its size should be
accessed using PyLong_Export().
® Note
The ob_size field should be accessed using the Py_SIZE() and Py_SET_SIZE() macros.
Also, the presence of an ob_size field in the instance layout doesn’t mean that the instance structure is variable-
length. For example, the list type has fixed-length instances, yet those instances have a ob_size field. (As
with int, avoid reading lists’ ob_size directly. Call PyList_Size() instead.)
The tp_basicsize includes size needed for data of the type’s tp_base, plus any extra data needed by each
instance.
The correct way to set tp_basicsize is to use the sizeof operator on the struct used to declare the instance
layout. This struct must include the struct used to declare the base type. In other words, tp_basicsize must
be greater than or equal to the base’s tp_basicsize.
Since every type is a subtype of object, this struct must include PyObject or PyVarObject (depend-
ing on whether ob_size should be included). These are usually defined by the macro PyObject_HEAD or
PyObject_VAR_HEAD, respectively.
The basic size does not include the GC header size, as that header is not part of PyObject_HEAD.
For cases where struct used to declare the base type is unknown, see PyType_Spec.basicsize and
PyType_FromMetaclass().
The destructor function is called by the Py_DECREF() and Py_XDECREF() macros when the new reference
count is zero. At this point, the instance is still in existence, but there are no references to it. The destructor
function should free all references which the instance owns, free all memory buffers owned by the instance
(using the freeing function corresponding to the allocation function used to allocate the buffer), and call the
type’s tp_free function. If the type is not subtypable (doesn’t have the Py_TPFLAGS_BASETYPE flag bit set),
it is permissible to call the object deallocator directly instead of via tp_free. The object deallocator should
be the one used to allocate the instance; this is normally PyObject_Free() if the instance was allocated
using PyObject_New or PyObject_NewVar, or PyObject_GC_Del() if the instance was allocated using
PyObject_GC_New or PyObject_GC_NewVar.
If the type supports garbage collection (has the Py_TPFLAGS_HAVE_GC flag bit set), the destructor should call
PyObject_GC_UnTrack() before clearing any member fields.
static void
foo_dealloc(PyObject *op)
{
foo_object *self = (foo_object *) op;
PyObject_GC_UnTrack(self);
Py_CLEAR(self->ref);
Py_TYPE(self)->tp_free(self);
}
Finally, if the type is heap allocated (Py_TPFLAGS_HEAPTYPE), the deallocator should release the owned
reference to its type object (via Py_DECREF()) after calling the type deallocator. In order to avoid dangling
pointers, the recommended way to achieve this is:
static void
foo_dealloc(PyObject *op)
{
PyTypeObject *tp = Py_TYPE(op);
// free references and buffers here
tp->tp_free(op);
Py_DECREF(tp);
}
Á Warning
In a garbage collected Python, tp_dealloc may be called from any Python thread, not just the thread
which created the object (if the object becomes part of a refcount cycle, that cycle might be collected
by a garbage collection on any thread). This is not a problem for Python API calls, since the thread on
which tp_dealloc is called with an attached thread state. However, if the object being destroyed in turn
destroys objects from some other C or C++ library, care should be taken to ensure that destroying those
objects on the thread which called tp_dealloc will not violate any assumptions of the library.
Inheritance:
This field is inherited by subtypes.
Py_ssize_t PyTypeObject.tp_vectorcall_offset
An optional offset to a per-instance function that implements calling the object using the vectorcall protocol, a
more efficient alternative of the simpler tp_call.
This field is only used if the flag Py_TPFLAGS_HAVE_VECTORCALL is set. If so, this must be a positive integer
containing the offset in the instance of a vectorcallfunc pointer.
The vectorcallfunc pointer may be NULL, in which case the instance behaves as if
Py_TPFLAGS_HAVE_VECTORCALL was not set: calling the instance falls back to tp_call.
Any class that sets Py_TPFLAGS_HAVE_VECTORCALL must also set tp_call and make sure its behaviour is
consistent with the vectorcallfunc function. This can be done by setting tp_call to PyVectorcall_Call().
Changed in version 3.8: Before version 3.8, this slot was named tp_print. In Python 2.x, it was used for
printing to a file. In Python 3.0 to 3.7, it was unused.
Changed in version 3.12: Before version 3.12, it was not recommended for mutable heap types to implement
the vectorcall protocol. When a user sets __call__ in Python code, only tp_call is updated, likely making it
inconsistent with the vectorcall function. Since 3.12, setting __call__ will disable vectorcall optimization by
clearing the Py_TPFLAGS_HAVE_VECTORCALL flag.
Inheritance:
This field is always inherited. However, the Py_TPFLAGS_HAVE_VECTORCALL flag is not always inherited. If
it’s not set, then the subclass won’t use vectorcall, except when PyVectorcall_Call() is explicitly called.
getattrfunc PyTypeObject.tp_getattr
An optional pointer to the get-attribute-string function.
This field is deprecated. When it is defined, it should point to a function that acts the same as the tp_getattro
function, but taking a C string instead of a Python string object to give the attribute name.
Inheritance:
Group: tp_getattr, tp_getattro
This field is inherited by subtypes together with tp_getattro: a subtype inherits both tp_getattr and
tp_getattro from its base type when the subtype’s tp_getattr and tp_getattro are both NULL.
setattrfunc PyTypeObject.tp_setattr
An optional pointer to the function for setting and deleting attributes.
This field is deprecated. When it is defined, it should point to a function that acts the same as the tp_setattro
function, but taking a C string instead of a Python string object to give the attribute name.
Inheritance:
Group: tp_setattr, tp_setattro
This field is inherited by subtypes together with tp_setattro: a subtype inherits both tp_setattr and
tp_setattro from its base type when the subtype’s tp_setattr and tp_setattro are both NULL.
PyAsyncMethods *PyTypeObject.tp_as_async
Pointer to an additional structure that contains fields relevant only to objects which implement awaitable and
asynchronous iterator protocols at the C-level. See Async Object Structures for details.
Added in version 3.5: Formerly known as tp_compare and tp_reserved.
Inheritance:
The tp_as_async field is not inherited, but the contained fields are inherited individually.
reprfunc PyTypeObject.tp_repr
An optional pointer to a function that implements the built-in function repr().
The signature is the same as for PyObject_Repr():
The function must return a string or a Unicode object. Ideally, this function should return a string that, when
passed to eval(), given a suitable environment, returns an object with the same value. If this is not feasible,
it should return a string starting with '<' and ending with '>' from which both the type and the value of the
object can be deduced.
Inheritance:
This field is inherited by subtypes.
Default:
When this field is not set, a string of the form <%s object at %p> is returned, where %s is replaced by the
type name, and %p by the object’s memory address.
PyNumberMethods *PyTypeObject.tp_as_number
Pointer to an additional structure that contains fields relevant only to objects which implement the number
protocol. These fields are documented in Number Object Structures.
Inheritance:
The tp_as_number field is not inherited, but the contained fields are inherited individually.
PySequenceMethods *PyTypeObject.tp_as_sequence
Pointer to an additional structure that contains fields relevant only to objects which implement the sequence
protocol. These fields are documented in Sequence Object Structures.
Inheritance:
The tp_as_sequence field is not inherited, but the contained fields are inherited individually.
PyMappingMethods *PyTypeObject.tp_as_mapping
Pointer to an additional structure that contains fields relevant only to objects which implement the mapping
protocol. These fields are documented in Mapping Object Structures.
Inheritance:
The tp_as_mapping field is not inherited, but the contained fields are inherited individually.
hashfunc PyTypeObject.tp_hash
An optional pointer to a function that implements the built-in function hash().
The signature is the same as for PyObject_Hash():
The value -1 should not be returned as a normal return value; when an error occurs during the computation
of the hash value, the function should set an exception and return -1.
When this field is not set (and tp_richcompare is not set), an attempt to take the hash of the object raises
TypeError. This is the same as setting it to PyObject_HashNotImplemented().
This field can be set explicitly to PyObject_HashNotImplemented() to block inheritance of the hash
method from a parent type. This is interpreted as the equivalent of __hash__ = None at the Python level,
causing isinstance(o, collections.Hashable) to correctly return False. Note that the converse is
also true - setting __hash__ = None on a class at the Python level will result in the tp_hash slot being set
to PyObject_HashNotImplemented().
Inheritance:
Group: tp_hash, tp_richcompare
This field is inherited by subtypes together with tp_richcompare: a subtype inherits both of
tp_richcompare and tp_hash, when the subtype’s tp_richcompare and tp_hash are both NULL.
Default:
PyBaseObject_Type uses PyObject_GenericHash().
ternaryfunc PyTypeObject.tp_call
An optional pointer to a function that implements calling the object. This should be NULL if the object is not
callable. The signature is the same as for PyObject_Call():
Inheritance:
This field is inherited by subtypes.
reprfunc PyTypeObject.tp_str
An optional pointer to a function that implements the built-in operation str(). (Note that str is a type now,
and str() calls the constructor for that type. This constructor calls PyObject_Str() to do the actual work,
and PyObject_Str() will call this handler.)
The signature is the same as for PyObject_Str():
The function must return a string or a Unicode object. It should be a “friendly” string representation of the
object, as this is the representation that will be used, among other things, by the print() function.
Inheritance:
This field is inherited by subtypes.
Default:
When this field is not set, PyObject_Repr() is called to return a string representation.
getattrofunc PyTypeObject.tp_getattro
An optional pointer to the get-attribute function.
The signature is the same as for PyObject_GetAttr():
It is usually convenient to set this field to PyObject_GenericGetAttr(), which implements the normal
way of looking for object attributes.
Inheritance:
Group: tp_getattr, tp_getattro
This field is inherited by subtypes together with tp_getattr: a subtype inherits both tp_getattr and
tp_getattro from its base type when the subtype’s tp_getattr and tp_getattro are both NULL.
Default:
PyBaseObject_Type uses PyObject_GenericGetAttr().
setattrofunc PyTypeObject.tp_setattro
An optional pointer to the function for setting and deleting attributes.
The signature is the same as for PyObject_SetAttr():
In addition, setting value to NULL to delete an attribute must be supported. It is usually convenient to set this
field to PyObject_GenericSetAttr(), which implements the normal way of setting object attributes.
Inheritance:
Group: tp_setattr, tp_setattro
This field is inherited by subtypes together with tp_setattr: a subtype inherits both tp_setattr and
tp_setattro from its base type when the subtype’s tp_setattr and tp_setattro are both NULL.
Default:
PyBaseObject_Type uses PyObject_GenericSetAttr().
PyBufferProcs *PyTypeObject.tp_as_buffer
Pointer to an additional structure that contains fields relevant only to objects which implement the buffer in-
terface. These fields are documented in Buffer Object Structures.
Inheritance:
The tp_as_buffer field is not inherited, but the contained fields are inherited individually.
Bit Masks:
The following bit masks are currently defined; these can be ORed together using the | operator to form the
value of the tp_flags field. The macro PyType_HasFeature() takes a type and a flags value, tp and f,
and checks whether tp->tp_flags & f is non-zero.
Py_TPFLAGS_HEAPTYPE
This bit is set when the type object itself is allocated on the heap, for example, types created dynamically
using PyType_FromSpec(). In this case, the ob_type field of its instances is considered a reference
to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when
an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the
instance’s ob_type gets INCREF’ed or DECREF’ed). Heap types should also support garbage collection
as they can form a reference cycle with their own module object.
Inheritance:
???
Py_TPFLAGS_BASETYPE
This bit is set when the type can be used as the base type of another type. If this bit is clear, the type
cannot be subtyped (similar to a “final” class in Java).
Inheritance:
???
Py_TPFLAGS_READY
This bit is set when the type object has been fully initialized by PyType_Ready().
Inheritance:
???
Py_TPFLAGS_READYING
This bit is set while PyType_Ready() is in the process of initializing the type object.
Inheritance:
???
Py_TPFLAGS_HAVE_GC
This bit is set when the object supports garbage collection. If this bit is set, instances must be created
using PyObject_GC_New and destroyed using PyObject_GC_Del(). More information in section
Supporting Cyclic Garbage Collection. This bit also implies that the GC-related fields tp_traverse and
tp_clear are present in the type object.
Inheritance:
Inheritance:
???
Py_TPFLAGS_METHOD_DESCRIPTOR
This bit indicates that objects behave like unbound methods.
If this flag is set for type(meth), then:
• meth.__get__(obj, cls)(*args, **kwds) (with obj not None) must be equivalent to
meth(obj, *args, **kwds).
• meth.__get__(None, cls)(*args, **kwds) must be equivalent to meth(*args,
**kwds).
This flag enables an optimization for typical method calls like obj.meth(): it avoids creating a tempo-
rary “bound method” object for obj.meth.
Added in version 3.8.
Inheritance:
This flag is never inherited by types without the Py_TPFLAGS_IMMUTABLETYPE flag set. For extension
types, it is inherited whenever tp_descr_get is inherited.
Py_TPFLAGS_MANAGED_DICT
This bit indicates that instances of the class have a ~object.__dict__ attribute, and that the space for the
dictionary is managed by the VM.
If this flag is set, Py_TPFLAGS_HAVE_GC should also be set.
The type traverse function must call PyObject_VisitManagedDict() and its clear function must call
PyObject_ClearManagedDict().
Inheritance:
This flag is inherited.
Py_TPFLAGS_LONG_SUBCLASS
Py_TPFLAGS_LIST_SUBCLASS
Py_TPFLAGS_TUPLE_SUBCLASS
Py_TPFLAGS_BYTES_SUBCLASS
Py_TPFLAGS_UNICODE_SUBCLASS
Py_TPFLAGS_DICT_SUBCLASS
Py_TPFLAGS_BASE_EXC_SUBCLASS
Py_TPFLAGS_TYPE_SUBCLASS
These flags are used by functions such as PyLong_Check() to quickly determine if a type is a subclass
of a built-in type; such specific checks are faster than a generic check, like PyObject_IsInstance().
Custom types that inherit from built-ins should have their tp_flags set appropriately, or the code that
interacts with such types will behave differently depending on what kind of check is used.
Py_TPFLAGS_HAVE_FINALIZE
This bit is set when the tp_finalize slot is present in the type structure.
Added in version 3.4.
Deprecated since version 3.8: This flag isn’t necessary anymore, as the interpreter assumes the
tp_finalize slot is always present in the type structure.
Py_TPFLAGS_HAVE_VECTORCALL
This bit is set when the class implements the vectorcall protocol. See tp_vectorcall_offset for
details.
Inheritance:
This bit is inherited if tp_call is also inherited.
Added in version 3.9.
Changed in version 3.12: This flag is now removed from a class when the class’s __call__() method
is reassigned.
This flag can now be inherited by mutable classes.
Py_TPFLAGS_IMMUTABLETYPE
This bit is set for type objects that are immutable: type attributes cannot be set nor deleted.
PyType_Ready() automatically applies this flag to static types.
Inheritance:
This flag is not inherited.
Added in version 3.10.
Py_TPFLAGS_DISALLOW_INSTANTIATION
Disallow creating instances of the type: set tp_new to NULL and don’t create the __new__ key in the
type dictionary.
The flag must be set before creating the type, not after. For example, it must be set before
PyType_Ready() is called on the type.
The flag is set automatically on static types if tp_base is NULL or &PyBaseObject_Type and tp_new
is NULL.
Inheritance:
This flag is not inherited. However, subclasses will not be instantiable unless they provide a non-NULL
tp_new (which is only possible via the C API).
® Note
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.
® Note
Inheritance:
This flag is inherited by types that do not already set Py_TPFLAGS_SEQUENCE.
µ See also
® Note
Inheritance:
This flag is inherited by types that do not already set Py_TPFLAGS_MAPPING .
µ See also
Á Warning
This flag is present in header files, but is not be used. It will be removed in a future version of CPython
More information about Python’s garbage collection scheme can be found in section Supporting Cyclic Garbage
Collection.
The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical implemen-
tation of a tp_traverse function simply calls Py_VISIT() on each of the instance’s members that are
Python objects that the instance owns. For example, this is function local_traverse() from the _thread
extension module:
static int
local_traverse(PyObject *op, visitproc visit, void *arg)
{
localobject *self = (localobject *) op;
Py_VISIT(self->args);
Py_VISIT(self->kw);
Py_VISIT(self->dict);
return 0;
}
Note that Py_VISIT() is called only on those members that can participate in reference cycles. Although
there is also a self->key member, it can only be NULL or a Python string and therefore cannot be part of a
reference cycle.
On the other hand, even if you know a member can never be part of a cycle, as a debugging aid you may want
to visit it anyway just so the gc module’s get_referents() function will include it.
Heap types (Py_TPFLAGS_HEAPTYPE) must visit their type with:
Py_VISIT(Py_TYPE(self));
It is only needed since Python 3.9. To support Python 3.8 and older, this line must be conditional:
If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, the traverse function must call
PyObject_VisitManagedDict() like this:
Á Warning
When implementing tp_traverse, only the members that the instance owns (by having strong references
to them) must be visited. For instance, if an object supports weak references via the tp_weaklist slot,
the pointer supporting the linked list (what tp_weaklist points to) must not be visited as the instance does
not directly own the weak references to itself (the weakreference list is there to support the weak reference
machinery, but the instance has no strong reference to the elements inside it, as they are allowed to be
removed even if the instance is still alive).
Note that Py_VISIT() requires the visit and arg parameters to local_traverse() to have these specific
names; don’t name them just anything.
Instances of heap-allocated types hold a reference to their type. Their traversal function must therefore either
visit Py_TYPE(self), or delegate this responsibility by calling tp_traverse of another heap-allocated type
(such as a heap-allocated superclass). If they do not, the type object may not be garbage-collected.
Changed in version 3.9: Heap-allocated types are expected to visit Py_TYPE(self) in tp_traverse. In
earlier versions of Python, due to bug 40217, doing this may lead to crashes in subclasses.
Inheritance:
Group: Py_TPFLAGS_HAVE_GC , tp_traverse, tp_clear
This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the flag
bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.
inquiry PyTypeObject.tp_clear
An optional pointer to a clear function for the garbage collector. This is only used if the
Py_TPFLAGS_HAVE_GC flag bit is set. The signature is:
The tp_clear member function is used to break reference cycles in cyclic garbage detected by the garbage
collector. Taken together, all tp_clear functions in the system must combine to break all reference cycles.
This is subtle, and if in any doubt supply a tp_clear function. For example, the tuple type does not implement
a tp_clear function, because it’s possible to prove that no reference cycle can be composed entirely of tuples.
Therefore the tp_clear functions of other types must be sufficient to break any cycle containing a tuple. This
isn’t immediately obvious, and there’s rarely a good reason to avoid implementing tp_clear.
Implementations of tp_clear should drop the instance’s references to those of its members that may be
Python objects, and set its pointers to those members to NULL, as in the following example:
static int
local_clear(PyObject *op)
{
localobject *self = (localobject *) op;
Py_CLEAR(self->key);
Py_CLEAR(self->args);
Py_CLEAR(self->kw);
Py_CLEAR(self->dict);
return 0;
}
The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the contained
object must not be released (via Py_DECREF()) until after the pointer to the contained object is set to NULL.
This is because releasing the reference may cause the contained object to become trash, triggering a chain of
reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks,
associated with the contained object). If it’s possible for such code to reference self again, it’s important that
the pointer to the contained object be NULL at that time, so that self knows the contained object can no longer
be used. The Py_CLEAR() macro performs the operations in a safe order.
If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, the traverse function must call
PyObject_ClearManagedDict() like this:
PyObject_ClearManagedDict((PyObject*)self);
Note that tp_clear is not always called before an instance is deallocated. For example, when reference
counting is enough to determine that an object is no longer used, the cyclic garbage collector is not involved
and tp_dealloc is called directly.
Because the goal of tp_clear functions is to break reference cycles, it’s not necessary to clear contained
objects like Python strings or Python integers, which can’t participate in reference cycles. On the other hand, it
may be convenient to clear all contained Python objects, and write the type’s tp_dealloc function to invoke
tp_clear.
More information about Python’s garbage collection scheme can be found in section Supporting Cyclic Garbage
Collection.
Inheritance:
Group: Py_TPFLAGS_HAVE_GC , tp_traverse, tp_clear
This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit: the
flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.
richcmpfunc PyTypeObject.tp_richcompare
An optional pointer to the rich comparison function, whose signature is:
The first parameter is guaranteed to be an instance of the type that is defined by PyTypeObject.
The function should return the result of the comparison (usually Py_True or Py_False). If the comparison
is undefined, it must return Py_NotImplemented, if another error occurred it must return NULL and set an
exception condition.
The following constants are defined to be used as the third argument for tp_richcompare and for
PyObject_RichCompare():
Constant Comparison
<
Py_LT
<=
Py_LE
==
Py_EQ
!=
Py_NE
>
Py_GT
>=
Py_GE
Inheritance:
This field is inherited by subtypes.
iternextfunc PyTypeObject.tp_iternext
An optional pointer to a function that returns the next item in an iterator. The signature is:
When the iterator is exhausted, it must return NULL; a StopIteration exception may or may not be set.
When another error occurs, it must return NULL too. Its presence signals that the instances of this type are
iterators.
Iterator types should also define the tp_iter function, and that function should return the iterator instance
itself (not a new iterator instance).
This function has the same signature as PyIter_Next().
Inheritance:
This field is inherited by subtypes.
struct PyMethodDef *PyTypeObject.tp_methods
An optional pointer to a static NULL-terminated array of PyMethodDef structures, declaring regular methods
of this type.
For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a method
descriptor.
Inheritance:
This field is not inherited by subtypes (methods are inherited through a different mechanism).
struct PyMemberDef *PyTypeObject.tp_members
An optional pointer to a static NULL-terminated array of PyMemberDef structures, declaring regular data
members (fields or slots) of instances of this type.
For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a member
descriptor.
Inheritance:
This field is not inherited by subtypes (members are inherited through a different mechanism).
struct PyGetSetDef *PyTypeObject.tp_getset
An optional pointer to a static NULL-terminated array of PyGetSetDef structures, declaring computed at-
tributes of instances of this type.
For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a getset
descriptor.
Inheritance:
This field is not inherited by subtypes (computed attributes are inherited through a different mechanism).
PyTypeObject *PyTypeObject.tp_base
An optional pointer to a base type from which type properties are inherited. At this level, only single inheritance
is supported; multiple inheritance require dynamically creating a type object by calling the metatype.
® Note
Slot initialization is subject to the rules of initializing globals. C99 requires the initializers to be “address
constants”. Function designators like PyType_GenericNew(), with implicit conversion to a pointer, are
valid C99 address constants.
However, the unary ‘&’ operator applied to a non-static variable like PyBaseObject_Type is not required
to produce an address constant. Compilers may support this (gcc does), MSVC does not. Both compilers
are strictly standard conforming in this particular behavior.
Consequently, tp_base should be set in the extension module’s init function.
Inheritance:
This field is not inherited by subtypes (obviously).
Default:
This field defaults to &PyBaseObject_Type (which to Python programmers is known as the type object).
PyObject *PyTypeObject.tp_dict
The type’s dictionary is stored here by PyType_Ready().
This field should normally be initialized to NULL before PyType_Ready is called; it may also be initialized to
a dictionary containing initial attributes for the type. Once PyType_Ready() has initialized the type, extra
attributes for the type may be added to this dictionary only if they don’t correspond to overloaded operations
(like __add__()). 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.
Changed in version 3.12: Internals detail: For static builtin types, this is always NULL. Instead, the dict for such
types is stored on PyInterpreterState. Use PyType_GetDict() to get the dict for an arbitrary type.
Inheritance:
This field is not inherited by subtypes (though the attributes defined in here are inherited through a different
mechanism).
Default:
If this field is NULL, PyType_Ready() will assign a new dictionary to it.
Á Warning
It is not safe to use PyDict_SetItem() on or otherwise modify tp_dict with the dictionary C-API.
descrgetfunc PyTypeObject.tp_descr_get
An optional pointer to a “descriptor get” function.
The function signature is:
Inheritance:
This field is inherited by subtypes.
descrsetfunc PyTypeObject.tp_descr_set
An optional pointer to a function for setting and deleting a descriptor’s value.
The function signature is:
Do not confuse this field with tp_dict; that is the dictionary for attributes of the type object itself.
The value specifies the offset of the dictionary from the start of the instance structure.
The tp_dictoffset should be regarded as write-only. To get the pointer to the dictionary call
PyObject_GenericGetDict(). Calling PyObject_GenericGetDict() may need to allocate memory
for the dictionary, so it is may be more efficient to call PyObject_GetAttr() when accessing an attribute
on the object.
Default:
This slot has no default. For static types, if the field is NULL then no __dict__ gets created for instances.
If the Py_TPFLAGS_MANAGED_DICT bit is set in the tp_flags field, then tp_dictoffset will be set to
-1, to indicate that it is unsafe to use this field.
initproc PyTypeObject.tp_init
An optional pointer to an instance initialization function.
This function corresponds to the __init__() method of classes. Like __init__(), it is possible to create an
instance without calling __init__(), and it is possible to reinitialize an instance by calling its __init__()
method again.
The function signature is:
The self argument is the instance to be initialized; the args and kwds arguments represent positional and key-
word arguments of the call to __init__().
The tp_init function, if not NULL, is called when an instance is created normally by calling its type, after
the type’s tp_new function has returned an instance of the type. If the tp_new function returns an instance
of some other type that is not a subtype of the original type, no tp_init function is called; if tp_new returns
an instance of a subtype of the original type, the subtype’s tp_init is called.
Returns 0 on success, -1 and sets an exception on error.
Inheritance:
This field is inherited by subtypes.
Default:
For static types this field does not have a default.
allocfunc PyTypeObject.tp_alloc
An optional pointer to an instance allocation function.
The function signature is:
Inheritance:
This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement).
Default:
For dynamic subtypes, this field is always set to PyType_GenericAlloc(), to force a standard heap alloca-
tion strategy.
For static subtypes, PyBaseObject_Type uses PyType_GenericAlloc(). That is the recommended value
for all statically defined types.
newfunc PyTypeObject.tp_new
An optional pointer to an instance creation function.
The function signature is:
The subtype argument is the type of the object being created; the args and kwds arguments represent positional
and keyword arguments of the call to the type. Note that subtype doesn’t have to equal the type whose tp_new
function is called; it may be a subtype of that type (but not an unrelated type).
The tp_new function should call subtype->tp_alloc(subtype, nitems) to allocate space for the ob-
ject, and then do only as much further initialization as is absolutely necessary. Initialization that can safely be
ignored or repeated should be placed in the tp_init handler. A good rule of thumb is that for immutable
types, all initialization should take place in tp_new , while for mutable types, most initialization should be
deferred to tp_init.
Set the Py_TPFLAGS_DISALLOW_INSTANTIATION flag to disallow creating instances of the type in Python.
Inheritance:
This field is inherited by subtypes, except it is not inherited by static types whose tp_base is NULL or
&PyBaseObject_Type.
Default:
For static types this field has no default. This means if the slot is defined as NULL, the type cannot be called to
create new instances; presumably there is some other way to create instances, like a factory function.
freefunc PyTypeObject.tp_free
An optional pointer to an instance deallocation function. Its signature is:
(The only example of this are types themselves. The metatype, PyType_Type, defines this function to distin-
guish between statically and dynamically allocated types.)
Inheritance:
This field is inherited by subtypes.
Default:
This slot has no default. If this field is NULL, Py_TPFLAGS_HAVE_GC is used as the functional equivalent.
PyObject *PyTypeObject.tp_bases
Tuple of base types.
This 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.
Á Warning
Multiple inheritance does not work well for statically defined types. If you set tp_bases to a tuple, Python
will not raise an error, but some slots will only be inherited from the first base.
Inheritance:
This field is not inherited.
PyObject *PyTypeObject.tp_mro
Tuple containing the expanded set of base types, starting with the type itself and ending with object, in
Method Resolution Order.
This field should be set to NULL and treated as read-only. Python will fill it in when the type is initialized.
Inheritance:
This field is not inherited; it is calculated fresh by PyType_Ready().
PyObject *PyTypeObject.tp_cache
Unused. Internal use only.
Inheritance:
This field is not inherited.
void *PyTypeObject.tp_subclasses
A collection of subclasses. Internal use only. May be an invalid pointer.
To get a list of subclasses, call the Python method __subclasses__().
Changed in version 3.12: For some types, this field does not hold a valid PyObject*. The type was changed
to void* to indicate this.
Inheritance:
This field is not inherited.
PyObject *PyTypeObject.tp_weaklist
Weak reference list head, for weak references to this type object. Not inherited. Internal use only.
Changed in version 3.12: Internals detail: For the static builtin types this is always NULL, even if weakrefs are
added. Instead, the weakrefs for each are stored on PyInterpreterState. Use the public C-API or the
internal _PyObject_GET_WEAKREFS_LISTPTR() macro to avoid the distinction.
Inheritance:
This field is not inherited.
destructor PyTypeObject.tp_del
This field is deprecated. Use tp_finalize instead.
unsigned int PyTypeObject.tp_version_tag
Used to index into the method cache. Internal use only.
Inheritance:
This field is not inherited.
destructor PyTypeObject.tp_finalize
An optional pointer to an instance finalization function. Its signature is:
If tp_finalize is set, the interpreter calls it once when finalizing an instance. It is called either from the
garbage collector (if the instance is part of an isolated reference cycle) or just before the object is deallocated.
Either way, it is guaranteed to be called before attempting to break reference cycles, ensuring that it finds the
object in a sane state.
tp_finalize should not mutate the current exception status; therefore, a recommended way to write a non-
trivial finalizer is:
static void
local_finalize(PyObject *self)
{
/* Save the current exception, if any. */
PyObject *exc = PyErr_GetRaisedException();
/* ... */
Inheritance:
This field is inherited by subtypes.
Added in version 3.4.
Changed in version 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.
µ See also
vectorcallfunc PyTypeObject.tp_vectorcall
A vectorcall function to use for calls of this type object (rather than instances). In other words,
tp_vectorcall can be used to optimize type.__call__, which typically returns a new instance of type.
As with any vectorcall function, if tp_vectorcall is NULL, the tp_call protocol
(Py_TYPE(type)->tp_call) is used instead.
® Note
The vectorcall protocol requires that the vectorcall function has the same behavior as the cor-
responding tp_call. This means that type->tp_vectorcall must match the behavior of
Py_TYPE(type)->tp_call.
Specifically, if type uses the default metaclass, type->tp_vectorcall must behave the same as
PyType_Type->tp_call, which:
• calls type->tp_new,
• if the result is a subclass of type, calls type->tp_init on the result of tp_new, and
• returns the result of tp_new.
Typically, tp_vectorcall is overridden to optimize this process for specific tp_new and tp_init.
When doing this for user-subclassable types, note that both can be overridden (using __new__() and
__init__(), respectively).
Inheritance:
This field is never inherited.
Added in version 3.9: (the field exists since 3.8 but it’s only used since 3.9)
unsigned char PyTypeObject.tp_watched
Internal. Do not use.
Added in version 3.12.
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;
(continues on next page)
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;
® Note
Binary and ternary functions must check the type of all their operands, and implement the necessary con-
versions (at least one of the operands is an instance of the defined type). If the operation is not defined
for the given operands, binary and ternary functions must return Py_NotImplemented, if another error
occurred they must return NULL and set an exception.
® Note
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
ssizeargfunc PySequenceMethods.sq_inplace_repeat
This function is used by PySequence_InPlaceRepeat() and has the same signature. It should modify its
first operand, and return it. This slot may be left to NULL, in this case PySequence_InPlaceRepeat() will
fall back to PySequence_Repeat(). It is also used by the augmented assignment *=, after trying numeric
in-place multiplication via the nb_inplace_multiply slot.
Handle a request to exporter to fill in view as specified by flags. Except for point (3), an implementation of this
function MUST take these steps:
(1) Check if the request can be met. If not, raise BufferError, set view->obj to NULL and return -1.
(2) Fill in the requested fields.
(3) Increment an internal counter for the number of exports.
(4) Set view->obj to exporter and increment view->obj.
(5) Return 0.
If exporter is part of a chain or tree of buffer providers, two main schemes can be used:
• Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference
to itself.
• Redirect: The buffer request is redirected to the root object of the tree. Here, view->obj will be a new
reference to the root object.
The individual fields of view are described in section Buffer structure, the rules how an exporter must react to
specific requests are in section Buffer request types.
All memory pointed to in the Py_buffer structure belongs to the exporter and must remain valid until there are
no consumers left. format, shape, strides, suboffsets and internal are read-only for the consumer.
PyBuffer_FillInfo() provides an easy way of exposing a simple bytes buffer while dealing correctly with
all request types.
PyObject_GetBuffer() is the interface for the consumer that wraps this function.
releasebufferproc PyBufferProcs.bf_releasebuffer
The signature of this function is:
Handle a request to release the resources of the buffer. If no resources need to be released, PyBufferProcs.
bf_releasebuffer may be NULL. Otherwise, a standard implementation of this function will take these
optional steps:
(1) Decrement an internal counter for the number of exports.
(2) If the counter is 0, free all memory associated with view.
The exporter MUST use the internal field to keep track of buffer-specific resources. This field is guaranteed
to remain constant, while a consumer MAY pass a copy of the original buffer as the view argument.
This function MUST NOT decrement view->obj, since that is done automatically in PyBuffer_Release()
(this scheme is useful for breaking reference cycles).
PyBuffer_Release() is the interface for the consumer that wraps this function.
typedef struct {
unaryfunc am_await;
unaryfunc am_aiter;
unaryfunc am_anext;
sendfunc am_send;
} PyAsyncMethods;
unaryfunc PyAsyncMethods.am_await
The signature of this function is:
The returned object must be an iterator, i.e. PyIter_Check() must return 1 for it.
This slot may be set to NULL if an object is not an awaitable.
unaryfunc PyAsyncMethods.am_aiter
The signature of this function is:
Must return an awaitable object. See __anext__() for details. This slot may be set to NULL.
sendfunc PyAsyncMethods.am_send
The signature of this function is:
This function should not do any other instance initialization, not even to allocate additional memory; that should
be done by tp_new .
typedef void (*destructor)(PyObject*)
Part of the Stable ABI.
typedef void (*freefunc)(void*)
See tp_free.
typedef PyObject *(*newfunc)(PyTypeObject*, PyObject*, PyObject*)
Part of the Stable ABI. See tp_new .
typedef int (*initproc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. See tp_init.
typedef PyObject *(*reprfunc)(PyObject*)
Part of the Stable ABI. See tp_repr.
typedef PyObject *(*getattrfunc)(PyObject *self, char *attr)
Part of the Stable ABI. Return the value of the named attribute for the object.
typedef int (*setattrfunc)(PyObject *self, char *attr, PyObject *value)
Part of the Stable ABI. Set the value of the named attribute for the object. The value argument is set to NULL
to delete the attribute.
typedef PyObject *(*getattrofunc)(PyObject *self, PyObject *attr)
Part of the Stable ABI. Return the value of the named attribute for the object.
See tp_getattro.
typedef int (*setattrofunc)(PyObject *self, PyObject *attr, PyObject *value)
Part of the Stable ABI. Set the value of the named attribute for the object. The value argument is set to NULL
to delete the attribute.
See tp_setattro.
typedef PyObject *(*descrgetfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. See tp_descr_get.
typedef int (*descrsetfunc)(PyObject*, PyObject*, PyObject*)
Part of the Stable ABI. See tp_descr_set.
typedef Py_hash_t (*hashfunc)(PyObject*)
Part of the Stable ABI. See tp_hash.
typedef PyObject *(*richcmpfunc)(PyObject*, PyObject*, int)
Part of the Stable ABI. See tp_richcompare.
typedef PyObject *(*getiterfunc)(PyObject*)
Part of the Stable ABI. See tp_iter.
typedef PyObject *(*iternextfunc)(PyObject*)
Part of the Stable ABI. See tp_iternext.
typedef Py_ssize_t (*lenfunc)(PyObject*)
Part of the Stable ABI.
typedef int (*getbufferproc)(PyObject*, Py_buffer*, int)
Part of the Stable ABI since version 3.12.
typedef void (*releasebufferproc)(PyObject*, Py_buffer*)
Part of the Stable ABI since version 3.12.
12.3.14 Examples
The following are simple examples of Python type definitions. They include common usage you may encounter.
Some demonstrate tricky corner cases. For more examples, practical info, and a tutorial, see defining-new-types and
new-types-topics.
A basic static type:
typedef struct {
PyObject_HEAD
const char *data;
} MyObject;
You may also find older code (especially in the CPython code base) with a more verbose initializer:
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;
2. Once all the fields which may contain references to other containers are initialized, it must call
PyObject_GC_Track().
Similarly, the deallocator for the object must conform to a similar pair of rules:
1. Before fields which refer to other containers are invalidated, PyObject_GC_UnTrack() must be called.
2. The object’s memory must be deallocated using PyObject_GC_Del().
Á Warning
If a type adds the Py_TPFLAGS_HAVE_GC, then it must implement at least a tp_traverse handler or
explicitly use one from its subclass or subclasses.
When calling PyType_Ready() or some of the APIs that indirectly call it like
PyType_FromSpecWithBases() or PyType_FromSpec() the interpreter will automatically populate
the tp_flags, tp_traverse and tp_clear fields if the type inherits from a class that implements the
garbage collector protocol and the child class does not include the Py_TPFLAGS_HAVE_GC flag.
PyObject_GC_New(TYPE, typeobj)
Analogous to PyObject_New but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
PyObject_GC_NewVar(TYPE, typeobj, size)
Analogous to PyObject_NewVar but for container objects with the Py_TPFLAGS_HAVE_GC flag set.
PyObject *PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *type, size_t extra_size)
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.
Á Warning
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.
Changed in version 3.8: The _PyObject_GC_TRACK() and _PyObject_GC_UNTRACK() macros have been re-
moved from the public C API.
The tp_traverse handler accepts a function parameter of this type:
typedef int (*visitproc)(PyObject *object, void *arg)
Part of the Stable ABI. Type of the visitor function passed to the tp_traverse handler. The function should
be called with an object to traverse as object and the third parameter to the tp_traverse handler as arg. The
Python core uses several visitor functions to implement cyclic garbage detection; it’s not expected that users
will need to write their own visitor functions.
The tp_traverse handler must have the following type:
typedef int (*traverseproc)(PyObject *self, visitproc visit, void *arg)
Part of the Stable ABI. Traversal function for a container object. Implementations must call the visit function
for each object directly contained by self, with the parameters to visit being the contained object and the arg
value passed to the handler. The visit function must not be called with a NULL object argument. If visit returns
a non-zero value that value should be returned immediately.
To simplify writing tp_traverse handlers, a Py_VISIT() macro is provided. In order to use this macro, the
tp_traverse implementation must name its arguments exactly visit and arg:
void Py_VISIT(PyObject *o)
If o is not NULL, call the visit callback, with arguments o and arg. If visit returns a non-zero value, then return
it. Using this macro, tp_traverse handlers look like:
static int
my_traverse(Noddy *self, visitproc visit, void *arg)
{
Py_VISIT(self->foo);
Py_VISIT(self->bar);
return 0;
}
The tp_clear handler must be of the inquiry type, or NULL if the object is immutable.
Returns the number of collected + unreachable objects which cannot be collected. If the garbage collector
is disabled or already collecting, returns 0 immediately. Errors during garbage collection are passed to sys.
unraisablehook. This function does not raise exceptions.
int PyGC_Enable(void)
Part of the Stable ABI since version 3.10. Enable the garbage collector: similar to gc.enable(). Returns the
previous state, 0 for disabled and 1 for enabled.
Added in version 3.10.
int PyGC_Disable(void)
Part of the Stable ABI since version 3.10. Disable the garbage collector: similar to gc.disable(). Returns
the previous state, 0 for disabled and 1 for enabled.
Added in version 3.10.
int PyGC_IsEnabled(void)
Part of the Stable ABI since version 3.10. Query the state of the garbage collector: similar to gc.
isenabled(). Returns the current state, 0 for disabled and 1 for enabled.
Run supplied callback on all live GC-capable objects. arg is passed through to all invocations of callback.
Á Warning
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.
THIRTEEN
331
The Python/C API, Release 3.14.0a7
For example:
Out-of range bits in the arguments are ignored. That is, the macro can be defined as:
#ifndef Py_PACK_FULL_VERSION
#define Py_PACK_FULL_VERSION(X, Y, Z, LEVEL, SERIAL) ( \
(((X) & 0xff) << 24) | \
(((Y) & 0xff) << 16) | \
(((Z) & 0xff) << 8) | \
(((LEVEL) & 0xf) << 4) | \
(((SERIAL) & 0xf) << 0))
#endif
Py_PACK_FULL_VERSION is primarily a macro, intended for use in #if directives, but it is also available as
an exported function.
Added in version 3.14.
uint32_t Py_PACK_VERSION(int major, int minor)
Part of the Stable ABI since version 3.14. Equivalent to Py_PACK_FULL_VERSION(major, minor, 0,
0, 0). The result does not correspond to any Python release, but is useful in numeric comparisons.
FOURTEEN
MONITORING C API
333
The Python/C API, Release 3.14.0a7
FIFTEEN
The functions below make it possible for an extension to fire monitoring events as it emulates the execution of Python
code. Each of these functions accepts a PyMonitoringState struct which contains concise information about the
activation state of events, as well as the event arguments, which include a PyObject* representing the code object,
the instruction offset and sometimes additional, event-specific arguments (see sys.monitoring for details about
the signatures of the different event callbacks). The codelike argument should be an instance of types.CodeType
or of a type that emulates it.
The VM disables tracing when firing an event, so there is no need for user code to do that.
Monitoring functions should not be called with an exception set, except those listed below as working with the current
exception.
type PyMonitoringState
Representation of the state of an event type. It is allocated by the user while its contents are maintained by the
monitoring API functions described below.
All of the functions below return 0 on success and -1 (with an exception set) on error.
See sys.monitoring for descriptions of the events.
int PyMonitoring_FirePyStartEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
Fire a PY_START event.
int PyMonitoring_FirePyResumeEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
Fire a PY_RESUME event.
int PyMonitoring_FirePyReturnEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
PyObject *retval)
Fire a PY_RETURN event.
int PyMonitoring_FirePyYieldEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject
*retval)
Fire a PY_YIELD event.
int PyMonitoring_FireCallEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject
*callable, PyObject *arg0)
Fire a CALL event.
int PyMonitoring_FireLineEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, int lineno)
Fire a LINE event.
int PyMonitoring_FireJumpEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject
*target_offset)
Fire a JUMP event.
int PyMonitoring_FireBranchLeftEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
PyObject *target_offset)
Fire a BRANCH_LEFT event.
335
The Python/C API, Release 3.14.0a7
The version argument is a pointer to a value which should be allocated by the user together with
state_array and initialized to 0, and then set only by PyMonitoring_EnterScope() itself. It allows
this function to determine whether event states have changed since the previous call, and to return quickly if
they have not.
The scopes referred to here are lexical scopes: a function, class or method. PyMonitoring_EnterScope()
should be called whenever the lexical scope is entered. Scopes can be reentered, reusing the same state_array
and version, in situations like when emulating a recursive Python function. When a code-like’s execution is
paused, such as when emulating a generator, the scope needs to be exited and re-entered.
The macros for event_types are:
Macro Event
BRANCH_LEFT
PY_MONITORING_EVENT_BRANCH_LEFT
BRANCH_RIGHT
PY_MONITORING_EVENT_BRANCH_RIGHT
CALL
PY_MONITORING_EVENT_CALL
C_RAISE
PY_MONITORING_EVENT_C_RAISE
C_RETURN
PY_MONITORING_EVENT_C_RETURN
EXCEPTION_HANDLED
PY_MONITORING_EVENT_EXCEPTION_HANDLED
INSTRUCTION
PY_MONITORING_EVENT_INSTRUCTION
JUMP
PY_MONITORING_EVENT_JUMP
LINE
PY_MONITORING_EVENT_LINE
PY_RESUME
PY_MONITORING_EVENT_PY_RESUME
PY_RETURN
PY_MONITORING_EVENT_PY_RETURN
PY_START
PY_MONITORING_EVENT_PY_START
PY_THROW
PY_MONITORING_EVENT_PY_THROW
PY_UNWIND
PY_MONITORING_EVENT_PY_UNWIND
PY_YIELD
PY_MONITORING_EVENT_PY_YIELD
RAISE
PY_MONITORING_EVENT_RAISE
RERAISE
PY_MONITORING_EVENT_RERAISE
STOP_ITERATION
PY_MONITORING_EVENT_STOP_ITERATION
int PyMonitoring_ExitScope(void)
GLOSSARY
>>>
The default Python prompt of the interactive shell. Often seen for code examples which can be executed
interactively in the interpreter.
...
Can refer to:
• The default Python prompt of the interactive shell when entering the code for an indented code block,
when within a pair of matching left and right delimiters (parentheses, square brackets, curly braces or
triple quotes), or after specifying a decorator.
• The Ellipsis built-in constant.
abstract base class
Abstract base classes complement duck-typing by providing a way to define interfaces when other techniques
like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual
subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and
issubclass(); see the abc module documentation. Python comes with many built-in ABCs for data struc-
tures (in the collections.abc module), numbers (in the numbers module), streams (in the io module),
import finders and loaders (in the importlib.abc module). You can create your own ABCs with the abc
module.
annotate function
A function that can be called to retrieve the annotations of an object. This function is accessible as the
__annotate__ attribute of functions, classes, and modules. Annotate functions are a subset of evaluate
functions.
annotation
A label associated with a variable, a class attribute or a function parameter or return value, used by convention
as a type hint.
Annotations of local variables cannot be accessed at runtime, but annotations of global variables, class at-
tributes, and functions can be retrieved by calling annotationlib.get_annotations() on modules,
classes, and functions, respectively.
See variable annotation, function annotation, PEP 484, PEP 526, and PEP 649, which describe this func-
tionality. Also see annotations-howto for best practices on working with annotations.
argument
A value passed to a function (or method) when calling the function. There are two kinds of argument:
• keyword argument: an argument preceded by an identifier (e.g. name=) in a function call or passed as a
value in a dictionary preceded by **. For example, 3 and 5 are both keyword arguments in the following
calls to complex():
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})
• positional argument: an argument that is not a keyword argument. Positional arguments can appear at the
beginning of an argument list and/or be passed as elements of an iterable preceded by *. For example, 3
339
The Python/C API, Release 3.14.0a7
complex(3, 5)
complex(*(3, 5))
Arguments are assigned to the named local variables in a function body. See the calls section for the rules
governing this assignment. Syntactically, any expression can be used to represent an argument; the evaluated
value is assigned to the local variable.
See also the parameter glossary entry, the FAQ question on the difference between arguments and parameters,
and PEP 362.
asynchronous context manager
An object which controls the environment seen in an async with statement by defining __aenter__() and
__aexit__() methods. Introduced by PEP 492.
asynchronous generator
A function which returns an asynchronous generator iterator. It looks like a coroutine function defined with
async def except that it contains yield expressions for producing a series of values usable in an async
for loop.
Usually refers to an asynchronous generator function, but may refer to an asynchronous generator iterator in
some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity.
An asynchronous generator function may contain await expressions as well as async for, and async with
statements.
asynchronous generator iterator
An object created by a asynchronous generator function.
This is an asynchronous iterator which when called using the __anext__() method returns an awaitable object
which will execute the body of the asynchronous generator function until the next yield expression.
Each yield temporarily suspends processing, remembering the execution state (including local variables and
pending try-statements). When the asynchronous generator iterator effectively resumes with another awaitable
returned by __anext__(), it picks up where it left off. See PEP 492 and PEP 525.
asynchronous iterable
An object, that can be used in an async for statement. Must return an asynchronous iterator from its
__aiter__() method. Introduced by PEP 492.
asynchronous iterator
An object that implements the __aiter__() and __anext__() methods. __anext__() must return an
awaitable object. async for resolves the awaitables returned by an asynchronous iterator’s __anext__()
method until it raises a StopAsyncIteration exception. Introduced by PEP 492.
attached thread state
A thread state that is active for the current OS thread.
When a thread state is attached, the OS thread has access to the full Python C API and can safely invoke the
bytecode interpreter.
Unless a function explicitly notes otherwise, attempting to call the C API without an attached thread state will
result in a fatal error or undefined behavior. A thread state can be attached and detached explicitly by the
user through the C API, or implicitly by the runtime, including during blocking C calls and by the bytecode
interpreter in between calls.
On most builds of Python, having an attached thread state implies that the caller holds the GIL for the current
interpreter, so only one OS thread can have an attached thread state at a given moment. In free-threaded builds
of Python, threads can concurrently hold an attached thread state, allowing for true parallelism of the bytecode
interpreter.
attribute
A value associated with an object which is usually referenced by name using dotted expressions. For example,
if an object o has an attribute a it would be referenced as o.a.
It is possible to give an object an attribute whose name is not an identifier as defined by identifiers, for example
using setattr(), if the object allows it. Such an attribute will not be accessible using a dotted expression,
and would instead need to be retrieved with getattr().
awaitable
An object that can be used in an await expression. Can be a coroutine or an object with an __await__()
method. See also PEP 492.
BDFL
Benevolent Dictator For Life, a.k.a. Guido van Rossum, Python’s creator.
binary file
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.
See also text file for a file object able to read and write str objects.
borrowed reference
In Python’s C API, a borrowed reference is a reference to an object, where the code using the object does not
own the reference. It becomes a dangling pointer if the object is destroyed. For example, a garbage collection
can remove the last strong reference to the object and so destroy it.
Calling Py_INCREF() on the borrowed reference is recommended to convert it to a strong reference in-place,
except when the object cannot be destroyed before the last usage of the borrowed reference. The Py_NewRef()
function can be used to create a new strong reference.
bytes-like object
An object that supports the Buffer Protocol and can export a C-contiguous buffer. This includes all bytes,
bytearray, and array.array objects, as well as many common memoryview objects. Bytes-like objects
can be used for various operations that work with binary data; these include compression, saving to a binary
file, and sending over a socket.
Some operations need the binary data to be mutable. The documentation often refers to these as “read-write
bytes-like objects”. Example mutable buffer objects include bytearray and a memoryview of a bytearray.
Other operations require the binary data to be stored in immutable objects (“read-only bytes-like objects”);
examples of these include bytes and a memoryview of a bytes object.
bytecode
Python source code is compiled into bytecode, the internal representation of a Python program in the CPython
interpreter. The bytecode is also cached in .pyc files so that executing the same file is faster the second time
(recompilation from source to bytecode can be avoided). This “intermediate language” is said to run on a
virtual machine that executes the machine code corresponding to each bytecode. Do note that bytecodes are
not expected to work between different Python virtual machines, nor to be stable between Python releases.
A list of bytecode instructions can be found in the documentation for the dis module.
callable
A callable is an object that can be called, possibly with a set of arguments (see argument), with the following
syntax:
A function, and by extension a method, is a callable. An instance of a class that implements the __call__()
method is also a callable.
callback
A subroutine function which is passed as an argument to be executed at some point in the future.
class
A template for creating user-defined objects. Class definitions normally contain method definitions which
operate on instances of the class.
class variable
A variable defined in a class and intended to be modified only at class level (i.e., not in an instance of the class).
341
The Python/C API, Release 3.14.0a7
closure variable
A free variable referenced from a nested scope that is defined in an outer scope rather than being resolved at
runtime from the globals or builtin namespaces. May be explicitly defined with the nonlocal keyword to
allow write access, or implicitly defined if the variable is only being read.
For example, in the inner function in the following code, both x and print are free variables, but only x is
a closure variable:
def outer():
x = 0
def inner():
nonlocal x
x += 1
print(x)
return inner
Due to the codeobject.co_freevars attribute (which, despite its name, only includes the names of closure
variables rather than listing all referenced free variables), the more general free variable term is sometimes used
even when the intended meaning is to refer specifically to closure variables.
complex number
An extension of the familiar real number system in which all numbers are expressed as a sum of a real part and
an imaginary part. Imaginary numbers are real multiples of the imaginary unit (the square root of -1), often
written i in mathematics or j in engineering. Python has built-in support for complex numbers, which are
written with this latter notation; the imaginary part is written with a j suffix, e.g., 3+1j. To get access to com-
plex equivalents of the math module, use cmath. Use of complex numbers is a fairly advanced mathematical
feature. If you’re not aware of a need for them, it’s almost certain you can safely ignore them.
context
This term has different meanings depending on where and how it is used. Some common meanings:
• The temporary state or environment established by a context manager via a with statement.
• The collection of keyvalue bindings associated with a particular contextvars.Context object and
accessed via ContextVar objects. Also see context variable.
• A contextvars.Context object. Also see current context.
context management protocol
The __enter__() and __exit__() methods called by the with statement. See PEP 343.
context manager
An object which implements the context management protocol and controls the environment seen in a with
statement. See PEP 343.
context variable
A variable whose value depends on which context is the current context. Values are accessed via
contextvars.ContextVar objects. Context variables are primarily used to isolate state between concur-
rent asynchronous tasks.
contiguous
A buffer is considered contiguous exactly if it is either C-contiguous or Fortran contiguous. Zero-dimensional
buffers are C and Fortran contiguous. In one-dimensional arrays, the items must be laid out in memory next
to each other, in order of increasing indexes starting from zero. In multidimensional C-contiguous arrays, the
last index varies the fastest when visiting items in order of memory address. However, in Fortran contiguous
arrays, the first index varies the fastest.
coroutine
Coroutines are a more generalized form of subroutines. Subroutines are entered at one point and exited at
another point. Coroutines can be entered, exited, and resumed at many different points. They can be imple-
mented with the async def statement. See also PEP 492.
coroutine function
A function which returns a coroutine object. A coroutine function may be defined with the async def state-
ment, and may contain await, async for, and async with keywords. These were introduced by PEP
492.
CPython
The canonical implementation of the Python programming language, as distributed on python.org. The term
“CPython” is used when necessary to distinguish this implementation from others such as Jython or IronPython.
current context
The context (contextvars.Context object) that is currently used by ContextVar objects to access (get
or set) the values of context variables. Each thread has its own current context. Frameworks for executing
asynchronous tasks (see asyncio) associate each task with a context which becomes the current context
whenever the task starts or resumes execution.
decorator
A function returning another function, usually applied as a function transformation using the @wrapper syntax.
Common examples for decorators are classmethod() and staticmethod().
The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equiv-
alent:
def f(arg):
...
f = staticmethod(f)
@staticmethod
def f(arg):
...
The same concept exists for classes, but is less commonly used there. See the documentation for function
definitions and class definitions for more about decorators.
descriptor
Any object which defines the methods __get__(), __set__(), or __delete__(). When a class attribute
is a descriptor, its special binding behavior is triggered upon attribute lookup. Normally, using a.b to get,
set or delete an attribute looks up the object named b in the class dictionary for a, but if b is a descriptor,
the respective descriptor method gets called. Understanding descriptors is a key to a deep understanding of
Python because they are the basis for many features including functions, methods, properties, class methods,
static methods, and reference to super classes.
For more information about descriptors’ methods, see descriptors or the Descriptor How To Guide.
dictionary
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.
dictionary comprehension
A compact way to process all or part of the elements in an iterable and return a dictionary with the re-
sults. results = {n: n ** 2 for n in range(10)} generates a dictionary containing key n mapped
to value n ** 2. See comprehensions.
dictionary view
The objects returned from dict.keys(), dict.values(), and dict.items() are called dictionary views.
They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the
view reflects these changes. To force the dictionary view to become a full list use list(dictview). See
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.
duck-typing
A programming style which does not look at an object’s type to determine if it has the right interface; instead,
343
The Python/C API, Release 3.14.0a7
the method or attribute is simply called or used (“If it looks like a duck and quacks like a duck, it must be
a duck.”) By emphasizing interfaces rather than specific types, well-designed code improves its flexibility
by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). (Note,
however, that duck-typing can be complemented with abstract base classes.) Instead, it typically employs
hasattr() tests or EAFP programming.
EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of
valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is
characterized by the presence of many try and except statements. The technique contrasts with the LBYL
style common to many other languages such as C.
evaluate function
A function that can be called to evaluate a lazily evaluated attribute of an object, such as the value of type
aliases created with the type statement.
expression
A piece of syntax which can be evaluated to some value. In other words, an expression is an accumulation of
expression elements like literals, names, attribute access, operators or function calls which all return a value. In
contrast to many other languages, not all language constructs are expressions. There are also statements which
cannot be used as expressions, such as while. Assignments are also statements, not expressions.
extension module
A module written in C or C++, using Python’s C API to interact with the core and with user code.
f-string
String literals prefixed with 'f' or 'F' are commonly called “f-strings” which is short for formatted string
literals. See also PEP 498.
file object
An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.
Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of
storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.).
File objects are also called file-like objects or streams.
There are actually three categories of file objects: raw binary files, buffered binary files and text files. Their
interfaces are defined in the io module. The canonical way to create a file object is by using the open()
function.
file-like object
A synonym for file object.
filesystem encoding and error handler
Encoding and error handler used by Python to decode bytes from the operating system and encode Unicode to
the operating system.
The filesystem encoding must guarantee to successfully decode all bytes below 128. If the file system encoding
fails to provide this guarantee, API functions can raise UnicodeError.
The sys.getfilesystemencoding() and sys.getfilesystemencodeerrors() functions can be
used to get the filesystem encoding and error handler.
The filesystem encoding and error handler are configured at Python startup by the PyConfig_Read() func-
tion: see filesystem_encoding and filesystem_errors members of PyConfig .
See also the locale encoding.
finder
An object that tries to find the loader for a module that is being imported.
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 finders-and-loaders and importlib for much more detail.
floor division
Mathematical division that rounds down to nearest integer. The floor division operator is //. For example, the
expression 11 // 4 evaluates to 2 in contrast to the 2.75 returned by float true division. Note that (-11)
// 4 is -3 because that is -2.75 rounded downward. See PEP 238.
free threading
A threading model where multiple threads can run Python bytecode simultaneously within the same interpreter.
This is in contrast to the global interpreter lock which allows only one thread to execute Python bytecode at a
time. See PEP 703.
free variable
Formally, as defined in the language execution model, a free variable is any variable used in a namespace
which is not a local variable in that namespace. See closure variable for an example. Pragmatically, due to the
name of the codeobject.co_freevars attribute, the term is also sometimes used as a synonym for closure
variable.
function
A series of statements which returns some value to a caller. It can also be passed zero or more arguments which
may be used in the execution of the body. See also parameter, method, and the function section.
function annotation
An annotation of a function parameter or return value.
Function annotations are usually used for type hints: for example, this function is expected to take two int
arguments and is also expected to have an int return value:
garbage collection
The process of freeing memory when it is not used anymore. Python performs garbage collection via reference
counting and a cyclic garbage collector that is able to detect and break reference cycles. The garbage collector
can be controlled using the gc module.
generator
A function which returns a generator iterator. It looks like a normal function except that it contains yield
expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the
next() function.
Usually refers to a generator function, but may refer to a generator iterator in some contexts. In cases where
the intended meaning isn’t clear, using the full terms avoids ambiguity.
generator iterator
An object created by a generator function.
Each yield temporarily suspends processing, remembering the execution state (including local variables and
pending try-statements). When the generator iterator resumes, it picks up where it left off (in contrast to
functions which start fresh on every invocation).
generator expression
An expression that returns an iterator. It looks like a normal expression followed by a for clause defining a
345
The Python/C API, Release 3.14.0a7
loop variable, range, and an optional if clause. The combined expression generates values for an enclosing
function:
generic function
A function composed of multiple functions implementing the same operation for different types. Which im-
plementation should be used during a call is determined by the dispatch algorithm.
See also the single dispatch glossary entry, the functools.singledispatch() decorator, and PEP 443.
generic type
A type that can be parameterized; typically a container class such as list or dict. Used for type hints and
annotations.
For more details, see generic alias types, PEP 483, PEP 484, PEP 585, and the typing module.
GIL
See global interpreter lock.
global interpreter lock
The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at
a time. This simplifies the CPython implementation by making the object model (including critical built-in
types such as dict) implicitly safe against concurrent access. Locking the entire interpreter makes it easier
for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor
machines.
However, some extension modules, either standard or third-party, are designed so as to release the GIL when
doing computationally intensive tasks such as compression or hashing. Also, the GIL is always released when
doing I/O.
As of Python 3.13, the GIL can be disabled using the --disable-gil build configuration. After building
Python with this option, code must be run with -X gil=0 or after setting the PYTHON_GIL=0 environment
variable. This feature enables improved performance for multi-threaded applications and makes it easier to
use multi-core CPUs efficiently. For more details, see PEP 703.
In prior versions of Python’s C API, a function might declare that it requires the GIL to be held in order to use
it. This refers to having an attached thread state.
hash-based pyc
A bytecode cache file that uses the hash rather than the last-modified time of the corresponding source file to
determine its validity. See 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.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the
hash value internally.
Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries)
are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable.
Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except
with themselves), and their hash value is derived from their id().
IDLE
An Integrated Development and Learning Environment for Python. idle is a basic editor and interpreter envi-
ronment which ships with the standard distribution of Python.
immortal
Immortal objects are a CPython implementation detail introduced in PEP 683.
If an object is immortal, its reference count is never modified, and therefore it is never deallocated while the
interpreter is running. For example, True and None are immortal in CPython.
347
The Python/C API, Release 3.14.0a7
A number of tools in Python accept key functions to control how elements are ordered or grouped. They
include min(), max(), sorted(), list.sort(), heapq.merge(), heapq.nsmallest(), heapq.
nlargest(), and itertools.groupby().
There are several ways to create a key function. For example. the str.lower() method can serve as a
key function for case insensitive sorts. Alternatively, a key function can be built from a lambda expression
such as lambda r: (r[0], r[2]). Also, operator.attrgetter(), operator.itemgetter(), and
operator.methodcaller() are three key function constructors. See the Sorting HOW TO for examples
of how to create and use key functions.
keyword argument
See argument.
lambda
An anonymous inline function consisting of a single expression which is evaluated when the function is called.
The syntax to create a lambda function is lambda [parameters]: expression
LBYL
Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This
style contrasts with the EAFP approach and is characterized by the presence of many if statements.
In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the
looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can
fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved
with locks or by using the EAFP approach.
lexical analyzer
Formal name for the tokenizer; see token.
list
A built-in Python sequence. Despite its name it is more akin to an array in other languages than to a linked list
since access to elements is O(1).
list comprehension
A compact way to process all or part of the elements in a sequence and return a list with the results. result
= ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] generates a list of strings con-
taining even hex numbers (0x..) in the range from 0 to 255. The if clause is optional. If omitted, all elements
in range(256) are processed.
loader
An object that loads a module. It must define the exec_module() and create_module() methods to
implement the Loader interface. A loader is typically returned by a finder. See also:
• finders-and-loaders
• importlib.abc.Loader
• PEP 302
locale encoding
On Unix, it is the encoding of the LC_CTYPE locale. It can be set with locale.setlocale(locale.
LC_CTYPE, new_locale).
On Windows, it is the ANSI code page (ex: "cp1252").
On Android and VxWorks, Python uses "utf-8" as the locale encoding.
locale.getencoding() can be used to get the locale encoding.
349
The Python/C API, Release 3.14.0a7
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.
namespace
The place where a variable is stored. Namespaces are implemented as dictionaries. There are the local,
global and built-in namespaces as well as nested namespaces in objects (in methods). Namespaces support
modularity by preventing naming conflicts. For instance, the functions builtins.open and os.open() are
distinguished by their namespaces. Namespaces also aid readability and maintainability by making it clear
which module implements a function. For instance, writing random.seed() or itertools.islice()
makes it clear that those functions are implemented by the random and itertools modules, respectively.
namespace package
A package which serves only as a container for subpackages. Namespace packages may have no physical
representation, and specifically are not like a regular package because they have no __init__.py file.
Namespace packages allow several individually installable packages to have a common parent package. Oth-
erwise, it is recommended to use a regular package.
For more information, see PEP 420 and reference-namespace-package.
See also module.
nested scope
The ability to refer to a variable in an enclosing definition. For instance, a function defined inside another
function can refer to variables in the outer function. Note that nested scopes by default work only for reference
and not for assignment. Local variables both read and write in the innermost scope. Likewise, global variables
read and write to the global namespace. The nonlocal allows writing to outer scopes.
new-style class
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.
object
Any data with state (attributes or value) and defined behavior (methods). Also the ultimate base class of any
new-style class.
optimized scope
A scope where target local variable names are reliably known to the compiler when the code is compiled,
allowing optimization of read and write access to these names. The local namespaces for functions, generators,
coroutines, comprehensions, and generator expressions are optimized in this fashion. Note: most interpreter
optimizations are applied to all scopes, only those relying on a known set of local and nonlocal variable names
are restricted to optimized scopes.
package
A Python module which can contain submodules or recursively, subpackages. Technically, a package is a
Python module with a __path__ attribute.
See also regular package and namespace package.
parameter
A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments)
that the function can accept. There are five kinds of parameter:
• positional-or-keyword: specifies an argument that can be passed either positionally or as a keyword argu-
ment. This is the default kind of parameter, for example foo and bar in the following:
• positional-only: specifies an argument that can be supplied only by position. Positional-only parameters
can be defined by including a / character in the parameter list of the function definition after them, for
example posonly1 and posonly2 in the following:
• keyword-only: specifies an argument that can be supplied only by keyword. Keyword-only parameters
can be defined by including a single var-positional parameter or bare * in the parameter list of the function
definition before them, for example kw_only1 and kw_only2 in the following:
• var-positional: specifies that an arbitrary sequence of positional arguments can be provided (in addition
to any positional arguments already accepted by other parameters). Such a parameter can be defined by
prepending the parameter name with *, for example args in the following:
• var-keyword: specifies that arbitrarily many keyword arguments can be provided (in addition to any key-
word arguments already accepted by other parameters). Such a parameter can be defined by prepending
the parameter name with **, for example kwargs in the example above.
Parameters can specify both optional and required arguments, as well as default values for some optional
arguments.
See also the argument glossary entry, the FAQ question on the difference between arguments and parameters,
the inspect.Parameter class, the function section, and PEP 362.
path entry
A single location on the import path which the path based finder consults to find modules for importing.
path entry finder
A finder returned by a callable on sys.path_hooks (i.e. a path entry hook) which knows how to locate
modules given a path entry.
See importlib.abc.PathEntryFinder for the methods that path entry finders implement.
path entry hook
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.
path based finder
One of the default meta path finders which searches an import path for modules.
path-like object
An object representing a file system path. A path-like object is either a str or bytes object representing
a path, or an object implementing the os.PathLike protocol. An object that supports the os.PathLike
protocol can be converted to a str or bytes file system path by calling the os.fspath() function; os.
fsdecode() and os.fsencode() can be used to guarantee a str or bytes result instead, respectively.
Introduced by PEP 519.
PEP
Python Enhancement Proposal. A PEP is a design document providing information to the Python community,
or describing a new feature for Python or its processes or environment. PEPs should provide a concise technical
specification and a rationale for proposed features.
PEPs are intended to be the primary mechanisms for proposing major new features, for collecting community
input on an issue, and for documenting the design decisions that have gone into Python. The PEP author is
responsible for building consensus within the community and documenting dissenting opinions.
See PEP 1.
portion
A set of files in a single directory (possibly stored in a zip file) that contribute to a namespace package, as
defined in PEP 420.
positional argument
See argument.
351
The Python/C API, Release 3.14.0a7
provisional API
A provisional API is one which has been deliberately excluded from the standard library’s backwards com-
patibility guarantees. While major changes to such interfaces are not expected, as long as they are marked
provisional, backwards incompatible changes (up to and including removal of the interface) may occur if
deemed necessary by core developers. Such changes will not be made gratuitously – they will occur only if
serious fundamental flaws are uncovered that were missed prior to the inclusion of the API.
Even for provisional APIs, backwards incompatible changes are seen as a “solution of last resort” - every
attempt will still be made to find a backwards compatible resolution to any identified problems.
This process allows the standard library to continue to evolve over time, without locking in problematic design
errors for extended periods of time. See PEP 411 for more details.
provisional package
See provisional API.
Python 3000
Nickname for the Python 3.x release line (coined long ago when the release of version 3 was something in the
distant future.) This is also abbreviated “Py3k”.
Pythonic
An idea or piece of code which closely follows the most common idioms of the Python language, rather than
implementing code using concepts common to other languages. For example, a common idiom in Python is
to loop over all elements of an iterable using a for statement. Many other languages don’t have this type of
construct, so people unfamiliar with Python sometimes use a numerical counter instead:
for i in range(len(food)):
print(food[i])
qualified name
A dotted name showing the “path” from a module’s global scope to a class, function or method defined in that
module, as defined in PEP 3155. For top-level functions and classes, the qualified name is the same as the
object’s name:
>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'
When used to refer to modules, the fully qualified name means the entire dotted path to the module, including
any parent packages, e.g. email.mime.text:
reference count
The number of references to an object. When the reference count of an object drops to zero, it is deallocated.
Some objects are immortal and have reference counts that are never modified, and therefore the objects are
never deallocated. Reference counting is generally not visible to Python code, but it is a key element of the
CPython implementation. Programmers can call the sys.getrefcount() function to return the reference
count for a particular object.
regular package
A traditional package, such as a directory containing an __init__.py file.
See also namespace package.
REPL
An acronym for the “read–eval–print loop”, another name for the interactive interpreter shell.
__slots__
A declaration inside a class that saves memory by pre-declaring space for instance attributes and eliminating
instance dictionaries. Though popular, the technique is somewhat tricky to get right and is best reserved for
rare cases where there are large numbers of instances in a memory-critical application.
sequence
An iterable which supports efficient element access using integer indices via the __getitem__() special
method and defines a __len__() method that returns the length of the sequence. Some built-in sequence
types are list, str, tuple, and bytes. Note that dict also supports __getitem__() and __len__(),
but is considered a mapping rather than a sequence because the lookups use arbitrary hashable keys rather
than integers.
The collections.abc.Sequence abstract base class defines a much richer interface that goes beyond 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.
set comprehension
A compact way to process all or part of the elements in an iterable and return a set with the results. results
= {c for c in 'abracadabra' if c not in 'abc'} generates the set of strings {'r', 'd'}. See
comprehensions.
single dispatch
A form of generic function dispatch where the implementation is chosen based on the type of a single argument.
slice
An object usually containing a portion of a sequence. A slice is created using the subscript notation, [] with
colons between numbers when several are given, such as in variable_name[1:3:5]. The bracket (sub-
script) notation uses slice objects internally.
soft deprecated
A soft deprecated API should not be used in new code, but it is safe for already existing code to use it. The
API remains documented and tested, but will not be enhanced further.
Soft deprecation, unlike normal deprecation, does not plan on removing the API and will not emit warnings.
See PEP 387: Soft Deprecation.
special method
A method that is called implicitly by Python to execute a certain operation on a type, such as addition. Such
methods have names starting and ending with double underscores. Special methods are documented in spe-
cialnames.
statement
A statement is part of a suite (a “block” of code). A statement is either an expression or one of several constructs
with a keyword, such as if, while or 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.
strong reference
In Python’s C API, a strong reference is a reference to an object which is owned by the code holding the
353
The Python/C API, Release 3.14.0a7
reference. The strong reference is taken by calling Py_INCREF() when the reference is created and released
with Py_DECREF() when the reference is deleted.
The Py_NewRef() function can be used to create a strong reference to an object. Usually, the Py_DECREF()
function must be called on the strong reference before exiting the scope of the strong reference, to avoid leaking
one reference.
See also borrowed reference.
text encoding
A string in Python is a sequence of Unicode code points (in range U+0000–U+10FFFF). To store or transfer
a string, it needs to be serialized as a sequence of bytes.
Serializing a string into a sequence of bytes is known as “encoding”, and recreating the string from the sequence
of bytes is known as “decoding”.
There are a variety of different text serialization codecs, which are collectively referred to as “text encodings”.
text file
A file object able to read and write str objects. Often, a text file actually accesses a byte-oriented datastream
and handles the text encoding automatically. Examples of text files are files opened in text mode ('r' or 'w'),
sys.stdin, sys.stdout, and instances of io.StringIO.
See also binary file for a file object able to read and write bytes-like objects.
thread state
The information used by the CPython runtime to run in an OS thread. For example, this includes the current
exception, if any, and the state of the bytecode interpreter.
Each thread state is bound to a single OS thread, but threads may have many thread states available. At most,
one of them may be attached at once.
An attached thread state is required to call most of Python’s C API, unless a function explicitly documents
otherwise. The bytecode interpreter only runs under an attached thread state.
Each thread state belongs to a single interpreter, but each interpreter may have many thread states, including
multiple for the same OS thread. Thread states from multiple interpreters may be bound to the same thread,
but only one can be attached in that thread at any given moment.
See Thread State and the Global Interpreter Lock for more information.
token
A small unit of source code, generated by the lexical analyzer (also called the tokenizer). Names, numbers,
strings, operators, newlines and similar are represented by tokens.
The tokenize module exposes Python’s lexical analyzer. The token module contains information on the
various types of tokens.
triple-quoted string
A string which is bound by three instances of either a quotation mark (”) or an apostrophe (‘). While they don’t
provide any functionality not available with single-quoted strings, they are useful for a number of reasons.
They allow you to include unescaped single and double quotes within a string and they can span multiple lines
without the use of the continuation character, making them especially useful when writing docstrings.
type
The type of a Python object determines what kind of object it is; every object has a type. An object’s type is
accessible as its __class__ attribute or can be retrieved with type(obj).
type alias
A synonym for a type, created by assigning the type to an identifier.
Type aliases are useful for simplifying type hints. For example:
def remove_gray_shades(
colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
pass
class C:
field: 'annotation'
Variable annotations are usually used for type hints: for example this variable is expected to take int values:
count: int = 0
355
The Python/C API, Release 3.14.0a7
Python’s documentation is generated from reStructuredText sources using Sphinx, a documentation generator origi-
nally created for Python and now maintained as an independent project.
Development of the documentation and its toolchain is an entirely volunteer effort, just like Python itself. If you
want to contribute, please take a look at the reporting-bugs page for information on how to do so. New volunteers
are always welcome!
Many thanks go to:
• Fred L. Drake, Jr., the creator of the original Python documentation toolset and author of much of the content;
• the Docutils project for creating reStructuredText and the Docutils suite;
• Fredrik Lundh for his Alternative Python Reference project from which Sphinx got many good ideas.
357
The Python/C API, Release 3.14.0a7
® Note
(1) GPL-compatible doesn’t mean that we’re distributing Python under the GPL. All Python licenses, unlike
the GPL, let you distribute a modified version without making your changes open source. The GPL-
compatible licenses make it possible to combine Python with other software that is released under the
GPL; the others don’t.
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license has a choice of law clause.
According to CNRI, however, Stallman’s lawyer has told CNRI’s lawyer that 1.6.1 is “not incompatible”
with the GPL.
Thanks to the many outside volunteers who have worked under Guido’s direction to make these releases possible.
359
The Python/C API, Release 3.14.0a7
2. Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python alone or in any derivative
version, provided, however, that PSF's License Agreement and PSF's notice of
copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
Reserved" are retained in Python alone or in any derivative version
prepared by Licensee.
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
(continues on next page)
C.2. Terms and conditions for accessing or otherwise using Python 361
The Python/C API, Release 3.14.0a7
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
(continues on next page)
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
C.3.2 Sockets
The socket module uses the functions, getaddrinfo(), and getnameinfo(), which are coded in separate source
files from the WIDE Project, https://www.wide.ad.jp/.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
C.3.8 test_epoll
The test.test_epoll module contains the following notice:
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
The file Python/pyhash.c contains Marek Majkowski’ implementation of Dan Bernstein’s SipHash24 algorithm.
It contains the following note:
<MIT License>
Copyright (c) 2013 Marek Majkowski <marek@popcount.org>
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</MIT License>
Original location:
https://github.com/majek/csiphash/
/****************************************************************
*
* The author of this software is David M. Gay.
*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
***************************************************************/
C.3.12 OpenSSL
The modules hashlib, posix and ssl use the OpenSSL library for added performance if made available by the
operating system. Additionally, the Windows and macOS installers for Python may include a copy of the OpenSSL
libraries, so we include a copy of the OpenSSL license here. For the OpenSSL 3.0 release, and later releases derived
from that, the Apache License v2 applies:
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
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.
(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.
C.3.13 expat
The pyexpat extension is built using an included copy of the expat sources unless the build is configured
--with-system-expat:
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper
C.3.14 libffi
The _ctypes C extension underlying the ctypes module is built using an included copy of the libffi sources unless
the build is configured --with-system-libffi:
Copyright (c) 1996-2008 Red Hat, Inc and others.
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
C.3.15 zlib
The zlib extension is built using an included copy of the zlib sources if the zlib version found on the system is too
old to be used for the build:
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
(continues on next page)
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
The implementation of the hash table used by the tracemalloc is based on the cfuhash project:
Copyright (c) 2005 Don Owens
All rights reserved.
C.3.17 libmpdec
The _decimal C extension underlying the decimal module is built using an included copy of the libmpdec library
unless the build is configured --with-system-libmpdec:
Copyright (c) 2008-2020 Stefan Krah. 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.19 mimalloc
MIT License:
Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
C.3.20 asyncio
Parts of the asyncio module are incorporated from uvloop 0.16, which is distributed under the MIT license:
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
COPYRIGHT
See History and License for complete license and permissions information.
379
The Python/C API, Release 3.14.0a7
Non-alphabetical A
..., 339 abort (C function), 72
>>>, 339 abs
__all__ (package variable), 72 built-in function, 110
__dict__ (module attribute), 188 abstract base class, 339
__doc__ (module attribute), 188 allocfunc (C type), 322
__file__ (module attribute), 188, 189 annotate function, 339
__future__, 345 annotation, 339
__import__ argument, 339
built-in function, 72 argv (in module sys), 222, 255
__loader__ (module attribute), 188 ascii
__main__ built-in function, 99
module, 12, 217, 232, 233 asynchronous context manager, 340
__name__ (module attribute), 188, 189 asynchronous generator, 340
__package__ (module attribute), 188 asynchronous generator iterator, 340
__PYVENV_LAUNCHER__, 256, 262 asynchronous iterable, 340
__slots__, 353 asynchronous iterator, 340
_frozen (C struct), 75 attached thread state, 340
_inittab (C struct), 76 attribute, 340
_inittab.initfunc (C member), 76 awaitable, 341
_inittab.name (C member), 76
_Py_c_diff (C function), 142 B
_Py_c_neg (C function), 142 BDFL, 341
_Py_c_pow (C function), 143 binary file, 341
_Py_c_prod (C function), 142 binaryfunc (C type), 324
_Py_c_quot (C function), 142 borrowed reference, 341
_Py_c_sum (C function), 142 buffer interface
_Py_NoneStruct (C var), 281 (see buffer protocol), 116
_PyBytes_Resize (C function), 146 buffer object
_PyCode_GetExtra (C function), 186 (see buffer protocol), 116
_PyCode_SetExtra (C function), 187 buffer protocol, 116
_PyEval_RequestCodeExtraIndex (C function), built-in function
186 __import__, 72
_PyFrameEvalFunction (C type), 230 abs, 110
_PyInterpreterFrame (C struct), 204 ascii, 99
_PyInterpreterState_GetEvalFrameFunc (C bytes, 100
function), 230 classmethod, 286
_PyInterpreterState_SetEvalFrameFunc (C compile, 74
function), 230 divmod, 109
_PyObject_GetDictPtr (C function), 99 float, 111
_PyObject_New (C function), 281 hash, 100, 301
_PyObject_NewVar (C function), 281 int, 111
_PyTuple_Resize (C function), 170 len, 101, 112, 114, 172, 176, 179
_thread pow, 109, 111
module, 226 repr, 99, 300
staticmethod, 286
381
The Python/C API, Release 3.14.0a7
382 Index
The Python/C API, Release 3.14.0a7
Index 383
The Python/C API, Release 3.14.0a7
384 Index
The Python/C API, Release 3.14.0a7
Index 385
The Python/C API, Release 3.14.0a7
386 Index
The Python/C API, Release 3.14.0a7
Index 387
The Python/C API, Release 3.14.0a7
388 Index
The Python/C API, Release 3.14.0a7
Index 389
The Python/C API, Release 3.14.0a7
390 Index
The Python/C API, Release 3.14.0a7
Index 391
The Python/C API, Release 3.14.0a7
392 Index
The Python/C API, Release 3.14.0a7
Index 393
The Python/C API, Release 3.14.0a7
394 Index
The Python/C API, Release 3.14.0a7
Index 395
The Python/C API, Release 3.14.0a7
396 Index
The Python/C API, Release 3.14.0a7
Index 397
The Python/C API, Release 3.14.0a7
398 Index
The Python/C API, Release 3.14.0a7
Index 399
The Python/C API, Release 3.14.0a7
400 Index
The Python/C API, Release 3.14.0a7
Index 401
The Python/C API, Release 3.14.0a7
PyUnicodeDecodeError_SetReason (C function), 60
62 PyUnstable_GC_VisitObjects (C function), 329
PyUnicodeDecodeError_SetStart (C function), 61 PyUnstable_InterpreterFrame_GetCode (C
PyUnicodeEncodeError_GetEncoding (C func- function), 204
tion), 61 PyUnstable_InterpreterFrame_GetLasti (C
PyUnicodeEncodeError_GetEnd (C function), 61 function), 204
PyUnicodeEncodeError_GetObject (C function), PyUnstable_InterpreterFrame_GetLine (C
61 function), 205
PyUnicodeEncodeError_GetReason (C function), PyUnstable_InterpreterState_GetMainModule
62 (C function), 229
PyUnicodeEncodeError_GetStart (C function), 61 PyUnstable_IsImmortal (C function), 102
PyUnicodeEncodeError_SetEnd (C function), 62 PyUnstable_Long_CompactValue (C function), 137
PyUnicodeEncodeError_SetReason (C function), PyUnstable_Long_IsCompact (C function), 137
62 PyUnstable_Module_SetGIL (C function), 195
PyUnicodeEncodeError_SetStart (C function), 61 PyUnstable_Object_ClearWeakRefsNoCallbacks
PyUnicodeObject (C type), 147 (C function), 200
PyUnicodeTranslateError_GetEnd (C function), PyUnstable_Object_EnableDeferredRefcount
61 (C function), 102
PyUnicodeTranslateError_GetObject (C func- PyUnstable_Object_GC_NewWithExtraData (C
tion), 61 function), 327
PyUnicodeTranslateError_GetReason (C func- PyUnstable_PerfMapState_Fini (C function), 94
tion), 62 PyUnstable_PerfMapState_Init (C function), 93
PyUnicodeTranslateError_GetStart (C func- PyUnstable_TryIncRef (C function), 103
tion), 61 PyUnstable_Type_AssignVersionTag (C func-
PyUnicodeTranslateError_SetEnd (C function), tion), 126
62 PyUnstable_WritePerfMapEntry (C function), 93
PyUnicodeTranslateError_SetReason (C func- PyVarObject (C type), 282
tion), 62 PyVarObject_HEAD_INIT (C macro), 283
PyUnicodeTranslateError_SetStart (C func- PyVarObject.ob_size (C member), 297
tion), 61 PyVectorcall_Call (C function), 106
PyUnicodeWriter (C type), 166 PyVectorcall_Function (C function), 106
PyUnicodeWriter_Create (C function), 167 PyVectorcall_NARGS (C function), 106
PyUnicodeWriter_DecodeUTF8Stateful (C func- PyWeakref_Check (C function), 199
tion), 168 PyWeakref_CheckProxy (C function), 199
PyUnicodeWriter_Discard (C function), 167 PyWeakref_CheckRef (C function), 199
PyUnicodeWriter_Finish (C function), 167 PyWeakref_GET_OBJECT (C function), 200
PyUnicodeWriter_Format (C function), 168 PyWeakref_GetObject (C function), 200
PyUnicodeWriter_WriteChar (C function), 167 PyWeakref_GetRef (C function), 200
PyUnicodeWriter_WriteRepr (C function), 167 PyWeakref_IsDead (C function), 200
PyUnicodeWriter_WriteStr (C function), 167 PyWeakref_NewProxy (C function), 200
PyUnicodeWriter_WriteSubstring (C function), PyWeakref_NewRef (C function), 199
167 PyWideStringList (C type), 249
PyUnicodeWriter_WriteUCS4 (C function), 167 PyWideStringList_Append (C function), 249
PyUnicodeWriter_WriteUTF8 (C function), 167 PyWideStringList_Insert (C function), 250
PyUnicodeWriter_WriteWideChar (C function), PyWideStringList.items (C member), 250
167 PyWideStringList.length (C member), 250
PyUnstable, 15 PyWrapper_New (C function), 197
PyUnstable_AtExit (C function), 219
PyUnstable_Code_GetExtra (C function), 186 Q
PyUnstable_Code_GetFirstFree (C function), 183 qualified name, 352
PyUnstable_Code_New (C function), 184
PyUnstable_Code_NewWithPosOnlyArgs (C func- R
tion), 184 READ_RESTRICTED (C macro), 288
PyUnstable_Code_SetExtra (C function), 187
READONLY (C macro), 288
PyUnstable_EnableTryIncRef (C function), 104
realloc (C function), 271
PyUnstable_Eval_RequestCodeExtraIndex (C
reference count, 352
function), 186 regular package, 353
PyUnstable_Exc_PrepReraiseStar (C function),
releasebufferproc (C type), 323
402 Index
The Python/C API, Release 3.14.0a7
T
T_BOOL (C macro), 290
T_BYTE (C macro), 290
T_CHAR (C macro), 290
T_DOUBLE (C macro), 290
T_FLOAT (C macro), 290
T_INT (C macro), 290
Index 403