Added improved error messages to the derive FromPyObject macro for basic structs and enums

This commit is contained in:
R2D2 2021-05-27 15:42:57 +02:00
parent 5446fe2062
commit f68ab481ba
1 changed files with 19 additions and 3 deletions

View File

@ -77,7 +77,10 @@ impl<'a> Enum<'a> {
quote!(
#(#var_extracts)*
let type_name = obj.get_type().name()?;
let err_msg = format!("'{}' object cannot be converted to '{}'", type_name, #error_names);
let err_msg = format!("In {} : '{}' object cannot be converted to '{}'",
self.enum_ident,
type_name,
#error_names);
Err(pyo3::exceptions::PyTypeError::new_err(err_msg))
)
}
@ -241,8 +244,21 @@ impl<'a> Container<'a> {
let get_field = quote!(obj.#getter?);
let extractor = match &attrs.from_py_with {
None => quote!(#get_field.extract()?),
Some(FromPyWithAttribute(expr_path)) => quote! (#expr_path(#get_field)?),
None => quote!(#get_field.extract().map_err(|inner| {
let err_msg = format!("Failed to extract field {} of {}:\n{} ",
stringify!(#ident),
stringify!(#self_ty),
inner);
pyo3::exceptions::PyTypeError::new_err(err_msg)
})?),
Some(FromPyWithAttribute(expr_path)) => quote! (#expr_path(#get_field).
map_err(|inner| {
let err_msg = format!("Failed to extract field {} of {}:\n{} ",
stringify!(#ident),
stringify!(#self_ty),
inner);
pyo3::exceptions::PyTypeError::new_err(err_msg)
})?),
};
fields.push(quote!(#ident: #extractor));