Cython conditional compilation based on external value given via `setuptools`
Asked Answered
T

1

5

I try to conditionally generate C code from a Cython pyx file. I found in the Cython documentation that I can use DEF to define a value and IF to conditionally generate code based on a defined value, but how can I set the value from the setup.py via Extension from setuptools.

Thank You

Turbulence answered 3/12, 2014 at 13:44 Comment(1)
What you are looking for was shown in this answer.Kynan
T
5

Thank you for the link.

The interesting flag in the setup.py is cython_compile_time_env. And to import the Extension from Cython.

from setuptools import setup
from Cython.Distutils.extension import Extension

ext = Extension(
    name,
    include_dirs=include_dirs,
    cython_compile_time_env=dict(OPENMP=True),
    sources=['test.pyx'])

setup(name=name,
      cmdclass=dict(build_ext=build_ext),
      ext_modules=[ext])

And in the test.pyx:

...
IF OPENMP:
#Do openmp
ELSE:
#No openmp
...

Cython conditional statements (IF...ELSE above) are documented here.

Turbulence answered 5/12, 2014 at 14:38 Comment(4)
Here is the report of this feature being added to Cython. It's not well-documented. Sometimes one is told to use the keyword pyrex_compile_time_env instead of cython_compile_time_env. Also worth knowing is that if your setuptools directories can fail to be clean in ways that aren't obvious: so that building again with what you expect would be new compile time variables will just go with the previously cached results. Even python setup.py clean --all didn't avoid this. I ended up just touching my .pyx file before each build.Peatroy
Relevant to users of the function cythonize: github.com/cython/cython/issues/1572Berube
And example usage of the argument compile_time_env of cythonize: github.com/pywr/pywr/blob/…Berube
In a more complicated setup, you may want to modify the environment (just a dict) at a later stage when you have more information like this class custom_build_ext(build_ext): ... def build_extensions(self): self.cython_compile_time_env = {}Nganngc

© 2022 - 2024 — McMap. All rights reserved.