This wiki is in the process of being archived due to lack of usage and the resources necessary to serve it — predominately to bots, crawlers, and LLM companies. Edits are discouraged.
Pages are preserved as they were at the time of archival. For current information, please visit python.org.
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list.

Creating a Python Extension Module from Scratch

This guide will take you through the process of creating a Python extension module. It is assumed that you have a recent Python version (2.4 or later) and setuptools installed.

We'll be creating a project called 'examp' (short for 'example'.)

Step 1: Create the project directory

> mkdir examp
> cd examp

Step 2: Create the setup.py script

In the directory you just created, make a new file, setup.py containing the following:

   1 from setuptools import setup, Extension
   2 
   3 setup(
   4     # Name of this package
   5     name="examp",
   6     
   7     # Package version
   8     version=0.1,
   9     
  10     # This tells setup how to find our unit tests.
  11     test_suite = "test.examp_unittest",
  12     
  13     # Describes how to build the actual extension module from C source files.
  14     ext_modules = [
  15         Extension(
  16           'examp',         # Python name of the module
  17           ['src/examp.c']  # Source files to build
  18         )]
  19     )

The setup.py file tells Python how to compile, test, and install your extension module.

Step 3: Create the module source file

This will be located in the location specified in the setup.py script given above; in this example, the location is examp/src/examp.c. This file will contain the following:

   1 #include <Python.h>
   2 
   3 PyMODINIT_FUNC initexamp(void)
   4 {
   5     PyObject *m;
   6     
   7     m = Py_InitModule(