Skip to content
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
2 changes: 1 addition & 1 deletion dataclass_wizard/_loaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ def load_to_union(cls, tp: TypeInfo, extras: Extras):

possible_tp = eval_forward_ref_if_needed(possible_tp, actual_cls)

tp_new = TypeInfo(possible_tp, i=i)
tp_new = TypeInfo(possible_tp, i=i, prefix=tp.prefix)
tp_new.in_optional = in_optional

if possible_tp is NoneType:
Expand Down
38 changes: 38 additions & 0 deletions tests/unit/test_loaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -3646,3 +3646,41 @@ class Test(JSONWizard):
t2 = Test.from_dict(t.to_dict())
assert t2.str_e is MyStrEnum.B
assert t2.int_e is MyIntEnum.Z


def test_dict_with_union_key_of_int_and_literal():
"""
Regression test for https://github.com/rnag/dataclass-wizard/issues/245

When a ``Dict`` has a ``Union`` key type (e.g. ``int | Literal["AAA"]``),
the generated union-loader for the *key* must reference the key variable
rather than the value variable. Previously the sub-type loaders emitted
references to ``v2`` while the enclosing key-loader parameter was ``k2``,
so every otherwise-valid key raised ``ParseError``.
"""

@dataclass
class Test(JSONWizard):
error: Dict[Union[int, Literal["AAA"]], str]
successful: Union[int, Literal["AAA"]]

# int-coercible keys *and* the literal key should all parse.
t = Test.from_dict(
{'error': {'1': '1', '2': '2', '3': '3', 'AAA': '4'},
'successful': '1'}
)
assert t.error == {1: '1', 2: '2', 3: '3', 'AAA': '4'}
assert t.successful == 1

# The literal value is also accepted for the scalar union field.
t2 = Test.from_dict(
{'error': {'1': '1', 'AAA': '4'}, 'successful': 'AAA'}
)
assert t2.error == {1: '1', 'AAA': '4'}
assert t2.successful == 'AAA'

# A key that is neither an int nor the literal is still rejected.
with pytest.raises(ParseError):
Test.from_dict(
{'error': {'1': '1', 'BBB': '4'}, 'successful': '1'}
)