Skip to main content

Overview

Extension modules allow you to extend Python with C/C++ code for:
  • Performance-critical operations
  • Integration with existing C libraries
  • Access to system-level APIs
  • Custom data types
This guide covers the fundamentals of creating Python extension modules in C.

Module Structure

A minimal extension module consists of:
  1. Method definitions
  2. Module definition structure
  3. Module initialization function

Basic Example

Method Definitions

PyMethodDef Structure

Method Flags

int
Function accepts positional arguments tuple
int
Function accepts positional and keyword arguments
int
Function takes no arguments (only self)
int
Function takes exactly one Python object argument
int
Class method - first argument is the class, not instance
int
Static method - receives no implicit first argument

Method Examples

Module Definition

PyModuleDef Structure

Module State

The m_size field controls module state:
  • -1 - Module uses global state (simple modules)
  • >= 0 - Per-module state size (multi-phase init)
Example with module state:

Initialization Function

PyMODINIT_FUNC Macro

The initialization function must:
  1. Be named PyInit_ followed by the module name
  2. Return a PyObject* (the module object)
  3. Use the PyMODINIT_FUNC macro
The function name must exactly match the module filename. For a module file spam.so, the function must be named PyInit_spam.

Single-Phase Initialization

Argument Parsing

PyArg_ParseTuple

Parse positional arguments:
Format strings:
  • s - String (char*)
  • s# - String and length (char*, Py_ssize_t)
  • i - Integer (int)
  • l - Long (long)
  • L - Long long (long long)
  • f - Float (float)
  • d - Double (double)
  • O - Python object (PyObject*)
  • O! - Python object with type check (PyTypeObject*, PyObject*)
  • | - Optional arguments follow
Examples:

PyArg_ParseTupleAndKeywords

Parse positional and keyword arguments:

Building Return Values

Py_BuildValue

Create Python objects from C values:
Examples:

Adding Module Constants

Error Handling in Extensions

Setting Exceptions

Cleanup on Error

Building and Installing

Using setuptools

Create setup.py:
Build and install:

Development Mode

Best Practices

Reference CountingAlways manage reference counts correctly:
  • Py_INCREF() when storing a reference
  • Py_DECREF() when done with a reference
  • Functions return new or borrowed references
Error CheckingCheck every API call that can fail:
Thread SafetyRelease the GIL for long operations:

See Also

Type Objects

Define custom Python types in C

Memory Management

Allocate and free memory properly

Exception Handling

Handle errors in extension code

Utilities

Parsing arguments and building values