Text of docs.python.org › 3.13 › extending › extending.html as Styx crawled it on Nov 20, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

1. Extending Python with C or C++ — Python 3.13.18 documentation

Navigation index modules | next | previous | Python » 3.13.18 Documentation » Extending and Embedding the Python Interpreter » 1. Extending Python with C or C++ | Theme | 1. Extending Python with C or C++ ¶ It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can’t be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.

To support extensions, the Python API (Application Programmers Interface) defines a set of functions, macros and variables that provide access to most aspects of the Python run-time system. The Python API is incorporated in a C source file by including the header "Python.h" . The compilation of an extension module depends on its intended use as well as on your system setup; details are given in later chapters. Note The C extension interface is specific to CPython, and extension modules do not work on other Python implementations.

In many cases, it is possible to avoid writing C extensions and preserve portability to other implementations. For example, if your use case is calling C library functions or system calls, you should consider using the ctypes module or the cffi library rather than writing custom C code. These modules let you write Python code to interface with C code and are more portable between implementations of Python than writing and compiling a C extension module.

1.1. A Simple Example ¶ Let’s create an extension module called spam (the favorite food of Monty Python fans…) and let’s say we want to create a Python interface to the C library function system() [ 1 ] . This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows: >>> import spam >>> status = spam . system ( "ls -l" ) Begin by creating a file spammodule.c . (Historically, if a module is called spam , the C file containing its implementation is called spammodule.c ; if the module name is very long, like spammify , the module name can be just spammify.c .) The first two lines of our file can be: #define PY_SSIZE_T_CLEAN #include <Python.h> which pulls in the Python API (you can add a comment describing the purpose of the module and a copyright notice if you like).

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. #define PY_SSIZE_T_CLEAN was used to indicate that Py_ssize_t should be used in some APIs instead of int . It is not necessary since Python 3.13, but we keep it here for backward compatibility. See Strings and buffers for a description of this macro.

All user-visible symbols defined by Python.h have a prefix of Py or PY , except those defined in standard header files. Tip For backward compatibility, Python.h includes several standard header files. C extensions should include the standard headers that they use, and should not rely on these implicit includes. If using the limited C API version 3.13 or newer, the implicit includes are: <assert.h> <intrin.h> (on Windows) <inttypes.h> <limits.h> <math.h> <stdarg.h> <wchar.h> <sys/types.h> (if present) If Py_LIMITED_API is not defined, or is set to version 3.12 or older, the headers below are also included: <ctype.h> <unistd.h> (on POSIX) If Py_LIMITED_API is not defined, or is set to version 3.10 or older, the headers below are also included: <errno.h> <stdio.h> <stdlib.h> <string.h> The next thing we add to our module file is the C function that will be called when the Python expression spam.system(string) is evaluated (we’ll see shortly how it ends up being called): static PyObject * spam_system ( PyObject * self , PyObject * args ) { const char * command ; int sts ; if ( !

PyArg_ParseTuple ( args , "s" , & command )) return NULL ; sts = system ( command ); return PyLong_FromLong ( sts ); } There is a straightforward translation from the argument list in Python (for example, the single expression "ls -l" ) to the arguments passed to the C function. The C function always has two arguments, conventionally named self and args . The self argument points to the module object for module-level functions; for a method it would point to the object instance.

The args argument will be a pointer to a Python tuple object containing the arguments. Each item of the tuple corresponds to an argument in the call’s argument list. The arguments are Python objects — in order to do anything with them in our C function we have to convert them to C values. The function PyArg_ParseTuple() in the Python API checks the argument types and converts them to C values. It uses a template string to determine the required types of the arguments as well as the types of the C variables into which to store the converted values.

More about this later. PyArg_ParseTuple() returns true (nonzero) if all arguments have the right type and its components have been stored in the variables whose addresses are passed. It returns false (zero) if an invalid argument list was passed. In the latter case it also raises an appropriate exception so the calling function can return NULL immediately (as we saw in the example). 1.2. Intermezzo: Errors and Exceptions ¶ An important convention throughout the Python interpreter is the following: when a function fails, it should set an exception condition and return an error value (usually -1 or a NULL pointer).

Exception information is stored in three members of the interpreter’s thread state. These are NULL if there is no exception. Otherwise they are the C equivalents of the members of the Python tuple returned by sys.exc_info() . These are the exception type, exception instance, and a traceback object. It is important to know about them to understand how errors are passed around. The Python API defines a number of functions to set various types of exceptions.

The most common one is PyErr_SetString() . Its arguments are an exception object and a C string. The exception object is usually a predefined object like PyExc_ZeroDivisionError . The C string indicates the cause of the error and is converted to a Python string object and stored as the “associated value” of the exception. Another useful function is PyErr_SetFromErrno() , which only takes an exception argument and constructs the associated value by inspection of the global variable errno .

The most general function is PyErr_SetObject() , which takes two object arguments, the exception and its associated value. You don’t need to Py_INCREF() the objects passed to any of these functions. You can test non-destructively whether an exception has been set with PyErr_Occurred() . This returns the current exception object, or NULL if no exception has occurred. You normally don’t need to call PyErr_Occurred() to see whether an error occurred in a function call, since you should be able to tell from the return value.

When a function f that calls another function g detects that the latter fails, f should itself return an error value (usually NULL or -1 ). It should not call one of the PyErr_* functions — one has already been called by g . f ’s caller is then supposed to also return an error indication to its caller, again without calling PyErr_* , and so on — the most detailed cause of the error was already reported by the function that first detected it.

Once the error reaches the Python interpreter’s main loop, this aborts the currently executing Python code and tries to find an exception handler specified by the Python programmer. (There are situations where a module can actually give a more detailed error message by calling another PyErr_* function, and in such cases it is fine to do so. As a general rule, however, this is not necessary, and can cause information about the cause of the error to be lost: most operations can fail for a variety of reasons.) To i

The rest of this page is on the live site.