Skip to content

Commit

Permalink
Merge pull request #149 from ermakov-oleg/new-type-support
Browse files Browse the repository at this point in the history
Added typing.NewType support
  • Loading branch information
ermakov-oleg authored May 8, 2024
2 parents a313159 + 2538ecd commit b719a54
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ classifiers = [
]

dependencies = [
"typing-inspect>=0.8.0",
"attributes-doc",
"typing-extensions",
]
Expand Down
7 changes: 7 additions & 0 deletions python/serpyco_rs/_describe.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@ def describe_type(
return LiteralType(args=list(args), custom_encoder=custom_encoder)
raise RuntimeError('Supported only Literal[str | int, ...]')

if _is_new_type(t):
return describe_type(t.__supertype__, meta, custom_type_resolver)

if t is Union:
if _NoneType in args:
new_args = tuple(arg for arg in args if arg is not _NoneType)
Expand Down Expand Up @@ -555,3 +558,7 @@ def _is_frozen_dataclass(cls: Any, field: EntityField) -> bool:
return True
else:
return False


def _is_new_type(t: Any) -> bool:
return hasattr(t, '__supertype__')
28 changes: 28 additions & 0 deletions tests/test_simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,3 +308,31 @@ class Foo:

assert serializer.dump(Foo(bar=1)) == {'bar': 1}
assert serializer.dump(Foo(bar='2')) == {'bar': '2'}


def test_load_new_type():
from typing import NewType

Foo = NewType('Foo', int)

@dataclass
class Bar:
foo: Foo

serializer = Serializer(Bar)

assert serializer.load({'foo': 1}) == Bar(foo=Foo(1))


def test_dump_new_type():
from typing import NewType

Foo = NewType('Foo', int)

@dataclass
class Bar:
foo: Foo

serializer = Serializer(Bar)

assert serializer.dump(Bar(foo=Foo(1))) == {'foo': 1}

0 comments on commit b719a54

Please sign in to comment.