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
Module Structure
A minimal extension module consists of:- Method definitions
- Module definition structure
- 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
Them_size field controls module state:
-1- Module uses global state (simple modules)>= 0- Per-module state size (multi-phase init)
Initialization Function
PyMODINIT_FUNC Macro
- Be named
PyInit_followed by the module name - Return a
PyObject*(the module object) - Use the
PyMODINIT_FUNCmacro
Single-Phase Initialization
Argument Parsing
PyArg_ParseTuple
Parse positional arguments: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
PyArg_ParseTupleAndKeywords
Parse positional and keyword arguments:Building Return Values
Py_BuildValue
Create Python objects from C values:Adding Module Constants
Error Handling in Extensions
Setting Exceptions
Cleanup on Error
Building and Installing
Using setuptools
Createsetup.py:
Development Mode
Best Practices
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
