implement ToPyObject and IntoPyObject for PyErr
This commit is contained in:
parent
e5c1fcf11d
commit
139a31b1e4
27
src/err.rs
27
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<PyDowncastError> for PyErr {
|
||||
fn from(_err: PyDowncastError) -> PyErr {
|
||||
|
|
|
@ -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]
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue