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.
Language version compatibility¶
Python’s C API is compatible with C11 and C++11 versions of C and C++.
This is a lower limit: the C API does not require features from later C/C++ versions. You do not need to enable your compiler’s “c11 mode”.
Coding standards¶
If you’re writing C code for inclusion in CPython, you must follow the guidelines and standards defined in PEP 7. These guidelines apply regardless of the version of Python you are contributing to. Following these conventions is not necessary for your own third party extension modules, unless you eventually expect to contribute them to Python.
Include Files¶
All function, type and macro definitions needed to use the Python/C API are included in your code by the following line:
#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.
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 installation
directory specified to the installer.
To include the headers, place both directories (if different) on your compiler’s
search path for includes. Do not place the parent directories on the search
path and then use #include <pythonX.Y/Python.h>; this will break on
multi-platform builds since the platform independent headers under
prefix include the platform specific headers from
exec_prefix.
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++.
System includes¶
Python.hincludes several standard header files. C extensions should include the standard headers that they use, and should not rely on these implicit includes. The implicit includes are:
<assert.h>
<intrin.h>(on Windows)
<inttypes.h>
<limits.h>
<math.h>
<stdarg.h>
<string.h>
<wchar.h>
<sys/types.h>(if present)The following are included for backwards compatibility, unless using Limited API 3.13 or newer:
<ctype.h>
<unistd.h>(on POSIX)The following are included for backwards compatibility, unless using Limited API 3.11 or newer:
<errno.h>
<stdio.h>
<stdlib.h>
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.
Useful macros¶
Several useful macros are defined in the Python header files. Many are
defined closer to where they are useful (for example, Py_RETURN_NONE,
PyMODINIT_FUNC).
Others of a more general utility are defined here. This is not necessarily a
complete listing.
-
Py_CAN_START_THREADS¶
If this macro is defined, then the current system is able to start threads.
Currently, all systems supported by CPython (per PEP 11), with the exception of some WebAssembly platforms, support starting threads.
Added in version 3.13.
-
Py_GETENV(s)¶
Like
getenv(s), but returnsNULLif-Ewas passed on the command line (seePyConfig.use_environment).
Docstring macros¶
-
PyDoc_STRVAR(name, str)¶
Creates a variable with name name that can be used in docstrings. If Python is built without docstrings (
--without-doc-strings), the value will be an empty string.Example:
PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element."); static PyMethodDef deque_methods[] = { // ... {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc}, // ... }
Expands to
PyDoc_VAR(name) = PyDoc_STR(str).
-
PyDoc_STR(str)¶
Expands to the given input string, or an empty string if docstrings are disabled (
--without-doc-strings).Example:
static PyMethodDef pysqlite_row_methods[] = { {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS, PyDoc_STR("Returns the keys of the row.")}, {NULL, NULL} };
-
PyDoc_VAR(name)¶
Declares a static character array variable with the given name. Expands to
static const char name[]For example:
PyDoc_VAR(python_doc) =