cattrs
cattrs copied to clipboard
Obtain object/field instance causing validation error
I can't work out how to obtain a reference to the object instance or field causing a validation error when calling cattrs.structure
For example:
from attrs import define
from cattrs import structure, BaseValidationError
data = [
{
'id': 'aaa',
'title': 'atitle',
},
{
'XX': 'bbb',
'title': 'btitle'
}
]
@define
class Example:
id: str
title: str
try:
example = structure(data, list[Example])
except BaseValidationError as e:
print(f"Exception: {e}")
example = None
print(example)
In the example above, one of the list items causes an IterableValidationError (as expected), and within the exception there is a ClassValidationError sub-exception (and KeyErrors within that).
The question is, how do I obtain the instance of the object causing the exception? The reasons for needing this information, is that the dictionary will be decorated with additional metadata (line number information) as the dict is a result from parsing with the ruamel.yaml library. I need to have the object instance causing the error as this will give better error messages in my use-case
thanks