pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Expose `Py_CompileString`

Open nschloe opened this issue 8 months ago • 3 comments

When using py.run, pyo3 will always compile the code (https://pyo3.rs/main/doc/src/pyo3/marker.rs#653).

I'd like to see ffi::Py_CompileString exposed in the API so I can compile once, and py.run_code_object multiple times after that.

nschloe avatar May 08 '25 10:05 nschloe

Seems like a reasonable addition by extending our PyCode type.

davidhewitt avatar May 09 '25 12:05 davidhewitt

I'd be interested in working on this if it hasn't been picked up yet. Could you explain more about extending PyCode?

I'm also curious if the following could be a possible approach:

(1) Create 2 new methods:

pub fn compile_code_string(self, code_str: &CStr, start: c_int) -> Bound<'py, PyCode> {...}
pub fn run_code_object(self, code_obj: &Bound<'py, PyCode>, globals: Option<&Bound<'py, PyDict>>, locals: Option<&Bound<'py, PyDict>>) -> PyResult<Bound<'py, PyAny>> {...}

(2) Modify run_code so that it calls compile_code_string followed by run_code_object.

(3) Document the methods as part of the public API.

I'm still new to the codebase, so this is just an initial thought.

superserious-dev avatar May 13 '25 02:05 superserious-dev

Yeah something like that. I'd just call them compile and run though.

mejrs avatar May 13 '25 17:05 mejrs