use crate::run::run_python_code;
use crate::PythonBlock;
use pyo3::{
prelude::*,
types::{PyCFunction, PyDict},
FromPyObject, IntoPyObject, Py, PyResult, Python,
};
pub struct Context {
pub(crate) globals: Py<PyDict>,
}
impl Context {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Python::with_gil(Self::new_with_gil)
}
pub(crate) fn new_with_gil(py: Python) -> Self {
match Self::try_new(py) {
Ok(x) => x,
Err(error) => {
error.print(py);
panic!("failed to create Python context");
}
}
}
fn try_new(py: Python) -> PyResult<Self> {
Ok(Self {
globals: py.import("__main__")?.dict().copy()?.into(),
})
}
pub fn globals<'p>(&self) -> &Py<PyDict> {
&self.globals
}
pub fn get<T: for<'p> FromPyObject<'p>>(&self, name: &str) -> T {
Python::with_gil(|py| match self.globals.bind(py).get_item(name) {
Err(_) | Ok(None) => panic!("Python context does not contain a variable named `{}`", name),
Ok(Some(value)) => match FromPyObject::extract_bound(&value) {
Ok(value) => value,
Err(e) => {
e.print(py);
panic!("Unable to convert `{}` to `{}`", name, std::any::type_name::<T>());
}
},
})
}
pub fn set<T: for<'p> IntoPyObject<'p>>(&self, name: &str, value: T) {
Python::with_gil(|py| match self.globals().bind(py).set_item(name, value) {
Ok(()) => (),
Err(e) => {
e.print(py);
panic!("Unable to set `{}` from a `{}`", name, std::any::type_name::<T>());
}
})
}
pub fn add_wrapped(&self, wrapper: &impl Fn(Python) -> PyResult<Bound<'_, PyCFunction>>) {
Python::with_gil(|py| {
let obj = wrapper(py).unwrap();
let name = obj.getattr("__name__").expect("Missing __name__");
if let Err(e) = self.globals().bind(py).set_item(name, obj) {
e.print(py);
panic!("Unable to add wrapped function");
}
})
}
pub fn run<F: FnOnce(&Bound<PyDict>)>(&self, code: PythonBlock<F>) {
Python::with_gil(|py| self.run_with_gil(py, code));
}
pub(crate) fn run_with_gil<F: FnOnce(&Bound<PyDict>)>(&self, py: Python<'_>, code: PythonBlock<F>) {
(code.set_variables)(self.globals().bind(py));
match run_python_code(py, self, code.bytecode) {
Ok(_) => (),
Err(e) => {
e.print(py);
panic!("{}", "python!{...} failed to execute");
}
}
}
}