Skip to content

Commit

Permalink
Adding literal support
Browse files Browse the repository at this point in the history
  • Loading branch information
jmdacruz committed Oct 31, 2023
1 parent 7ab5e55 commit 1af88b5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
9 changes: 8 additions & 1 deletion dataconf/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from enum import IntEnum
from inspect import isclass

from typing import Any
from typing import Any, Literal
from typing import Dict
from typing import get_args
from typing import get_origin
Expand Down Expand Up @@ -200,6 +200,13 @@ def __parse(value: any, clazz: Type, path: str, strict: bool, ignore_unexpected:

raise TypeConfigException(f"expected str or int at {path}, got {type(value)}")

if get_origin(clazz) is (Literal):
if value in args:
return value
raise TypeConfigException(
f"expected one of {', '.join(map(str, args))} at {path}, got {value}"
)

if clazz is datetime:
dt = __parse_type(value, clazz, path, isinstance(value, str))
try:
Expand Down
37 changes: 36 additions & 1 deletion tests/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from enum import Enum
from enum import IntEnum
import os
from typing import Any
from typing import Any, Literal
from typing import Dict
from typing import List
from typing import Optional
Expand Down Expand Up @@ -712,3 +712,38 @@ class TopLevel:
top_b="some other value",
top_c=Nested(nested_a=False, nested_b="some default value"),
)

def test_literals(self):
@dataclass
class Something:
literal: Literal["a", "b", 3] = field(default="a")

config_string = """
literal: "a"
"""

assert loads(config_string, Something, loader=dataconf.YAML) == Something(
literal="a"
)

config_string = """
literal: "b"
"""

assert loads(config_string, Something, loader=dataconf.YAML) == Something(
literal="b"
)

config_string = """
literal: 3
"""

assert loads(config_string, Something, loader=dataconf.YAML) == Something(
literal=3
)

with pytest.raises(TypeConfigException):
config_string = """
literal: "d"
"""
loads(config_string, Something, loader=dataconf.YAML)

0 comments on commit 1af88b5

Please sign in to comment.