Build C Extensions with Poetry: Step-by-Step
In this article
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
- Create a new Poetry project (or use an existing one). Run
poetry new my_c_extand navigate into it. - Set up the package structure. Inside your project, create a subdirectory for the extension, e.g.,
my_c_ext/. Place your C source file, sayhello.c, there. The structure should look like:my_c_ext/ my_c_ext/ __init__.py hello.c pyproject.toml - 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); } - Edit
pyproject.tomlto tell Poetry about the extension. Add a[tool.poetry.build]section with a custom script, or use thepoetry-dynamic-versioningplugin. The simplest method is to use a custom build script. Create a filebuild.pyin the project root with:from setuptools import setup, Extension setup( ext_modules=[Extension("my_c_ext.hello", ["my_c_ext/hello.c"])] ) - Configure Poetry to use the script. In
pyproject.toml, add:[tool.poetry.build] script = "build.py"
- Install the package in editable mode. Run
poetry install. Poetry will execute the build script, compile the C code, and make the extension importable. - Test the extension. Run
poetry run pythonand try:from my_c_ext.hello import hello print(hello())
You should seeHello from C!. - Build a distributable wheel. Run
poetry build. This will produce a wheel and a source tarball in thedist/directory. The wheel will include the compiled extension for your current platform. - Publish to PyPI (optional). Run
poetry publishafter building. Ensure you have configured credentials.
Common Mistakes
- Forgetting the
__init__.pyin the package directory. Without it, Python won't recognize the package. - Naming the init function wrong. The init function must be
PyInit_<module_name>, wheremodule_namematches 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 cleanor delete thebuild/directory and*.sofiles before rebuilding. - Using relative paths incorrectly. In the build script, paths are relative to the project root, not the script location. Use
os.path.joinif 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.tomlwisely. 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 runto execute commands within the virtual environment, ensuring the correct Python and dependencies. - Use
package_dataif your extension needs non-code files, though for C extensions it's rarely needed. - Consider
cffiorpybind11if 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-essentialon 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. Runpoetry install -vto see verbose output. - Wheel doesn't include the extension: Check that the extension is built before packaging. Run
poetry buildafter a successfulpoetry 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__.pyimports 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.