pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Automatically provide fallback constructor for all-public Rust structs

Open kangalio opened this issue 5 years ago • 2 comments

In my application I have many "plain-old-data" structs, i.e. structs with only public fields that are supposed to be instantiated with the StructName { field1: ..., field2: ... } syntax in Rust.

Making those structs usable from Python-land currently involves a bit of avoidable boilerplate:

struct StructName {
    #[pyo3(get, set)] pub field1: u32,
    #[pyo3(get, set)] pub field1: u32,
}

// this is the boilerplate I'm talking about
#[pymethods]
impl StructName {
    #[new]
    pub fn new(field1: u32, field2: u32) -> Self {
        Self { field1, field2 }
    }
}

This kind of class is equivalent to Python's dataclasses. Python's dataclasses include default constructors which is very convenient and sensible. I think it would be nice for PyO3 to do the same and automatically provide default constructors like above, for plain-old-data structs with all pub fields.

kangalio avatar Jan 10 '21 00:01 kangalio

Thanks for this suggestion. I've often wanted such a constructor generated for me. In combination with #1375, binding pod structs would be very convenient.

I don't think we want to enable this for all #[pyclass] structs automatically, at least not without a long period of making it opt-in and learning if anyone doesn't use the option.

I wondered in the past if this could be done as an external crate first (e.g. pyo3-pod-structs) to give us a first implementation to experiment with, though I haven't thought too hard about the design.

davidhewitt avatar Jan 10 '21 07:01 davidhewitt

:+1: for this being more convenient, but still explicit.

It can just be an attribute on the struct itself to mark it as pod/dataclass.

birkenfeld avatar Jan 10 '21 11:01 birkenfeld