Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically provide fallback constructor for all-public Rust structs #1376

Open
kangalio opened this issue Jan 10, 2021 · 2 comments
Open

Comments

@kangalio
Copy link
Contributor

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.

@davidhewitt
Copy link
Member

davidhewitt commented Jan 10, 2021

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.

@birkenfeld
Copy link
Member

👍 for this being more convenient, but still explicit.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants