liveBook · Manning

Py.run

As explained in Refactoring to Rust

py.run is a PyO3 operation that executes Python source code with supplied global and local namespaces.

py.run executes Python source code from Rust. Pass the code as a string, then provide optional global and local namespaces; a PyDict commonly supplies local variables and imported modules. section 6.5

Run Python with Rust-provided locals

Python::with_gil(|py| {\n let locals = PyDict::new(py);\n locals.set_item("json", py.import("json").unwrap()).unwrap();\n locals.set_item("INPUT", input).unwrap();\n py.run(code, None, Some(&locals)).unwrap();\n});\n\nHere, code can read json and INPUT as ordinary Python names. In a Criterion benchmark, place py.run inside b.iter while constructing namespaces outside the measured loop. section 6.5

How Refactoring to Rust covers it

How deep it goes
Defines code and namespace arguments, then demonstrates execution inside a Criterion loop; it stops short of Python execution internals.
Examples
Uses imported json, a rust_json module, an INPUT string, and Python JSON-processing code.
What it assumes
Assumes basic Rust closures and Python code, while demonstrating namespace setup and GIL access through concrete integration code.
What you can do after
Operate PyO3 to run Python code with Rust-supplied globals and locals.
How it connects
Connects PyO3, Python::with_gil, PyDict, Criterion, Python extension modules, and namespace variables.

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.