Conditional importing in "from extern" in cython based on python version

394 views Asked by At

I found that naive conditions in def extern from ... blocks are not allowed. For example if I use something like this:

from cpython.object cimport PyObject, PyObject_Hash
from cpython.version cimport PY_MAJOR_VERSION, PY_MINOR_VERSION

cdef extern from "Python.h":
    if PY_MAJOR_VERSION >= 3 and PY_MINOR_VERSION >= 5:
        PyObject* _PyDict_GetItem_KnownHash(object mp, object key, Py_hash_t hash)

if not (PY_MAJOR_VERSION >= 3 and PY_MINOR_VERSION >= 5):
    def _PyDict_GetItem_KnownHash(object mp, object key, Py_hash_t hash):
        return mp[key]

...

When trying to %%cython this it aborts with the error:

Error compiling Cython file:
------------------------------------------------------------
...
from cpython.object cimport PyObject, PyObject_Hash
from cpython.version cimport PY_MAJOR_VERSION, PY_MINOR_VERSION


cdef extern from "Python.h":
    if PY_MAJOR_VERSION >= 3 and PY_MINOR_VERSION >= 5:
   ^
------------------------------------------------------------

C:\x\.ipython\cython\_cython_magic_ff85a968c2e8e5cee0075b8a4862fc8a.pyx:7:4: Expected an identifier, found 'if'

Error compiling Cython file:
------------------------------------------------------------
...
from cpython.object cimport PyObject, PyObject_Hash
from cpython.version cimport PY_MAJOR_VERSION, PY_MINOR_VERSION


cdef extern from "Python.h":
    if PY_MAJOR_VERSION >= 3 and PY_MINOR_VERSION >= 5:
                       ^
------------------------------------------------------------

C:\x\.ipython\cython\_cython_magic_ff85a968c2e8e5cee0075b8a4862fc8a.pyx:7:24: Syntax error in C variable declaration

Is there a (working) way to use conditionals when importing functions with cython "from extern" or any alternatives?

0

There are 0 answers