-
-
Notifications
You must be signed in to change notification settings - Fork 108
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
structure: how to report path to invalid data element #47
Comments
Here is possibly quite crazy idea how to report an error incl. path within input data leading to the failure. Requirements:
Concept:
Here is code to demonstrate how to detect the path from an exception raised in deeply nested call. If you store the code into def int_structure_hook(val, dtype):
return int(val)
def list_structure_hook(lst, dtype):
return [int_structure_hook(itm, int) for cattrs_i, itm in enumerate(lst)]
def dict_structure_hook(dct, dtype):
return [list_structure_hook(val, list) for cattrs_i, val in dct.items()]
def structure(val):
try:
return dict_structure_hook(val, dict)
except ValueError as exc:
path = []
tb = exc.__traceback__
while tb:
path_elm = tb.tb_frame.f_locals.get("cattrs_i")
if path_elm:
path.append(path_elm)
tb = tb.tb_next
exc.path = path
raise exc
def test_it():
try:
res = structure({"oak": [1, "0aa", 3], "birch": [9, 2, 0]})
print(f"Happy result is: {res}")
except ValueError as exc:
print(f"Path {exc.path}: has problem: {exc}") When called:
What do you think of that? No perfect results, but something, what helps navigating close to source of problem in many cases. Definitely would require (small) modifications in existing converters. |
This is something I would definitely like to support, since getting an error somewhere deep can be very annoying indeed. Need to think about it. |
@Tinche take your time, it is not an easy problem. Here is alternative method: pass """alternative passing path context via argument `path`
Converters have singature: func(val, dtype, *path)
where `path` is the path to the current element (list of values)
When calling, one uses original `path` value with * and adds new selector to the end
fun(val, dtype, *path, index)
what results in extended `path` value within the deeper function.
"""
def int_structure_hook(val, dtype, *path):
return int(val)
def list_structure_hook(lst, dtype, *path):
return [int_structure_hook(itm, int, *path, i) for i, itm in enumerate(lst)]
def dict_structure_hook(dct, dtype, *path):
return [list_structure_hook(val, list, *path, key) for key, val in dct.items()]
def structure(val, dtype):
try:
return dict_structure_hook(val, dict)
except ValueError as exc:
path = []
tb = exc.__traceback__
while tb:
deeper_path = tb.tb_frame.f_locals.get("path")
if deeper_path:
path = deeper_path
tb = tb.tb_next
exc.path = path
raise exc
def test_it():
try:
res = structure({"oak": [1, "0aa", 3], "birch": [9, 2, 0]}, dict)
print(f"Happy result is: {res}")
except ValueError as exc:
print(f"Path {exc.path}: has problem: {exc}")
assert exc.args[0] == "invalid literal for int() with base 10: '0aa'"
assert isinstance(exc, ValueError)
assert exc.path == ("oak", 1) To avoid confusion with intermediate functions using |
Incidentally, one of the hardest things to debug is when you have a NoneType that can't be converted into whatever the expected type is. Without a path, currently there's no way to even guess at which of the many |
We could copy a few ideas from But have a look at their ValidationError, there's a few fields there that we could potentially use. |
Hey, sorry for kinda necro-post, but have there been any progress on this? It would really be very handy to have this feature :) |
This is probably the next big feature I work on :) |
Nice to hear it! Sorry for the question, but do you have any ETA for it? |
So there's https://catt.rs/en/stable/validation.html#transforming-exceptions-into-error-messages in the last release, 23.1.x. I'm going to close this as complete, let's open new tickets for any desired improvements! |
Description
I want to cattrs to load complex nested data and in case some validation/conversion fails, I want to provide reasonable context information about what part of data did not work properly.
What I Did
Having attrs based classes: Config with attributes source, fetch and publish, each holding value of specific (attrs based) class Source, Fetch and Publish.
If some data element is wrong (e.g. expecting integer and providing string "5a"), the structure process fails raising
ValueError("could not convert string to float: '5a'",)
However, the error does not include any contextual information about where in my nested input the problem was read from.
It would be nice to get some sort of path in the exception, which I could use.
marshmallow
andtrafaret
are examples of similar solutions providing contextual information.The text was updated successfully, but these errors were encountered: