You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
use pyo3::prelude::*;use pyo3::types::PyType;use rand::random;#[pyclass(subclass)]pubstructSpam{#[pyo3(get)]eggs:i32,}#[pymethods]implSpam{#[classmethod]fnmk<'py>(cls:Bound<'py,PyType>) -> Self{// Naive attempt to return Spam, considering it may// automatically get converted to subtype like `#[new]`Spam{eggs:random(),}}}
and in python:
fromtest_pyo3importSpamclassChild(Spam):
passprint(Child.mk()) # <builtins.Spam object at 0x74993d11bf10>
The mk function doesn't automatically convert the returned Spam into a Child instance
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!
The text was updated successfully, but these errors were encountered:
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!
The text was updated successfully, but these errors were encountered: