Skip to content

Commit

Permalink
Improve dictionary type detection
Browse files Browse the repository at this point in the history
  • Loading branch information
thombashi committed Apr 15, 2020
1 parent e20c2e3 commit 0449899
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
5 changes: 4 additions & 1 deletion test/checker/test_checker_dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@ class Test_Dictionary_is_type:
[True],
)
)
+ [['{"foo": 10}', StrictLevel.MIN, True], ['{"foo": 10}', StrictLevel.MAX, False],]
+ list(
itertools.product(
[1, "a", nan, True, None], [StrictLevel.MIN, StrictLevel.MAX], [False]
[1, "a", "あ".encode("utf8"), nan, True, None],
[StrictLevel.MIN, StrictLevel.MAX],
[False],
)
),
)
Expand Down
16 changes: 13 additions & 3 deletions typepy/converter/_dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

import json

from ..error import TypeConversionError
from ._interface import AbstractValueConverter

Expand All @@ -11,6 +13,14 @@ def force_convert(self):
try:
return dict(self._value)
except (TypeError, ValueError):
raise TypeConversionError(
"failed to force_convert to dictionary: type={}".format(type(self._value))
)
pass

if isinstance(self._value, str):
try:
return json.loads(self._value)
except json.JSONDecodeError:
pass

raise TypeConversionError(
"failed to force_convert to dictionary: type={}".format(type(self._value))
)

0 comments on commit 0449899

Please sign in to comment.