|
3 | 3 | use std::error::Error;
|
4 | 4 | use std::fmt;
|
5 | 5 |
|
6 |
| -use pyo3::{exceptions::PyTypeError, PyErr, PyErrArguments, PyObject, Python, ToPyObject}; |
| 6 | +use pyo3::{exceptions::PyTypeError, Py, PyErr, PyErrArguments, PyObject, Python, ToPyObject}; |
7 | 7 |
|
8 | 8 | use crate::dtype::PyArrayDescr;
|
9 | 9 |
|
@@ -59,32 +59,51 @@ impl_pyerr!(DimensionalityError);
|
59 | 59 |
|
60 | 60 | /// Represents that types of the given arrays do not match.
|
61 | 61 | #[derive(Debug)]
|
62 |
| -pub struct TypeError { |
63 |
| - from: String, |
64 |
| - to: String, |
| 62 | +pub struct TypeError<'a> { |
| 63 | + from: &'a PyArrayDescr, |
| 64 | + to: &'a PyArrayDescr, |
65 | 65 | }
|
66 | 66 |
|
67 |
| -impl TypeError { |
68 |
| - pub(crate) fn new(from: &PyArrayDescr, to: &PyArrayDescr) -> Self { |
69 |
| - let dtype_to_str = |dtype: &PyArrayDescr| { |
70 |
| - dtype |
71 |
| - .str() |
72 |
| - .map_or_else(|_| "(unknown)".into(), |s| s.to_string_lossy().into_owned()) |
73 |
| - }; |
74 |
| - Self { |
75 |
| - from: dtype_to_str(from), |
76 |
| - to: dtype_to_str(to), |
77 |
| - } |
| 67 | +impl<'a> TypeError<'a> { |
| 68 | + pub(crate) fn new(from: &'a PyArrayDescr, to: &'a PyArrayDescr) -> Self { |
| 69 | + Self { from, to } |
78 | 70 | }
|
79 | 71 | }
|
80 | 72 |
|
81 |
| -impl fmt::Display for TypeError { |
| 73 | +impl fmt::Display for TypeError<'_> { |
82 | 74 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
83 | 75 | write!(f, "type mismatch:\n from={}, to={}", self.from, self.to)
|
84 | 76 | }
|
85 | 77 | }
|
86 | 78 |
|
87 |
| -impl_pyerr!(TypeError); |
| 79 | +impl Error for TypeError<'_> {} |
| 80 | + |
| 81 | +struct TypeErrorArguments { |
| 82 | + from: Py<PyArrayDescr>, |
| 83 | + to: Py<PyArrayDescr>, |
| 84 | +} |
| 85 | + |
| 86 | +impl PyErrArguments for TypeErrorArguments { |
| 87 | + fn arguments(self, py: Python) -> PyObject { |
| 88 | + let err = TypeError { |
| 89 | + from: self.from.as_ref(py), |
| 90 | + to: self.to.as_ref(py), |
| 91 | + }; |
| 92 | + |
| 93 | + err.to_string().to_object(py) |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +impl From<TypeError<'_>> for PyErr { |
| 98 | + fn from(err: TypeError<'_>) -> PyErr { |
| 99 | + let args = TypeErrorArguments { |
| 100 | + from: err.from.into(), |
| 101 | + to: err.to.into(), |
| 102 | + }; |
| 103 | + |
| 104 | + PyTypeError::new_err(args) |
| 105 | + } |
| 106 | +} |
88 | 107 |
|
89 | 108 | /// Represents that given `Vec` cannot be treated as an array.
|
90 | 109 | #[derive(Debug)]
|
|
0 commit comments