Skip to content

Commit 8b2fb3e

Browse files
committed
Cleaned up some of the python 2 code
1 parent 01b6e17 commit 8b2fb3e

23 files changed

+78
-193
lines changed

jupyter_client/blocking/client.py

Lines changed: 7 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,36 +5,20 @@
55
# Copyright (c) Jupyter Development Team.
66
# Distributed under the terms of the Modified BSD License.
77

8-
from __future__ import print_function
9-
108
from functools import partial
119
from getpass import getpass
12-
try:
13-
from queue import Empty # Python 3
14-
except ImportError:
15-
from Queue import Empty # Python 2
10+
from queue import Empty
1611
import sys
1712
import time
1813

1914
import zmq
2015

16+
from time import monotonic
2117
from traitlets import Type
2218
from jupyter_client.channels import HBChannel
2319
from jupyter_client.client import KernelClient
2420
from .channels import ZMQSocketChannel
2521

26-
try:
27-
monotonic = time.monotonic
28-
except AttributeError:
29-
# py2
30-
monotonic = time.time # close enough
31-
32-
try:
33-
TimeoutError
34-
except NameError:
35-
# py2
36-
TimeoutError = RuntimeError
37-
3822

3923
def reqrep(meth, channel='shell'):
4024
def wrapped(self, *args, **kwargs):
@@ -45,12 +29,12 @@ def wrapped(self, *args, **kwargs):
4529
return msg_id
4630

4731
return self._recv_reply(msg_id, timeout=timeout, channel=channel)
48-
32+
4933
if not meth.__doc__:
5034
# python -OO removes docstrings,
5135
# so don't bother building the wrapped docstring
5236
return wrapped
53-
37+
5438
basedoc, _ = meth.__doc__.split('Returns\n', 1)
5539
parts = [basedoc.strip()]
5640
if 'Parameters' not in basedoc:
@@ -76,14 +60,14 @@ def wrapped(self, *args, **kwargs):
7660

7761
class BlockingKernelClient(KernelClient):
7862
"""A KernelClient with blocking APIs
79-
63+
8064
``get_[channel]_msg()`` methods wait for and return messages on channels,
8165
raising :exc:`queue.Empty` if no message arrives within ``timeout`` seconds.
8266
"""
83-
67+
8468
def wait_for_ready(self, timeout=None):
8569
"""Waits for a response when a client is blocked
86-
70+
8771
- Sets future time for timeout
8872
- Blocks on shell channel until a message is received
8973
- Exit if the kernel has died

jupyter_client/channels.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
# Copyright (c) Jupyter Development Team.
44
# Distributed under the terms of the Modified BSD License.
55

6-
from __future__ import absolute_import
7-
86
import atexit
97
import errno
108
from threading import Thread, Event

jupyter_client/client.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33
# Copyright (c) Jupyter Development Team.
44
# Distributed under the terms of the Modified BSD License.
55

6-
from __future__ import absolute_import
76
from jupyter_client.channels import major_protocol_version
8-
from ipython_genutils.py3compat import string_types, iteritems
97

108
import zmq
119

@@ -25,10 +23,10 @@ def validate_string_dict(dct):
2523
"""Validate that the input is a dict with string keys and values.
2624
2725
Raises ValueError if not."""
28-
for k,v in iteritems(dct):
29-
if not isinstance(k, string_types):
26+
for k,v in dct.items():
27+
if not isinstance(k, str):
3028
raise ValueError('key %r in dict must be a string' % k)
31-
if not isinstance(v, string_types):
29+
if not isinstance(v, str):
3230
raise ValueError('value %r in dict must be a string' % v)
3331

3432

@@ -264,7 +262,7 @@ def execute(self, code, silent=False, store_history=True,
264262

265263

266264
# Don't waste network traffic if inputs are invalid
267-
if not isinstance(code, string_types):
265+
if not isinstance(code, str):
268266
raise ValueError('code %r must be a string' % code)
269267
validate_string_dict(user_expressions)
270268

@@ -384,7 +382,7 @@ def kernel_info(self):
384382

385383
def comm_info(self, target_name=None):
386384
"""Request comm info
387-
385+
388386
Returns
389387
-------
390388
The msg_id of the message sent

jupyter_client/connect.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,6 @@
77
# Copyright (c) Jupyter Development Team.
88
# Distributed under the terms of the Modified BSD License.
99

10-
11-
from __future__ import absolute_import
12-
1310
import errno
1411
import glob
1512
import json
@@ -27,7 +24,7 @@
2724
from .localinterfaces import localhost
2825
from ipython_genutils.path import filefind
2926
from ipython_genutils.py3compat import (
30-
bytes_to_str, cast_bytes, cast_bytes_py2, string_types,
27+
bytes_to_str, cast_bytes, cast_bytes_py2,
3128
)
3229
from traitlets import (
3330
Bool, Integer, Unicode, CaselessStrEnum, Instance, Type, observe
@@ -195,7 +192,7 @@ def find_connection_file(filename='kernel-*.json', path=None, profile=None):
195192
warnings.warn("Jupyter has no profiles. profile=%s has been ignored." % profile)
196193
if path is None:
197194
path = ['.', jupyter_runtime_dir()]
198-
if isinstance(path, string_types):
195+
if isinstance(path, str):
199196
path = [path]
200197

201198
try:
@@ -254,7 +251,7 @@ def tunnel_to_kernel(connection_info, sshserver, sshkey=None):
254251
The five ports on localhost that have been forwarded to the kernel.
255252
"""
256253
from .ssh import tunnel
257-
if isinstance(connection_info, string_types):
254+
if isinstance(connection_info, str):
258255
# it's a path, unpack it
259256
with open(connection_info) as f:
260257
connection_info = json.loads(f.read())

jupyter_client/ioloop/manager.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
# Copyright (c) Jupyter Development Team.
44
# Distributed under the terms of the Modified BSD License.
55

6-
from __future__ import absolute_import
7-
86
from tornado import ioloop
97
from zmq.eventloop.zmqstream import ZMQStream
108

jupyter_client/ioloop/restarter.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
# Copyright (c) Jupyter Development Team.
88
# Distributed under the terms of the Modified BSD License.
99

10-
from __future__ import absolute_import
1110
import warnings
1211

1312
from zmq.eventloop import ioloop

jupyter_client/jsonutil.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
from dateutil.tz import tzlocal
1313

1414
from ipython_genutils import py3compat
15-
from ipython_genutils.py3compat import string_types, iteritems
16-
next_attr_name = '__next__' if py3compat.PY3 else 'next'
15+
next_attr_name = '__next__' # Not sure what downstream library uses this, but left it to be safe
1716

1817
#-----------------------------------------------------------------------------
1918
# Globals and constants
@@ -33,7 +32,7 @@
3332

3433
def _ensure_tzinfo(dt):
3534
"""Ensure a datetime object has tzinfo
36-
35+
3736
If no tzinfo is present, add tzlocal
3837
"""
3938
if not dt.tzinfo:
@@ -46,7 +45,7 @@ def _ensure_tzinfo(dt):
4645

4746
def parse_date(s):
4847
"""parse an ISO8601 date string
49-
48+
5049
If it is None or not a valid ISO8601 timestamp,
5150
it will be returned unmodified.
5251
Otherwise, it will return a datetime object.
@@ -63,20 +62,20 @@ def extract_dates(obj):
6362
"""extract ISO8601 dates from unpacked JSON"""
6463
if isinstance(obj, dict):
6564
new_obj = {} # don't clobber
66-
for k,v in iteritems(obj):
65+
for k,v in obj.items():
6766
new_obj[k] = extract_dates(v)
6867
obj = new_obj
6968
elif isinstance(obj, (list, tuple)):
7069
obj = [ extract_dates(o) for o in obj ]
71-
elif isinstance(obj, string_types):
70+
elif isinstance(obj, str):
7271
obj = parse_date(obj)
7372
return obj
7473

7574
def squash_dates(obj):
7675
"""squash datetime objects into ISO8601 strings"""
7776
if isinstance(obj, dict):
7877
obj = dict(obj) # don't clobber
79-
for k,v in iteritems(obj):
78+
for k,v in obj.items():
8079
obj[k] = squash_dates(v)
8180
elif isinstance(obj, (list, tuple)):
8281
obj = [ squash_dates(o) for o in obj ]

jupyter_client/kernelspec.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313

1414
pjoin = os.path.join
1515

16-
from ipython_genutils.py3compat import PY3
1716
from traitlets import (
1817
HasTraits, List, Unicode, Dict, Set, Bool, Type, CaselessStrEnum
1918
)
@@ -22,7 +21,7 @@
2221
from jupyter_core.paths import jupyter_data_dir, jupyter_path, SYSTEM_JUPYTER_PATH
2322

2423

25-
NATIVE_KERNEL_NAME = 'python3' if PY3 else 'python2'
24+
NATIVE_KERNEL_NAME = 'python3'
2625

2726

2827
class KernelSpec(HasTraits):

jupyter_client/kernelspecapp.py

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,14 @@
1818
from . import __version__
1919
from .kernelspec import KernelSpecManager
2020

21-
try:
22-
raw_input
23-
except NameError:
24-
# py3
25-
raw_input = input
2621

2722
class ListKernelSpecs(JupyterApp):
2823
version = __version__
2924
description = """List installed kernel specifications."""
3025
kernel_spec_manager = Instance(KernelSpecManager)
3126
json_output = Bool(False, help='output spec name and location as machine-readable json.',
3227
config=True)
33-
28+
3429
flags = {'json': ({'ListKernelSpecs': {'json_output': True}},
3530
"output spec name and location as machine-readable json."),
3631
'debug': base_flags['debug'],
@@ -71,7 +66,7 @@ def path_key(item):
7166
class InstallKernelSpec(JupyterApp):
7267
version = __version__
7368
description = """Install a kernel specification directory.
74-
69+
7570
Given a SOURCE DIRECTORY containing a kernel spec,
7671
jupyter will copy that directory into one of the Jupyter kernel directories.
7772
The default is to install kernelspecs for all users.
@@ -157,44 +152,44 @@ class RemoveKernelSpec(JupyterApp):
157152
version = __version__
158153
description = """Remove one or more Jupyter kernelspecs by name."""
159154
examples = """jupyter kernelspec remove python2 [my_kernel ...]"""
160-
155+
161156
force = Bool(False, config=True,
162157
help="""Force removal, don't prompt for confirmation."""
163158
)
164159
spec_names = List(Unicode())
165-
160+
166161
kernel_spec_manager = Instance(KernelSpecManager)
167162
def _kernel_spec_manager_default(self):
168163
return KernelSpecManager(data_dir=self.data_dir, parent=self)
169-
164+
170165
flags = {
171166
'f': ({'RemoveKernelSpec': {'force': True}}, force.get_metadata('help')),
172167
}
173168
flags.update(JupyterApp.flags)
174-
169+
175170
def parse_command_line(self, argv):
176171
super(RemoveKernelSpec, self).parse_command_line(argv)
177172
# accept positional arg as profile name
178173
if self.extra_args:
179174
self.spec_names = sorted(set(self.extra_args)) # remove duplicates
180175
else:
181176
self.exit("No kernelspec specified.")
182-
177+
183178
def start(self):
184179
self.kernel_spec_manager.ensure_native_kernel = False
185180
spec_paths = self.kernel_spec_manager.find_kernel_specs()
186181
missing = set(self.spec_names).difference(set(spec_paths))
187182
if missing:
188183
self.exit("Couldn't find kernel spec(s): %s" % ', '.join(missing))
189-
184+
190185
if not self.force:
191186
print("Kernel specs to remove:")
192187
for name in self.spec_names:
193188
print(" %s\t%s" % (name.ljust(20), spec_paths[name]))
194-
answer = raw_input("Remove %i kernel specs [y/N]: " % len(self.spec_names))
189+
answer = input("Remove %i kernel specs [y/N]: " % len(self.spec_names))
195190
if not answer.lower().startswith('y'):
196191
return
197-
192+
198193
for kernel_name in self.spec_names:
199194
try:
200195
path = self.kernel_spec_manager.remove_kernel_spec(kernel_name)

jupyter_client/launcher.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from subprocess import Popen, PIPE
99

1010
from ipython_genutils.encoding import getdefaultencoding
11-
from ipython_genutils.py3compat import cast_bytes_py2, PY3
11+
from ipython_genutils.py3compat import cast_bytes_py2
1212
from traitlets.log import get_logger
1313

1414

@@ -127,10 +127,7 @@ def launch_kernel(cmd, stdin=None, stdout=None, stderr=None, env=None,
127127
# because we want to interrupt the whole process group.
128128
# We don't use setpgrp, which is known to cause problems for kernels starting
129129
# certain interactive subprocesses, such as bash -i.
130-
if PY3:
131-
kwargs['start_new_session'] = True
132-
else:
133-
kwargs['preexec_fn'] = lambda: os.setsid()
130+
kwargs['start_new_session'] = True
134131
if not independent:
135132
env['JPY_PARENT_PID'] = str(os.getpid())
136133

0 commit comments

Comments
 (0)