Skip to content

Commit 1479775

Browse files
committed
remove clean_json
1 parent 770afbe commit 1479775

File tree

7 files changed

+11
-236
lines changed

7 files changed

+11
-236
lines changed

ipykernel/comm/comm.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import traitlets.config
1212
from traitlets import Bool, Bytes, Instance, Unicode, default
1313

14-
from ipykernel.jsonutil import json_clean
1514
from ipykernel.kernelbase import Kernel
1615

1716

@@ -28,7 +27,7 @@ def publish_msg(self, msg_type, data=None, metadata=None, buffers=None, **keys):
2827

2928
data = {} if data is None else data
3029
metadata = {} if metadata is None else metadata
31-
content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))
30+
content = dict(data=data, comm_id=self.comm_id, **keys)
3231

3332
if self.kernel is None:
3433
self.kernel = Kernel.instance()
@@ -38,7 +37,7 @@ def publish_msg(self, msg_type, data=None, metadata=None, buffers=None, **keys):
3837
self.kernel.iopub_socket,
3938
msg_type,
4039
content,
41-
metadata=json_clean(metadata),
40+
metadata=metadata,
4241
parent=self.kernel.get_parent(),
4342
ident=self.topic,
4443
buffers=buffers,

ipykernel/displayhook.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from jupyter_client.session import Session, extract_header
1414
from traitlets import Any, Instance
1515

16-
from ipykernel.jsonutil import encode_images, json_clean
16+
from ipykernel.jsonutil import encode_images
1717

1818

1919
class ZMQDisplayHook:
@@ -120,7 +120,7 @@ def write_output_prompt(self):
120120
def write_format_data(self, format_dict, md_dict=None):
121121
"""Write format data to the message."""
122122
if self.msg:
123-
self.msg["content"]["data"] = json_clean(encode_images(format_dict))
123+
self.msg["content"]["data"] = encode_images(format_dict)
124124
self.msg["content"]["metadata"] = md_dict
125125

126126
def finish_displayhook(self):

ipykernel/inprocess/ipkernel.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
from traitlets import Any, Enum, Instance, List, Type, default
1313

1414
from ipykernel.ipkernel import IPythonKernel
15-
from ipykernel.jsonutil import json_clean
1615
from ipykernel.zmqshell import ZMQInteractiveShell
1716

1817
from ..iostream import BackgroundSocket, IOPubThread, OutStream
@@ -98,7 +97,7 @@ def _input_request(self, prompt, ident, parent, password=False):
9897
sys.stderr.flush()
9998

10099
# Send the input request.
101-
content = json_clean(dict(prompt=prompt, password=password))
100+
content = dict(prompt=prompt, password=password)
102101
assert self.session is not None
103102
msg = self.session.msg("input_request", content, parent)
104103
for frontend in self.frontends:

ipykernel/jsonutil.py

Lines changed: 1 addition & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,8 @@
33
# Copyright (c) IPython Development Team.
44
# Distributed under the terms of the Modified BSD License.
55

6-
import math
7-
import numbers
86
import re
9-
import types
10-
from binascii import b2a_base64
11-
from datetime import date, datetime
7+
from datetime import datetime
128

139
from jupyter_client._version import version_info as jupyter_client_version
1410

@@ -52,8 +48,6 @@
5248
def encode_images(format_dict):
5349
"""b64-encodes images in a displaypub format dict
5450
55-
Perhaps this should be handled in json_clean itself?
56-
5751
Parameters
5852
----------
5953
format_dict : dict
@@ -72,92 +66,3 @@ def encode_images(format_dict):
7266
# where bytes objects always represent binary data and thus
7367
# base64-encoded.
7468
return format_dict
75-
76-
77-
def json_clean(obj): # pragma: no cover
78-
"""Deprecated, this is a no-op for jupyter-client>=7.
79-
80-
Clean an object to ensure it's safe to encode in JSON.
81-
82-
Atomic, immutable objects are returned unmodified. Sets and tuples are
83-
converted to lists, lists are copied and dicts are also copied.
84-
85-
Note: dicts whose keys could cause collisions upon encoding (such as a dict
86-
with both the number 1 and the string '1' as keys) will cause a ValueError
87-
to be raised.
88-
89-
Parameters
90-
----------
91-
obj : any python object
92-
93-
Returns
94-
-------
95-
out : object
96-
A version of the input which will not cause an encoding error when
97-
encoded as JSON. Note that this function does not *encode* its inputs,
98-
it simply sanitizes it so that there will be no encoding errors later.
99-
100-
"""
101-
if int(JUPYTER_CLIENT_MAJOR_VERSION) >= 7:
102-
return obj
103-
104-
# types that are 'atomic' and ok in json as-is.
105-
atomic_ok = (str, type(None))
106-
107-
# containers that we need to convert into lists
108-
container_to_list = (tuple, set, types.GeneratorType)
109-
110-
# Since bools are a subtype of Integrals, which are a subtype of Reals,
111-
# we have to check them in that order.
112-
113-
if isinstance(obj, bool):
114-
return obj
115-
116-
if isinstance(obj, numbers.Integral):
117-
# cast int to int, in case subclasses override __str__ (e.g. boost enum, #4598)
118-
return int(obj)
119-
120-
if isinstance(obj, numbers.Real):
121-
# cast out-of-range floats to their reprs
122-
if math.isnan(obj) or math.isinf(obj):
123-
return repr(obj)
124-
return float(obj)
125-
126-
if isinstance(obj, atomic_ok):
127-
return obj
128-
129-
if isinstance(obj, bytes):
130-
# unanmbiguous binary data is base64-encoded
131-
# (this probably should have happened upstream)
132-
return b2a_base64(obj).decode("ascii")
133-
134-
if isinstance(obj, container_to_list) or (
135-
hasattr(obj, "__iter__") and hasattr(obj, next_attr_name)
136-
):
137-
obj = list(obj)
138-
139-
if isinstance(obj, list):
140-
return [json_clean(x) for x in obj]
141-
142-
if isinstance(obj, dict):
143-
# First, validate that the dict won't lose data in conversion due to
144-
# key collisions after stringification. This can happen with keys like
145-
# True and 'true' or 1 and '1', which collide in JSON.
146-
nkeys = len(obj)
147-
nkeys_collapsed = len(set(map(str, obj)))
148-
if nkeys != nkeys_collapsed:
149-
msg = (
150-
"dict cannot be safely converted to JSON: "
151-
"key collision would lead to dropped values"
152-
)
153-
raise ValueError(msg)
154-
# If all OK, proceed by making the new dict that will be json-safe
155-
out = {}
156-
for k, v in obj.items():
157-
out[str(k)] = json_clean(v)
158-
return out
159-
if isinstance(obj, datetime | date):
160-
return obj.strftime(ISO8601)
161-
162-
# we don't understand it, it's probably an unserializable object
163-
raise ValueError("Can't clean for JSON: %r" % obj)

ipykernel/kernelbase.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,6 @@
5656
)
5757
from zmq.eventloop.zmqstream import ZMQStream
5858

59-
from ipykernel.jsonutil import json_clean
60-
6159
from ._version import kernel_protocol_version
6260
from .iostream import OutStream
6361
from .utils import LazyDict, _async_in_context
@@ -851,7 +849,6 @@ async def execute_request(self, stream, ident, parent):
851849
time.sleep(self._execute_sleep)
852850

853851
# Send the reply.
854-
reply_content = json_clean(reply_content)
855852
metadata = self.finish_metadata(parent, metadata, reply_content)
856853

857854
reply_msg: dict[str, t.Any] = self.session.send( # type:ignore[assignment]
@@ -901,7 +898,6 @@ async def complete_request(self, stream, ident, parent):
901898
stacklevel=1,
902899
)
903900

904-
matches = json_clean(matches)
905901
self.session.send(stream, "complete_reply", matches, parent, ident)
906902

907903
async def do_complete(self, code, cursor_pos):
@@ -936,7 +932,6 @@ async def inspect_request(self, stream, ident, parent):
936932
)
937933

938934
# Before we send this object over, we scrub it for JSON usage
939-
reply_content = json_clean(reply_content)
940935
msg = self.session.send(stream, "inspect_reply", reply_content, parent, ident)
941936
self.log.debug("%s", msg)
942937

@@ -960,7 +955,6 @@ async def history_request(self, stream, ident, parent):
960955
stacklevel=1,
961956
)
962957

963-
reply_content = json_clean(reply_content)
964958
msg = self.session.send(stream, "history_reply", reply_content, parent, ident)
965959
self.log.debug("%s", msg)
966960

@@ -1126,7 +1120,6 @@ async def is_complete_request(self, stream, ident, parent):
11261120
PendingDeprecationWarning,
11271121
stacklevel=1,
11281122
)
1129-
reply_content = json_clean(reply_content)
11301123
reply_msg = self.session.send(stream, "is_complete_reply", reply_content, parent, ident)
11311124
self.log.debug("%s", reply_msg)
11321125

@@ -1150,7 +1143,6 @@ async def debug_request(self, stream, ident, parent):
11501143
PendingDeprecationWarning,
11511144
stacklevel=1,
11521145
)
1153-
reply_content = json_clean(reply_content)
11541146
reply_msg = self.session.send(stream, "debug_reply", reply_content, parent, ident)
11551147
self.log.debug("%s", reply_msg)
11561148

@@ -1425,7 +1417,7 @@ def _input_request(self, prompt, ident, parent, password=False):
14251417

14261418
# Send the input request.
14271419
assert self.session is not None
1428-
content = json_clean(dict(prompt=prompt, password=password))
1420+
content = dict(prompt=prompt, password=password)
14291421
self.session.send(self.stdin_socket, "input_request", content, parent, ident=ident)
14301422

14311423
# Await a response.

ipykernel/zmqshell.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040

4141
from ipykernel import connect_qtconsole, get_connection_file, get_connection_info
4242
from ipykernel.displayhook import ZMQShellDisplayHook
43-
from ipykernel.jsonutil import encode_images, json_clean
43+
from ipykernel.jsonutil import encode_images
4444

4545
try:
4646
from IPython.core.history import HistoryOutput
@@ -164,7 +164,7 @@ def publish( # type:ignore[override]
164164
# in order to put it through the transform
165165
# hooks before potentially sending.
166166
assert self.session is not None
167-
msg = self.session.msg(msg_type, json_clean(content), parent=self.parent_header)
167+
msg = self.session.msg(msg_type, content, parent=self.parent_header)
168168

169169
# Each transform either returns a new
170170
# message or None. If None is returned,
@@ -194,7 +194,7 @@ def clear_output(self, wait=False):
194194
content = dict(wait=wait)
195195
self._flush_streams()
196196
assert self.session is not None
197-
msg = self.session.msg("clear_output", json_clean(content), parent=self.parent_header)
197+
msg = self.session.msg("clear_output", content, parent=self.parent_header)
198198

199199
# see publish() for details on how this works
200200
for hook in self._hooks:
@@ -684,7 +684,7 @@ def _showtraceback(self, etype, evalue, stb):
684684
dh.session.send( # type:ignore[attr-defined]
685685
dh.pub_socket, # type:ignore[attr-defined]
686686
"error",
687-
json_clean(exc_content),
687+
exc_content,
688688
dh.parent_header, # type:ignore[attr-defined]
689689
ident=topic,
690690
)

tests/test_jsonutil.py

Lines changed: 0 additions & 120 deletions
This file was deleted.

0 commit comments

Comments
 (0)