Skip to content

Commit

Permalink
Merge pull request #3403 from bdarnell/pyupgrade
Browse files Browse the repository at this point in the history
*: Automated changes from pyupgrade
  • Loading branch information
bdarnell authored Jun 25, 2024
2 parents bdfc017 + f7818e7 commit 167d327
Show file tree
Hide file tree
Showing 50 changed files with 235 additions and 256 deletions.
2 changes: 1 addition & 1 deletion demos/chat/chatdemo.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
define("debug", default=True, help="run in debug mode")


class MessageBuffer(object):
class MessageBuffer:
def __init__(self):
# cond is notified whenever the message cache is updated
self.cond = tornado.locks.Condition()
Expand Down
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
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"

[tool.black]
target-version = ['py38', 'py39', 'py310', 'py311', 'py312']

[tool.cibuildwheel]
build = "cp3[89]* cp310* cp311* cp312*"
test-command = "python -m tornado.test"
Expand Down
36 changes: 15 additions & 21 deletions tornado/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class AuthError(Exception):
pass


class OpenIdMixin(object):
class OpenIdMixin:
"""Abstract implementation of OpenID and Attribute Exchange.
Class attributes:
Expand Down Expand Up @@ -147,9 +147,9 @@ async def get_authenticated_user(
"""
handler = cast(RequestHandler, self)
# Verify the OpenID response via direct request to the OP
args = dict(
(k, v[-1]) for k, v in handler.request.arguments.items()
) # type: Dict[str, Union[str, bytes]]
args = {
k: v[-1] for k, v in handler.request.arguments.items()
} # type: Dict[str, Union[str, bytes]]
args["openid.mode"] = "check_authentication"
url = self._OPENID_ENDPOINT # type: ignore
if http_client is None:
Expand Down Expand Up @@ -185,7 +185,7 @@ def _openid_args(
ax_attrs = set(ax_attrs)
required = [] # type: List[str]
if "name" in ax_attrs:
ax_attrs -= set(["name", "firstname", "fullname", "lastname"])
ax_attrs -= {"name", "firstname", "fullname", "lastname"}
required += ["firstname", "fullname", "lastname"]
args.update(
{
Expand Down Expand Up @@ -284,7 +284,7 @@ def get_auth_http_client(self) -> httpclient.AsyncHTTPClient:
return httpclient.AsyncHTTPClient()


class OAuthMixin(object):
class OAuthMixin:
"""Abstract implementation of OAuth 1.0 and 1.0a.
See `TwitterMixin` below for an example implementation.
Expand Down Expand Up @@ -375,9 +375,9 @@ async def get_authenticated_user(
if not request_cookie:
raise AuthError("Missing OAuth request token cookie")
handler.clear_cookie("_oauth_request_token")
cookie_key, cookie_secret = [
cookie_key, cookie_secret = (
base64.b64decode(escape.utf8(i)) for i in request_cookie.split("|")
]
)
if cookie_key != request_key:
raise AuthError("Request token does not match cookie")
token = dict(
Expand Down Expand Up @@ -552,7 +552,7 @@ def get_auth_http_client(self) -> httpclient.AsyncHTTPClient:
return httpclient.AsyncHTTPClient()


class OAuth2Mixin(object):
class OAuth2Mixin:
"""Abstract implementation of OAuth 2.0.
See `FacebookGraphMixin` or `GoogleOAuth2Mixin` below for example
Expand Down Expand Up @@ -632,7 +632,7 @@ async def oauth2_request(
url: str,
access_token: Optional[str] = None,
post_args: Optional[Dict[str, Any]] = None,
**args: Any
**args: Any,
) -> Any:
"""Fetches the given URL auth an OAuth2 access token.
Expand Down Expand Up @@ -761,7 +761,7 @@ async def twitter_request(
path: str,
access_token: Dict[str, Any],
post_args: Optional[Dict[str, Any]] = None,
**args: Any
**args: Any,
) -> Any:
"""Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``
Expand Down Expand Up @@ -1047,9 +1047,7 @@ async def get(self):
"client_secret": client_secret,
}

fields = set(
["id", "name", "first_name", "last_name", "locale", "picture", "link"]
)
fields = {"id", "name", "first_name", "last_name", "locale", "picture", "link"}
if extra_fields:
fields.update(extra_fields)

Expand Down Expand Up @@ -1098,7 +1096,7 @@ async def facebook_request(
path: str,
access_token: Optional[str] = None,
post_args: Optional[Dict[str, Any]] = None,
**args: Any
**args: Any,
) -> Any:
"""Fetches the given relative API path, e.g., "/btaylor/picture"
Expand Down Expand Up @@ -1172,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 @@ -1205,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/curl_httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ def write_function(b: Union[bytes, bytearray]) -> int:
"PUT": pycurl.UPLOAD,
"HEAD": pycurl.NOBODY,
}
custom_methods = set(["DELETE", "OPTIONS", "PATCH"])
custom_methods = {"DELETE", "OPTIONS", "PATCH"}
for o in curl_options.values():
curl.setopt(o, False)
if request.method in curl_options:
Expand Down
6 changes: 2 additions & 4 deletions tornado/escape.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,7 @@ def recursive_unicode(obj: Any) -> Any:
Supports lists, tuples, and dictionaries.
"""
if isinstance(obj, dict):
return dict(
(recursive_unicode(k), recursive_unicode(v)) for (k, v) in obj.items()
)
return {recursive_unicode(k): recursive_unicode(v) for (k, v) in obj.items()}
elif isinstance(obj, list):
return list(recursive_unicode(i) for i in obj)
elif isinstance(obj, tuple):
Expand Down Expand Up @@ -394,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
12 changes: 6 additions & 6 deletions tornado/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def __init__(self, value: Any = None) -> None:
self.args = (value,)


class WaitIterator(object):
class WaitIterator:
"""Provides an iterator to yield the results of awaitables as they finish.
Yielding a set of awaitables like this:
Expand Down Expand Up @@ -362,10 +362,10 @@ def __init__(self, *args: Future, **kwargs: Future) -> None:
raise ValueError("You must provide args or kwargs, not both")

if kwargs:
self._unfinished = dict((f, k) for (k, f) in kwargs.items())
self._unfinished = {f: k for (k, f) in kwargs.items()}
futures = list(kwargs.values()) # type: Sequence[Future]
else:
self._unfinished = dict((f, i) for (i, f) in enumerate(args))
self._unfinished = {f: i for (i, f) in enumerate(args)}
futures = args

self._finished = collections.deque() # type: Deque[Future]
Expand Down Expand Up @@ -668,7 +668,7 @@ def sleep(duration: float) -> "Future[None]":
return f


class _NullFuture(object):
class _NullFuture:
"""_NullFuture resembles a Future that finished with a result of None.
It's not actually a `Future` to avoid depending on a particular event loop.
Expand Down Expand Up @@ -713,7 +713,7 @@ def done(self) -> bool:
"""


class Runner(object):
class Runner:
"""Internal implementation of `tornado.gen.coroutine`.
Maintains information about pending callbacks and their results.
Expand Down 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)
8 changes: 4 additions & 4 deletions tornado/http1connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(self) -> None:
pass


class _ExceptionLoggingContext(object):
class _ExceptionLoggingContext:
"""Used with the ``with`` statement when calling delegate methods to
log any exceptions with the given logger. Any exceptions caught are
converted to _QuietException
Expand All @@ -70,7 +70,7 @@ def __exit__(
raise _QuietException


class HTTP1ConnectionParameters(object):
class HTTP1ConnectionParameters:
"""Parameters for `.HTTP1Connection` and `.HTTP1ServerConnection`."""

def __init__(
Expand Down 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 Expand Up @@ -761,7 +761,7 @@ def on_connection_close(self) -> None:
return self._delegate.on_connection_close()


class HTTP1ServerConnection(object):
class HTTP1ServerConnection:
"""An HTTP/1.x server."""

def __init__(
Expand Down
18 changes: 9 additions & 9 deletions tornado/httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
from typing import Type, Any, Union, Dict, Callable, Optional, cast


class HTTPClient(object):
class HTTPClient:
"""A blocking HTTP client.
This interface is provided to make it easier to share code between
Expand Down Expand Up @@ -89,7 +89,7 @@ class HTTPClient(object):
def __init__(
self,
async_client_class: "Optional[Type[AsyncHTTPClient]]" = None,
**kwargs: Any
**kwargs: Any,
) -> None:
# Initialize self._closed at the beginning of the constructor
# so that an exception raised here doesn't lead to confusing
Expand Down Expand Up @@ -203,7 +203,7 @@ def __new__(cls, force_instance: bool = False, **kwargs: Any) -> "AsyncHTTPClien
instance_cache = cls._async_clients()
if instance_cache is not None and io_loop in instance_cache:
return instance_cache[io_loop]
instance = super(AsyncHTTPClient, cls).__new__(cls, **kwargs) # type: ignore
instance = super().__new__(cls, **kwargs) # type: ignore
# Make sure the instance knows which cache to remove itself from.
# It can't simply call _async_clients() because we may be in
# __new__(AsyncHTTPClient) but instance.__class__ may be
Expand Down Expand Up @@ -250,7 +250,7 @@ def fetch(
self,
request: Union[str, "HTTPRequest"],
raise_error: bool = True,
**kwargs: Any
**kwargs: Any,
) -> "Future[HTTPResponse]":
"""Executes a request, asynchronously returning an `HTTPResponse`.
Expand Down Expand Up @@ -333,10 +333,10 @@ def configure(
AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
"""
super(AsyncHTTPClient, cls).configure(impl, **kwargs)
super().configure(impl, **kwargs)


class HTTPRequest(object):
class HTTPRequest:
"""HTTP client request object."""

_headers = None # type: Union[Dict[str, str], httputil.HTTPHeaders]
Expand Down Expand Up @@ -571,7 +571,7 @@ def body(self, value: Union[bytes, str]) -> None:
self._body = utf8(value)


class HTTPResponse(object):
class HTTPResponse:
"""HTTP Response object.
Attributes:
Expand Down 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 Expand Up @@ -732,7 +732,7 @@ def __str__(self) -> str:
HTTPError = HTTPClientError


class _RequestProxy(object):
class _RequestProxy:
"""Combines an object with a dictionary of defaults.
Used internally by AsyncHTTPClient implementations.
Expand Down
2 changes: 1 addition & 1 deletion tornado/httpserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ def on_connection_close(self) -> None:
del self._chunks


class _HTTPRequestContext(object):
class _HTTPRequestContext:
def __init__(
self,
stream: iostream.IOStream,
Expand Down
Loading

0 comments on commit 167d327

Please sign in to comment.