Jij-Inc / pyo3-stub-gen

Stub file (*.pyi) generator for PyO3
Apache License 2.0
61 stars 12 forks source link

pyo3::pyclass(get_all) results in no class attributes being generated #93

Closed gsleap closed 1 month ago

gsleap commented 1 month ago

Hi - I have this rust struct:

#[cfg(feature = "python")]
use pyo3_stub_gen_derive::gen_stub_pyclass;

#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyo3::pyclass(get_all, set_all))]
#[derive(Clone)]
pub struct Baseline {
    pub ant1_index: usize,
    pub ant2_index: usize,
}

The generated stub pyi is:

class Baseline:
    r"""
    This is a struct for our baselines, so callers know the antenna ordering
    """
    ...

However if I use #[pyo3(get,set)] on each attribute like this:

#[cfg_attr(feature = "python", gen_stub_pyclass)]
#[cfg_attr(feature = "python", pyo3::pyclass)]
#[derive(Clone)]
pub struct Baseline {
    #[pyo3(get, set)]
    pub ant1_index: usize,
    #[pyo3(get, set)]
    pub ant2_index: usize,
}

it then produces the correct pyi stub output:

class Baseline:
    r"""
    This is a struct for our baselines, so callers know the antenna ordering
    """
    ant1_index: int
    ant2_index: int

Due to this issue, I cannot use that syntax though as I need it to be behind the python feature, e.g.

    #[cfg_attr(feature = "python", pyo3(get, set))]
    pub ant1_index: usize,
     #[cfg_attr(feature = "python", pyo3(get, set))]
    pub ant2_index: usize,

Is there any chance of supporting the pyo3::pyclass(get_all,set_all) syntax for class members (since that does work behind a feature) - or am I doing something wrong?

ThatOneShortGuy commented 1 month ago

Hi @gsleap! I'm not completely sure why it doesn't work when separated like that, but I was able to make it work by combining the macros into one:

#[cfg(feature = "python")]
use pyo3_stub_gen::derive::gen_stub_pyclass;

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

/// This is a struct for our baselines, so callers know the antenna ordering
#[cfg_attr(feature = "python", gen_stub_pyclass, pyclass(get_all, set_all))]
#[derive(Clone)]
pub struct Baseline {
    pub ant1_index: usize,
    pub ant2_index: usize,
}

This results in:

class Baseline:
    r"""
    This is a struct for our baselines, so callers know the antenna ordering
    """
    ant1_index: int
    ant2_index: int

It has to be ordered #[cfg_attr(feature = "python", gen_stub_pyclass, pyclass(get_all, set_all))] instead of #[cfg_attr(feature = "python", pyclass(get_all, set_all), gen_stub_pyclass)] to apply correctly as well.

Hope this helps!

gsleap commented 1 month ago

@ThatOneShortGuy that worked perfectly, thanks so much!