Skip to content

Commit

Permalink
*: Switch from percent formatting to f-strings
Browse files Browse the repository at this point in the history
Automated change using pyupgrade in two passes (once to go from percent
formatting to str.format, then to go from str.format to f-strings),
followed by black.

This left a few uses of str.format for unknown reasons.
  • Loading branch information
bdarnell committed Jun 13, 2024
1 parent 90ae304 commit f7818e7
Show file tree
Hide file tree
Showing 22 changed files with 59 additions and 71 deletions.
2 changes: 1 addition & 1 deletion demos/webspider/webspider.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ async def worker():
try:
await fetch_url(url)
except Exception as e:
print("Exception: %s %s" % (e, url))
print(f"Exception: {e} {url}")
dead.add(url)
finally:
q.task_done()
Expand Down
8 changes: 2 additions & 6 deletions tornado/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -1170,9 +1170,7 @@ def _oauth_signature(
base_elems.append(method.upper())
base_elems.append(normalized_url)
base_elems.append(
"&".join(
"%s=%s" % (k, _oauth_escape(str(v))) for k, v in sorted(parameters.items())
)
"&".join(f"{k}={_oauth_escape(str(v))}" for k, v in sorted(parameters.items()))
)
base_string = "&".join(_oauth_escape(e) for e in base_elems)

Expand Down Expand Up @@ -1203,9 +1201,7 @@ def _oauth10a_signature(
base_elems.append(method.upper())
base_elems.append(normalized_url)
base_elems.append(
"&".join(
"%s=%s" % (k, _oauth_escape(str(v))) for k, v in sorted(parameters.items())
)
"&".join(f"{k}={_oauth_escape(str(v))}" for k, v in sorted(parameters.items()))
)

base_string = "&".join(_oauth_escape(e) for e in base_elems)
Expand Down
2 changes: 1 addition & 1 deletion tornado/escape.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ def make_link(m: typing.Match) -> str:
# have a status bar, such as Safari by default)
params += ' title="%s"' % href

return '<a href="%s"%s>%s</a>' % (href, params, url)
return f'<a href="{href}"{params}>{url}</a>'

# First HTML-escape so that our strings are all safe.
# The regex is modified to avoid character entites other than &amp; so
Expand Down
2 changes: 1 addition & 1 deletion tornado/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -874,7 +874,7 @@ def _(asyncio_future):
elif isawaitable(yielded):
return _wrap_awaitable(yielded) # type: ignore
else:
raise BadYieldError("yielded unknown object %r" % (yielded,))
raise BadYieldError(f"yielded unknown object {yielded!r}")


convert_yielded = singledispatch(convert_yielded)
2 changes: 1 addition & 1 deletion tornado/http1connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ def write_headers(
if self.is_client:
assert isinstance(start_line, httputil.RequestStartLine)
self._request_start_line = start_line
lines.append(utf8("%s %s HTTP/1.1" % (start_line[0], start_line[1])))
lines.append(utf8(f"{start_line[0]} {start_line[1]} HTTP/1.1"))
# Client requests with a non-empty body must have either a
# Content-Length or a Transfer-Encoding. If Content-Length is not
# present we'll add our Transfer-Encoding below.
Expand Down
2 changes: 1 addition & 1 deletion tornado/httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ def rethrow(self) -> None:

def __repr__(self) -> str:
args = ",".join("%s=%r" % i for i in sorted(self.__dict__.items()))
return "%s(%s)" % (self.__class__.__name__, args)
return f"{self.__class__.__name__}({args})"


class HTTPClientError(Exception):
Expand Down
10 changes: 5 additions & 5 deletions tornado/httputil.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def copy(self) -> "HTTPHeaders":
def __str__(self) -> str:
lines = []
for name, value in self.get_all():
lines.append("%s: %s\n" % (name, value))
lines.append(f"{name}: {value}\n")
return "".join(lines)

__unicode__ = __str__
Expand Down Expand Up @@ -471,8 +471,8 @@ def _parse_body(self) -> None:

def __repr__(self) -> str:
attrs = ("protocol", "host", "method", "uri", "version", "remote_ip")
args = ", ".join(["%s=%r" % (n, getattr(self, n)) for n in attrs])
return "%s(%s)" % (self.__class__.__name__, args)
args = ", ".join([f"{n}={getattr(self, n)!r}" for n in attrs])
return f"{self.__class__.__name__}({args})"


class HTTPInputError(Exception):
Expand Down Expand Up @@ -741,7 +741,7 @@ def _get_content_range(start: Optional[int], end: Optional[int], total: int) ->
"""
start = start or 0
end = (end or total) - 1
return "bytes %s-%s/%s" % (start, end, total)
return f"bytes {start}-{end}/{total}"


def _int_or_none(val: str) -> Optional[int]:
Expand Down Expand Up @@ -1008,7 +1008,7 @@ def _encode_header(key: str, pdict: Dict[str, str]) -> str:
out.append(k)
else:
# TODO: quote if necessary.
out.append("%s=%s" % (k, v))
out.append(f"{k}={v}")
return "; ".join(out)


Expand Down
6 changes: 3 additions & 3 deletions tornado/locale.py
Original file line number Diff line number Diff line change
Expand Up @@ -569,8 +569,8 @@ def pgettext(
if plural_message is not None:
assert count is not None
msgs_with_ctxt = (
"%s%s%s" % (context, CONTEXT_SEPARATOR, message),
"%s%s%s" % (context, CONTEXT_SEPARATOR, plural_message),
f"{context}{CONTEXT_SEPARATOR}{message}",
f"{context}{CONTEXT_SEPARATOR}{plural_message}",
count,
)
result = self.ngettext(*msgs_with_ctxt)
Expand All @@ -579,7 +579,7 @@ def pgettext(
result = self.ngettext(message, plural_message, count)
return result
else:
msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message)
msg_with_ctxt = f"{context}{CONTEXT_SEPARATOR}{message}"
result = self.gettext(msg_with_ctxt)
if CONTEXT_SEPARATOR in result:
# Translation not found
Expand Down
14 changes: 6 additions & 8 deletions tornado/locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ async def runner():
"""

def __repr__(self) -> str:
result = "<%s" % (self.__class__.__name__,)
result = f"<{self.__class__.__name__}"
if self._waiters:
result += " waiters[%s]" % len(self._waiters)
return result + ">"
Expand Down Expand Up @@ -200,7 +200,7 @@ def __init__(self) -> None:
self._waiters = set() # type: Set[Future[None]]

def __repr__(self) -> str:
return "<%s %s>" % (
return "<{} {}>".format(
self.__class__.__name__,
"set" if self.is_set() else "clear",
)
Expand Down Expand Up @@ -389,12 +389,10 @@ def __init__(self, value: int = 1) -> None:

def __repr__(self) -> str:
res = super().__repr__()
extra = (
"locked" if self._value == 0 else "unlocked,value:{0}".format(self._value)
)
extra = "locked" if self._value == 0 else f"unlocked,value:{self._value}"
if self._waiters:
extra = "{0},waiters:{1}".format(extra, len(self._waiters))
return "<{0} [{1}]>".format(res[1:-1], extra)
extra = f"{extra},waiters:{len(self._waiters)}"
return f"<{res[1:-1]} [{extra}]>"

def release(self) -> None:
"""Increment the counter and wake one waiter."""
Expand Down Expand Up @@ -525,7 +523,7 @@ def __init__(self) -> None:
self._block = BoundedSemaphore(value=1)

def __repr__(self) -> str:
return "<%s _block=%s>" % (self.__class__.__name__, self._block)
return f"<{self.__class__.__name__} _block={self._block}>"

def acquire(
self, timeout: Optional[Union[float, datetime.timedelta]] = None
Expand Down
2 changes: 1 addition & 1 deletion tornado/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def format(self, record: Any) -> str:
# byte strings wherever possible).
record.message = _safe_unicode(message)
except Exception as e:
record.message = "Bad message (%r): %r" % (e, record.__dict__)
record.message = f"Bad message ({e!r}): {record.__dict__!r}"

record.asctime = self.formatTime(record, cast(str, self.datefmt))

Expand Down
6 changes: 3 additions & 3 deletions tornado/queues.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,13 +328,13 @@ def _consume_expired(self) -> None:
self._getters.popleft()

def __repr__(self) -> str:
return "<%s at %s %s>" % (type(self).__name__, hex(id(self)), self._format())
return f"<{type(self).__name__} at {hex(id(self))} {self._format()}>"

def __str__(self) -> str:
return "<%s %s>" % (type(self).__name__, self._format())
return f"<{type(self).__name__} {self._format()}>"

def _format(self) -> str:
result = "maxsize=%r" % (self.maxsize,)
result = f"maxsize={self.maxsize!r}"
if getattr(self, "_queue", None):
result += " queue=%r" % self._queue
if self._getters:
Expand Down
4 changes: 2 additions & 2 deletions tornado/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ def reverse(self, *args: Any) -> Optional[str]:
return self.matcher.reverse(*args)

def __repr__(self) -> str:
return "%s(%r, %s, kwargs=%r, name=%r)" % (
return "{}({!r}, {}, kwargs={!r}, name={!r})".format(
self.__class__.__name__,
self.matcher,
self.target,
Expand Down Expand Up @@ -686,7 +686,7 @@ def __init__(
self.kwargs = kwargs

def __repr__(self) -> str:
return "%s(%r, %s, kwargs=%r, name=%r)" % (
return "{}({!r}, {}, kwargs={!r}, name={!r})".format(
self.__class__.__name__,
self.regex.pattern,
self.handler_class,
Expand Down
8 changes: 4 additions & 4 deletions tornado/simple_httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def _on_timeout(self, key: object, info: Optional[str] = None) -> None:
request, callback, timeout_handle = self.waiting[key]
self.queue.remove((key, request, callback))

error_message = "Timeout {0}".format(info) if info else "Timeout"
error_message = f"Timeout {info}" if info else "Timeout"
timeout_response = HTTPResponse(
request,
599,
Expand Down Expand Up @@ -399,7 +399,7 @@ async def run(self) -> None:
if self.request.user_agent:
self.request.headers["User-Agent"] = self.request.user_agent
elif self.request.headers.get("User-Agent") is None:
self.request.headers["User-Agent"] = "Tornado/{}".format(version)
self.request.headers["User-Agent"] = f"Tornado/{version}"
if not self.request.allow_nonstandard_methods:
# Some HTTP methods nearly always have bodies while others
# almost never do. Fail in this case unless the user has
Expand Down Expand Up @@ -485,7 +485,7 @@ def _on_timeout(self, info: Optional[str] = None) -> None:
:info string key: More detailed timeout information.
"""
self._timeout = None
error_message = "Timeout {0}".format(info) if info else "Timeout"
error_message = f"Timeout {info}" if info else "Timeout"
if self.final_callback is not None:
self._handle_exception(
HTTPTimeoutError, HTTPTimeoutError(error_message), None
Expand Down Expand Up @@ -605,7 +605,7 @@ async def headers_received(
# Reassemble the start line.
self.request.header_callback("%s %s %s\r\n" % first_line)
for k, v in self.headers.get_all():
self.request.header_callback("%s: %s\r\n" % (k, v))
self.request.header_callback(f"{k}: {v}\r\n")
self.request.header_callback("\r\n")

def _should_follow_redirect(self) -> bool:
Expand Down
10 changes: 4 additions & 6 deletions tornado/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@ def generate(self, writer: "_CodeWriter") -> None:
self.body.generate(writer)
writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line)
writer.write_line(
"_tt_append(_tt_utf8(%s(%s())))" % (self.method, method_name), self.line
f"_tt_append(_tt_utf8({self.method}({method_name}())))", self.line
)


Expand Down Expand Up @@ -944,12 +944,10 @@ def _parse(
allowed_parents = intermediate_blocks.get(operator)
if allowed_parents is not None:
if not in_block:
reader.raise_parse_error(
"%s outside %s block" % (operator, allowed_parents)
)
reader.raise_parse_error(f"{operator} outside {allowed_parents} block")
if in_block not in allowed_parents:
reader.raise_parse_error(
"%s block cannot be attached to %s block" % (operator, in_block)
f"{operator} block cannot be attached to {in_block} block"
)
body.chunks.append(_IntermediateControlBlock(contents, line))
continue
Expand Down Expand Up @@ -1038,7 +1036,7 @@ def _parse(
elif operator in ("break", "continue"):
if not in_loop:
reader.raise_parse_error(
"%s outside %s block" % (operator, {"for", "while"})
"{} outside {} block".format(operator, {"for", "while"})
)
body.chunks.append(_Statement(contents, line))
continue
Expand Down
12 changes: 4 additions & 8 deletions tornado/test/curl_httpclient_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,9 @@ def get(self):
assert param_dict["nonce"] == nonce
assert param_dict["username"] == self.username
assert param_dict["uri"] == self.request.path
h1 = md5(
utf8("%s:%s:%s" % (self.username, realm, self.password))
).hexdigest()
h2 = md5(
utf8("%s:%s" % (self.request.method, self.request.path))
).hexdigest()
digest = md5(utf8("%s:%s:%s" % (h1, nonce, h2))).hexdigest()
h1 = md5(utf8(f"{self.username}:{realm}:{self.password}")).hexdigest()
h2 = md5(utf8(f"{self.request.method}:{self.request.path}")).hexdigest()
digest = md5(utf8(f"{h1}:{nonce}:{h2}")).hexdigest()
if digest == param_dict["response"]:
self.write("ok")
else:
Expand All @@ -66,7 +62,7 @@ def get(self):
self.set_status(401)
self.set_header(
"WWW-Authenticate",
'Digest realm="%s", nonce="%s", opaque="%s"' % (realm, nonce, opaque),
f'Digest realm="{realm}", nonce="{nonce}", opaque="{opaque}"',
)


Expand Down
2 changes: 1 addition & 1 deletion tornado/test/gen_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -853,7 +853,7 @@ def test_already_done(self):
"WaitIterator dict status incorrect",
)
else:
self.fail("got bad WaitIterator index {}".format(dg.current_index))
self.fail(f"got bad WaitIterator index {dg.current_index}")

i += 1
self.assertIsNone(g.current_index, "bad nil current index")
Expand Down
4 changes: 2 additions & 2 deletions tornado/test/httpclient_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def get(self) -> None:
# Triggering the potential bug seems to depend on input length.
# This length is taken from the bad-response example reported in
# https://github.com/tornadoweb/tornado/pull/2875 (uncompressed).
text = "".join("Hello World {}\n".format(i) for i in range(9000))[:149051]
text = "".join(f"Hello World {i}\n" for i in range(9000))[:149051]
body = gzip.compress(text.encode(), compresslevel=6) + b"\00"
self.write(body)

Expand Down Expand Up @@ -701,7 +701,7 @@ def test_response_times(self):
self.assertLess(abs(response.start_time - start_time), 1.0)

for k, v in response.time_info.items():
self.assertTrue(0 <= v < 1.0, "time_info[%s] out of bounds: %s" % (k, v))
self.assertTrue(0 <= v < 1.0, f"time_info[{k}] out of bounds: {v}")

def test_zero_timeout(self):
response = self.fetch("/hello", connect_timeout=0)
Expand Down
2 changes: 1 addition & 1 deletion tornado/test/httpserver_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ def get(self):
def check_type(self, name, obj, expected_type):
actual_type = type(obj)
if expected_type != actual_type:
self.errors[name] = "expected %s, got %s" % (expected_type, actual_type)
self.errors[name] = f"expected {expected_type}, got {actual_type}"


class PostEchoHandler(RequestHandler):
Expand Down
2 changes: 1 addition & 1 deletion tornado/test/simple_httpclient_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def test_header_reuse(self: typing.Any):
def test_default_user_agent(self: typing.Any):
response = self.fetch("/user_agent", method="GET")
self.assertEqual(200, response.code)
self.assertEqual(response.body.decode(), "Tornado/{}".format(version))
self.assertEqual(response.body.decode(), f"Tornado/{version}")

def test_see_other_redirect(self: typing.Any):
for code in (302, 303):
Expand Down
Loading

0 comments on commit f7818e7

Please sign in to comment.