basic orjson serialize, json.dumps fallback

This commit is contained in:
Sean Breckenridge 2021-03-16 22:32:38 -07:00
parent 02a9fb5e8f
commit 0593c69056
2 changed files with 50 additions and 4 deletions

View file

@ -531,7 +531,13 @@ def test_guess_datetime() -> None:
# TODO test @property?
def asdict(thing) -> Json:
def is_namedtuple(thing: Any) -> bool:
# basic check to see if this is a namedtuple-like
_asdict = getattr(thing, '_asdict', None)
return _asdict and callable(_asdict)
def asdict(thing: Any) -> Json:
# todo primitive?
# todo exception?
if isinstance(thing, dict):
@ -539,9 +545,9 @@ def asdict(thing) -> Json:
import dataclasses as D
if D.is_dataclass(thing):
return D.asdict(thing)
# must be a NT otherwise?
# todo add a proper check.. ()
return thing._asdict()
if is_namedtuple(thing):
return thing._asdict()
raise TypeError(f'Could not convert object {thing} to dict')
# todo not sure about naming