Skip to content

Commit 65f4d47

Browse files
committed
Remove json_clean
1 parent 38ad84f commit 65f4d47

File tree

9 files changed

+40
-183
lines changed

9 files changed

+40
-183
lines changed

ipykernel/comm/comm.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from traitlets.config import LoggingConfigurable
99
from ipykernel.kernelbase import Kernel
1010

11-
from ipykernel.jsonutil import json_clean
1211
from traitlets import Instance, Unicode, Bytes, Bool, Dict, Any, default
1312

1413

@@ -62,10 +61,10 @@ def _publish_msg(self, msg_type, data=None, metadata=None, buffers=None, **keys)
6261
"""Helper for sending a comm message on IOPub"""
6362
data = {} if data is None else data
6463
metadata = {} if metadata is None else metadata
65-
content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))
64+
content = dict(data=data, comm_id=self.comm_id, **keys)
6665
self.kernel.session.send(self.kernel.iopub_socket, msg_type,
6766
content,
68-
metadata=json_clean(metadata),
67+
metadata=metadata,
6968
parent=self.kernel.get_parent("shell"),
7069
ident=self.topic,
7170
buffers=buffers,

ipykernel/datapub.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212

1313
from traitlets.config import Configurable
1414
from traitlets import Instance, Dict, CBytes, Any
15-
from ipykernel.jsonutil import json_clean
1615
try:
1716
# available since ipyparallel 5.0.0
1817
from ipyparallel.serialize import serialize_object
@@ -46,7 +45,7 @@ def publish_data(self, data):
4645
buffer_threshold=session.buffer_threshold,
4746
item_threshold=session.item_threshold,
4847
)
49-
content = json_clean(dict(keys=list(data.keys())))
48+
content = dict(keys=list(data.keys()))
5049
session.send(self.pub_socket, 'data_message', content=content,
5150
parent=self.parent_header,
5251
buffers=buffers,
@@ -66,6 +65,6 @@ def publish_data(data):
6665
DeprecationWarning,
6766
stacklevel=2
6867
)
69-
68+
7069
from ipykernel.zmqshell import ZMQInteractiveShell
7170
ZMQInteractiveShell.instance().data_pub.publish_data(data)

ipykernel/debugger.py

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import logging
21
import os
32
import re
43

@@ -8,16 +7,19 @@
87
from tornado.queues import Queue
98
from tornado.locks import Event
109

10+
from IPython.core.getipython import get_ipython
11+
12+
from jupyter_client.jsonutil import date_default
13+
1114
from .compiler import (get_file_name, get_tmp_directory, get_tmp_hash_seed)
1215

13-
from IPython.core.getipython import get_ipython
14-
import debugpy
1516

16-
from .jsonutil import json_clean
17+
1718

1819
# Required for backwards compatiblity
1920
ROUTING_ID = getattr(zmq, 'ROUTING_ID', None) or zmq.IDENTITY
2021

22+
2123
class DebugpyMessageQueue:
2224

2325
HEADER = 'Content-Length: '
@@ -60,7 +62,7 @@ def put_tcp_frame(self, frame):
6062
self.header_pos = self.tcp_buffer.find(DebugpyMessageQueue.HEADER)
6163
if self.header_pos == -1:
6264
return
63-
65+
6466
self.log.debug('QUEUE - found header at pos %i', self.header_pos)
6567

6668
#Finds separator
@@ -96,7 +98,7 @@ def put_tcp_frame(self, frame):
9698

9799
async def get_message(self):
98100
return await self.message_queue.get()
99-
101+
100102

101103
class DebugpyClient:
102104

@@ -125,15 +127,20 @@ def _forward_event(self, msg):
125127
def _send_request(self, msg):
126128
if self.routing_id is None:
127129
self.routing_id = self.debugpy_stream.socket.getsockopt(ROUTING_ID)
128-
content = jsonapi.dumps(msg)
130+
content = jsonapi.dumps(
131+
msg,
132+
default=date_default,
133+
ensure_ascii=False,
134+
allow_nan=False,
135+
)
129136
content_length = str(len(content))
130137
buf = (DebugpyMessageQueue.HEADER + content_length + DebugpyMessageQueue.SEPARATOR).encode('ascii')
131138
buf += content
132139
self.log.debug("DEBUGPYCLIENT:")
133140
self.log.debug(self.routing_id)
134141
self.log.debug(buf)
135142
self.debugpy_stream.send_multipart((self.routing_id, buf))
136-
143+
137144
async def _wait_for_response(self):
138145
# Since events are never pushed to the message_queue
139146
# we can safely assume the next message in queue
@@ -143,7 +150,7 @@ async def _wait_for_response(self):
143150
async def _handle_init_sequence(self):
144151
# 1] Waits for initialized event
145152
await self.init_event.wait()
146-
153+
147154
# 2] Sends configurationDone request
148155
configurationDone = {
149156
'type': 'request',
@@ -195,6 +202,7 @@ async def send_dap_request(self, msg):
195202
self.log.debug(rep)
196203
return rep
197204

205+
198206
class Debugger:
199207

200208
# Requests that requires that the debugger has started
@@ -204,7 +212,7 @@ class Debugger:
204212
'variables', 'attach',
205213
'configurationDone'
206214
]
207-
215+
208216
# Requests that can be handled even if the debugger is not running
209217
static_debug_msg_types = [
210218
'debugInfo', 'inspectVariables'
@@ -217,7 +225,7 @@ def __init__(self, log, debugpy_stream, event_callback, shell_socket, session):
217225
self.session = session
218226
self.is_started = False
219227
self.event_callback = event_callback
220-
228+
221229
self.started_debug_handlers = {}
222230
for msg_type in Debugger.started_debug_msg_types:
223231
self.started_debug_handlers[msg_type] = getattr(self, msg_type)
@@ -266,7 +274,7 @@ def start(self):
266274
}
267275
self.session.send(self.shell_socket, 'execute_request', content,
268276
None, (self.shell_socket.getsockopt(ROUTING_ID)))
269-
277+
270278
ident, msg = self.session.recv(self.shell_socket, mode=0)
271279
self.debugpy_initialized = msg['content']['status'] == 'ok'
272280
self.debugpy_client.connect_tcp_socket()
@@ -420,8 +428,12 @@ async def inspectVariables(self, message):
420428
for k, v in get_ipython().user_ns.items():
421429
if self.accept_variable(k):
422430
try:
423-
val = json_clean(v)
424-
431+
val = jsonapi.dumps(
432+
v,
433+
default=date_default,
434+
ensure_ascii=False,
435+
allow_nan=False,
436+
)
425437
except ValueError:
426438
val = str(v)
427439
var_list.append({
@@ -478,4 +490,3 @@ async def process_request(self, message):
478490
self.log.info('The debugger has stopped')
479491

480492
return reply
481-

ipykernel/displayhook.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import sys
88

99
from IPython.core.displayhook import DisplayHook
10-
from ipykernel.jsonutil import encode_images, json_clean
1110
from traitlets import Instance, Dict, Any
1211
from jupyter_client.session import extract_header, Session
1312

@@ -68,7 +67,7 @@ def write_output_prompt(self):
6867
self.msg['content']['execution_count'] = self.prompt_count
6968

7069
def write_format_data(self, format_dict, md_dict=None):
71-
self.msg['content']['data'] = json_clean(encode_images(format_dict))
70+
self.msg['content']['data'] = format_dict
7271
self.msg['content']['metadata'] = md_dict
7372

7473
def finish_displayhook(self):

ipykernel/inprocess/ipkernel.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import sys
99

1010
from IPython.core.interactiveshell import InteractiveShellABC
11-
from ipykernel.jsonutil import json_clean
1211
from traitlets import Any, Enum, Instance, List, Type, default
1312
from ipykernel.ipkernel import IPythonKernel
1413
from ipykernel.zmqshell import ZMQInteractiveShell
@@ -98,7 +97,7 @@ def _input_request(self, prompt, ident, parent, password=False):
9897
sys.stdout.flush()
9998

10099
# Send the input request.
101-
content = json_clean(dict(prompt=prompt, password=password))
100+
content = dict(prompt=prompt, password=password)
102101
msg = self.session.msg('input_request', content, parent)
103102
for frontend in self.frontends:
104103
if frontend.session.session == parent['header']['session']:

ipykernel/jsonutil.py

Lines changed: 4 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ def encode_images(format_dict):
7070

7171

7272
def json_clean(obj):
73-
"""Clean an object to ensure it's safe to encode in JSON.
73+
"""Deprecated, this is a no-op now.
74+
75+
Clean an object to ensure it's safe to encode in JSON.
7476
7577
Atomic, immutable objects are returned unmodified. Sets and tuples are
7678
converted to lists, lists are copied and dicts are also copied.
@@ -91,46 +93,4 @@ def json_clean(obj):
9193
it simply sanitizes it so that there will be no encoding errors later.
9294
9395
"""
94-
# types that are 'atomic' and ok in json as-is.
95-
atomic_ok = (bool, str, type(None))
96-
97-
# containers that we need to convert into lists
98-
container_to_list = (list, tuple, set, types.GeneratorType)
99-
100-
# Since bools are a subtype of Integrals, which are a subtype of Reals,
101-
# we have to check them in that order.
102-
103-
if isinstance(obj, atomic_ok):
104-
return obj
105-
106-
if isinstance(obj, numbers.Integral):
107-
# cast int to int, in case subclasses override __str__ (e.g. boost enum, #4598)
108-
return int(obj)
109-
110-
if isinstance(obj, numbers.Real):
111-
# cast out-of-range floats to their reprs
112-
if math.isnan(obj) or math.isinf(obj):
113-
return repr(obj)
114-
return float(obj)
115-
116-
if isinstance(obj, bytes):
117-
# unanmbiguous binary data is base64-encoded
118-
# (this probably should have happened upstream)
119-
return b2a_base64(obj).decode('ascii')
120-
121-
if isinstance(obj, container_to_list) or (
122-
hasattr(obj, '__iter__') and hasattr(obj, next_attr_name)):
123-
return [json_clean(x) for x in obj]
124-
125-
if isinstance(obj, dict):
126-
# If all OK, proceed by making the new dict that will be json-safe
127-
out = {}
128-
for k, v in obj.items():
129-
out[str(k)] = json_clean(v)
130-
return out
131-
132-
if isinstance(obj, datetime):
133-
return obj.strftime(ISO8601)
134-
135-
# we don't understand it, it's probably an unserializable object
136-
raise ValueError("Can't clean for JSON: %r" % obj)
96+
return obj

ipykernel/kernelbase.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@
3030

3131
from traitlets.config.configurable import SingletonConfigurable
3232
from IPython.core.error import StdinNotImplementedError
33-
from ipykernel.jsonutil import json_clean
3433
from traitlets import (
3534
Any, Instance, Float, Dict, List, Set, Integer, Unicode, Bool,
3635
observe, default
@@ -656,7 +655,6 @@ async def execute_request(self, stream, ident, parent):
656655
time.sleep(self._execute_sleep)
657656

658657
# Send the reply.
659-
reply_content = json_clean(reply_content)
660658
metadata = self.finish_metadata(parent, metadata, reply_content)
661659

662660
reply_msg = self.session.send(stream, 'execute_reply',
@@ -683,7 +681,6 @@ async def complete_request(self, stream, ident, parent):
683681
if inspect.isawaitable(matches):
684682
matches = await matches
685683

686-
matches = json_clean(matches)
687684
self.session.send(stream, "complete_reply", matches, parent, ident)
688685

689686
def do_complete(self, code, cursor_pos):
@@ -706,7 +703,6 @@ async def inspect_request(self, stream, ident, parent):
706703
reply_content = await reply_content
707704

708705
# Before we send this object over, we scrub it for JSON usage
709-
reply_content = json_clean(reply_content)
710706
msg = self.session.send(stream, 'inspect_reply',
711707
reply_content, parent, ident)
712708
self.log.debug("%s", msg)
@@ -723,7 +719,6 @@ async def history_request(self, stream, ident, parent):
723719
if inspect.isawaitable(reply_content):
724720
reply_content = await reply_content
725721

726-
reply_content = json_clean(reply_content)
727722
msg = self.session.send(stream, 'history_reply',
728723
reply_content, parent, ident)
729724
self.log.debug("%s", msg)
@@ -813,7 +808,6 @@ async def is_complete_request(self, stream, ident, parent):
813808
reply_content = self.do_is_complete(code)
814809
if inspect.isawaitable(reply_content):
815810
reply_content = await reply_content
816-
reply_content = json_clean(reply_content)
817811
reply_msg = self.session.send(stream, 'is_complete_reply',
818812
reply_content, parent, ident)
819813
self.log.debug("%s", reply_msg)
@@ -829,7 +823,6 @@ async def debug_request(self, stream, ident, parent):
829823
reply_content = self.do_debug_request(content)
830824
if inspect.isawaitable(reply_content):
831825
reply_content = await reply_content
832-
reply_content = json_clean(reply_content)
833826
reply_msg = self.session.send(stream, 'debug_reply', reply_content,
834827
parent, ident)
835828
self.log.debug("%s", reply_msg)
@@ -1001,7 +994,7 @@ def _input_request(self, prompt, ident, parent, password=False):
1001994
raise
1002995

1003996
# Send the input request.
1004-
content = json_clean(dict(prompt=prompt, password=password))
997+
content = dict(prompt=prompt, password=password)
1005998
self.session.send(self.stdin_socket, 'input_request', content, parent,
1006999
ident=ident)
10071000

0 commit comments

Comments
 (0)