8000 Merge pull request #106 from admire93/test-optional-type · nirum-lang/nirum-python@328b4af · GitHub
[go: up one dir, main page]

Skip to content

Commit 328b4af

Browse files
authored
Merge pull request #106 from admire93/test-optional-type
Ensure optional type include `None` type
2 parents 6bbb4ec + 2f85525 commit 328b4af

File tree

3 files changed

+12
-6
lines changed

3 files changed

+12
-6
lines changed

CHANGES.rst

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@ Version 0.6.2
66

77
To be released.
88

9+
- Added ``is_optional_type()`` to ensure optional type includes ``None`` type.
10+
911

1012
Version 0.6.1
1113
-------------
1214

1315
Released on December 9, 2017.
1416

15-
- Made `nirum.datastructures.List` to copy the given value so that
17+
- Made ``nirum.datastructures.List`` to copy the given value so that
1618
it doesn't refer given value's state and is immutable.
1719

1820

nirum/_compat.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import datetime
22
import typing
33

4-
__all__ = 'utc', 'is_union_type', 'get_union_types'
4+
__all__ = 'utc', 'is_optional_type', 'is_union_type', 'get_union_types'
55

66

77
try:
@@ -43,6 +43,10 @@ def get_union_types(type_):
4343
else type_.__args__
4444

4545

46+
def is_optional_type(type_):
47+
return is_union_type(type_) and type(None) in get_union_types(type_)
48+
49+
4650
def get_abstract_param_types(type_):
4751
return type_.__parameters__ if type_.__parameters__ else type_.__args__
4852

nirum/deserialize.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from iso8601 import iso8601, parse_date
1414
from six import text_type
1515

16-
from ._compat import get_tuple_param_types, get_union_types, is_union_type
16+
from ._compat import get_tuple_param_types, get_union_types, is_optional_type
1717
from .datastructures import Map
1818

1919
__all__ = (
@@ -175,9 +175,9 @@ def deserialize_primitive(cls, data):
175175

176176

177177
def deserialize_optional(cls, data):
178+
if not is_optional_type(cls):
179+
raise ValueError('{!r} is not optional type'.format(cls))
178180
union_types = get_union_types(cls)
179-
if not any(isinstance(None, ut) for ut in union_types):
180-
raise ValueError(cls)
181181
if data is None:
182182
return data
183183
for union_type in union_types:
@@ -206,7 +206,7 @@ def deserialize_meta(cls, data):
206206
d = deserialize_tuple_type(cls, data)
207207
elif is_support_abstract_type(cls):
208208
d = deserialize_abstract_type(cls, data)
209-
elif is_union_type(cls):
209+
elif is_optional_type(cls):
210210
d = deserialize_optional(cls, data)
211211
elif callable(cls) and cls in _NIRUM_PRIMITIVE_TYPE:
212212
d = deserialize_primitive(cls, data)

0 commit comments

Comments
 (0)
0