Repository navigation
How to keep variables between calls of with_gil/run but also add my own objects #2331
Answered
by
adamreichold
RudolfVonKrugstein
asked this question in
Questions
|
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? |
Answered by
adamreichold
Apr 25, 2022
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, |
1 reply
Answer selected by
RudolfVonKrugstein
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just keep the
localsdictionary around between calls toPython::run: