Skip to content

Commit 71f6cf9

Browse files
committed
Remove json_clean
1 parent 38ad84f commit 71f6cf9

File tree

9 files changed

+41
-183
lines changed

9 files changed

+41
-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: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,26 @@
1-
import logging
21
import os
32
import re
3+
import json
44

55
import zmq
66
from zmq.utils import jsonapi
77

88
from tornado.queues import Queue
99
from tornado.locks import Event
1010

11+
from IPython.core.getipython import get_ipython
12+
13+
from jupyter_client.jsonutil import date_default
14+
1115
from .compiler import (get_file_name, get_tmp_directory, get_tmp_hash_seed)
1216

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

16-
from .jsonutil import json_clean
18+
1719

1820
# Required for backwards compatiblity
1921
ROUTING_ID = getattr(zmq, 'ROUTING_ID', None) or zmq.IDENTITY
2022

23+
2124
class DebugpyMessageQueue:
2225

2326
HEADER = 'Content-Length: '
@@ -60,7 +63,7 @@ def put_tcp_frame(self, frame):
6063
self.header_pos = self.tcp_buffer.find(DebugpyMessageQueue.HEADER)
6164
if self.header_pos == -1:
6265
return
63-
66+
6467
self.log.debug('QUEUE - found header at pos %i', self.header_pos)
6568

6669
#Finds separator
@@ -96,7 +99,7 @@ def put_tcp_frame(self, frame):
9699

97100
async def get_message(self):
98101
return await self.message_queue.get()
99-
102+
100103

101104
class DebugpyClient:
102105

@@ -125,15 +128,20 @@ def _forward_event(self, msg):
125128
def _send_request(self, msg):
126129
if self.routing_id is None:
127130
self.routing_id = self.debugpy_stream.socket.getsockopt(ROUTING_ID)
128-
content = jsonapi.dumps(msg)
131+
content = jsonapi.dumps(
132+
msg,
133+
default=date_default,
134+
ensure_ascii=False,
135+
allow_nan=False,
136+
)
129137
content_length = str(len(content))
130138
buf = (DebugpyMessageQueue.HEADER + content_length + DebugpyMessageQueue.SEPARATOR).encode('ascii')
131139
buf += content
132140
self.log.debug("DEBUGPYCLIENT:")
133141
self.log.debug(self.routing_id)
134142
self.log.debug(buf)
135143
self.debugpy_stream.send_multipart((self.routing_id, buf))
136-
144+
137145
async def _wait_for_response(self):
138146
# Since events are never pushed to the message_queue
139147
# we can safely assume the next message in queue
@@ -143,7 +151,7 @@ async def _wait_for_response(self):
143151
async def _handle_init_sequence(self):
144152
# 1] Waits for initialized event
145153
await self.init_event.wait()
146-
154+
147155
# 2] Sends configurationDone request
148156
configurationDone = {
149157
'type': 'request',
@@ -195,6 +203,7 @@ async def send_dap_request(self, msg):
195203
self.log.debug(rep)
196204
return rep
197205

206+
198207
class Debugger:
199208

200209
# Requests that requires that the debugger has started
@@ -204,7 +213,7 @@ class Debugger:
204213
'variables', 'attach',
205214
'configurationDone'
206215
]
207-
216+
208217
# Requests that can be handled even if the debugger is not running
209218
static_debug_msg_types = [
210219
'debugInfo', 'inspectVariables'
@@ -217,7 +226,7 @@ def __init__(self, log, debugpy_stream, event_callback, shell_socket, session):
217226
self.session = session
218227
self.is_started = False
219228
self.event_callback = event_callback
220-
229+
221230
self.started_debug_handlers = {}
222231
for msg_type in Debugger.started_debug_msg_types:
223232
self.started_debug_handlers[msg_type] = getattr(self, msg_type)
@@ -266,7 +275,7 @@ def start(self):
266275
}
267276
self.session.send(self.shell_socket, 'execute_request', content,
268277
None, (self.shell_socket.getsockopt(ROUTING_ID)))
269-
278+
270279
ident, msg = self.session.recv(self.shell_socket, mode=0)
271280
self.debugpy_initialized = msg['content']['status'] == 'ok'
272281
self.debugpy_client.connect_tcp_socket()
@@ -420,8 +429,12 @@ async def inspectVariables(self, message):
420429
for k, v in get_ipython().user_ns.items():
421430
if self.accept_variable(k):
422431
try:
423-
val = json_clean(v)
424-
432+
val = jsonapi.dumps(
433+
v,
434+
default=date_default,
435+
ensure_ascii=False,
436+
allow_nan=False,
437+
)
425438
except ValueError:
426439
val = str(v)
427440
var_list.append({
@@ -478,4 +491,3 @@ async def process_request(self, message):
478491
self.log.info('The debugger has stopped')
479492

480493
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)