Skip to content

Commit 8e37cc3

Browse files
authored
Api additions: to_dict and from_dict (#100)
* Added support for from_json() accepting dict in addition to str-like types (#97) * Added support for mypy of versions 0.710+ * Added support .from_json() accepting dict * feat(api): add to_dict and from_dict methods
1 parent c0b449f commit 8e37cc3

6 files changed

Lines changed: 50 additions & 20 deletions

File tree

‎dataclasses_json/api.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import abc
22
import json
3-
from typing import Any, Callable, List, Optional, Tuple, TypeVar, Union, Type
3+
from typing import (Any, Callable, List, Optional, Tuple, Type, TypeVar, Union)
44

5-
from dataclasses_json.mm import build_schema, SchemaType, JsonData
6-
from dataclasses_json.core import _ExtendedEncoder, _asdict, _decode_dataclass
5+
from dataclasses_json.core import (Json, _ExtendedEncoder, _asdict,
6+
_decode_dataclass)
7+
from dataclasses_json.mm import JsonData, SchemaType, build_schema
78

89
A = TypeVar('A')
910
B = TypeVar('B')
@@ -57,8 +58,18 @@ def from_json(cls: Type[A],
5758
parse_int=parse_int,
5859
parse_constant=parse_constant,
5960
**kw)
61+
return cls.from_dict(kvs, infer_missing=infer_missing)
62+
63+
@classmethod
64+
def from_dict(cls: Type[A],
65+
kvs: Json,
66+
*,
67+
infer_missing=False) -> A:
6068
return _decode_dataclass(cls, kvs, infer_missing)
6169

70+
def to_dict(self):
71+
return _asdict(self)
72+
6273
@classmethod
6374
def schema(cls: Type[A],
6475
*,
@@ -87,6 +98,8 @@ def dataclass_json(cls):
8798
# unwrap and rewrap classmethod to tag it to cls rather than the literal
8899
# DataClassJsonMixin ABC
89100
cls.from_json = classmethod(DataClassJsonMixin.from_json.__func__)
101+
cls.to_dict = DataClassJsonMixin.to_dict
102+
cls.from_dict = classmethod(DataClassJsonMixin.from_dict.__func__)
90103
cls.schema = classmethod(DataClassJsonMixin.schema.__func__)
91104
# register cls as a virtual subclass of DataClassJsonMixin
92105
DataClassJsonMixin.register(cls)

‎dataclasses_json/core.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import json
33
import warnings
44
from collections import namedtuple
5-
from dataclasses import MISSING, _is_dataclass_instance, fields, is_dataclass
5+
from dataclasses import MISSING, _is_dataclass_instance, fields, is_dataclass, asdict
66
from datetime import datetime, timezone
77
from decimal import Decimal
88
from enum import Enum
@@ -19,12 +19,12 @@
1919
_isinstance_safe,
2020
_issubclass_safe)
2121

22-
JSON = Union[dict, list, str, int, float, bool, None]
22+
Json = Union[dict, list, str, int, float, bool, None]
2323

2424

2525
class _ExtendedEncoder(json.JSONEncoder):
26-
def default(self, o) -> JSON:
27-
result: JSON
26+
def default(self, o) -> Json:
27+
result: Json
2828
if _isinstance_safe(o, Collection):
2929
if _isinstance_safe(o, Mapping):
3030
result = dict(o)

‎dataclasses_json/mm.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ def dumps(self, *args, **kwargs):
284284
return Schema.dumps(self, *args, **kwargs)
285285

286286
schema_ = schema(cls, mixin, infer_missing)
287-
DataClassSchema: SchemaType = type(
287+
DataClassSchema: typing.Type[SchemaType] = type(
288288
f'{cls.__name__.capitalize()}Schema',
289289
(Schema,),
290290
{'Meta': Meta,

‎setup.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
],
2424
python_requires=">=3.6",
2525
extras_require={
26-
"dev": ["pytest", "ipython", "mypy", "hypothesis"]
26+
"dev": ["pytest", "ipython", "mypy>=0.710", "hypothesis"]
2727
},
2828
include_package_data=True
2929
)

‎tests/test_annotations.py‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from mypy.main import main as mypy_main
1010
from typing import List, Dict, Any, Tuple, NewType, Optional, Union
1111

12+
1213
@dataclass
1314
class User(DataClassJsonMixin):
1415
id: str
@@ -20,13 +21,15 @@ class User(DataClassJsonMixin):
2021
ErrorLevel = NewType('ErrorLevel', str)
2122
ErrorMessage = NewType('ErrorMessage', str)
2223

24+
2325
class TestAnnotations:
2426
u: User = User('ax9ssFxH')
2527
j: str = u.to_json()
2628
u2: User = User.from_json(j)
2729
u2a: User = User.from_json(j.encode())
2830

29-
jMany = [{"id":"115412", "name": "Peter"}, {"id": "atxXxGhg", "name": "Parker"}]
31+
jMany = [{"id": "115412", "name": "Peter"},
32+
{"id": "atxXxGhg", "name": "Parker"}]
3033
sch = User.schema()
3134
users1: List[User] = sch.loads(json.dumps(jMany), many=True)
3235
n: str = users1[1].name
@@ -36,6 +39,10 @@ class TestAnnotations:
3639
j3: List[Dict[str, Any]] = sch.dump([u2, u3], many=True)
3740
j4: str = sch.dumps(u2)
3841

42+
j4_dict: Dict[str, Any] = json.loads(j4)
43+
u4a: User = User.from_json(j4)
44+
u4b: User = User.from_dict(j4_dict)
45+
3946
def filter_errors(self, errors: List[str]) -> List[str]:
4047
real_errors: List[str] = list()
4148
current_file = __file__
@@ -57,7 +64,8 @@ def filter_errors(self, errors: List[str]) -> List[str]:
5764
return real_errors
5865

5966
def parse_trace_line(self, line: str) -> \
60-
Tuple[Optional[Filename], Optional[LineNumber], Optional[ErrorLevel], ErrorMessage]:
67+
Tuple[Optional[Filename], Optional[LineNumber], Optional[
68+
ErrorLevel], ErrorMessage]:
6169
# Define variables
6270
file_name: Union[str, Filename, None]
6371
line_no: Union[str, LineNumber, None]
@@ -89,27 +97,19 @@ def parse_trace_line(self, line: str) -> \
8997
msg = ErrorMessage(msg)
9098
return file_name, line_no, level, msg
9199

92-
93100
def test_type_hints(self):
94-
old_stdout = sys.stdout
95-
old_stderr = sys.stderr
96101
text_io = StringIO('')
97102
try:
98103
# mypy.main uses sys.stdout for printing
99104
# We override it to catch error messages
100-
sys.stdout = text_io
101-
sys.stderr = text_io
102-
mypy_main(None, [ __file__ ])
105+
mypy_main(None, text_io, text_io, [__file__])
103106
except SystemExit:
104107
# mypy.main could return errors found inside other files.
105108
# filter_errors() will filter out all errors outside this file.
106109
errors = text_io.getvalue().splitlines()
107110
errors = self.filter_errors(errors)
108111
else:
109112
errors = None
110-
finally:
111-
sys.stdout = old_stdout
112-
sys.stderr = old_stderr
113113

114114
# To prevent large errors raise error out of try/except
115115
if (errors):

‎tests/test_api.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
from decimal import Decimal
23
from uuid import UUID
34

@@ -36,6 +37,22 @@ def test_uuid_decode(self):
3637
== DataClassWithUuid(UUID(self.uuid_s)))
3738

3839

40+
class TestDictDecode:
41+
decimal_s = "12345.12345"
42+
dc_decimal_json = {"x": decimal_s}
43+
44+
uuid_s = 'd1d61dd7-c036-47d3-a6ed-91cc2e885fc8'
45+
dc_uuid_json = {"id": uuid_s}
46+
47+
def test_decimal_decode(self):
48+
assert (DataClassWithDecimal.from_dict(self.dc_decimal_json)
49+
== DataClassWithDecimal(Decimal(self.decimal_s)))
50+
51+
def test_uuid_decode(self):
52+
assert (DataClassWithUuid.from_dict(self.dc_uuid_json)
53+
== DataClassWithUuid(UUID(self.uuid_s)))
54+
55+
3956
class TestNewType:
4057
new_type_s = 'd1d61dd7-c036-47d3-a6ed-91cc2e885fc8'
4158
dc_new_type_json = f'{{"id": "{new_type_s}"}}'

0 commit comments

Comments
 (0)