Skip to content

Closest implementation for enums with fields in pyO3 #2959

Answered by shivamka1
shivamka1 asked this question in Questions
Discussion options

You must be logged in to vote

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", 
                   "…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@davidhewitt
Comment options

@shivamka1
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by shivamka1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants