0

When cython generates a example.c files using

cython example.pyx

this file contains a lot of preprocessor directives to conditionally select different implementations based on conditions like the Python Version. Is there an option to do the same thing inside the cython code.

I did see here, that there is support for conditional compilation of cython to c. So when I use e.g.

IF PY_MAJOR_VERSION < 3:
   codepath1
ELSE
   codepath2

I have to provide this value when generating the c file:

cython src/test.pyx --compile-time-env PY_MAJOR_VERSION=3

The generated c file will only contain one of the two codepaths. So it is only compatible with a very specific version of Python, but still contains a lot of code handling other versions. I am searching for a way to generate a c file, that contains both codepaths and selects them using preprocessor directives as well.

...
#if PY_MAJOR_VERSION < 3
   codepath1
#else
   codepath2
#endif
...

So far I did not find a way to achieve this in cython. Is there a way, or do I have to place all version dependent code (e.g. when using the Python C-API) inside a c file instead?

maxbachmann
  • 2,862
  • 1
  • 11
  • 35
  • 1
    You can put small blocks of C code inline using `cdef extern from *: """ C code goes here """` (instead of a C file). But I don't think there's really a way to generate the code you want using Cython. – DavidW Feb 19 '21 at 09:12
  • @DavidW As far as I can see I can not use #if/#else in there either (or a similar functionality using the cython syntax) – maxbachmann Feb 19 '21 at 10:16
  • 1
    I don't see why not. It just includes the C code verbatim. It isn't really any better than putting the version-dependent code into a C file though - it just saves making an extra file. – DavidW Feb 19 '21 at 13:22
  • Ah I misunderstood your comment. Yes at least this way everything can be placed in a single file – maxbachmann Feb 19 '21 at 13:35

0 Answers0