Skip to content
Advertisement

Mix cython and cmake extensions in python setuptools

I have a python package with the following setup.py:

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext


class CMakeExtension(Extension):
    # ...


class CMakeBuild(build_ext):
    # ...


extensions = [
    CMakeExtension("cmake_extension", "path-to-sources"),
    Extension("cython_extension", ["file.pyx"]),
]


setup(
    # ...
    ext_modules=extensions,
    # ...
)

I would like to know if I can call python setup.py build_ext --inplace and build each extension with the appropriate builder.

I am aware of the cmdclass setup function argument but did not find a way to specify that build_ext should be used for the cython extensions and CMakeBuild for the cmake ones.

Note that each extension is building fine with the correct builder class (and the cmdclass argument).

Thanks!

Advertisement

Answer

The workaround I found:

from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext


class CMakeExtension(Extension):
    # ...


class CMakeBuild(build_ext):
    # ...


if sys.argv[1] == "build_ext":
    c_ext = [Extension(...)]
elif sys.argv[1] == "build_cmk":
    c_ext = [CMakeExtension(...)]
else:
    raise NotImplementedError


setup(
    # ...
    ext_modules=cythonize(c_ext),
    cmdclass={"build_ext": build_ext, "build_cmk": CMakeBuild},
    # ...
)

And then run:

python setup.py build_ext --inplace
python setup.py build_cmk --inplace
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement