Place boost python extension inside package

Viewed 3226

I have the following boost python code:

#include <boost/python.hpp>

namespace bp = boost::python;

class PyExtTest
{
public:
    std::string get_name() { return m_name; }
    void set_name(std::string const& name) { m_name = name; }

private:
    std::string m_name;
};

BOOST_PYTHON_MODULE(test_ext)
{
    bp::class_<PyExtTest>("pet")
        .add_property("name", &PyExtTest::get_name, &PyExtTest::set_name)
        ;
}

which I compile into the the following directory hierarchy using distutils:

build/lib/test_ext.so

and then use (with PYTHONPATH set to build/lib) as so:

import test_ext
a = test_ext.pet
a.name = 'dog'
print a.name     # dog

When I configure distutils to install test_ext as part of package pkg, python can no longer find the module. I end up with the directory hierarchy:

build/lib/pkg
build/lib/pkg/__init__.py
build/lib/pkg/test_ext.so

from using a setup script like:

test_module = Extension('pkg.test_ext'
                        , define_macros = module_macros
                        , extra_compile_args = module_compiler_flags
                        , sources = ['pkg/test_ext/test.cpp']
                        , include_dirs = module_include_dirs
                        , library_dirs = module_lib_dirs
                        , libraries = module_libs)

setup (name = 'Test'
       , version = '0.1'
       , description = 'Test'
       , packages = ['pkg']
       , ext_modules = [test_module])

but trying to import the module:

import pkg.test_ext

results in the error:

ImportError: No module named test_ext

If I substitute a pure python module for test_ext, then everything works as expected.

I think I need to change the boost code in some manner to indicate that the test_ext extension is inside the pkg package, but I cannot figure out exactly how to do it.

I tried just moving test_ext.so to the correct location in the build/lib directory hierarchy to get the package layout that I wanted, but the only place it is recognized as a module is directly under build/lib. This is different the .py files, which I can import successfully from wherever I place them in the directory hierarchy.

I am using python 2.7.6 and boost 1.55.

Any help is appreciated.

1 Answers
Related