1

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?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • Have you tried to swap the `cdef extern …:` and `if …:` lines? – Kijewski Jan 04 '17 at 18:11
  • @Kay that throws `cdef statement not allowed here`. – MSeifert Jan 04 '17 at 18:15
  • Possible duplicate of [Try statement in Cython for cimport (for use with mpi4py)](http://stackoverflow.com/questions/26225187/try-statement-in-cython-for-cimport-for-use-with-mpi4py) – DavidW Jan 04 '17 at 19:28
  • See http://docs.cython.org/en/latest/src/userguide/language_basics.html#conditional-statements – DavidW Jan 04 '17 at 19:28

0 Answers0