From 9d890561ad17b84bb67806bd777ce8a7902f7965 Mon Sep 17 00:00:00 2001 From: Adam Reichold Date: Wed, 6 Apr 2022 14:23:06 +0200 Subject: [PATCH] Add PyDowncastErrorArguments to delay formatting downcast errors. --- src/err/mod.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/err/mod.rs b/src/err/mod.rs index 869ff20a997..eed6798ad58 100644 --- a/src/err/mod.rs +++ b/src/err/mod.rs @@ -663,10 +663,34 @@ impl<'a> IntoPy for &'a PyErr { } } +struct PyDowncastErrorArguments { + from: Py, + to: Cow<'static, str>, +} + +impl PyErrArguments for PyDowncastErrorArguments { + fn arguments(self, py: Python<'_>) -> PyObject { + format!( + "'{}' object cannot be converted to '{}'", + self.from + .as_ref(py) + .name() + .unwrap_or(""), + self.to + ) + .to_object(py) + } +} + /// Convert `PyDowncastError` to Python `TypeError`. impl<'a> std::convert::From> for PyErr { fn from(err: PyDowncastError<'_>) -> PyErr { - exceptions::PyTypeError::new_err(err.to_string()) + let args = PyDowncastErrorArguments { + from: err.from.get_type().into(), + to: err.to, + }; + + exceptions::PyTypeError::new_err(args) } }