Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pyo3 optionally generate python bindings for rust struct

I have defined a few structs in my code and if a certain feature is enabled on the crate, I would like to generate Python bindings for those structs as well. Right now I am not able to get it correctly. Let’s say I have a struct MyStruct for which I want to optionally generate Python Bindings.

I have tried something like the following

cfg_if! {
    if #[cfg(feature = "python-bindings")] {
        #[pyclass]
    } 
    else {
    }  
}
struct MyStruct{
   value: i32
}

I would like to only add #[pyclass] if feature python-bindings is enabled and not otherwise.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This works fine if python-bindings is not enabled. But if I compile with --features python-bindings, I get the following error.

error: expected item after attributes

As far as possible I do not want to duplicate the code. like

cfg_if! {
    if #[cfg(feature = "python-bindings")] {
        #[pyclass]
        struct MyStruct{
           value: i32
        }
    } 
    else {
        struct MyStruct{
        value: i32
    }  
}

Is there a way of doing it without duplicating the code?

>Solution :

Yes, with #[cfg_attr]:

#[cfg_attr(feature = "python-bindings", pyclass)]
struct MyStruct {
    value: i32
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading