From f0c5dc713d094aa02216f24c37685e8330c7e7e2 Mon Sep 17 00:00:00 2001 From: Askaholic Date: Sat, 3 Oct 2020 14:36:40 -0800 Subject: [PATCH] Add argument name to error messages in conversion errors --- pyo3-derive-backend/src/pymethod.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/pyo3-derive-backend/src/pymethod.rs b/pyo3-derive-backend/src/pymethod.rs index 62ced447077..7d8afb29fad 100644 --- a/pyo3-derive-backend/src/pymethod.rs +++ b/pyo3-derive-backend/src/pymethod.rs @@ -475,10 +475,21 @@ fn impl_arg_param( let ty = arg.ty; let name = arg.name; + let transform_error = quote! { + |e| { + let reason = e.instance(_py).str() + .unwrap_or_else(|_| pyo3::types::PyString::new(_py, "")); + pyo3::PyErr::from_type( + e.ptype(_py), + format!("argument '{}': {}", stringify!(#name), reason) + ) + } + }; if spec.is_args(&name) { return quote! { - let #arg_name = <#ty as pyo3::FromPyObject>::extract(_args.as_ref())?; + let #arg_name = <#ty as pyo3::FromPyObject>::extract(_args.as_ref()) + .map_err(#transform_error)?; }; } else if spec.is_kwargs(&name) { return quote! { @@ -518,7 +529,7 @@ fn impl_arg_param( quote! { let #mut_ _tmp: #target_ty = match #arg_value { - Some(_obj) => _obj.extract()?, + Some(_obj) => _obj.extract().map_err(#transform_error)?, None => #default, }; let #arg_name = #borrow_tmp; @@ -526,7 +537,7 @@ fn impl_arg_param( } else { quote! { let #arg_name = match #arg_value { - Some(_obj) => _obj.extract()?, + Some(_obj) => _obj.extract().map_err(#transform_error)?, None => #default, }; }