Tente a declaração no Cython para cimport (para uso com o mpi4py)

Existe uma maneira de ter o equivalente da instrução try Python no Cython para o cimport?

Algo parecido:

try:
    cimport something
except ImportError:
    pass

Eu precisaria disso para escrever uma extensão Cython que possa ser compilada com ou sem mpi4py. Isso é muito padrão em linguagens compiladas, onde os comandos mpi podem ser colocados entre as diretivas #ifdef e #endif pré-processador. Como podemos obter o mesmo resultado no Cython?

Eu tentei isso, mas não funciona:

try:
    from mpi4py import MPI
    from mpi4py cimport MPI
    from mpi4py.mpi_c cimport *
except ImportError:
    rank = 0
    nb_proc = 1

# solve a incompatibility between openmpi and mpi4py versions
cdef extern from 'mpi-compat.h': pass

does_it_work = 'Not yet'

Na verdade, funciona bem se o mpi4py estiver instalado corretamente, mas seimport mpi4py gera um ImportError, o arquivo Cython não compila e eu recebo o erro:

Error compiling Cython file:
------------------------------------------------------------
...

try:
    from mpi4py import MPI
    from mpi4py cimport MPI
   ^
------------------------------------------------------------

mod.pyx:4:4: 'mpi4py.pxd' not found

O arquivosetup.py:

from setuptools import setup, Extension
from Cython.Distutils import build_ext

import os
here = os.path.abspath(os.path.dirname(__file__))

include_dirs = [here]

try:
    import mpi4py
except ImportError:
    pass
else:
    INCLUDE_MPI = '/usr/lib/openmpi/include'
    include_dirs.extend([
        INCLUDE_MPI,
        mpi4py.get_include()])

name = 'mod'
ext = Extension(
    name,
    include_dirs=include_dirs,
    sources=['mod.pyx'])

setup(name=name,
      cmdclass={"build_ext": build_ext},
      ext_modules=[ext])

questionAnswers(2)

yourAnswerToTheQuestion