Skip to content

Commit

Permalink
Update super usage (#2912)
Browse files Browse the repository at this point in the history
On Python 3, super does not need to be called with arguments where as on
Python 2, super needs to be called with a class object and an instance.

This commit updates the super usage using automated regex-based search
and replace. After the automated changes were made, each change was
individually checked before committing.
  • Loading branch information
Poruri Sai Rahul authored Sep 13, 2020
1 parent 68efd61 commit b3c63fb
Show file tree
Hide file tree
Showing 36 changed files with 122 additions and 130 deletions.
2 changes: 1 addition & 1 deletion demos/blog/blog.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def __init__(self, db):
login_url="/auth/login",
debug=True,
)
super(Application, self).__init__(handlers, **settings)
super().__init__(handlers, **settings)


class BaseHandler(tornado.web.RequestHandler):
Expand Down
2 changes: 1 addition & 1 deletion demos/websocket/chatdemo.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def __init__(self):
static_path=os.path.join(os.path.dirname(__file__), "static"),
xsrf_cookies=True,
)
super(Application, self).__init__(handlers, **settings)
super().__init__(handlers, **settings)


class MainHandler(tornado.web.RequestHandler):
Expand Down
2 changes: 1 addition & 1 deletion maint/test/redbot/red_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def get_app(self):
return Application(self.get_handlers(), gzip=True, **self.get_app_kwargs())

def get_allowed_errors(self):
return super(GzipHTTPTest, self).get_allowed_errors() + [
return super().get_allowed_errors() + [
# TODO: The Etag is supposed to change when Content-Encoding is
# used. This should be fixed, but it's difficult to do with the
# way GZipContentEncoding fits into the pipeline, and in practice
Expand Down
4 changes: 2 additions & 2 deletions tornado/curl_httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class CurlAsyncHTTPClient(AsyncHTTPClient):
def initialize( # type: ignore
self, max_clients: int = 10, defaults: Optional[Dict[str, Any]] = None
) -> None:
super(CurlAsyncHTTPClient, self).initialize(defaults=defaults)
super().initialize(defaults=defaults)
# Typeshed is incomplete for CurlMulti, so just use Any for now.
self._multi = pycurl.CurlMulti() # type: Any
self._multi.setopt(pycurl.M_TIMERFUNCTION, self._set_timeout)
Expand Down Expand Up @@ -87,7 +87,7 @@ def close(self) -> None:
for curl in self._curls:
curl.close()
self._multi.close()
super(CurlAsyncHTTPClient, self).close()
super().close()

# Set below properties to None to reduce the reference count of current
# instance, because those properties hold some methods of current
Expand Down
2 changes: 1 addition & 1 deletion tornado/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ def fetch_json(url):
"""

def __init__(self, value: Any = None) -> None:
super(Return, self).__init__()
super().__init__()
self.value = value
# Cython recognizes subclasses of StopIteration with a .args tuple.
self.args = (value,)
Expand Down
2 changes: 1 addition & 1 deletion tornado/httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,7 @@ def __init__(
self.code = code
self.message = message or httputil.responses.get(code, "Unknown")
self.response = response
super(HTTPClientError, self).__init__(code, message, response)
super().__init__(code, message, response)

def __str__(self) -> str:
return "HTTP %d: %s" % (self.code, self.message)
Expand Down
22 changes: 11 additions & 11 deletions tornado/iostream.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class StreamClosedError(IOError):
"""

def __init__(self, real_error: Optional[BaseException] = None) -> None:
super(StreamClosedError, self).__init__("Stream is closed")
super().__init__("Stream is closed")
self.real_error = real_error


Expand Down Expand Up @@ -1122,7 +1122,7 @@ async def main():
def __init__(self, socket: socket.socket, *args: Any, **kwargs: Any) -> None:
self.socket = socket
self.socket.setblocking(False)
super(IOStream, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def fileno(self) -> Union[int, ioloop._Selectable]:
return self.socket
Expand Down Expand Up @@ -1360,7 +1360,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
for `ssl.wrap_socket`
"""
self._ssl_options = kwargs.pop("ssl_options", _client_ssl_defaults)
super(SSLIOStream, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self._ssl_accepting = True
self._handshake_reading = False
self._handshake_writing = False
Expand All @@ -1378,10 +1378,10 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
self._add_io_state(self.io_loop.WRITE)

def reading(self) -> bool:
return self._handshake_reading or super(SSLIOStream, self).reading()
return self._handshake_reading or super().reading()

def writing(self) -> bool:
return self._handshake_writing or super(SSLIOStream, self).writing()
return self._handshake_writing or super().writing()

def _do_ssl_handshake(self) -> None:
# Based on code from test_ssl.py in the python stdlib
Expand Down Expand Up @@ -1477,13 +1477,13 @@ def _handle_read(self) -> None:
if self._ssl_accepting:
self._do_ssl_handshake()
return
super(SSLIOStream, self)._handle_read()
super()._handle_read()

def _handle_write(self) -> None:
if self._ssl_accepting:
self._do_ssl_handshake()
return
super(SSLIOStream, self)._handle_write()
super()._handle_write()

def connect(
self, address: Tuple, server_hostname: Optional[str] = None
Expand All @@ -1500,13 +1500,13 @@ def connect(
# (There's a test for it, but I think in practice users
# either wait for the connect before performing a write or
# they don't care about the connect Future at all)
fut = super(SSLIOStream, self).connect(address)
fut = super().connect(address)
fut.add_done_callback(lambda f: f.exception())
return self.wait_for_handshake()

def _handle_connect(self) -> None:
# Call the superclass method to check for errors.
super(SSLIOStream, self)._handle_connect()
super()._handle_connect()
if self.closed():
return
# When the connection is complete, wrap the socket for SSL
Expand Down Expand Up @@ -1605,7 +1605,7 @@ def read_from_fd(self, buf: Union[bytearray, memoryview]) -> Optional[int]:
def _is_connreset(self, e: BaseException) -> bool:
if isinstance(e, ssl.SSLError) and e.args[0] == ssl.SSL_ERROR_EOF:
return True
return super(SSLIOStream, self)._is_connreset(e)
return super()._is_connreset(e)


class PipeIOStream(BaseIOStream):
Expand All @@ -1623,7 +1623,7 @@ def __init__(self, fd: int, *args: Any, **kwargs: Any) -> None:
self.fd = fd
self._fio = io.FileIO(self.fd, "r+")
os.set_blocking(fd, False)
super(PipeIOStream, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def fileno(self) -> int:
return self.fd
Expand Down
4 changes: 2 additions & 2 deletions tornado/locale.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ class CSVLocale(Locale):

def __init__(self, code: str, translations: Dict[str, Dict[str, str]]) -> None:
self.translations = translations
super(CSVLocale, self).__init__(code)
super().__init__(code)

def translate(
self,
Expand Down Expand Up @@ -520,7 +520,7 @@ def __init__(self, code: str, translations: gettext.NullTranslations) -> None:
self.gettext = translations.gettext
# self.gettext must exist before __init__ is called, since it
# calls into self.translate
super(GettextLocale, self).__init__(code)
super().__init__(code)

def translate(
self,
Expand Down
10 changes: 5 additions & 5 deletions tornado/locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ async def runner():
"""

def __init__(self) -> None:
super(Condition, self).__init__()
super().__init__()
self.io_loop = ioloop.IOLoop.current()

def __repr__(self) -> str:
Expand Down Expand Up @@ -380,14 +380,14 @@ def worker(worker_id):
"""

def __init__(self, value: int = 1) -> None:
super(Semaphore, self).__init__()
super().__init__()
if value < 0:
raise ValueError("semaphore initial value must be >= 0")

self._value = value

def __repr__(self) -> str:
res = super(Semaphore, self).__repr__()
res = super().__repr__()
extra = (
"locked" if self._value == 0 else "unlocked,value:{0}".format(self._value)
)
Expand Down Expand Up @@ -473,14 +473,14 @@ class BoundedSemaphore(Semaphore):
"""

def __init__(self, value: int = 1) -> None:
super(BoundedSemaphore, self).__init__(value=value)
super().__init__(value=value)
self._initial_value = value

def release(self) -> None:
"""Increment the counter and wake one waiter."""
if self._value >= self._initial_value:
raise ValueError("Semaphore released too many times")
super(BoundedSemaphore, self).release()
super().release()


class Lock(object):
Expand Down
6 changes: 2 additions & 4 deletions tornado/netutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ class BlockingResolver(ExecutorResolver):
"""

def initialize(self) -> None: # type: ignore
super(BlockingResolver, self).initialize()
super().initialize()


class ThreadedResolver(ExecutorResolver):
Expand Down Expand Up @@ -485,9 +485,7 @@ class ThreadedResolver(ExecutorResolver):

def initialize(self, num_threads: int = 10) -> None: # type: ignore
threadpool = ThreadedResolver._create_threadpool(num_threads)
super(ThreadedResolver, self).initialize(
executor=threadpool, close_executor=False
)
super().initialize(executor=threadpool, close_executor=False)

@classmethod
def _create_threadpool(
Expand Down
8 changes: 4 additions & 4 deletions tornado/platform/asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def initialize( # type: ignore

self._thread_identity = 0

super(BaseAsyncIOLoop, self).initialize(**kwargs)
super().initialize(**kwargs)

def assign_thread_identity() -> None:
self._thread_identity = get_ident()
Expand Down Expand Up @@ -221,7 +221,7 @@ class AsyncIOMainLoop(BaseAsyncIOLoop):
"""

def initialize(self, **kwargs: Any) -> None: # type: ignore
super(AsyncIOMainLoop, self).initialize(asyncio.get_event_loop(), **kwargs)
super().initialize(asyncio.get_event_loop(), **kwargs)

def make_current(self) -> None:
# AsyncIOMainLoop already refers to the current asyncio loop so
Expand Down Expand Up @@ -253,7 +253,7 @@ def initialize(self, **kwargs: Any) -> None: # type: ignore
self.is_current = False
loop = asyncio.new_event_loop()
try:
super(AsyncIOLoop, self).initialize(loop, **kwargs)
super().initialize(loop, **kwargs)
except Exception:
# If initialize() does not succeed (taking ownership of the loop),
# we have to close it.
Expand All @@ -263,7 +263,7 @@ def initialize(self, **kwargs: Any) -> None: # type: ignore
def close(self, all_fds: bool = False) -> None:
if self.is_current:
self.clear_current()
super(AsyncIOLoop, self).close(all_fds=all_fds)
super().close(all_fds=all_fds)

def make_current(self) -> None:
if not self.is_current:
Expand Down
6 changes: 3 additions & 3 deletions tornado/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,10 +411,10 @@ class ReversibleRuleRouter(ReversibleRouter, RuleRouter):

def __init__(self, rules: Optional[_RuleList] = None) -> None:
self.named_rules = {} # type: Dict[str, Any]
super(ReversibleRuleRouter, self).__init__(rules)
super().__init__(rules)

def process_rule(self, rule: "Rule") -> "Rule":
rule = super(ReversibleRuleRouter, self).process_rule(rule)
rule = super().process_rule(rule)

if rule.name:
if rule.name in self.named_rules:
Expand Down Expand Up @@ -679,7 +679,7 @@ def __init__(
"""
matcher = PathMatches(pattern)
super(URLSpec, self).__init__(matcher, handler, kwargs, name)
super().__init__(matcher, handler, kwargs, name)

self.regex = matcher.regex
self.handler_class = self.target
Expand Down
8 changes: 4 additions & 4 deletions tornado/simple_httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class HTTPTimeoutError(HTTPError):
"""

def __init__(self, message: str) -> None:
super(HTTPTimeoutError, self).__init__(599, message=message)
super().__init__(599, message=message)

def __str__(self) -> str:
return self.message or "Timeout"
Expand All @@ -70,7 +70,7 @@ class HTTPStreamClosedError(HTTPError):
"""

def __init__(self, message: str) -> None:
super(HTTPStreamClosedError, self).__init__(599, message=message)
super().__init__(599, message=message)

def __str__(self) -> str:
return self.message or "Stream closed"
Expand Down Expand Up @@ -128,7 +128,7 @@ def initialize( # type: ignore
.. versionchanged:: 4.2
Added the ``max_body_size`` argument.
"""
super(SimpleAsyncHTTPClient, self).initialize(defaults=defaults)
super().initialize(defaults=defaults)
self.max_clients = max_clients
self.queue = (
collections.deque()
Expand Down Expand Up @@ -157,7 +157,7 @@ def initialize( # type: ignore
self.tcp_client = TCPClient(resolver=self.resolver)

def close(self) -> None:
super(SimpleAsyncHTTPClient, self).close()
super().close()
if self.own_resolver:
self.resolver.close()
self.tcp_client.close()
Expand Down
6 changes: 3 additions & 3 deletions tornado/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ class Loader(BaseLoader):
"""

def __init__(self, root_directory: str, **kwargs: Any) -> None:
super(Loader, self).__init__(**kwargs)
super().__init__(**kwargs)
self.root = os.path.abspath(root_directory)

def resolve_path(self, name: str, parent_path: Optional[str] = None) -> str:
Expand Down Expand Up @@ -483,7 +483,7 @@ class DictLoader(BaseLoader):
"""A template loader that loads from a dictionary."""

def __init__(self, dict: Dict[str, str], **kwargs: Any) -> None:
super(DictLoader, self).__init__(**kwargs)
super().__init__(**kwargs)
self.dict = dict

def resolve_path(self, name: str, parent_path: Optional[str] = None) -> str:
Expand Down Expand Up @@ -677,7 +677,7 @@ def generate(self, writer: "_CodeWriter") -> None:

class _Module(_Expression):
def __init__(self, expression: str, line: int) -> None:
super(_Module, self).__init__("_tt_modules." + expression, line, raw=True)
super().__init__("_tt_modules." + expression, line, raw=True)


class _Text(_Node):
Expand Down
4 changes: 2 additions & 2 deletions tornado/test/concurrent_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,15 @@ class ClientTestMixin(object):
client_class = None # type: typing.Callable

def setUp(self):
super(ClientTestMixin, self).setUp() # type: ignore
super().setUp() # type: ignore
self.server = CapServer()
sock, port = bind_unused_port()
self.server.add_sockets([sock])
self.client = self.client_class(port=port)

def tearDown(self):
self.server.stop()
super(ClientTestMixin, self).tearDown() # type: ignore
super().tearDown() # type: ignore

def test_future(self: typing.Any):
future = self.client.capitalize("hello")
Expand Down
2 changes: 1 addition & 1 deletion tornado/test/curl_httpclient_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def get(self):
@unittest.skipIf(pycurl is None, "pycurl module not present")
class CurlHTTPClientTestCase(AsyncHTTPTestCase):
def setUp(self):
super(CurlHTTPClientTestCase, self).setUp()
super().setUp()
self.http_client = self.create_client()

def get_app(self):
Expand Down
4 changes: 2 additions & 2 deletions tornado/test/gen_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,10 +285,10 @@ def setUp(self):
# so we need explicit checks here to make sure the tests run all
# the way through.
self.finished = False
super(GenCoroutineTest, self).setUp()
super().setUp()

def tearDown(self):
super(GenCoroutineTest, self).tearDown()
super().tearDown()
assert self.finished

def test_attributes(self):
Expand Down
Loading

0 comments on commit b3c63fb

Please sign in to comment.