Skip to content

Commit 07c1040

Browse files
committed
Cast only if number has same value
1 parent 49670ee commit 07c1040

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

jupyter_ydoc/utils.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
1-
from typing import Dict, List, Union
1+
from typing import Dict, List, Type, Union
22

3+
INT = Type[int]
4+
FLOAT = Type[float]
35

4-
def cast_all(o: Union[List, Dict], from_type, to_type) -> Union[List, Dict]:
6+
7+
def cast_all(
8+
o: Union[List, Dict], from_type: Union[INT, FLOAT], to_type: Union[FLOAT, INT]
9+
) -> Union[List, Dict]:
510
if isinstance(o, list):
611
for i, v in enumerate(o):
712
if type(v) == from_type:
8-
o[i] = to_type(v)
13+
v2 = to_type(v)
14+
if v == v2:
15+
o[i] = v2
916
elif isinstance(v, (list, dict)):
1017
cast_all(v, from_type, to_type)
1118
elif isinstance(o, dict):
1219
for k, v in o.items():
1320
if type(v) == from_type:
14-
o[k] = to_type(v)
21+
v2 = to_type(v)
22+
if v == v2:
23+
o[k] = v2
1524
elif isinstance(v, (list, dict)):
1625
cast_all(v, from_type, to_type)
1726
return o

jupyter_ydoc/ydoc.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def __init__(self, *args, **kwargs):
8686
def get_cell(self, index: int) -> Dict[str, Any]:
8787
meta = self._ymeta.to_json()
8888
cell = self._ycells[index].to_json()
89-
cast_all(cell, float, int)
89+
cast_all(cell, float, int) # cells coming from Yjs have e.g. execution_count as float
9090
if "id" in cell and meta["nbformat"] == 4 and meta["nbformat_minor"] <= 4:
9191
# strip cell IDs if we have notebook format 4.0-4.4
9292
del cell["id"]
@@ -136,7 +136,7 @@ def set_ycell(self, index: int, ycell: Y.YMap, txn=None):
136136

137137
def get(self):
138138
meta = self._ymeta.to_json()
139-
cast_all(meta, float, int)
139+
cast_all(meta, float, int) # notebook coming from Yjs has e.g. nbformat as float
140140
cells = []
141141
for i in range(len(self._ycells)):
142142
cell = self.get_cell(i)
@@ -161,7 +161,7 @@ def get(self):
161161
def set(self, value):
162162
nb_without_cells = {key: value[key] for key in value.keys() if key != "cells"}
163163
nb = copy.deepcopy(nb_without_cells)
164-
cast_all(nb, int, float)
164+
cast_all(nb, int, float) # Yjs expects numbers to be floating numbers
165165
cells = value["cells"] or [
166166
{
167167
"cell_type": "code",

0 commit comments

Comments
 (0)