Skip to content

Commit

Permalink
Merge pull request #36 from NathanVaughn/bugfix/literal
Browse files Browse the repository at this point in the history
Fix issue with typing.Literal type hints
  • Loading branch information
NathanVaughn authored Nov 27, 2024
2 parents fb0ec9f + 96cc590 commit 97a66b6
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 5 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "simple-file-settings"
version = "0.1.5"
version = "0.1.6"
description = "Easily load and save simple configuration data to and from disk through a type-checked data class."
readme = "README.md"
authors = [{ name = "Nathan Vaughn", email = "[email protected]" }]
Expand Down
5 changes: 4 additions & 1 deletion simplefilesettings/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import enum
import pathlib
import typing
import inspect

T = typing.TypeVar("T", bound=enum.Enum)

Expand Down Expand Up @@ -85,7 +86,9 @@ def serialize(value: typing.Any) -> typing.Any:


def deserialize(value: typing.Any, type_hint: typing.Any) -> typing.Any:
if issubclass(type_hint, enum.Enum):
# https://stackoverflow.com/a/395782/9944427
# Fixes bug where typing.Literal as a type hint would error
if inspect.isclass(type_hint) and issubclass(type_hint, enum.Enum):
return _deserialize_enum(value, type_hint)
elif type_hint == datetime.datetime:
return _deserialize_datetime(value)
Expand Down
18 changes: 18 additions & 0 deletions tests/test__base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import enum
import json

import typing
import pytest
import typeguard

Expand Down Expand Up @@ -288,3 +289,20 @@ class Config:
tc = TestClass()
assert tc.key1 == TestEnum.A
assert tc.key2 == datetime.datetime(2024, 2, 3, 5, 3, 0)


@pytest.mark.parametrize("temp_file", [("valid.json")], indirect=["temp_file"])
def test_valid_file_3(temp_file: str) -> None:
"""
Ensure normal behavior works with Literal type hint
"""

class TestClass(JSONClass):
key1: str = "value1"
key2: typing.Literal["value1", "value2"] = "value1"

class Config:
json_file = temp_file

tc = TestClass()
assert tc.key2 == "value2"
6 changes: 3 additions & 3 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 97a66b6

Please sign in to comment.