Conditional compilation of attributes defined by attribute macros

When an attribute macro like #[pyclass] defines further attributes to be used on the fields of a struct, like in the following example:

use pyo3::prelude::*;

#[pyclass]
struct Point {
    #[pyo3(get, set)]
    x: i32,
    y: i32,
}

is it possible to apply these attributes conditionally, gated by a crate feature?

When trying something like the following:

#[cfg(feature = "pyo3")]
use pyo3::prelude::*;

#[cfg_attr(feature = "pyo3", pyclass)]
struct Point {
    #[cfg_attr(feature = "pyo3", pyo3(get, set))]
    x: i32,
    y: i32,
}

and compiling with the feature activated:

cargo check --features pyo3

rustc complains about the unknown attribute pyo3.

You can't do that, basically. For a workaround see `pyo3(get, set)` attribute not found when using `cfg_attr` · Issue #1003 · PyO3/pyo3 · GitHub

See that thread and the links in it if you are curious why it doesnt work.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.