用户警告:未知扩展选项:'cython_directives' 在本地安装 Cython 包时

UserWarning: Unknown Extension options: 'cython_directives' when locally installing Cython package

我使用的是 Cython 版本 0.29.26。 我有一个带有 Cython 扩展的 python 包,如下所示:

./setup.py:

from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext
import numpy as np


cython_directives = {'boundscheck': "False",
                     'cdivision': "True",
                     'wraparound': "False",
                     'language_level': "3"}

setup(name='debug_example',
      packages=find_packages(),
      cmdclass={'build_ext': build_ext},
      ext_modules=[
          Extension('debug_example.example',
                    sources=['debug_example/example.pyx'],
                    language='c++',
                    include_dirs=[np.get_include()],
                    cython_directives=cython_directives,
                    )
      ]
      )

./debug_example/example.pyx

cimport numpy as  np

cpdef int increment(int a):
    return a + 1

./debug_example/__init__.py:

from .example import increment

当我编译它时,我收到一条关于 cython_directives 未知的警告消息(除此之外编译工作正常)。 pip install -e . -v 的输出:

(base) ➜  debug_cython pip install -e . -v
Using pip 21.2.4 from /home/mm/anaconda3/lib/python3.9/site-packages/pip (python 3.9)
Obtaining file:///home/mm/tmp/debug_cython
    Running command python setup.py egg_info
    /home/mm/anaconda3/lib/python3.9/site-packages/setuptools/_distutils/extension.py:131: UserWarning: Unknown Extension options: 'cython_directives'

这是什么原因?

Extension 来自 setuptools,它对 Cython 的支持有限:它会自动为 *.pyx 文件调用 cythonize,但对于更多选项,应该使用 cythonize 直接。这意味着您的 setup.py 如下:

...
from Cython.Build import cythonize

...
extensions = [Extension('debug_example.example',
                    sources=['debug_example/example.pyx'],
                    language='c++',
                    include_dirs=[np.get_include()],
                    ),
              ]
...

setup(...
      ext_modules = cythonize(extensions, compiler_directives=cython_directives)
      ...
      )

compiler_directives 可以传递给 cythonize。