pyo3: `#[new]` doesn't play nice with `cfg_attr`

Compiles:

use pyo3::prelude::*;

#[pyclass]
#[derive(Debug)]
pub struct Foo {
  field: i32
}

#[pymethods]
impl Foo {
  #[new]
  pub fn new(field: i32) -> Self {
    Self { field }
  }
}

Doesn’t compile with Invalid type as custom self and cannot find attribute 'new' in this scope errors:

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

#[cfg_attr(feature = "with_pyo3", pyclass)]
#[derive(Debug)]
pub struct Foo {
  field: i32
}

#[cfg_attr(feature = "with_pyo3", pymethods)]
impl Foo {
  // Change `#[cfg_attr(feature = "with_pyo3", new)]` for `#[new]` and `cargo build --feature with_py03` to see a successful compilation.
  #[cfg_attr(feature = "with_pyo3", new)]
  pub fn new(field: i32) -> Self {
    Self { field }
  }
}

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 34 (26 by maintainers)

Commits related to this issue

Most upvoted comments

Hello, I ran into the same issue today. It seems that the solution using cfg_eval is not going to be adopted. Are there alternatives to solve #[cfg_attr(feature = "with_pyo3", new)] problem?

#[pyclass(get_all, set_all)] are already released. https://pyo3.rs/v0.19.2/class#customizing-the-class

At least for this project, it seems that upstream is the only solution.

You guys might want to reach out Vadim Petrochenkov (OP of https://github.com/rust-lang/rust/pull/87221) to see if any help is needed. Otherwise, it is possible that this issue will be open for years to come.

@andyblarblar see https://github.com/mejrs/rs3cache/blob/master/rs3cache_macros/src/lib.rs

Note that functionality like #[pyclass(get_all, set_all)] is still something I want to add to pyo3 😃

My current workaround is just to define the new function twice and then conditionally compile one or the other:

#[cfg_attr(feature = "python-bindings", pymethods)]
impl Parser {
    #[cfg(feature = "python-bindings")]
    #[new]
    pub fn new() -> Parser {
        Parser {
            token_definitions: TokenDefinitions::new(),
        }
    }

    pub fn parse_variable(&self, input: &str) -> Result<Variable, Error> {
        let token_definition = &self.token_definitions.variable;

        match (&token_definition.regex).find(input) {
            Some(m) => {
                let name = String::from(m.as_str());
                Ok(Variable { name })
            }
            None => {
                let message = format!("Not a {}.", token_definition.description);
                Err(Error { message })
            }
        }
    }
}

#[cfg(not(feature = "python-bindings"))]
impl Parser {
    pub fn new() -> Parser {
        Parser {
            token_definitions: TokenDefinitions::new(),
        }
    }
}

Just for reference. I might have missed a similar approach somewhere above. If the new functions grew to something more substantial I’d probably extract it and share between both “compilations”.

I think this issue needs to be reopened seeing as it doesn’t look like cfg_eval will ever be stabilized.

~As for how to move forward, it is probably worth it look look at parsing out features and build configurations using CARGO_FEATURE_<name> and CARGO_CFG_<cfg>, respectively. It’s fair to say that this would not be solely helpful to PyO3, but where it lives can be figured out once it works.~

EDIT: never mind, the environment variables in question are not set when cargo runs the proc macro.

The example @c410-f3r posted now works if you use #[cfg_eval] on your impl! 🙌

#![feature(cfg_eval)]

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

#[cfg_attr(feature = "with_pyo3", pyclass)]
#[derive(Debug)]
pub struct Foo {
    field: i32,
}

#[cfg_eval]
#[cfg_attr(feature = "with_pyo3", pymethods)]
impl Foo {
    #[cfg_attr(feature = "with_pyo3", new)]
    pub fn new(field: i32) -> Self {
        Self { field }
    }

    pub fn get_field(&self) -> i32 {
        self.field
    }
}

#[cfg(feature = "with_pyo3")]
#[pymodule]
fn my_module(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<Foo>()?;
    Ok(())
}
from my_module import Foo

c = Foo(5)
print(c.get_field())

This currently requires Rust nightly (so #![feature(cfg_eval)] needs to be added), but it seems that cfg_eval will be stabilised in this PR: rust-lang/rust#87221.

I worked around this by creating a proc macro that inserts #[pyo3(get)] for every field:

#[cfg_attr(feature = "pyo3", macro_utils::pyo3_get_all)]
#[cfg_attr(feature = "pyo3", pyclass)]
#[derive(Serialize, Clone, Debug, Default)]
pub struct Foo{
    pub id: u32,
    pub name: Option<String>,
}

That works out because all the (hundred+) fields are public anyway. Perhaps we can do something similar like #[pyclass(get_all, set_all)]?

I guess we could have

#[pyclass]
struct Foo { }

literally just adds #[cfg_eval], expanding to

#[cfg_eval]
#[pyclass(cfg_eval = false)]
struct Foo {}

where #[pyclass(cfg_eval = false)] then expands as normal.

… but if we do that, we’ll suprise people because the #[cfg_eval] happens behind the scenes. I think it’ll also regress compilation times because we’ll be forcing two extra proc macro expansions for every pyclass. It seems better to me to leave it for users to add #[cfg_eval] themselves when needed?

We’d also only be able to do the automatic cfg-eval on Rust versions which actually support it, which again makes it seem better that users should have to manually update to a new enough compiler version and explicitly add #[cfg_eval].

Version 0.10 worsens conditional compilation. Now #[cfg_attr(feature = "with_pyo3", pymethods)] and #[cfg_attr(feature = "with_pyo3", pyclass)] doesn’t compile either.