Using boost python I need create nested namespace.
Assume I have following cpp class structure:
namespace a
{
class A{...}
namespace b
{
class B{...}
}
}
Obvious solution not work:
BOOST_PYTHON_MODULE( a ) {
boost::python::class_<a::A>("A")
...
;
BOOST_PYTHON_MODULE(b){
boost::python::class_<a::b::B>("B")
...
;
}
}
It causes compile-time error: linkage specification must be at global scope
Is there any way to declare class B that would be accessed from Python as a.b.B
?
What you want is a boost::python::scope.
Python has no concept of 'namespaces', but you can use a class very much like 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
All a
, a.A
, a.b
and a.b.B
are actually classes, but you can treat a
and a.b
just like namespaces - and never actually instantiate them
The trick with dummy classes is quite fine, but doesn't allow:
import mylib.a
from mylib.a.b import B
So, instead, use PyImport_AddModule(). You may find full featured examples in the following article: Packages in Python extension modules, by Vadim Macagon.
In short:
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")...