PyO3 / PyO3/pyo3

Support automatic `__new__` generation in `#[pyclass]` with `set_all`

Open
#5,416 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
16.2k
Forks
1k
Avg merge
2d 6h
Merged PRs (30d)
66

Description

Currently, if the developer does not provide a #[new] method for a class, the object can only be constructed in Rust land. However, if a struct derives #[pyclass(set_all)], there can also be a default constructor that implements __new__ using all the attributes of the struct.

Example:

#[pyclass(set_all, auto_new)]
struct Foo {
    bar: u64,
    baz: String
}

// auto_new would generate the following
#[pymethods]
impl Foo {
    #[new]
    fn pyo3_new(bar: u64, baz: String) -> Self {
        Self {
            bar,
            baz
        }
    }
}

Since set_all already requires all the fields to implement IntoPyObject, arguments for method shouldnt have any issue, even in the case of classes as parameters. Only issue I see is that it would require the multiple-pymethods feature, since this would be a block on its own.

Personal use-case - I am writing a library that exposes a bunch of structs generated from proto files, and I want to expose them to python land, including constructors.

I am happy to work on this, unless I am missing something it should be another field to PyClassPyO3Options in pyo3-macros-backend and then add some code to pyclass.rs impl_class(), but would also appreciate pointers.

Also open to bikeshedding around the auto_new name.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in pyo3-macros-backend at PyClassPyO3Options and follow pyclass.rs impl_class(), then examine how the multiple-pymethods feature structures generated methods. Implement the opt-in automatic new behavior for #[pyclass(set_all)] using all struct attributes, and confirm the generated constructor exposes those fields to Python.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
backend-api-design
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.