setup_requires with Cython?

前端 未结 3 984
时光说笑
时光说笑 2020-12-01 10:29

I\'m creating a setup.py file for a project with some Cython extension modules.

I\'ve already gotten this to work:

from setuptools impor         


        
相关标签:
3条回答
  • 2020-12-01 11:10

    Starting from 18.0 release of setuptools (released on 2015-06-23) it is possible to specify Cython in setup_requires and pass *.pyx modules sources for regular setuptools.Extension:

    from setuptools import setup, Extension
    
    
    setup(
        # ...
        setup_requires=[
            # Setuptools 18.0 properly handles Cython extensions.
            'setuptools>=18.0',
            'cython',
        ],
        ext_modules=[
            Extension(
                'mylib',
                sources=['src/mylib.pyx'],
            ),
        ],
    )
    
    0 讨论(0)
  • 2020-12-01 11:12

    You must wrap the from Cython.Build import cythonize in a try-except, and in the except, define cythonize as a dummy function. This way the script can be loaded without failing with an ImportError.

    Then later when the setup_requires argument is handled, Cython will be installed and the setup script will be re-executed. Since at that point Cython is installed, you'll be able to successfully import cythonize

    try:
        from Cython.Build import cythonize
    except ImportError:
         def cythonize(*args, **kwargs):
             from Cython.Build import cythonize
             return cythonize(*args, **kwargs)
    

    EDIT

    As noted in comments, after setuptools deals with missing dependencies, it won't re-load Cython. I hadn't thought of it before, but you could also try a late-binding approach to stubbing out cythonize

    0 讨论(0)
  • 2020-12-01 11:20

    There seems to be a third way of having build dependencies installed before executing the actual setup.py described here (requires pip):

    https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html#basic-setup-

    In essence:

    1. Create the file pyproject.toml with the following contents:
    [build-system]
    requires = ["setuptools", "wheel", "Cython"]
    
    1. Use pip install -e . for setting things up
    0 讨论(0)
提交回复
热议问题