Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you tell pyximport to use the cython --cplus option?

Tags:

c++

python

cython

pyximport is super handy but I can't figure out how to get it to engage the C++ language options for Cython. From the command line you'd run cython --cplus foo.pyx. How do you achieve the equivalent with pyximport? Thanks!

like image 347
BrianTheLion Avatar asked Oct 01 '11 11:10

BrianTheLion


People also ask

Does Cython use C or C++?

Cython improves the use of C-based third-party number-crunching libraries like NumPy. Because Cython code compiles to C, it can interact with those libraries directly, and take Python's bottlenecks out of the loop.


3 Answers

One way to make Cython create C++ files is to use a pyxbld file. For example, create foo.pyxbld containing the following:

def make_ext(modname, pyxfilename):
    from distutils.extension import Extension
    return Extension(name=modname,
                     sources=[pyxfilename],
                     language='c++')
like image 132
Eryk Sun Avatar answered Sep 25 '22 21:09

Eryk Sun


Here's a hack.

The following code monkey-patches the get_distutils_extension function in pyximport so that the Extension objects it creates all have their language attribute set to c++.

import pyximport
from pyximport import install

old_get_distutils_extension = pyximport.pyximport.get_distutils_extension

def new_get_distutils_extension(modname, pyxfilename, language_level=None):
    extension_mod, setup_args = old_get_distutils_extension(modname, pyxfilename, language_level)
    extension_mod.language='c++'
    return extension_mod,setup_args

pyximport.pyximport.get_distutils_extension = new_get_distutils_extension

Put the above code in pyximportcpp.py. Then, instead of using import pyximport; pyximport.install(), use import pyximportcpp; pyximportcpp.install().

like image 39
user4967717 Avatar answered Sep 25 '22 21:09

user4967717


A more lightweight/less intrusive solution would be to use setup_args/script_args, which pyximport would pass to distutils used under the hood:

script_args = ["--cython-cplus"]
setup_args = {
    "script_args": script_args,
}
pyximport.install(setup_args=setup_args, language_level=3)

Other options for python setup.py build_ext can be passed in similar maner, e.g. script_args = ["--cython-cplus", "--force"].

The corresponding part of the documentation mentions the usage of setup_args, but the exact meaning is probably clearest from the code itself (here is a good starting point).

like image 25
ead Avatar answered Sep 22 '22 21:09

ead