How to keep variables between calls of with_gil/run but also add my own objects #2331
-
I want to use PyO3 to add scripting to my rust application. For this I execute python code at various places in my code like this:
Now I want to preserve defined variable and functions between the calls, which works if I do it like this:
Additional I want to use rust classes in my python scripts. I try to make them available using the locals:
While this also works, I cannot combine both. If I set the
How can I make both work at the same time? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Just keep the use pyo3::prelude::*;
use pyo3::{
prepare_freethreaded_python,
types::{IntoPyDict, PyDict},
};
#[pyclass]
#[derive(Default)]
struct MyPythonObject;
#[pymethods]
impl MyPythonObject {
fn do_something(&mut self) {
println!("something");
}
}
fn main() {
prepare_freethreaded_python();
let locals: Py<PyDict> = Python::with_gil(|py| {
let python_object = Py::new(py, MyPythonObject::default()).unwrap();
let locals = [("o", python_object)].into_py_dict(py);
locals.into_py(py)
});
Python::with_gil(|py| {
py.run("x = 5", None, Some(locals.as_ref(py))).unwrap();
});
Python::with_gil(|py| {
py.run("o.do_something()", None, Some(locals.as_ref(py)))
.unwrap();
});
Python::with_gil(|py| {
assert!(locals.as_ref(py).contains("x").unwrap());
});
Python::with_gil(|py| {
py.run("print(x)", None, Some(locals.as_ref(py))).unwrap();
});
} This additionally allows you to access the local variables defined by the scripts. (Depending on the semantics, |
Beta Was this translation helpful? Give feedback.
Just keep the
locals
dictionary around between calls toPython::run
: