why i getting lifetime error when use Rust + PyO3

61 Views Asked by At

I have simple function like this:

fn get_python()-> (PyResult<&'static PyModule>, &'static Python){
    let indicators_file = fs::read_to_string(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/python_lib/base.py"
    ))
        .expect("Should have been able to read the file");

    let (module, &py) = Python::with_gil(|py| {
        let module = PyModule::from_code(py, &indicators_file, "indicators", "indicators");
        (module, &py)
    });

    (module, &py)
}

And i want to use this fn like rust let (mod, py) = get_python().expect("strange error"); but I get an error missing lifetime specifier [E0106] at "&'static Python" What i must do? Im beginner in the rust lang

i tried to google and modify code

1

There are 1 best solutions below

3
trust_nickol On

You cannot get the Python interpreter out of the closure as it is only valid with the closure method.

This is because Python has to acquire a lock for the gil and releases it at the end of the execution of the closure method.

Just call your code you want to execute by either passing a function / closure to your method or call it within the function.