Search code examples
rustpyo3

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.

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
    }