Skip to content

Instantly share code, notes, and snippets.

@mxgrey
Last active May 13, 2026 14:03
Show Gist options
  • Select an option

  • Save mxgrey/4774b67c6bda6e81c05121f0f9ee6808 to your computer and use it in GitHub Desktop.

Select an option

Save mxgrey/4774b67c6bda6e81c05121f0f9ee6808 to your computer and use it in GitHub Desktop.
Salad Test
[package]
name = "salad"
version = "0.1.0"
edition = "2024"
[dependencies]
pyo3 = { version = "0.28.2", features = ["auto-initialize"] }
#[pyo3::pymodule]
mod salad {
use pyo3::prelude::*;
#[derive(Debug, Clone, Copy, Default)]
#[pyclass(from_py_object)]
pub struct Bowl {
pub leaves: u32,
pub onions: u32,
pub cucumbers: u32,
}
#[pymethods]
impl Bowl {
#[new]
#[pyo3(signature = (leaves = 0, onions = 0, cucumbers = 0))]
pub fn py_new(leaves: u32, onions: u32, cucumbers: u32) -> PyResult<Self> {
Ok(Self { leaves, onions, cucumbers })
}
pub fn add_leaf(&mut self) -> PyResult<()> {
self.leaves += 1;
Ok(())
}
pub fn add_onion(&mut self) -> PyResult<()> {
self.onions += 1;
Ok(())
}
pub fn add_cucumber(&mut self) -> PyResult<()> {
self.cucumbers += 1;
Ok(())
}
}
}
use pyo3::{
prelude::*,
types::PyDict,
};
fn main() {
Python::attach(|py| {
let salad_mod = salad::_PYO3_DEF.make_module(py).unwrap();
let sys = PyModule::import(py, "sys").unwrap();
let sys_modules: Bound<'_, PyDict> = sys.getattr("modules").unwrap().cast_into().unwrap();
sys_modules.set_item("salad", salad_mod).unwrap();
});
// -------------
let modify_salad_bowl =
cr###"
def modify_salad_bowl(bowl):
bowl.add_leaf()
bowl.add_onion()
return bowl
"###;
let bowl = execute(modify_salad_bowl, c"modify_salad_bowl", salad::Bowl::default());
assert_eq!(bowl.leaves, 1);
assert_eq!(bowl.onions, 1);
assert_eq!(bowl.cucumbers, 0);
// -------------
let create_salad_bowl =
cr###"
from salad import Bowl
def create_salad_bowl(bowl):
return Bowl(leaves = 2, onions = 1)
"###;
let bowl = execute(create_salad_bowl, c"create_salad_bowl", salad::Bowl::default());
assert_eq!(bowl.leaves, 2);
assert_eq!(bowl.onions, 1);
assert_eq!(bowl.cucumbers, 0);
println!("SUCCESS");
}
use std::ffi::CStr;
fn execute(script: &CStr, func: &CStr, input: salad::Bowl) -> salad::Bowl {
Python::attach(|py| {
let vars = PyDict::new(py);
py.run(script, Some(&vars), None).unwrap();
let f = py.eval(func, Some(&vars), None).unwrap();
f.call1((input,)).unwrap().extract::<salad::Bowl>().unwrap()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment