Failing to convert struct to equivalent pyobject #3013
-
So I have been trying to mimic field based enums in rust in pyo3. Have come quite far with the implementation but I'm stuck trying to return the struct. I do understand that the any struct that implements #[pyclass]
#[derive(Clone)]
pub struct Point {
#[pyo3(get)]
x: usize,
#[pyo3(get)]
y: usize,
}
#[pymethods]
impl Point {
#[new]
fn new(x: usize, y: usize) -> Point {
Point { x, y }
}
}
#[pyfunction]
pub fn return_point(p: Point) -> Point {
p
} This works just fine: p = return_point(Point(4, 5))
print(p.x, p.y) However, with field enums I'm trying to implement I don't see #[derive(Debug)]
enum RProp {
Str(String),
Int(usize),
}
fn process_rprop(rprop: RProp) -> RProp {
match rprop {
RProp::Str(v) => RProp::Str(v),
RProp::Int(v) => RProp::Int(v),
}
}
#[pyclass(subclass)]
#[derive(Clone)]
pub struct Prop;
#[pymethods]
impl Prop {
#[new]
fn new() -> Self {
Prop
}
fn delegate_call(&self) {}
}
#[pyclass(extends=Prop, subclass)]
#[derive(Clone)]
pub struct Str {
value: String,
}
#[pymethods]
impl Str {
#[new]
fn new(value: String) -> (Self, Prop) {
(Str { value }, Prop::new())
}
fn delegate_call(&self, py: Python<'_>) -> Str {
process_rprop(self.clone().into()).into()
}
}
impl From<Str> for RProp {
fn from(v: Str) -> Self {
RProp::Str(v.value)
}
}
impl From<RProp> for Str {
fn from(value: RProp) -> Self {
match value {
RProp::Str(value) => Str { value },
RProp::Int(_) => panic!(),
}
}
}
#[pyfunction]
pub fn process_prop(s: &PyCell<Prop>) -> PyResult<&PyAny> {
s.call_method0("delegate_call")
} To explain a bit: I have How I intend to use in python: s = Str("pomtery")
print(process_prop(s))
# should print Str("pometry") Line:
Not really sure how to fix it. Please suggest. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Try this instead:
The reason is that |
Beta Was this translation helpful? Give feedback.
Try this instead:
The reason is that
Str
doesn't implementIntoPy
, because it needs to have aProp
base class paired with it when built into a Python object.