How to distribute a module with both a pure Python and Cython version
<p>I have a pure Python module and I want to rewrite some of submodules using Cython. Then I would like to add the new Cython submodules to the original Python module and make them available only as an option, meaning that cythoning the module is not compulsory (in which case the 'old' pure Python module should be used).</p>

<p>Here is an example:</p>

<pre><code>my_module
    - __init__.py
    - a.py
    - b.py
    - setup.py
</code></pre>

<p>where <code>a.py</code> contains <code>import b</code>.</p>

<p>I want to write <code>b.py</code> in Cython. The idea would be to add a folder containing the <code>.pyx</code> file, for example:</p>

<pre><code>my_module
    - __init_.py
    - a.py
    - b.py
    - setup.py
    cython
        -b.pyx
</code></pre>

<p><code>setup.py</code> would contain the direction to compile <code>b.pyx</code> and to install the module. However, I would like that if someone runs <code>python setup.py install</code> then the pure Python code is installed, whereas if an option is added then the Cython code is compiled and installed. </p>

<p>Any idea how to do that?</p>

<p>Also, how should the file <code>a.py</code> be modified in order to import the correct module?</p>

<p>My solution was to set up the module like this:</p>

<pre><code>my_module
    - __init_.py
    - a.py
    - b.py
    - setup.py
    cython_my_module
        - __init_.py
        - b.pyx
</code></pre>

<p>The <code>setup.py</code> would contain something similar to this:</p>

<pre><code>from distutils.core import setup
from Cython.Build import cythonize

import numpy

setup(
    name='My_module',
    ext_modules=cythonize(["cython_my_module/b.pyx",]),
    include_dirs=[numpy.get_include()],
) 
</code></pre>

<p>and the file <code>a.py</code> would contain the following lines in the header:</p>

<pre><code>try:
    import cython_my_module.b
except ImportError:
    import b
</code></pre>

<p>The way it works is very simple: if you don't do anything (i.e. if you don't compile the cython files) then module <code>a.py</code> imports module <code>b.py</code>; however, if you run <code>python setup.py build_ext --inplace</code> then the compiled cython files will appear inside <code>cython_my_module</code> and the next time you run <code>a.py</code> it will automatically import the cython module <code>b.pyx</code> (actually it will import the compiled library <code>b.so</code>).</p>

<p>So far it seems to work and requires almost no effort. Hope it helps.</p>

<p>fish2000 solution seems more generic but I haven't tried it yet. </p>

python module cython