Use PyO3 PyModule as reference in struct

Hi, I'm trying to set a PyModule to a Struct field to prevent multiple GIL adquiring. compute method will be called million or hungred of million of times, so I don't want to call acquire_gil all the times inside compute method.

use pyo3::prelude::*;

struct MyStruct<'py> {
    data: i32,
    module: &'py PyModule
}

impl<'py> for MyStruct<'py> {
    fn new(data: i32) -> Self {
        let gil = Python::acquire_gil();
        let py = gil.python();
        let scipy = PyModule::import(py, "scipy.stats").expect("Scipy was not found");
        MyStruct {
            data,
            scipy
        }
    }
    

    fn compute(&self) {
        // Makes some stuff with self.scipy
    }
}

fn main() {
    let my_struct = MyStruct::new(55);
    // Calls million times my_struct.compute()
}

Is there a way to do that? I've put everything inside a Python::with_gil(|py| {}) block but the program is being killed so I don't know what I'm missing. Any kind of light on the subject would be really appreciated

I'm sorry, I'm not very familiar with pyo3, so this may be an uninformed opinion. Wouldn't it make more sense to pass the GIL as an argument to the compute method? The documentation for acquire_gil seems to recommend that in a similar situation: pyo3::prelude::Python - Rust (docs.rs)

I did it that way, but I included all the code inside the block where the GIL was available and raised panic. I'll try as you say and tell you. Thank you very much for your answer

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.