Skip to content

Commit 0bc6a72

Browse files
Make to_py recursive (#55)
1 parent f85b7c0 commit 0bc6a72

File tree

5 files changed

+40
-4
lines changed

5 files changed

+40
-4
lines changed

python/pycrdt/array.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -168,8 +168,15 @@ def __str__(self) -> str:
168168

169169
def to_py(self) -> list | None:
170170
if self._integrated is None:
171-
return self._prelim
172-
return list(self)
171+
py = self._prelim
172+
if py is None:
173+
return None
174+
else:
175+
py = list(self)
176+
for idx, val in enumerate(py):
177+
if isinstance(val, BaseType):
178+
py[idx] = val.to_py()
179+
return py
173180

174181
def observe(self, callback: Callable[[Any], None]) -> str:
175182
_callback = partial(observe_callback, callback, self.doc)

python/pycrdt/map.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,15 @@ def __str__(self) -> str:
6262

6363
def to_py(self) -> dict | None:
6464
if self._integrated is None:
65-
return self._prelim
66-
return dict(self)
65+
py = self._prelim
66+
if py is None:
67+
return None
68+
else:
69+
py = dict(self)
70+
for key, val in py.items():
71+
if isinstance(val, BaseType):
72+
py[key] = val.to_py()
73+
return py
6774

6875
def __delitem__(self, key: str) -> None:
6976
with self.doc.transaction() as txn:

tests/test_array.py

+8
Original file line numberDiff line numberDiff line change
@@ -135,3 +135,11 @@ def test_move():
135135
doc["array"] = array = Array([1, 2, 3, 4])
136136
array.move(1, 3)
137137
assert str(array) == "[1.0,3.0,2.0,4.0]"
138+
139+
140+
def test_to_py():
141+
doc = Doc()
142+
submap = Map({"foo": "bar"})
143+
subarray = Array([1, submap])
144+
doc["array"] = array = Array([0, subarray])
145+
assert array.to_py() == [0, [1, {"foo": "bar"}]]

tests/test_map.py

+8
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,11 @@ def test_api():
5656
v = map0.pop("bar")
5757
assert v == 2
5858
assert str(map0) == "{}"
59+
60+
61+
def test_to_py():
62+
doc = Doc()
63+
submap = Map({"foo": "bar"})
64+
subarray = Array([0, submap])
65+
doc["map_"] = map_ = Map({"key0": "val0", "key1": subarray})
66+
assert map_.to_py() == {"key0": "val0", "key1": [0, {"foo": "bar"}]}

tests/test_text.py

+6
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,9 @@ def test_api():
3939
assert str(text) == hello + world + punct
4040
text[len(hello) : len(hello) + len(world)] = " Sir"
4141
assert str(text) == hello + " Sir" + punct
42+
43+
44+
def test_to_py():
45+
doc = Doc()
46+
doc["text"] = text = Text(hello)
47+
assert text.to_py() == hello

0 commit comments

Comments
 (0)