From 84df5297d5b26d32928b92da27227baba524fbe9 Mon Sep 17 00:00:00 2001 From: Sai Rahul Poruri Date: Sat, 10 Oct 2020 15:49:55 +0100 Subject: [PATCH] CLN : Update super usage This commit updates the super usage. Because Python 2 is not supported anymore, super usage can be updated such that super is called without any arguments in the default case where super is called with the class name and self. Note that all usage of super has not been updated - a few cases which smelled funny have been ignored. --- notebook/base/handlers.py | 31 +++++++++---------- notebook/base/zmqhandlers.py | 2 +- notebook/bundler/bundlerextensions.py | 2 +- notebook/files/handlers.py | 3 +- notebook/gateway/handlers.py | 8 ++--- notebook/gateway/managers.py | 6 ++-- notebook/jstest.py | 8 ++--- notebook/nbconvert/handlers.py | 6 ++-- notebook/nbextensions.py | 2 +- notebook/notebookapp.py | 10 +++--- notebook/serverextensions.py | 2 +- .../services/contents/largefilemanager.py | 4 +-- notebook/services/kernels/handlers.py | 12 +++---- .../sessions/tests/test_sessionmanager.py | 2 +- notebook/terminal/handlers.py | 6 ++-- notebook/terminal/terminalmanager.py | 4 +-- notebook/tests/test_gateway.py | 2 +- notebook/tests/test_notebookapp.py | 2 +- notebook/tests/test_serverextensions.py | 4 +-- 19 files changed, 56 insertions(+), 60 deletions(-) diff --git a/notebook/base/handlers.py b/notebook/base/handlers.py index 743f7bac7..e3400eba1 100755 --- a/notebook/base/handlers.py +++ b/notebook/base/handlers.py @@ -301,7 +301,7 @@ class IPythonHandler(AuthenticatedHandler): def set_default_headers(self): """Add CORS headers, if defined""" - super(IPythonHandler, self).set_default_headers() + super().set_default_headers() if self.allow_origin: self.set_header("Access-Control-Allow-Origin", self.allow_origin) elif self.allow_origin_pat: @@ -442,7 +442,7 @@ class IPythonHandler(AuthenticatedHandler): # Servers without authentication are vulnerable to XSRF return try: - return super(IPythonHandler, self).check_xsrf_cookie() + return super().check_xsrf_cookie() except web.HTTPError as e: if self.request.method in {'GET', 'HEAD'}: # Consider Referer a sufficient cross-origin check for GET requests @@ -496,7 +496,7 @@ class IPythonHandler(AuthenticatedHandler): def prepare(self): if not self.check_host(): raise web.HTTPError(403) - return super(IPythonHandler, self).prepare() + return super().prepare() #--------------------------------------------------------------- # template rendering @@ -591,7 +591,7 @@ class APIHandler(IPythonHandler): def prepare(self): if not self.check_origin(): raise web.HTTPError(404) - return super(APIHandler, self).prepare() + return super().prepare() def write_error(self, status_code, **kwargs): """APIHandler errors are JSON, not human pages""" @@ -618,7 +618,7 @@ class APIHandler(IPythonHandler): # preserve _user_cache so we don't raise more than once if hasattr(self, '_user_cache'): return self._user_cache - self._user_cache = user = super(APIHandler, self).get_current_user() + self._user_cache = user = super().get_current_user() return user def get_login_url(self): @@ -627,12 +627,12 @@ class APIHandler(IPythonHandler): # instead of redirecting, raise 403 instead. if not self.current_user: raise web.HTTPError(403) - return super(APIHandler, self).get_login_url() + return super().get_login_url() @property def content_security_policy(self): csp = '; '.join([ - super(APIHandler, self).content_security_policy, + super().content_security_policy, "default-src 'none'", ]) return csp @@ -653,7 +653,7 @@ class APIHandler(IPythonHandler): def finish(self, *args, **kwargs): self.update_api_activity() self.set_header('Content-Type', 'application/json') - return super(APIHandler, self).finish(*args, **kwargs) + return super().finish(*args, **kwargs) def options(self, *args, **kwargs): if 'Access-Control-Allow-Headers' in self.settings.get('headers', {}): @@ -700,13 +700,12 @@ class AuthenticatedFileHandler(IPythonHandler, web.StaticFileHandler): def content_security_policy(self): # In case we're serving HTML/SVG, confine any Javascript to a unique # origin so it can't interact with the notebook server. - return super(AuthenticatedFileHandler, self).content_security_policy + \ - "; sandbox allow-scripts" + return super().content_security_policy + "; sandbox allow-scripts" @web.authenticated def head(self, path): self.check_xsrf_cookie() - return super(AuthenticatedFileHandler, self).head(path) + return super().head(path) @web.authenticated def get(self, path): @@ -731,10 +730,10 @@ class AuthenticatedFileHandler(IPythonHandler, web.StaticFileHandler): if cur_mime == 'text/plain': return 'text/plain; charset=UTF-8' else: - return super(AuthenticatedFileHandler, self).get_content_type() + return super().get_content_type() def set_headers(self): - super(AuthenticatedFileHandler, self).set_headers() + super().set_headers() # disable browser caching, rely on 304 replies for savings if "v" not in self.request.arguments: self.add_header("Cache-Control", "no-cache") @@ -749,7 +748,7 @@ class AuthenticatedFileHandler(IPythonHandler, web.StaticFileHandler): Adding to tornado's own handling, forbids the serving of hidden files. """ - abs_path = super(AuthenticatedFileHandler, self).validate_absolute_path(root, absolute_path) + abs_path = super().validate_absolute_path(root, absolute_path) abs_root = os.path.abspath(root) if is_hidden(abs_path, abs_root) and not self.contents_manager.allow_hidden: self.log.info("Refusing to serve hidden file, via 404 Error, use flag 'ContentsManager.allow_hidden' to enable") @@ -795,7 +794,7 @@ class FileFindHandler(IPythonHandler, web.StaticFileHandler): _static_paths = {} def set_headers(self): - super(FileFindHandler, self).set_headers() + super().set_headers() # disable browser caching, rely on 304 replies for savings if "v" not in self.request.arguments or \ any(self.request.path.startswith(path) for path in self.no_cache_paths): @@ -842,7 +841,7 @@ class FileFindHandler(IPythonHandler, web.StaticFileHandler): if (absolute_path + os.sep).startswith(root): break - return super(FileFindHandler, self).validate_absolute_path(root, absolute_path) + return super().validate_absolute_path(root, absolute_path) class APIVersionHandler(APIHandler): diff --git a/notebook/base/zmqhandlers.py b/notebook/base/zmqhandlers.py index 327fdd559..dc3a7b69e 100644 --- a/notebook/base/zmqhandlers.py +++ b/notebook/base/zmqhandlers.py @@ -289,7 +289,7 @@ class AuthenticatedZMQStreamHandler(ZMQStreamHandler, IPythonHandler): # assign and yield in two step to avoid tornado 3 issues res = self.pre_get() yield maybe_future(res) - res = super(AuthenticatedZMQStreamHandler, self).get(*args, **kwargs) + res = super().get(*args, **kwargs) yield maybe_future(res) def initialize(self): diff --git a/notebook/bundler/bundlerextensions.py b/notebook/bundler/bundlerextensions.py index 576336c3a..2ac346f97 100644 --- a/notebook/bundler/bundlerextensions.py +++ b/notebook/bundler/bundlerextensions.py @@ -294,7 +294,7 @@ jupyter bundlerextension disable --py # disable all bundlers in def start(self): """Perform the App's functions as configured""" - super(BundlerExtensionApp, self).start() + super().start() # The above should have called a subcommand and raised NoStart; if we # get here, it didn't, so we should self.log.info a message. diff --git a/notebook/files/handlers.py b/notebook/files/handlers.py index 3b2570a18..b412cd84e 100644 --- a/notebook/files/handlers.py +++ b/notebook/files/handlers.py @@ -26,8 +26,7 @@ class FilesHandler(IPythonHandler): def content_security_policy(self): # In case we're serving HTML/SVG, confine any Javascript to a unique # origin so it can't interact with the notebook server. - return super(FilesHandler, self).content_security_policy + \ - "; sandbox allow-scripts" + return super().content_security_policy + "; sandbox allow-scripts" @web.authenticated def head(self, path): diff --git a/notebook/gateway/handlers.py b/notebook/gateway/handlers.py index 6576c3cef..75de06669 100644 --- a/notebook/gateway/handlers.py +++ b/notebook/gateway/handlers.py @@ -68,7 +68,7 @@ class WebSocketChannelsHandler(WebSocketHandler, IPythonHandler): def get(self, kernel_id, *args, **kwargs): self.authenticate() self.kernel_id = cast_unicode(kernel_id, 'ascii') - yield super(WebSocketChannelsHandler, self).get(kernel_id=kernel_id, *args, **kwargs) + yield super().get(kernel_id=kernel_id, *args, **kwargs) def send_ping(self): if self.ws_connection is None and self.ping_callback is not None: @@ -97,7 +97,7 @@ class WebSocketChannelsHandler(WebSocketHandler, IPythonHandler): if self.ws_connection: # prevent WebSocketClosedError if isinstance(message, bytes): binary = True - super(WebSocketChannelsHandler, self).write_message(message, binary=binary) + super().write_message(message, binary=binary) elif self.log.isEnabledFor(logging.DEBUG): msg_summary = WebSocketChannelsHandler._get_message_summary(json_decode(utf8(message))) self.log.debug("Notebook client closed websocket connection - message dropped: {}".format(msg_summary)) @@ -105,7 +105,7 @@ class WebSocketChannelsHandler(WebSocketHandler, IPythonHandler): def on_close(self): self.log.debug("Closing websocket connection %s", self.request.path) self.gateway.on_close() - super(WebSocketChannelsHandler, self).on_close() + super().on_close() @staticmethod def _get_message_summary(message): @@ -129,7 +129,7 @@ class GatewayWebSocketClient(LoggingConfigurable): """Proxy web socket connection to a kernel/enterprise gateway.""" def __init__(self, **kwargs): - super(GatewayWebSocketClient, self).__init__(**kwargs) + super().__init__(**kwargs) self.kernel_id = None self.ws = None self.ws_future = Future() diff --git a/notebook/gateway/managers.py b/notebook/gateway/managers.py index 30382e8c0..856cea494 100644 --- a/notebook/gateway/managers.py +++ b/notebook/gateway/managers.py @@ -205,7 +205,7 @@ class GatewayClient(SingletonConfigurable): return bool(os.environ.get(self.validate_cert_env, str(self.validate_cert_default_value)) not in ['no', 'false']) def __init__(self, **kwargs): - super(GatewayClient, self).__init__(**kwargs) + super().__init__(**kwargs) self._static_args = {} # initialized on first use env_whitelist_default_value = '' @@ -310,7 +310,7 @@ class GatewayKernelManager(MappingKernelManager): _kernels = {} def __init__(self, **kwargs): - super(GatewayKernelManager, self).__init__(**kwargs) + super().__init__(**kwargs) self.base_endpoint = url_path_join(GatewayClient.instance().url, GatewayClient.instance().kernels_endpoint) def __contains__(self, kernel_id): @@ -507,7 +507,7 @@ class GatewayKernelManager(MappingKernelManager): class GatewayKernelSpecManager(KernelSpecManager): def __init__(self, **kwargs): - super(GatewayKernelSpecManager, self).__init__(**kwargs) + super().__init__(**kwargs) base_endpoint = url_path_join(GatewayClient.instance().url, GatewayClient.instance().kernelspecs_endpoint) diff --git a/notebook/jstest.py b/notebook/jstest.py index 6849c9fd0..0447af8a5 100644 --- a/notebook/jstest.py +++ b/notebook/jstest.py @@ -45,7 +45,7 @@ class StreamCapturer(Thread): daemon = True # Don't hang if main thread crashes started = False def __init__(self, echo=False): - super(StreamCapturer, self).__init__() + super().__init__() self.echo = echo self.streams = [] self.buffer = BytesIO() @@ -264,14 +264,14 @@ class JSController(TestController): # If the engine is SlimerJS, we need to buffer the output because # SlimerJS does not support exit codes, so CasperJS always returns 0. if self.engine == 'slimerjs' and not buffer_output: - return super(JSController, self).launch(capture_output=True) + return super().launch(capture_output=True) else: - return super(JSController, self).launch(buffer_output=buffer_output) + return super().launch(buffer_output=buffer_output) def wait(self, *pargs, **kwargs): """Wait for the JSController to finish""" - ret = super(JSController, self).wait(*pargs, **kwargs) + ret = super().wait(*pargs, **kwargs) # If this is a SlimerJS controller, check the captured stdout for # errors. Otherwise, just return the return code. if self.engine == 'slimerjs': diff --git a/notebook/nbconvert/handlers.py b/notebook/nbconvert/handlers.py index faa1a6931..24a3f093f 100644 --- a/notebook/nbconvert/handlers.py +++ b/notebook/nbconvert/handlers.py @@ -83,8 +83,7 @@ class NbconvertFileHandler(IPythonHandler): def content_security_policy(self): # In case we're serving HTML/SVG, confine any Javascript to a unique # origin so it can't interact with the notebook server. - return super(NbconvertFileHandler, self).content_security_policy + \ - "; sandbox allow-scripts" + return super().content_security_policy + "; sandbox allow-scripts" @web.authenticated @gen.coroutine @@ -158,8 +157,7 @@ class NbconvertPostHandler(IPythonHandler): def content_security_policy(self): # In case we're serving HTML/SVG, confine any Javascript to a unique # origin so it can't interact with the notebook server. - return super(NbconvertPostHandler, self).content_security_policy + \ - "; sandbox allow-scripts" + return super().content_security_policy + "; sandbox allow-scripts" @web.authenticated def post(self, format): diff --git a/notebook/nbextensions.py b/notebook/nbextensions.py index c6dad116b..223aeff0e 100644 --- a/notebook/nbextensions.py +++ b/notebook/nbextensions.py @@ -980,7 +980,7 @@ class NBExtensionApp(BaseExtensionApp): def start(self): """Perform the App's functions as configured""" - super(NBExtensionApp, self).start() + super().start() # The above should have called a subcommand and raised NoStart; if we # get here, it didn't, so we should self.log.info a message. diff --git a/notebook/notebookapp.py b/notebook/notebookapp.py index dc7c84c57..43f3d7f5e 100755 --- a/notebook/notebookapp.py +++ b/notebook/notebookapp.py @@ -190,7 +190,7 @@ class NotebookWebApplication(web.Application): if settings['autoreload']: log.info('Autoreload enabled: the webapp will restart when any Python src file changes.') - super(NotebookWebApplication, self).__init__(handlers, **settings) + super().__init__(handlers, **settings) def init_settings(self, jupyter_app, kernel_manager, contents_manager, session_manager, kernel_spec_manager, @@ -511,7 +511,7 @@ class NbserverStopApp(JupyterApp): help="UNIX socket of the server to be killed.") def parse_command_line(self, argv=None): - super(NbserverStopApp, self).parse_command_line(argv) + super().parse_command_line(argv) if self.extra_args: try: self.port = int(self.extra_args[0]) @@ -1523,7 +1523,7 @@ class NotebookApp(JupyterApp): terminals_available = False def parse_command_line(self, argv=None): - super(NotebookApp, self).parse_command_line(argv) + super().parse_command_line(argv) if self.extra_args: arg0 = self.extra_args[0] @@ -2026,7 +2026,7 @@ class NotebookApp(JupyterApp): def initialize(self, argv=None): self._init_asyncio_patch() - super(NotebookApp, self).initialize(argv) + super().initialize(argv) self.init_logging() if self._dispatching: return @@ -2192,7 +2192,7 @@ class NotebookApp(JupyterApp): This method takes no arguments so all configuration and initialization must be done prior to calling this method.""" - super(NotebookApp, self).start() + super().start() if not self.allow_root: # check if we are running as root, and abort if it's not allowed diff --git a/notebook/serverextensions.py b/notebook/serverextensions.py index 7ca1fb03b..0e3084a92 100644 --- a/notebook/serverextensions.py +++ b/notebook/serverextensions.py @@ -291,7 +291,7 @@ class ServerExtensionApp(BaseExtensionApp): def start(self): """Perform the App's actions as configured""" - super(ServerExtensionApp, self).start() + super().start() # The above should have called a subcommand and raised NoStart; if we # get here, it didn't, so we should self.log.info a message. diff --git a/notebook/services/contents/largefilemanager.py b/notebook/services/contents/largefilemanager.py index a2b27ed99..6779a0b5c 100644 --- a/notebook/services/contents/largefilemanager.py +++ b/notebook/services/contents/largefilemanager.py @@ -27,7 +27,7 @@ class LargeFileManager(FileContentsManager): if chunk == 1: self.log.debug("Saving %s", os_path) self.run_pre_save_hook(model=model, path=path) - super(LargeFileManager, self)._save_file(os_path, model['content'], model.get('format')) + super()._save_file(os_path, model['content'], model.get('format')) else: self._save_large_file(os_path, model['content'], model.get('format')) except web.HTTPError: @@ -43,7 +43,7 @@ class LargeFileManager(FileContentsManager): self.run_post_save_hook(model=model, os_path=os_path) return model else: - return super(LargeFileManager, self).save(model, path) + return super().save(model, path) def _save_large_file(self, os_path, content, format): """Save content of a generic file.""" diff --git a/notebook/services/kernels/handlers.py b/notebook/services/kernels/handlers.py index bca99ce1b..73da737b1 100644 --- a/notebook/services/kernels/handlers.py +++ b/notebook/services/kernels/handlers.py @@ -190,7 +190,7 @@ class ZMQChannelsHandler(AuthenticatedZMQStreamHandler): self._kernel_info_future.set_result(info) def initialize(self): - super(ZMQChannelsHandler, self).initialize() + super().initialize() self.zmq_stream = None self.channels = {} self.kernel_id = None @@ -212,7 +212,7 @@ class ZMQChannelsHandler(AuthenticatedZMQStreamHandler): @gen.coroutine def pre_get(self): # authenticate first - super(ZMQChannelsHandler, self).pre_get() + super().pre_get() # check session collision: yield self._register_session() # then request kernel info, waiting up to a certain time before giving up. @@ -236,7 +236,7 @@ class ZMQChannelsHandler(AuthenticatedZMQStreamHandler): @gen.coroutine def get(self, kernel_id): self.kernel_id = cast_unicode(kernel_id, 'ascii') - yield super(ZMQChannelsHandler, self).get(kernel_id=kernel_id) + yield super().get(kernel_id=kernel_id) @gen.coroutine def _register_session(self): @@ -254,7 +254,7 @@ class ZMQChannelsHandler(AuthenticatedZMQStreamHandler): self._open_sessions[self.session_key] = self def open(self, kernel_id): - super(ZMQChannelsHandler, self).open() + super().open() km = self.kernel_manager km.notify_connect(kernel_id) @@ -419,10 +419,10 @@ class ZMQChannelsHandler(AuthenticatedZMQStreamHandler): self._iopub_window_byte_count -= byte_count self._iopub_window_byte_queue.pop(-1) return - super(ZMQChannelsHandler, self)._on_zmq_reply(stream, msg) + super()._on_zmq_reply(stream, msg) def close(self): - super(ZMQChannelsHandler, self).close() + super().close() return self._close_future def on_close(self): diff --git a/notebook/services/sessions/tests/test_sessionmanager.py b/notebook/services/sessions/tests/test_sessionmanager.py index 97331ebf9..719bbaef7 100644 --- a/notebook/services/sessions/tests/test_sessionmanager.py +++ b/notebook/services/sessions/tests/test_sessionmanager.py @@ -21,7 +21,7 @@ dummy_date_s = isoformat(dummy_date) class DummyMKM(MappingKernelManager): """MappingKernelManager interface that doesn't start kernels, for testing""" def __init__(self, *args, **kwargs): - super(DummyMKM, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.id_letters = iter(u'ABCDEFGHIJK') def _new_id(self): diff --git a/notebook/terminal/handlers.py b/notebook/terminal/handlers.py index dd305a75b..c201f5607 100644 --- a/notebook/terminal/handlers.py +++ b/notebook/terminal/handlers.py @@ -33,14 +33,14 @@ class TermSocket(WebSocketMixin, IPythonHandler, terminado.TermSocket): raise web.HTTPError(403) if not args[0] in self.term_manager.terminals: raise web.HTTPError(404) - return super(TermSocket, self).get(*args, **kwargs) + return super().get(*args, **kwargs) def on_message(self, message): - super(TermSocket, self).on_message(message) + super().on_message(message) self._update_activity() def write_message(self, message, binary=False): - super(TermSocket, self).write_message(message, binary=binary) + super().write_message(message, binary=binary) self._update_activity() def _update_activity(self): diff --git a/notebook/terminal/terminalmanager.py b/notebook/terminal/terminalmanager.py index 0521b6a84..c1bdecd8d 100644 --- a/notebook/terminal/terminalmanager.py +++ b/notebook/terminal/terminalmanager.py @@ -39,7 +39,7 @@ class TerminalManager(LoggingConfigurable, NamedTermManager): # Methods for managing terminals # ------------------------------------------------------------------------- def __init__(self, *args, **kwargs): - super(TerminalManager, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def create(self): """Create a new terminal.""" @@ -73,7 +73,7 @@ class TerminalManager(LoggingConfigurable, NamedTermManager): async def terminate(self, name, force=False): """Terminate terminal 'name'.""" self._check_terminal(name) - await super(TerminalManager, self).terminate(name, force=force) + await super().terminate(name, force=force) # Decrease the metric below by one # because a terminal has been shutdown diff --git a/notebook/tests/test_gateway.py b/notebook/tests/test_gateway.py index bc42014e4..2bf0089ca 100644 --- a/notebook/tests/test_gateway.py +++ b/notebook/tests/test_gateway.py @@ -161,7 +161,7 @@ class TestGateway(NotebookTestBase): def setUp(self): kwargs = dict() GatewayClient.instance().load_connection_args(**kwargs) - super(TestGateway, self).setUp() + super().setUp() def test_gateway_options(self): nt.assert_equal(self.notebook.gateway_config.gateway_enabled, True) diff --git a/notebook/tests/test_notebookapp.py b/notebook/tests/test_notebookapp.py index d8543feed..58bd7261b 100644 --- a/notebook/tests/test_notebookapp.py +++ b/notebook/tests/test_notebookapp.py @@ -142,7 +142,7 @@ def test_notebook_password(): class TestingStopApp(notebookapp.NbserverStopApp): """For testing the logic of NbserverStopApp.""" def __init__(self, **kwargs): - super(TestingStopApp, self).__init__(**kwargs) + super().__init__(**kwargs) self.servers_shut_down = [] def shutdown_server(self, server): diff --git a/notebook/tests/test_serverextensions.py b/notebook/tests/test_serverextensions.py index d279b81b3..9c2bf95dd 100644 --- a/notebook/tests/test_serverextensions.py +++ b/notebook/tests/test_serverextensions.py @@ -159,7 +159,7 @@ class TestOrderedServerExtension(MockEnvTestCase): """ def setUp(self): - super(TestOrderedServerExtension, self).setUp() + super().setUp() mockextension1 = SimpleNamespace() mockextension2 = SimpleNamespace() @@ -179,7 +179,7 @@ class TestOrderedServerExtension(MockEnvTestCase): sys.modules['mockextension1'] = mockextension1 def tearDown(self): - super(TestOrderedServerExtension, self).tearDown() + super().tearDown() del sys.modules['mockextension2'] del sys.modules['mockextension1']