在pyO3中实现具有字段的枚举的最接近方法是什么?

huangapple go评论50阅读模式
英文:

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&lt;usize&gt;),
}

#[pyfunction]
pub fn get_props(props: HashMap&lt;String, Prop&gt;) -&gt; PyResult&lt;()&gt; {
    let v = props.into_iter().collect::&lt;Vec&lt;(String, Prop)&gt;&gt;();
    for i in v {
        println!(&quot;K = {}, V = {:?}&quot;, i.0, i.1)
    }
    Ok(())
}

From python:

import pyo3_example

pyo3_example.get_props({
                   &quot;name&quot;: &quot;Shivam Kapoor&quot;, 
                   &quot;age&quot;: 35,  
                   &quot;hobbies&quot;: [1, 2, 3]
                 })
# K = name, V = String(&quot;Shivam Kapoor&quot;)
# K = age, V = Int(35)
# K = hobbies, V = Vec([1, 2, 3])

huangapple
  • 本文由 发表于 2023年2月16日 07:04:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75466245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定