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

0 _
  • 10,524
  • 11
  • 77
  • 109
3nt
  • 111
  • 6
  • 1
    What you are looking for was shown in [this answer](http://stackoverflow.com/questions/26225187/try-statement-in-cython-for-cimport-for-use-with-mpi4py/26226758#26226758). – IanH Dec 04 '14 at 05:32

1 Answers1

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.

0 _
  • 10,524
  • 11
  • 77
  • 109
3nt
  • 111
  • 6
  • 1
    Here is [the report of this feature being added to Cython](https://github.com/cython/cython/pull/81). 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 `touch`ing my `.pyx` file before each build. – dubiousjim Feb 21 '17 at 19:30
  • Relevant to users of the function `cythonize`: https://github.com/cython/cython/issues/1572 – 0 _ Jan 12 '18 at 01:19
  • 1
    And example usage of the argument `compile_time_env` of `cythonize`: https://github.com/pywr/pywr/blob/80784dfbe1aa0fc143247f4304c5f5eaa0dd3809/setup.py#L151 – 0 _ Jan 12 '18 at 01:27
  • 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 = {}` – Fred Schoen May 02 '18 at 14:03