implement ToPyObject and IntoPyObject for PyErr

This commit is contained in:
Nikolay Kim 2017-07-26 16:13:45 -07:00
parent e5c1fcf11d
commit 139a31b1e4
4 changed files with 35 additions and 4 deletions

View File

@ -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<PyDowncastError> for PyErr {
fn from(_err: PyDowncastError) -> PyErr {

View File

@ -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]

View File

@ -99,7 +99,7 @@ mod test {
let none = py.None();
if let Err(err) = PyByteArray::from(py, &none) {
assert!(py.is_instance::<exc::TypeError, _>(&err.instance(py)).unwrap())
assert!(err.is_instance::<exc::TypeError>(py));
} else {
panic!("error");
}

View File

@ -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();
}