Skip to content

Structs impling Default should have default Python constructors #5284

@adamchalmers

Description

@adamchalmers

Currently pyo3 bindings require you to explicitly annotate any Rust "constructor" as a Python constructor. This means that if your struct relies on its default() method from the Default trait you cannot expose the default() method directly. Instead you have to do this:

#[pymethods]
impl MyStruct {
    #[new]
    fn new() -> Self {
        Self::default()
    }
}

In my opinion, exposing this default() method is a common enough problem that this boilerplate is a little unnecessary. What if instead we could do

#[derive(Default)]
#[pyclass(default)]
struct MyStruct;

Here the pyclass(default) would create a zero-argument constructor method for the Python type, and its implementation would call MyStruct::default.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions