Skip to content

Commit b204c2b

Browse files
committed
Add PyValue::into_ref and into_ref_with_type.
1 parent 964a041 commit b204c2b

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

vm/src/pyobject.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1578,8 +1578,29 @@ impl PyObject {
15781578

15791579
// The intention is for this to replace `PyObjectPayload` once everything is
15801580
// converted to use `PyObjectPayload::AnyRustvalue`.
1581-
pub trait PyValue: Any + fmt::Debug {
1581+
pub trait PyValue: Any + fmt::Debug + Sized {
15821582
fn required_type(ctx: &PyContext) -> PyObjectRef;
1583+
1584+
fn into_ref(self, ctx: &PyContext) -> PyRef<Self> {
1585+
PyRef {
1586+
obj: PyObject::new(self, Self::required_type(ctx)),
1587+
_payload: PhantomData,
1588+
}
1589+
}
1590+
1591+
fn into_ref_with_type(self, vm: &mut VirtualMachine, cls: PyClassRef) -> PyResult<PyRef<Self>> {
1592+
let required_type = Self::required_type(&vm.ctx);
1593+
if objtype::issubclass(&cls.obj, &required_type) {
1594+
Ok(PyRef {
1595+
obj: PyObject::new(self, cls.obj),
1596+
_payload: PhantomData,
1597+
})
1598+
} else {
1599+
let subtype = vm.to_pystr(&cls.obj)?;
1600+
let basetype = vm.to_pystr(&required_type)?;
1601+
Err(vm.new_type_error(format!("{} is not a subtype of {}", subtype, basetype)))
1602+
}
1603+
}
15831604
}
15841605

15851606
impl FromPyObjectRef for PyRef<PyClass> {

0 commit comments

Comments
 (0)