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

Union matches: select type by number of matching fields #264

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
21 changes: 13 additions & 8 deletions dacite/core.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import is_dataclass
from functools import partial
from itertools import zip_longest
from typing import TypeVar, Type, Optional, get_type_hints, Mapping, Any, Collection, MutableMapping

Expand Down Expand Up @@ -120,21 +121,25 @@ def _build_value_for_union(union: Type, data: Any, config: Config) -> Any:
except Exception: # pylint: disable=broad-except
continue
if is_instance(value, inner_type):
if config.strict_unions_match:
union_matches[inner_type] = value
else:
return value
union_matches[inner_type] = value
except DaciteError:
pass
if config.strict_unions_match:
if len(union_matches) > 1:
raise StrictUnionMatchError(union_matches)
return union_matches.popitem()[1]
if len(union_matches) > 1 and config.strict_unions_match:
raise StrictUnionMatchError(union_matches)
if union_matches:
return union_matches[sorted(union_matches.keys(), key=partial(_field_key_matches, data))[0]]
if not config.check_types:
return data
raise UnionMatchError(field_type=union, value=data)


def _field_key_matches(data: Any, inner_type: Type) -> int:
if not is_dataclass(inner_type):
return 0
data_class_fields = cache(get_fields)(inner_type)
return len(set(data.keys()) | {f.name for f in data_class_fields})


def _build_value_for_collection(collection: Type, data: Any, config: Config) -> Any:
data_type = data.__class__
if isinstance(data, Mapping) and is_subclass(collection, Mapping):
Expand Down
18 changes: 18 additions & 0 deletions tests/core/test_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,3 +182,21 @@ class Y:
result = from_dict(Y, {"d": {"x": {"i": 42}, "z": {"i": 37}}})

assert result == Y(d={"x": X(i=42), "z": X(i=37)})


def test_from_dict_with_union_of_data_classes_selects_type_by_number_of_matching_fields():
@dataclass
class X:
i: Optional[int]

@dataclass
class Y:
j: int

@dataclass
class Z:
d: Union[X, Y]

result = from_dict(Z, {"d": {"j": 42}})

assert result == Z(d=Y(j=42))