How should I structure a Python package that contains Cython code

后端 未结 10 1843
傲寒
傲寒 2020-12-22 15:11

I\'d like to make a Python package containing some Cython code. I\'ve got the the Cython code working nicely. However, now I want to know how best to package it.

For

10条回答
  •  死守一世寂寞
    2020-12-22 15:16

    All other answers either rely on

    • distutils
    • importing from Cython.Build, which creates a chicken-and-egg problem between requiring cython via setup_requires and importing it.

    A modern solution is to use setuptools instead, see this answer (automatic handling of Cython extensions requires setuptools 18.0, i.e., it's available for many years already). A modern standard setup.py with requirements handling, an entry point, and a cython module could look like this:

    from setuptools import setup, Extension
    
    with open('requirements.txt') as f:
        requirements = f.read().splitlines()
    
    setup(
        name='MyPackage',
        install_requires=requirements,
        setup_requires=[
            'setuptools>=18.0',  # automatically handles Cython extensions
            'cython>=0.28.4',
        ],
        entry_points={
            'console_scripts': [
                'mymain = mypackage.main:main',
            ],
        },
        ext_modules=[
            Extension(
                'mypackage.my_cython_module',
                sources=['mypackage/my_cython_module.pyx'],
            ),
        ],
    )
    

提交回复
热议问题