Skip to content

Commit

Permalink
Add PyDowncastErrorArguments to delay formatting downcast errors.
Browse files Browse the repository at this point in the history
  • Loading branch information
adamreichold committed Apr 10, 2022
1 parent 74e93a2 commit 10c285b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed

- Default to "m" ABI tag when choosing `libpython` link name for CPython 3.7 on Unix. [#2288](https://github.com/PyO3/pyo3/pull/2288)
- Improved performance of failing calls to `FromPyObject::extract` which is common when functions accept multiple distinct types. [#2279](https://github.com/PyO3/pyo3/pull/2279)

## [0.16.3] - 2022-04-05

Expand Down
26 changes: 25 additions & 1 deletion src/err/mod.rs
Expand Up @@ -663,10 +663,34 @@ impl<'a> IntoPy<PyObject> for &'a PyErr {
}
}

struct PyDowncastErrorArguments {
from: Py<PyType>,
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("<failed to extract type name>"),
self.to
)
.to_object(py)
}
}

/// Convert `PyDowncastError` to Python `TypeError`.
impl<'a> std::convert::From<PyDowncastError<'a>> 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)
}
}

Expand Down

0 comments on commit 10c285b

Please sign in to comment.