Skip to content

Commit

Permalink
feat(wrappers): implement ToPython and PyTryFrom in py_wrap_simple_en…
Browse files Browse the repository at this point in the history
…um (#8)

* feat(wrappers): implement ToPython and PyTryFrom in py_wrap_simple_enum

* Update src/wrappers.rs

Co-authored-by: Michael Bryant <[email protected]>

* test(wrappers): integration test for enum wrappers inside data struct

* chore: make sure test is asserting

* Update tests/wrapper_tests.rs

Co-authored-by: Michael Bryant <[email protected]>

---------

Co-authored-by: Michael Bryant <[email protected]>
  • Loading branch information
jselig-rigetti and Shadow53 authored Feb 2, 2023
1 parent ca994d1 commit 146810e
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/wrappers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,14 @@ macro_rules! py_wrap_simple_enum {
cell.to_object(py)
}
}

$crate::private_impl_to_python_with_reference!(&self, _py, $rs_inner => $name {
Ok($name::from(self))
});

$crate::private_impl_py_try_from!(&item, _py, $name => $rs_inner {
Ok(*item.as_ref())
});
}
}

Expand Down
77 changes: 77 additions & 0 deletions tests/wrapper_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use pyo3::{self, pymodule, types::PyModule, PyResult, Python};

pub mod rust {
#[derive(Clone, Copy)]
pub enum TestEnum {
One,
Two,
}

#[derive(Clone, Copy)]
pub struct TestStruct {
pub test_enum: TestEnum,
}
}

pub mod python {
use super::rust::*;

use pyo3::pymethods;
use rigetti_pyo3::{create_init_submodule, py_wrap_data_struct, py_wrap_simple_enum};

create_init_submodule! {
classes: [ PyTestEnum, PyTestStruct ],
}

py_wrap_simple_enum! {
PyTestEnum(TestEnum) as "TestEnum" {
One,
Two
}
}

py_wrap_data_struct! {
PyTestStruct(TestStruct) as "TestStruct" {
test_enum: TestEnum => PyTestEnum
}
}

#[pymethods]
impl PyTestStruct {
#[new]
fn __new__() -> Self {
Self(TestStruct {
test_enum: TestEnum::One,
})
}
}
}

#[pymodule]
fn wrapper_tests(py: Python<'_>, m: &PyModule) -> PyResult<()> {
python::init_submodule("wrapper_tests", py, m)
}

#[test]
fn test_enum_as_data_struct_member() {
pyo3::append_to_inittab!(wrapper_tests);
pyo3::prepare_freethreaded_python();
let result: PyResult<()> = Python::with_gil(|py| {
let code = r#"
from wrapper_tests import TestEnum, TestStruct
struct = TestStruct()
assert struct.test_enum == TestEnum.One
struct.test_enum = TestEnum.Two
assert struct.test_enum == TestEnum.Two
"#;
PyModule::from_code(py, code, "example.py", "example")?;

Ok(())
});

result.expect("python code should execute without issue")
}

0 comments on commit 146810e

Please sign in to comment.