Skip to content
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

Fix a case when builtin subclass is not converted back to the hinted type #494

Open
wants to merge 7 commits into
base: master
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
2 changes: 2 additions & 0 deletions dataclasses_json/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,8 @@ def _decode_item(type_arg, x):
return _decode_dataclass(type_arg, x, infer_missing)
if _is_supported_generic(type_arg):
return _decode_generic(type_arg, x, infer_missing)
if type_arg.__class__.__module__ == "builtins":
return type_arg(x)
return x

def handle_pep0673(pre_0673_hint: str) -> Union[Type, str]:
Expand Down
33 changes: 32 additions & 1 deletion tests/test_builtins.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from decimal import Decimal
from typing import Optional
from typing import List

from pytest import mark, param

Expand All @@ -15,6 +15,15 @@ class DataClassWithBuiltins(DataClassJsonMixin):
actually_a_float: float


class StrSubclass(str):
pass


@dataclass
class DataClassWithBuiltinCollection(DataClassJsonMixin):
things: List[StrSubclass]


@mark.parametrize(
"model_dict, expected_model",
[
Expand All @@ -32,3 +41,25 @@ class DataClassWithBuiltins(DataClassJsonMixin):
)
def test__DataClassWithBuiltins__from_dict(model_dict, expected_model):
assert DataClassWithBuiltins.from_dict(model_dict) == expected_model


@mark.parametrize(
"serialized_model, expected_model",
[
param(
'{"things": ["John Doe"]}',
DataClassWithBuiltinCollection(things=[StrSubclass("John Doe")]),
id="Collection of str subclasses"
),
param(
'{"things": []}',
DataClassWithBuiltinCollection(things=[]),
id="Empty collection of str subclasses"
),
]
)
def test_builtins_collections_with_subclass(serialized_model: str, expected_model: DataClassWithBuiltinCollection):
deser = DataClassWithBuiltinCollection.from_json(serialized_model)
if len(deser.things) > 0:
assert isinstance(deser.things[0], StrSubclass)
# for empty list we just assert there is no exception