Skip to content

Commit

Permalink
Add argument name to error messages in conversion errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Askaholic committed Oct 3, 2020
1 parent 37ce406 commit f3b8257
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions pyo3-derive-backend/src/pymethod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,21 @@ pub fn impl_arg_params(
}}
}

macro_rules! transform_arg_error {
($name:tt) => {
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)
)
}
}
};
}

/// Re option_pos: The option slice doesn't contain the py: Python argument, so the argument
/// index and the index in option diverge when using py: Python
fn impl_arg_param(
Expand All @@ -475,10 +490,12 @@ fn impl_arg_param(

let ty = arg.ty;
let name = arg.name;
let transform_error = transform_arg_error!(name);

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! {
Expand Down Expand Up @@ -518,15 +535,15 @@ 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;
}
} else {
quote! {
let #arg_name = match #arg_value {
Some(_obj) => _obj.extract()?,
Some(_obj) => _obj.extract().map_err(#transform_error)?,
None => #default,
};
}
Expand Down

0 comments on commit f3b8257

Please sign in to comment.