User Agents

Web browsers and everyday web tech, explained

Build C Extensions with Poetry: Step-by-Step

· 4 min read · Extensions

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Poetry can manage Python projects that include C extensions, handling the build process seamlessly when configured correctly. This guide walks you through creating a C extension module, integrating it with Poetry, and building it locally and as a wheel. You'll need Python 3.7+, Poetry installed, and a C compiler (GCC, Clang, or MSVC).

What You'll Need

  • Python 3.7 or newer
  • Poetry installed (see poetry.io for instructions)
  • A C compiler: GCC (Linux/macOS), Clang (macOS), or MSVC (Windows)
  • Basic knowledge of Python packaging and C syntax

Step-by-Step

  1. Create a new Poetry project (or use an existing one). Run poetry new my_c_ext and navigate into it.
  2. Set up the package structure. Inside your project, create a subdirectory for the extension, e.g., my_c_ext/. Place your C source file, say hello.c, there. The structure should look like:
    my_c_ext/
      my_c_ext/
        __init__.py
        hello.c
      pyproject.toml
  3. Write your C extension code. A minimal example that returns a string:
    #include <Python.h>
    
    static PyObject* hello(PyObject* self, PyObject* args) {
        return PyUnicode_FromString("Hello from C!");
    }
    
    static PyMethodDef methods[] = {
        {"hello", hello, METH_NOARGS, "Return a greeting"},
        {NULL, NULL, 0, NULL}
    };
    
    static struct PyModuleDef module = {
        PyModuleDef_HEAD_INIT,
        "hello",
        NULL, -1, methods
    };
    
    PyMODINIT_FUNC PyInit_hello(void) {
        return PyModule_Create(&module);
    }
  4. Edit pyproject.toml to tell Poetry about the extension. Add a [tool.poetry.build] section with a custom script, or use the poetry-dynamic-versioning plugin. The simplest method is to use a custom build script. Create a file build.py in the project root with:
    from setuptools import setup, Extension
    
    setup(
        ext_modules=[Extension("my_c_ext.hello", ["my_c_ext/hello.c"])]
    )
  5. Configure Poetry to use the script. In pyproject.toml, add:
    [tool.poetry.build]
    script = "build.py"
  6. Install the package in editable mode. Run poetry install. Poetry will execute the build script, compile the C code, and make the extension importable.
  7. Test the extension. Run poetry run python and try:
    from my_c_ext.hello import hello
    print(hello())
    You should see Hello from C!.
  8. Build a distributable wheel. Run poetry build. This will produce a wheel and a source tarball in the dist/ directory. The wheel will include the compiled extension for your current platform.
  9. Publish to PyPI (optional). Run poetry publish after building. Ensure you have configured credentials.

Common Mistakes

  • Forgetting the __init__.py in the package directory. Without it, Python won't recognize the package.
  • Naming the init function wrong. The init function must be PyInit_<module_name>, where module_name matches the extension name exactly (case-sensitive).
  • Not cleaning old builds. If you change C code, Poetry might reuse cached objects. Run poetry run python setup.py clean or delete the build/ directory and *.so files before rebuilding.
  • Using relative paths incorrectly. In the build script, paths are relative to the project root, not the script location. Use os.path.join if needed.
  • Mixing Python versions. If you use multiple Python versions, ensure the extension is built with the same version used by Poetry's virtual environment.

Tips

  • Use pyproject.toml wisely. Keep the build script minimal; it's only for C extensions. Other build requirements can be listed in [build-system].
  • Test on multiple platforms. C extensions are platform-specific. Use CI (like GitHub Actions) to build on Linux, macOS, and Windows.
  • Leverage poetry run to execute commands within the virtual environment, ensuring the correct Python and dependencies.
  • Use package_data if your extension needs non-code files, though for C extensions it's rarely needed.
  • Consider cffi or pybind11 if you need more complex bindings; they integrate similarly but offer higher-level APIs.

Troubleshooting

  • Build fails with “unable to execute gcc”: Install a C compiler (e.g., apt install build-essential on Ubuntu, or Xcode Command Line Tools on macOS).
  • ImportError: undefined symbol: This usually means the extension was compiled with a different Python version. Rebuild with the same Python that Poetry uses (check poetry env info).
  • Poetry install doesn't compile the extension: Ensure the [tool.poetry.build] section is correctly spelled and the script path is correct. Run poetry install -v to see verbose output.
  • Wheel doesn't include the extension: Check that the extension is built before packaging. Run poetry build after a successful poetry install. If the wheel still lacks it, inspect the build script for errors.
  • Module not found when running poetry run python: The extension might not be in the package path. Ensure the __init__.py imports the submodule, or use a relative import in your test.

Frequently Asked Questions

Can I use Poetry with Cython instead of raw C?

Yes. Write .pyx files and use a build script that calls cythonize before setup(). The same [tool.poetry.build] approach works.

Does Poetry support pre-built wheels for multiple platforms?

Poetry itself doesn't build multi-platform wheels automatically. You need to build on each platform or use a CI service. Tools like cibuildwheel can be integrated.

How do I include headers from external libraries?

In the build script, pass include_dirs and library_dirs to the Extension constructor, and list the libraries in libraries.

Can I use Poetry with a setup.py instead of a script?

Yes. Set script = "setup.py" in [tool.poetry.build], but ensure setup.py exists and is configured correctly.

Why does my extension work in editable mode but not in a wheel?

Editable mode compiles in-place. For wheels, the build script must be executed during poetry build. Check that the script is correct and that the extension is included in the package data.

Can I use Poetry to manage a project with multiple C extensions?

Yes. In the build script, define multiple Extension objects and pass them as a list to ext_modules.