Reputation: 3585
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?
Upvotes: 1
Views: 489
Reputation: 70860
Yes, with #[cfg_attr]
:
#[cfg_attr(feature = "python-bindings", pyclass)]
struct MyStruct {
value: i32
}
Upvotes: 4