2

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.

iamsmkr
  • 800
  • 2
  • 10
  • 29

1 Answers1

1

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])
ozkanpakdil
  • 3,199
  • 31
  • 48