diff --git a/src/instance.rs b/src/instance.rs index a2cebc4b..c1058738 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -96,6 +96,12 @@ impl<'a, T: PyTypeInfo> ToPyObject for PyRef<'a, T> { } } +impl<'a, T: PyTypeInfo> IntoPyObject for PyRef<'a, T> { + fn into_object(self, py: Python) -> PyObject { + self.to_object(py) + } +} + impl<'a, T: PyTypeInfo> Deref for PyRef<'a, T> { type Target = T; fn deref(&self) -> &T { @@ -170,6 +176,12 @@ impl<'a, T: PyTypeInfo> ToPyObject for PyRefMut<'a, T> { } } +impl<'a, T: PyTypeInfo> IntoPyObject for PyRefMut<'a, T> { + fn into_object(self, py: Python) -> PyObject { + self.to_object(py) + } +} + impl<'a, T: PyTypeInfo> Deref for PyRefMut<'a, T> { type Target = T; fn deref(&self) -> &T { diff --git a/tests/test_pyself.rs b/tests/test_pyself.rs index f1fc9cbf..dc5a8ff0 100644 --- a/tests/test_pyself.rs +++ b/tests/test_pyself.rs @@ -17,6 +17,9 @@ struct Reader { #[pymethods] impl Reader { + fn clone_ref(slf: PyRef) -> PyRef { + slf + } fn get_iter(slf: PyRef, keys: Py) -> PyResult { Ok(Iter { reader: slf.into(), @@ -70,15 +73,18 @@ impl PyIterProtocol for Iter { } } +fn reader() -> Reader { + let reader = [(1, "a"), (2, "b"), (3, "c"), (4, "d"), (5, "e")]; + Reader { + inner: reader.iter().map(|(k, v)| (*k, v.to_string())).collect(), + } +} + #[test] fn test_nested_iter() { let gil = Python::acquire_gil(); let py = gil.python(); - let reader = [(1, "a"), (2, "b"), (3, "c"), (4, "d"), (5, "e")]; - let reader = Reader { - inner: reader.iter().map(|(k, v)| (*k, v.to_string())).collect(), - } - .into_object(py); + let reader = reader().into_object(py); py_assert!( py, reader, @@ -86,23 +92,23 @@ fn test_nested_iter() { ); } +#[test] +fn test_clone_ref() { + let gil = Python::acquire_gil(); + let py = gil.python(); + let reader = reader().into_object(py); + py_assert!(py, reader, "reader == reader.clone_ref()"); +} + #[test] fn test_nested_iter_reset() { let gil = Python::acquire_gil(); let py = gil.python(); - let reader = [(1, "a"), (2, "b"), (3, "c"), (4, "d"), (5, "e")]; - let reader = PyRef::new( - py, - Reader { - inner: reader.iter().map(|(k, v)| (*k, v.to_string())).collect(), - }, - ) - .unwrap(); - let obj = reader.into_object(py); + let reader = PyRef::new(py, reader()).unwrap(); py_assert!( py, - obj, - "list(obj.get_iter_and_reset(bytes([3, 5, 2]))) == ['c', 'e', 'b']" + reader, + "list(reader.get_iter_and_reset(bytes([3, 5, 2]))) == ['c', 'e', 'b']" ); assert!(reader.inner.is_empty()); }