英文:
Closest implementation for enums with fields in pyO3
问题
截止到 PyO3 版本 0.18.1,仅支持无字段的枚举。
如果要手动实现支持带字段的枚举,有哪些潜在的实现方式?如果我说的不对,请纠正我。
例如,如果我要为以下枚举实现:
pub enum Prop {
Str(String),
I32(i32),
I64(i64),
U32(u32),
U64(u64),
F32(f32),
F64(f64),
Bool(bool),
}
请提供建议。
英文:
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?? pyclass
is of no use here (Correct me if I am wrong).
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.
答案1
得分: 1
从 GitHub 复制的代码。以下是要翻译的部分:
这种方法的问题在于它不太符合 Python 的风格。只有在用户能够提供属性列表的情况下,它才是理想的,而不是字典。我已经成功地实现了它,如下所示:
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(())
}
从 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])
英文:
Copied from github.
>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:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论