开发者

setup.py adding options (aka setup.py --enable-feature )

I'm looking for a way to include some feature in a python (extension) module in installation phase.

In a practical manner:

I have a python library that has 2 implementations of the same function, one internal (slow) and one that depends from an external library (fast, in C).

I want that this library is optional and can be activated at compile/install time using a flag like:

开发者_StackOverflow中文版python setup.py install # (it doesn't include the fast library)
python setup.py --enable-fast install

I have to use Distutils, however all solution are well accepted!


The docs for distutils include a section on extending the standard functionality. The relevant suggestion seems to be to subclass the relevant classes from the distutils.command.* modules (such as build_py or install) and tell setup to use your new versions (through the cmdclass argument, which is a dictionary mapping commands to classes which are to be used to execute them). See the source of any of the command classes (e.g. the install command) to get a good idea of what one has to do to add a new option.


An example of exactly what you want is the sqlalchemy's cextensions, which are there specifically for the same purpose - faster C implementation. In order to see how SA implemented it you need to look at 2 files:

1) setup.py. As you can see from the extract below, they handle the cases with setuptools and distutils:

try:
    from setuptools import setup, Extension, Feature
except ImportError:
    from distutils.core import setup, Extension
    Feature = None

Later there is a check if Feature: and the extension is configured properly for each case using variable extra, which is later added to the setup() function.

2) base.py: here look at how BaseRowProxy is defined:

try:
    from sqlalchemy.cresultproxy import BaseRowProxy
except ImportError:
    class BaseRowProxy(object):
        #....

So basically once C extensions are installed (using --with-cextensions flag during setup), the C implementation will be used. Otherwise, pure Python implementation of the class/function is used.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜