From 588f0feb41b8a4627e0158cefbcd8da53afb7ca6 Mon Sep 17 00:00:00 2001 From: Theodore Chang Date: Thu, 6 Jun 2024 06:20:51 +0200 Subject: [PATCH] async to_obj --- src/msglc/reader.py | 10 ++++++++++ tests/test_msglc.py | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/msglc/reader.py b/src/msglc/reader.py index 1bbcd69..3d53d59 100644 --- a/src/msglc/reader.py +++ b/src/msglc/reader.py @@ -35,6 +35,16 @@ def to_obj(v): return v.to_obj() if isinstance(v, LazyItem) else v +async def async_to_obj(v): + """ + Ensure the given value is JSON serializable. + """ + if isinstance(v, LazyItem): + return await asyncio.to_thread(v.to_obj) + + return v + + async def async_get(v, key): if isinstance(v, LazyItem): return await v.async_get(key) diff --git a/tests/test_msglc.py b/tests/test_msglc.py index f7dd04e..13a081d 100644 --- a/tests/test_msglc.py +++ b/tests/test_msglc.py @@ -20,7 +20,7 @@ from msglc import LazyWriter, FileInfo, combine, append from msglc.config import config, increment_gc_counter, decrement_gc_counter, configure -from msglc.reader import LazyStats, LazyReader +from msglc.reader import LazyStats, LazyReader, async_to_obj from msglc.utility import MockIO @@ -142,6 +142,7 @@ async def test_async_msglc(monkeypatch, tmpdir, json_before, json_after, target, assert await reader.async_read("glossary/empty_list") == [] assert await reader.async_read("glossary/none_list/0") is None assert await reader.async_read() == json_after + assert await async_to_obj(reader) == json_after assert reader == json_after dict_container = await reader.async_read("glossary/GlossDiv")