Skip to content

Python C Extension Import Error Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Python C Extension Import Error Fix. We cover key concepts, practical examples, and best practices.

Python C extensions compiled with CPython's C API must export the correct initialization function. Missing or incorrectly named init functions, ABI mismatches, or missing dependencies cause ImportError when importing the module.

The Wrong Way

# mymodule.c
#include <Python.h>

static PyObject* my_func(PyObject* self, PyObject* args) {
    return PyLong_FromLong(42);
}

static PyMethodDef methods[] = {
    {"my_func", my_func, METH_VARARGS, "Returns 42"},
    {NULL, NULL, 0, NULL}
};

// Missing PyModuleDef struct and init function

Output:

Traceback (most recent call last):
  File "script.py", line 1, in <module>
    import mymodule
ImportError: dynamic module does not define module export function (PyInit_mymodule)

The Right Way

Define the module struct and initialization function with the correct naming convention:

// mymodule.c
#include <Python.h>

static PyObject* my_func(PyObject* self, PyObject* args) {
    return PyLong_FromLong(42);
}

static PyMethodDef methods[] = {
    {"my_func", my_func, METH_VARARGS, "Returns 42"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef mymodule_module = {
    PyModuleDef_HEAD_INIT,
    "mymodule",
    NULL,
    -1,
    methods
};

PyMODINIT_FUNC PyInit_mymodule(void) {
    return PyModule_Create(&mymodule_module);
}

Build with:

gcc -shared -fPIC -I/usr/include/python3.10 mymodule.c -o mymodule.so

Usage:

import mymodule
print(mymodule.my_func())

Output:

42

Step-by-Step Fix

1. Check the init function name

The init function must match the module name: PyInit_<modulename>.

2. Verify Python version compatibility

python3-config --includes
gcc -shared -fPIC $(python3-config --includes) mymodule.c -o mymodule.so

3. Use setuptools for portable builds

from setuptools import setup, Extension

module = Extension('mymodule', sources=['mymodule.c'])

setup(
    name='mymodule',
    version='1.0',
    description='Example C extension',
    ext_modules=[module]
)

Build with python setup.py build_ext --inplace.

4. Handle Cython modules

# mymodule.pyx
def my_func():
    return 42

Build with cythonize and setuptools.

Prevention Tips

  • Name the init function exactly PyInit_<module_name> matching the filename.
  • Use setuptools.Extension instead of manual compilation to avoid platform issues.
  • Build with the same Python version that will import the module.
  • Link against any required shared libraries with libraries parameter.
  • Test imports immediately after building to catch errors early.

Common Mistakes with c extensions

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the PyMODINIT_FUNC macro?

PyMODINIT_FUNC declares the init function with the correct return type (PyObject*) and visibility for the platform. On Windows it marks the function as __declspec(dllexport).

Why do I get undefined symbol errors?

Undefined symbol errors occur when the extension links against libraries not present on the system, or when compiled headers differ from the runtime Python version. Rebuild against the correct Python headers.

Can I write C extensions without the CPython API?

Yes. Use Cython, ctypes, or CFFI for simpler integration. Cython compiles Python-like code to C. ctypes loads shared libraries dynamically. CFFI provides a clean C foreign function interface.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro