Search code examples
pythonc++boostimportpath

attempted relative import beyond top-level package with boost/Python


I've tried multiple ways to import a module in a post here, but I decided to post a new question since that post was about boost not being able to find the module. Here's the structure of the folder:

project
   |__ utilities
   |      |__ foo.py
   |
   |__ boost_extensions
   |      |__ myclass.cpp
   |      |__ myclass.so
   |
   |__ someotherstuff
   |      |__ bar.py      
   |
   |__ mylib.py
   |
   |__ __main__.py

in foo.py, I have some code that imports from mylib.py:

from ..mylib import MyLib
class Foo:
    # code

in myclass.cpp, I could not find a way to import Foo using a relative path, so I used an absolute path (inspired from an answer to the post here):

boost::python::object mod;
void set_global(){
    boost::python::object importlib_util = import("importlib.util");

    boost::python::object spec = \
        importlib_util.attr("spec_from_file_location")("module.name",\
            "/home/username/projectfiles/project/utilities/foo.py");

    boost::python::object foo = importlib_util.attr("module_from_spec")(spec);
    mod = spec.attr("loader").attr("exec_module")(foo);
}

And this gave me an error:

    from ..mylib import MyLib
ValueError: attempted relative import beyond top-level package

How can I fix this?

Thanks

edit : not sure if this is relevant or not but if I print the variable __name__ it's always module.name, regardless of what I put in the code

# with ..utilities.foo instead of module.name in the function 
# importlib_util.attr("spec_from_file_location")("module.name",\
#            "home/username/projectfiles/project/utilities/foo.py");
print(__name__)
from ..mylib import MyLib
#output : module.name

Solution

  • I posted a similar question and the solution for that works here too (it was about trying to import a python module in C++ by using a relative path, I made a different post about it because it gave a completely different error). Basically I loaded the module in python and passed it as an argument to C++.