pythonboost-pythonpython-modulesynthetic

synthesized submodule: from A import B (ok) vs. import A.B (error)?


I have a module modA, which contains a synthesized submodule modB (created with PyModule_New); now importing the module:

  1. from modA import modB it is OK
  2. import modA.modB fails.

What am I missing?


Solution

  • Thanks to this answer, I found the solution, which consists in sys.modules['modA.modB']=modB, but written in c++ in the module initialization function:

    #include<boost/python.hpp>
    namespace py=boost::python;
    
    BOOST_PYTHON_MODULE(modA){
       py::object modB=py::object(py::handle<>(PyModule_New("modA.modB")));
       modB.attr("__file__")="<synthetic>";
       py::scope().attr("modB")=modB;
    
       // this was the missing piece: sys.modules['modA.modB']=modB
       py::extract<py::dict>(py::getattr(py::import("sys"),"modules"))()["modA.modB"]=modB;
    };