Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass detailed error message to python when parsing an argument fails #2178

Merged
merged 3 commits into from
Feb 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `PyDate_FromTimestamp`
- Deprecate the `gc` option for `pyclass` (e.g. `#[pyclass(gc)]`). Just implement a `__traverse__` `#[pymethod]`. [#2159](https://github.com/PyO3/pyo3/pull/2159)
- The `ml_meth` field of `PyMethodDef` is now represented by the `PyMethodDefPointer` union [2166](https://github.com/PyO3/pyo3/pull/2166)
- The `PyTypeError` thrown when argument parsing failed now contains the nested causes [2177](https://github.com/PyO3/pyo3/pull/2178)

### Removed

Expand Down
5 changes: 4 additions & 1 deletion src/impl_/extract_argument.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,10 @@ pub fn from_py_with_with_default<'py, T>(
#[cold]
pub fn argument_extraction_error(py: Python, arg_name: &str, error: PyErr) -> PyErr {
if error.get_type(py) == PyTypeError::type_object(py) {
PyTypeError::new_err(format!("argument '{}': {}", arg_name, error.value(py)))
let remapped_error =
PyTypeError::new_err(format!("argument '{}': {}", arg_name, error.value(py)));
remapped_error.set_cause(py, error.cause(py));
remapped_error
} else {
error
}
Expand Down
73 changes: 65 additions & 8 deletions tests/test_pyfunction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,24 @@ fn test_function_with_custom_conversion_error() {
);
}

#[pyclass]
#[derive(Debug, FromPyObject)]
struct ValueClass {
#[pyo3(get)]
value: usize,
}

#[pyfunction]
fn conversion_error(str_arg: &str, int_arg: i64, tuple_arg: (&str, f64), option_arg: Option<i64>) {
fn conversion_error(
str_arg: &str,
int_arg: i64,
tuple_arg: (&str, f64),
option_arg: Option<i64>,
struct_arg: Option<ValueClass>,
) {
println!(
"{:?} {:?} {:?} {:?}",
str_arg, int_arg, tuple_arg, option_arg
"{:?} {:?} {:?} {:?} {:?}",
str_arg, int_arg, tuple_arg, option_arg, struct_arg
);
}

Expand All @@ -182,38 +195,82 @@ fn test_conversion_error() {
py_expect_exception!(
py,
conversion_error,
"conversion_error(None, None, None, None)",
"conversion_error(None, None, None, None, None)",
PyTypeError,
"argument 'str_arg': 'NoneType' object cannot be converted to 'PyString'"
);
py_expect_exception!(
py,
conversion_error,
"conversion_error(100, None, None, None)",
"conversion_error(100, None, None, None, None)",
PyTypeError,
"argument 'str_arg': 'int' object cannot be converted to 'PyString'"
);
py_expect_exception!(
py,
conversion_error,
"conversion_error('string1', 'string2', None, None)",
"conversion_error('string1', 'string2', None, None, None)",
PyTypeError,
"argument 'int_arg': 'str' object cannot be interpreted as an integer"
);
py_expect_exception!(
py,
conversion_error,
"conversion_error('string1', -100, 'string2', None)",
"conversion_error('string1', -100, 'string2', None, None)",
PyTypeError,
"argument 'tuple_arg': 'str' object cannot be converted to 'PyTuple'"
);
py_expect_exception!(
py,
conversion_error,
"conversion_error('string1', -100, ('string2', 10.), 'string3')",
"conversion_error('string1', -100, ('string2', 10.), 'string3', None)",
PyTypeError,
"argument 'option_arg': 'str' object cannot be interpreted as an integer"
);
let exception = py_expect_exception!(
py,
conversion_error,
"
class ValueClass:
def __init__(self, value):
self.value = value
conversion_error('string1', -100, ('string2', 10.), None, ValueClass(\"no_expected_type\"))",
PyTypeError
);
assert_eq!(
extract_traceback(py, exception),
"TypeError: argument 'struct_arg': failed to \
extract field ValueClass.value: TypeError: 'str' object cannot be interpreted as an integer"
);

let exception = py_expect_exception!(
py,
conversion_error,
"
class ValueClass:
def __init__(self, value):
self.value = value
conversion_error('string1', -100, ('string2', 10.), None, ValueClass(-5))",
PyTypeError
);
assert_eq!(
extract_traceback(py, exception),
"TypeError: argument 'struct_arg': failed to \
extract field ValueClass.value: OverflowError: can't convert negative int to unsigned"
);
}

/// Helper function that concatenates the error message from
/// each error in the traceback into a single string that can
/// be tested.
fn extract_traceback(py: Python, mut error: PyErr) -> String {
let mut error_msg = error.to_string();
while let Some(cause) = error.cause(py) {
error_msg.push_str(": ");
error_msg.push_str(&cause.to_string());
error = cause
}
error_msg
}

#[test]
Expand Down