Skip to content

How to keep variables between calls of with_gil/run but also add my own objects #2331

Discussion options

You must be logged in to vote

Just keep the locals dictionary around between calls to Python::run:

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))).un…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@RudolfVonKrugstein
Comment options

Answer selected by RudolfVonKrugstein
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants