Skip to content

Commit

Permalink
Use str instead of repr in typename, fixing Union[Literal["str"], ...]
Browse files Browse the repository at this point in the history
  • Loading branch information
kngwyu committed Jul 23, 2022
1 parent 5a7fa3c commit b3905ef
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
2 changes: 1 addition & 1 deletion serde/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ def typename(typ, with_typing_module: bool = False) -> str:
args = type_args(typ)
if not args:
raise TypeError("Literal type requires at least one literal argument")
return f'Literal[{", ".join(repr(e) for e in args)}]'
return f'Literal[{", ".join(str(e) for e in args)}]'
elif typ is Any:
return f'{mod}Any'
else:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
from datetime import datetime
from typing import Dict, Generic, List, NewType, Optional, Set, Tuple, TypeVar, Union

if sys.version_info[:2] == (3, 7):
from typing_extensions import Literal
else:
from typing import Literal


import serde
from serde.compat import (
is_dict,
Expand Down Expand Up @@ -84,6 +90,7 @@ class Foo(Generic[T]):
assert typename(Dict[str, Foo]) == "Dict[str, Foo]"
assert typename(Set) == "Set"
assert typename(Set[int]) == "Set[int]"
assert typename(Literal[1, 1.0, "Hey"]) == "Literal[1, 1.0, Hey]"


def test_iter_types():
Expand Down
34 changes: 33 additions & 1 deletion tests/test_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import sys
from dataclasses import dataclass
from ipaddress import IPv4Address
from typing import Dict, Generic, List, Optional, Tuple, TypeVar, Union
from typing import Dict, Generic, List, Literal, Optional, Tuple, TypeVar, Union
from uuid import UUID

import pytest
Expand Down Expand Up @@ -61,6 +61,16 @@ class ContUnion:
v: Union[Dict[str, int], List[int], List[str]]


@serde
@dataclass(unsafe_hash=True)
class LitUnion:
"""
Union of literals
"""

v: Union[int, Literal["foo", "bar"]]


def test_union():
v = PriUnion(10)
s = '{"v":10}'
Expand Down Expand Up @@ -128,6 +138,28 @@ def test_union_containers():
assert v == from_json(ContUnion, s)


def test_union_with_literal():
v = LitUnion(10)
s = '{"v":10}'
assert s == to_json(v)
assert v == from_json(LitUnion, s)

v = LitUnion("foo")
s = '{"v":"foo"}'
assert s == to_json(v)
assert v == from_json(LitUnion, s)

v = LitUnion("bar")
s = '{"v":"bar"}'
assert s == to_json(v)
assert v == from_json(LitUnion, s)

s = '{"v":"boo"}'

with pytest.raises(SerdeError):
from_json(LitUnion, s)


def test_union_with_complex_types():
@serde
class A:
Expand Down

0 comments on commit b3905ef

Please sign in to comment.