Skip to content
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

Better error messages for nested structs #224

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 35 additions & 7 deletions dacite/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,10 @@ def _build_value(type_: Type, data: Any, config: Config) -> Any:
if is_generic_collection(type_):
data = extract_origin_collection(type_)(data)
else:
data = type_(data)
try:
data = type_(data)
except Exception as error:
raise WrongTypeError(type_, data) from error
break
return data

Expand Down Expand Up @@ -139,17 +142,42 @@ def _build_value_for_collection(collection: Type, data: Any, config: Config) ->
data_type = data.__class__
if isinstance(data, Mapping) and is_subclass(collection, Mapping):
item_type = extract_generic(collection, defaults=(Any, Any))[1]
return data_type((key, _build_value(type_=item_type, data=value, config=config)) for key, value in data.items())
items = []
for key, value in data.items():
try:
items.append((key, _build_value(type_=item_type, data=value, config=config)))
except DaciteFieldError as error:
error.update_path(f"[{key}]")
raise
return data_type(items)
elif isinstance(data, tuple) and is_subclass(collection, tuple):
if not data:
return data_type()
types = extract_generic(collection)
items = []
if len(types) == 2 and types[1] == Ellipsis:
return data_type(_build_value(type_=types[0], data=item, config=config) for item in data)
return data_type(
_build_value(type_=type_, data=item, config=config) for item, type_ in zip_longest(data, types)
)
for i, item in enumerate(data):
try:
items.append(_build_value(type_=types[0], data=item, config=config))
except DaciteFieldError as error:
error.update_path(f"[{i}]")
raise
return data_type(items)
for i, (item, type_) in enumerate(zip_longest(data, types)):
try:
items.append(_build_value(type_=type_, data=item, config=config))
except DaciteFieldError as error:
error.update_path(f"[{i}]")
raise
return data_type(items)
elif isinstance(data, Collection) and is_subclass(collection, Collection):
item_type = extract_generic(collection, defaults=(Any,))[0]
return data_type(_build_value(type_=item_type, data=item, config=config) for item in data)
items = []
for i, item in enumerate(data):
try:
items.append(_build_value(type_=item_type, data=item, config=config))
except DaciteFieldError as error:
error.update_path(f"[{i}]")
raise
return data_type(items)
return data
9 changes: 6 additions & 3 deletions dacite/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ def __init__(self, field_path: Optional[str] = None):

def update_path(self, parent_field_path: str) -> None:
if self.field_path:
self.field_path = f"{parent_field_path}.{self.field_path}"
if self.field_path.startswith("["):
self.field_path = f"{parent_field_path}{self.field_path}"
else:
self.field_path = f"{parent_field_path}.{self.field_path}"
else:
self.field_path = parent_field_path

Expand Down Expand Up @@ -70,11 +73,11 @@ def __str__(self) -> str:
return f"can not resolve forward reference: {self.message}"


class UnexpectedDataError(DaciteError):
class UnexpectedDataError(DaciteFieldError):
def __init__(self, keys: Set[str]) -> None:
super().__init__()
self.keys = keys

def __str__(self) -> str:
formatted_keys = ", ".join(f'"{key}"' for key in self.keys)
return f"can not match {formatted_keys} to any data class field"
return f"can not match {formatted_keys} to any data class field at '{self.field_path}'"