Skip to content

Fix Union with Literals #69

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

Open
wants to merge 3 commits into
base: develop
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
5 changes: 5 additions & 0 deletions .changelog/_unreleased.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[[entries]]
id = "6d0f41f2-f7f9-4808-af65-196a7a909b4f"
type = "fix"
description = "Fix #47: Union with Literal in them can now de/serialize"
author = "@rhaps0dy"
19 changes: 15 additions & 4 deletions databind/src/databind/json/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -763,13 +763,19 @@ def _check_style_compatibility(self, ctx: Context, style: str, value: t.Any) ->
def convert(self, ctx: Context) -> t.Any:
datatype = ctx.datatype
union: t.Optional[Union]
literal_types: t.List[TypeHint] = []

if isinstance(datatype, UnionTypeHint):
if datatype.has_none_type():
raise NotImplementedError("unable to handle Union type with None in it")
if not all(isinstance(a, ClassTypeHint) for a in datatype):
raise NotImplementedError(f"members of plain Union must be concrete types: {datatype}")
members = {t.cast(ClassTypeHint, a).type.__name__: a for a in datatype}
if len(members) != len(datatype):

literal_types = [a for a in datatype if isinstance(a, LiteralTypeHint)]
non_literal_types = [a for a in datatype if not isinstance(a, LiteralTypeHint)]
if not all(isinstance(a, ClassTypeHint) for a in non_literal_types):
raise NotImplementedError(f"members of plain Union must be concrete or Literal types: {datatype}")

members = {t.cast(ClassTypeHint, a).type.__name__: a for a in non_literal_types}
if len(members) != len(non_literal_types):
raise NotImplementedError(f"members of plain Union cannot have overlapping type names: {datatype}")
union = Union(members, Union.BEST_MATCH)
elif isinstance(datatype, (AnnotatedTypeHint, ClassTypeHint)):
Expand All @@ -788,6 +794,11 @@ def convert(self, ctx: Context) -> t.Any:
return ctx.spawn(ctx.value, member_type, None).convert()
except ConversionError as exc:
errors.append((exc.origin, exc))
for literal_type in literal_types:
try:
return ctx.spawn(ctx.value, literal_type, None).convert()
except ConversionError as exc:
errors.append((exc.origin, exc))
raise ConversionError(
self,
ctx,
Expand Down
42 changes: 42 additions & 0 deletions databind/src/databind/json/tests/converters_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
DatetimeConverter,
DecimalConverter,
EnumConverter,
LiteralConverter,
MappingConverter,
OptionalConverter,
PlainDatatypeConverter,
Expand Down Expand Up @@ -328,6 +329,22 @@ def test_union_converter_best_match(direction: Direction) -> None:
assert mapper.convert(direction, 42, t.Union[int, str]) == 42


@pytest.mark.parametrize("direction", (Direction.SERIALIZE, Direction.DESERIALIZE))
def test_union_converter_best_match_literal(direction: Direction) -> None:
mapper = make_mapper([UnionConverter(), PlainDatatypeConverter(), LiteralConverter()])

LiteralUnionType = t.Union[int, t.Literal["hi"], t.Literal["bye"]]

if direction == Direction.DESERIALIZE:
assert mapper.convert(direction, 42, LiteralUnionType) == 42
assert mapper.convert(direction, "hi", LiteralUnionType) == "hi"
assert mapper.convert(direction, "bye", LiteralUnionType) == "bye"
else:
assert mapper.convert(direction, 42, LiteralUnionType) == 42
assert mapper.convert(direction, "hi", LiteralUnionType) == "hi"
assert mapper.convert(direction, "bye", LiteralUnionType) == "bye"


@pytest.mark.parametrize("direction", (Direction.SERIALIZE, Direction.DESERIALIZE))
def test_union_converter_keyed(direction: Direction) -> None:
mapper = make_mapper([UnionConverter(), PlainDatatypeConverter()])
Expand All @@ -339,6 +356,31 @@ def test_union_converter_keyed(direction: Direction) -> None:
assert mapper.convert(direction, 42, th) == {"int": 42}


@pytest.mark.xfail
@pytest.mark.parametrize("direction", (Direction.SERIALIZE, Direction.DESERIALIZE))
def test_union_converter_keyed_literal(direction: Direction) -> None:
mapper = make_mapper([UnionConverter(), PlainDatatypeConverter(), LiteralConverter()])

th = te.Annotated[
t.Union[int, t.Literal["hi"], t.Literal["bye"]],
Union({"int": int, "HiType": t.Literal["hi"], "ByeType": t.Literal["bye"]}, style=Union.KEYED),
]
if direction == Direction.DESERIALIZE:
assert mapper.convert(direction, {"int": 42}, th) == 42
assert mapper.convert(direction, {"HiType": "hi"}, th) == "hi"
assert mapper.convert(direction, {"ByeType": "bye"}, th) == "bye"

with pytest.raises(ConversionError):
mapper.convert(direction, {"ByeType": "hi"}, th)
else:
assert mapper.convert(direction, 42, th) == {"int": 42}
assert mapper.convert(direction, "hi", th) == {"HiType": "hi"}
assert mapper.convert(direction, "bye", th) == {"ByeType": "bye"}

with pytest.raises(ConversionError):
mapper.convert(direction, {"ByeType": "hi"}, th)


@pytest.mark.parametrize("direction", (Direction.SERIALIZE, Direction.DESERIALIZE))
def test_union_converter_flat_plain_types_not_supported(direction: Direction) -> None:
mapper = make_mapper([UnionConverter(), PlainDatatypeConverter()])
Expand Down
Loading