-2

I created 2 files that have the same function. One is named test1.py and the other test2.py. I try to import test1 that imports test2. Rust throws this error. How can i import relative paths. Id prefer not to change the python code, since i want to convert a big project to rust from time to time. So i want to import the project as a whole and replace parts.

from .test2 import hello
def hello():
    print("Hello World")
Python::with_gil(|py| {
        let sys: &PyAny = py.import("sys")?.getattr("path")?;
        let sys: &PyList = pyo3::PyTryInto::try_into(sys).unwrap();
        sys.insert(0, project_path)?;
        let test = py.import("test1")?;
        Ok(())
    })

thread 'main' panicked at 'Python failed: ImportError: attempted relative import with no known parent package', src/main.rs:14:26
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Jonas Fassbender
  • 2,371
  • 1
  • 3
  • 19

1 Answers1

0

The error seems clear, and a basic python issue, nothing to do with Rust: to perform a relative import between two python modules, they need to be children of the same package, that is they need to be the siblings of an __init__.py file, and their parent directory needs to be below the PYTHONPATH (aka be the descendent of a directory on the PYTHONPATH).

Here you put the parent directory itself on the PYTHONPATH, so test1 and test2 are both top-level modules requiring absolute imports.

Masklinn
  • 34,759
  • 3
  • 38
  • 57