Create nested boost-python namespace

Using boost python I need to create a nested namespace.

Suppose I have the following cpp class structure:

namespace a
{
    class A{...}
    namespace b
    {
         class B{...}
    }
}

The obvious solution does not work:

BOOST_PYTHON_MODULE( a ) {
    boost::python::class_<a::A>("A")
     ...
    ;
    BOOST_PYTHON_MODULE(b){
        boost::python::class_<a::b::B>("B")
        ...
    ;
    }
}

This causes a compile-time error: linkage specification must be at global scope

Is there a way to declare a class B that can be accessed with Python like a.b.B?

+5
source share
2 answers

You want boost :: python :: scope .

Python has no concept of a namespace, but you can use a class very similar to a namespace:

#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/scope.hpp>
using namespace boost::python;

namespace a
{
    class A{};

    namespace b
    {
         class B{};
    }
}

class DummyA{};
class DummyB{};

BOOST_PYTHON_MODULE(mymodule)
{
    // Change the current scope 
    scope a
        = class_<DummyA>("a")
        ;

    // Define a class A in the current scope, a
    class_<a::A>("A")
        //.def("somemethod", &a::A::method)
        ;

    // Change the scope again, a.b:
    scope b
        = class_<DummyB>("b")
        ;

    class_<a::b::B>("B")
        //.def("somemethod", &a::b::B::method)
        ;
}

Then in python you have:

#!/usr/bin/env python
import mylib

print mylib.a,
print mylib.a.A
print mylib.a.b
print mylib.a.b.B

a, a.A, a.b a.b.B , a a.b , ,

+10

, :

import mylib.a
from mylib.a.b import B

, PyImport_AddModule(). : Python, .

:

namespace py = boost::python;
std::string nested_name = py::extract<std::string>(py::scope().attr("__name__") + ".nested");
py::object nested_module(py::handle<>(py::borrowed(PyImport_AddModule(nested_name.c_str()))));
py::scope().attr("nested") = nested_module;
py::scope parent = nested_module;
py::class_<a::A>("A")...
+7

All Articles