From 139a31b1e458aa7966b157413d414aa2e5790e57 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Wed, 26 Jul 2017 16:13:45 -0700 Subject: [PATCH] implement ToPyObject and IntoPyObject for PyErr --- src/err.rs | 27 +++++++++++++++++++++++++-- src/object.rs | 8 ++++++++ src/objects/bytearray.rs | 2 +- src/objects/exc_impl.rs | 2 +- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/err.rs b/src/err.rs index 6e793bec..a3f2e049 100644 --- a/src/err.rs +++ b/src/err.rs @@ -12,7 +12,7 @@ use object::PyObject; use objects::{PyObjectRef, PyType, exc}; use instance::Py; use typeob::PyTypeObject; -use conversion::{ToPyObject, ToBorrowedObject}; +use conversion::{ToPyObject, IntoPyObject, ToBorrowedObject}; /// Defines a new exception type. /// @@ -360,7 +360,7 @@ impl PyErr { /// Retrieves the exception instance for this error. /// This method takes `mut self` because the error might need /// to be normalized in order to create the exception instance. - pub fn instance(mut self, py: Python) -> PyObject { + fn instance(mut self, py: Python) -> PyObject { &self.normalize(py); match self.pvalue { PyErrValue::Value(ref instance) => instance.clone_ref(py), @@ -425,6 +425,29 @@ impl std::fmt::Debug for PyErr { } } +impl IntoPyObject for PyErr { + + fn into_object(self, py: Python) -> PyObject { + self.instance(py) + } +} + +impl ToPyObject for PyErr { + + fn to_object(&self, py: Python) -> PyObject { + let err = self.clone_ref(py); + err.instance(py) + } +} + +impl<'a> IntoPyObject for &'a PyErr { + + fn into_object(self, py: Python) -> PyObject { + let err = self.clone_ref(py); + err.instance(py) + } +} + /// Converts `PyDowncastError` to Python `TypeError`. impl std::convert::From for PyErr { fn from(_err: PyDowncastError) -> PyErr { diff --git a/src/object.rs b/src/object.rs index ceb57440..a51129eb 100644 --- a/src/object.rs +++ b/src/object.rs @@ -283,6 +283,14 @@ impl IntoPyObject for PyObject } } +impl<'a> IntoPyObject for &'a PyObject +{ + #[inline] + fn into_object(self, py: Python) -> PyObject { + unsafe {PyObject::from_borrowed_ptr(py, self.as_ptr())} + } +} + impl<'a> FromPyObject<'a> for PyObject { #[inline] diff --git a/src/objects/bytearray.rs b/src/objects/bytearray.rs index 28fd9d96..99e4b514 100644 --- a/src/objects/bytearray.rs +++ b/src/objects/bytearray.rs @@ -99,7 +99,7 @@ mod test { let none = py.None(); if let Err(err) = PyByteArray::from(py, &none) { - assert!(py.is_instance::(&err.instance(py)).unwrap()) + assert!(err.is_instance::(py)); } else { panic!("error"); } diff --git a/src/objects/exc_impl.rs b/src/objects/exc_impl.rs index 8c3a86d3..a3be797e 100644 --- a/src/objects/exc_impl.rs +++ b/src/objects/exc_impl.rs @@ -122,7 +122,7 @@ mod test { let d = PyDict::new(py); d.set_item("socket", py.import("socket").unwrap()).unwrap(); - d.set_item("exc", err.instance(py)).unwrap(); + d.set_item("exc", err).unwrap(); py.run("assert isinstance(exc, socket.gaierror)", None, Some(d)).unwrap(); }