-
As of PyO3 version 0.18.1, only fieldless enums are supported. What are the potential implementations to support enums with fields using PyO3 if implemented manually?? For instance if I have to implement for following enum? pub enum Prop {
Str(String),
I32(i32),
I64(i64),
U32(u32),
U64(u64),
F32(f32),
F64(f64),
Bool(bool),
} Please suggest. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
I was thinking in the line of class/subclass like so: #[pyclass(subclass)]
#[derive(Clone)]
struct Prop;
#[pymethods]
impl Prop {
#[new]
fn new() -> Self {
Prop
}
pub fn method(&self) {}
}
#[pyclass(extends=Prop, subclass)]
#[derive(Clone)]
struct Str {
value: String,
}
#[pymethods]
impl Str {
#[new]
fn new(value: String) -> (Self, Prop) {
(Str { value }, Prop::new())
}
pub fn method(&self) {
println!("value = {}", self.value)
}
}
#[pyfunction]
fn print_prop(s: Prop) {
s.method()
}
#[pyfunction]
fn print_str(s: Str) {
println!("{}", s.value)
} This allows me to keep the API similar to how I am using enums (with fields) in rust. >>> import pyo3_example
>>> s = pyo3_example.Str("pomtery")
>>> pyo3_example.print_prop(s)
>>> pyo3_example.print_str(s)
pomtery
>>> This seems to look nice but the problem I am facing is related to overriding methods! |
Beta Was this translation helpful? Give feedback.
-
The problem with this approach is that its not very pythonic. It would only be ideal if user could provide list of use pyo3::prelude::*;
use std::collections::HashMap;
#[derive(FromPyObject, Debug)]
pub enum Prop {
Int(usize),
String(String),
Vec(Vec<usize>),
}
#[pyfunction]
pub fn get_props(props: HashMap<String, Prop>) -> PyResult<()> {
let v = props.into_iter().collect::<Vec<(String, Prop)>>();
for i in v {
println!("K = {}, V = {:?}", i.0, i.1)
}
Ok(())
} From python: import pyo3_example
pyo3_example.get_props({
"name": "Shivam Kapoor",
"age": 35,
"hobbies": [1, 2, 3]
})
# K = name, V = String("Shivam Kapoor")
# K = age, V = Int(35)
# K = hobbies, V = Vec([1, 2, 3]) |
Beta Was this translation helpful? Give feedback.
The problem with this approach is that its not very pythonic. It would only be ideal if user could provide list of
Prop
as dictionary instead. I have managed to implement it as follows:From python: