Distributing a shared library and some C code with a Cython extension module

1) Distributing libbig.so

This is a problem that python isn’t going to help you with. Who are you targeting? If it’s linux, can you request that they install it with their package manager? If libbig isn’t distributed through a package manager or it’s not linux and you’re targeting multiple architectures, you might have to distribute the libbig source.

2) Cython/setuptools.

Frankly, I think its easiest to just require that people have Cython. This way there’s only one ground truth version of the code, and you don’t have to worry about inconsistencies between the .pyx and .cpp code. The easiest way to do this is to use setuptools instead of distutils. That way, you can use:

setup('mypackage',
    ...
    install_requires=['cython'])

In total, your setup.py script will look something like:

# setup.py

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

pysmall = Extension('pysmall',
    sources = ['pysmall.pyx', 'small.cpp'],
    include_dirs = ['include/'])

setup(name="mypackage",
      packages=['yourpurepythonpackage'],
      install_requires=['cython==0.17'],
      ext_modules=[pysmall],
      cmdclass = {'build_ext': build_ext})

If you don’t like the idea of requiring cython, you could do something like:

# setup.py

import warnings
try:
    from Cython.Distutils import build_ext
    from setuptools import setup, Extension
    HAVE_CYTHON = True
except ImportError as e:
    HAVE_CYTHON = False
    warnings.warn(e.message)
    from distutils.core import setup, Extension
    from distutils.command import build_ext

pysmall = Extension('pysmall',
    sources = ['pysmall.pyx', 'small.cpp'],
    include_dirs = ['include/'])

configuration = {'name': 'mypackage',
      'packages': ['yourpurepythonpackage'],
      'install_requires': ['cython==0.17'],
      'ext_modules': [pysmall],
      'cmdclass': {'build_ext': build_ext}}

if not HAVE_CYTHON:
    pysmall.sources[0] = 'pysmall.cpp'
    configuration.pop('install_requires')

setup(**configuration)

Leave a Comment

tech