Open Divy1211 opened 1 month ago
Great question. Closely related to this is other subclassing issues like #4443, #1647, #1644 and https://github.com/PyO3/pyo3/issues/1637#issuecomment-849444381
I think the API you propose fits a very relevant need, but I'd slightly prefer if instead of adding one new function a bit ad-hoc we tried to do a more complete review of what we are currently missing and where we don't match Python semantics.
Ideally we can then do a small API refresh to close a bunch of related awkward cases. Maybe targeting 0.24
The Problem
I have a struct in rust that is intended to be sub classed by python classes, and I need to provide factory class methods to this struct. Currently, there seems to be no direct way to instantiate an instance of a sub class with an already existing instance of the Rust struct.
Minimal Example
and in python:
The
mk
function doesn't automatically convert the returnedSpam
into aChild
instanceCurrent Workaround
The best I've managed to do is the following:
However, this is not ideal, since I had to define a
new
, and in a real scenario ifnew
is non trivial to call/or is costly, this is not feasible.Suggestion
Would it be possible to add something like this:
Note: This still keeps it possible to return the base type if so desired, since it doesn't automatically converting a classmethod's return value to the subtype like
#[new]
Implementation
I'd be happy to give implementing this a go, but I'm not sure how hard it might be, and may need some guidance/mentoring!