Skip to content

Commit fa56a44

Browse files
committed
Apply pyupgrade
1 parent 5b59f2c commit fa56a44

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+317
-326
lines changed

aiohttp/client.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ def __init__(
222222
trust_env: bool = False,
223223
requote_redirect_url: bool = True,
224224
trace_configs: Optional[List[TraceConfig]] = None,
225-
read_bufsize: int = 2 ** 16
225+
read_bufsize: int = 2 ** 16,
226226
) -> None:
227227

228228
if loop is None:
@@ -336,7 +336,7 @@ def __del__(self, _warnings: Any = warnings) -> None:
336336
else:
337337
kwargs = {}
338338
_warnings.warn(
339-
"Unclosed client session {!r}".format(self), ResourceWarning, **kwargs
339+
f"Unclosed client session {self!r}", ResourceWarning, **kwargs
340340
)
341341
context = {"client_session": self, "message": "Unclosed client session"}
342342
if self._source_traceback is not None:
@@ -377,7 +377,7 @@ async def _request(
377377
ssl: Optional[Union[SSLContext, bool, Fingerprint]] = None,
378378
proxy_headers: Optional[LooseHeaders] = None,
379379
trace_request_ctx: Optional[SimpleNamespace] = None,
380-
read_bufsize: Optional[int] = None
380+
read_bufsize: Optional[int] = None,
381381
) -> ClientResponse:
382382

383383
# NOTE: timeout clamps existing connect and read timeouts. We cannot
@@ -529,7 +529,7 @@ async def _request(
529529
)
530530
except asyncio.TimeoutError as exc:
531531
raise ServerTimeoutError(
532-
"Connection timeout " "to host {0}".format(url)
532+
"Connection timeout " "to host {}".format(url)
533533
) from exc
534534

535535
assert conn.transport is not None
@@ -677,7 +677,7 @@ def ws_connect(
677677
ssl_context: Optional[SSLContext] = None,
678678
proxy_headers: Optional[LooseHeaders] = None,
679679
compress: int = 0,
680-
max_msg_size: int = 4 * 1024 * 1024
680+
max_msg_size: int = 4 * 1024 * 1024,
681681
) -> "_WSRequestContextManager":
682682
"""Initiate websocket connection."""
683683
return _WSRequestContextManager(
@@ -727,7 +727,7 @@ async def _ws_connect(
727727
ssl_context: Optional[SSLContext] = None,
728728
proxy_headers: Optional[LooseHeaders] = None,
729729
compress: int = 0,
730-
max_msg_size: int = 4 * 1024 * 1024
730+
max_msg_size: int = 4 * 1024 * 1024,
731731
) -> ClientWebSocketResponse:
732732

733733
if headers is None:
@@ -1207,7 +1207,7 @@ def request(
12071207
version: HttpVersion = http.HttpVersion11,
12081208
connector: Optional[BaseConnector] = None,
12091209
read_bufsize: Optional[int] = None,
1210-
loop: Optional[asyncio.AbstractEventLoop] = None
1210+
loop: Optional[asyncio.AbstractEventLoop] = None,
12111211
) -> _SessionRequestContextManager:
12121212
"""Constructs and sends a request. Returns response object.
12131213
method - HTTP method

aiohttp/client_exceptions.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def __init__(
6464
code: Optional[int] = None,
6565
status: Optional[int] = None,
6666
message: str = "",
67-
headers: Optional[LooseHeaders] = None
67+
headers: Optional[LooseHeaders] = None,
6868
) -> None:
6969
self.request_info = request_info
7070
if code is not None:
@@ -90,21 +90,21 @@ def __init__(
9090
self.args = (request_info, history)
9191

9292
def __str__(self) -> str:
93-
return "%s, message=%r, url=%r" % (
93+
return "{}, message={!r}, url={!r}".format(
9494
self.status,
9595
self.message,
9696
self.request_info.real_url,
9797
)
9898

9999
def __repr__(self) -> str:
100-
args = "%r, %r" % (self.request_info, self.history)
100+
args = f"{self.request_info!r}, {self.history!r}"
101101
if self.status != 0:
102-
args += ", status=%r" % (self.status,)
102+
args += f", status={self.status!r}"
103103
if self.message != "":
104-
args += ", message=%r" % (self.message,)
104+
args += f", message={self.message!r}"
105105
if self.headers is not None:
106-
args += ", headers=%r" % (self.headers,)
107-
return "%s(%s)" % (type(self).__name__, args)
106+
args += f", headers={self.headers!r}"
107+
return "{}({})".format(type(self).__name__, args)
108108

109109
@property
110110
def code(self) -> int:
@@ -257,7 +257,7 @@ def url(self) -> Any:
257257
return self.args[0]
258258

259259
def __repr__(self) -> str:
260-
return "<{} {}>".format(self.__class__.__name__, self.url)
260+
return f"<{self.__class__.__name__} {self.url}>"
261261

262262

263263
class ClientSSLError(ClientConnectorError):

aiohttp/client_reqrep.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ def __init__(
267267
session: Optional["ClientSession"] = None,
268268
ssl: Union[SSLContext, bool, Fingerprint, None] = None,
269269
proxy_headers: Optional[LooseHeaders] = None,
270-
traces: Optional[List["Trace"]] = None
270+
traces: Optional[List["Trace"]] = None,
271271
):
272272

273273
if loop is None:
@@ -381,7 +381,7 @@ def update_version(self, version: Union[http.HttpVersion, str]) -> None:
381381
version = http.HttpVersion(int(v[0]), int(v[1]))
382382
except ValueError:
383383
raise ValueError(
384-
"Can not parse http version number: {}".format(version)
384+
f"Can not parse http version number: {version}"
385385
) from None
386386
self.version = version
387387

@@ -392,7 +392,7 @@ def update_headers(self, headers: Optional[LooseHeaders]) -> None:
392392
# add host
393393
netloc = cast(str, self.url.raw_host)
394394
if helpers.is_ipv6_address(netloc):
395-
netloc = "[{}]".format(netloc)
395+
netloc = f"[{netloc}]"
396396
if self.url.port is not None and not self.url.is_default_port():
397397
netloc += ":" + str(self.url.port)
398398
self.headers[hdrs.HOST] = netloc
@@ -615,8 +615,8 @@ async def send(self, conn: "Connection") -> "ClientResponse":
615615
connect_host = self.url.raw_host
616616
assert connect_host is not None
617617
if helpers.is_ipv6_address(connect_host):
618-
connect_host = "[{}]".format(connect_host)
619-
path = "{}:{}".format(connect_host, self.url.port)
618+
connect_host = f"[{connect_host}]"
619+
path = f"{connect_host}:{self.url.port}"
620620
elif self.proxy and not self.is_ssl():
621621
path = str(self.url)
622622
else:
@@ -731,7 +731,7 @@ def __init__(
731731
request_info: RequestInfo,
732732
traces: List["Trace"],
733733
loop: asyncio.AbstractEventLoop,
734-
session: "ClientSession"
734+
session: "ClientSession",
735735
) -> None:
736736
assert isinstance(url, URL)
737737

@@ -808,9 +808,7 @@ def __del__(self, _warnings: Any = warnings) -> None:
808808
kwargs = {"source": self}
809809
else:
810810
kwargs = {}
811-
_warnings.warn(
812-
"Unclosed response {!r}".format(self), ResourceWarning, **kwargs
813-
)
811+
_warnings.warn(f"Unclosed response {self!r}", ResourceWarning, **kwargs)
814812
context = {"client_response": self, "message": "Unclosed response"}
815813
if self._source_traceback:
816814
context["source_traceback"] = self._source_traceback
@@ -1087,7 +1085,7 @@ async def json(
10871085
*,
10881086
encoding: Optional[str] = None,
10891087
loads: JSONDecoder = DEFAULT_JSON_DECODER,
1090-
content_type: Optional[str] = "application/json"
1088+
content_type: Optional[str] = "application/json",
10911089
) -> Any:
10921090
"""Read and decodes JSON response."""
10931091
if self._body is None:

aiohttp/client_ws.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def __init__(
4040
receive_timeout: Optional[float] = None,
4141
heartbeat: Optional[float] = None,
4242
compress: int = 0,
43-
client_notakeover: bool = False
43+
client_notakeover: bool = False,
4444
) -> None:
4545
self._response = response
4646
self._conn = response.connection
@@ -159,7 +159,7 @@ async def send_json(
159159
data: Any,
160160
compress: Optional[int] = None,
161161
*,
162-
dumps: JSONEncoder = DEFAULT_JSON_ENCODER
162+
dumps: JSONEncoder = DEFAULT_JSON_ENCODER,
163163
) -> None:
164164
await self.send_str(dumps(data), compress=compress)
165165

@@ -273,24 +273,20 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
273273
async def receive_str(self, *, timeout: Optional[float] = None) -> str:
274274
msg = await self.receive(timeout)
275275
if msg.type != WSMsgType.TEXT:
276-
raise TypeError(
277-
"Received message {}:{!r} is not str".format(msg.type, msg.data)
278-
)
276+
raise TypeError(f"Received message {msg.type}:{msg.data!r} is not str")
279277
return msg.data
280278

281279
async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:
282280
msg = await self.receive(timeout)
283281
if msg.type != WSMsgType.BINARY:
284-
raise TypeError(
285-
"Received message {}:{!r} is not bytes".format(msg.type, msg.data)
286-
)
282+
raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes")
287283
return msg.data
288284

289285
async def receive_json(
290286
self,
291287
*,
292288
loads: JSONDecoder = DEFAULT_JSON_DECODER,
293-
timeout: Optional[float] = None
289+
timeout: Optional[float] = None,
294290
) -> Any:
295291
data = await self.receive_str(timeout=timeout)
296292
return loads(data)

aiohttp/connector.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -109,17 +109,15 @@ def __init__(
109109
self._source_traceback = traceback.extract_stack(sys._getframe(1))
110110

111111
def __repr__(self) -> str:
112-
return "Connection<{}>".format(self._key)
112+
return f"Connection<{self._key}>"
113113

114114
def __del__(self, _warnings: Any = warnings) -> None:
115115
if self._protocol is not None:
116116
if PY_36:
117117
kwargs = {"source": self}
118118
else:
119119
kwargs = {}
120-
_warnings.warn(
121-
"Unclosed connection {!r}".format(self), ResourceWarning, **kwargs
122-
)
120+
_warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs)
123121
if self._loop.is_closed():
124122
return
125123

@@ -213,7 +211,7 @@ def __init__(
213211
limit: int = 100,
214212
limit_per_host: int = 0,
215213
enable_cleanup_closed: bool = False,
216-
loop: Optional[asyncio.AbstractEventLoop] = None
214+
loop: Optional[asyncio.AbstractEventLoop] = None,
217215
) -> None:
218216

219217
if force_close:
@@ -276,9 +274,7 @@ def __del__(self, _warnings: Any = warnings) -> None:
276274
kwargs = {"source": self}
277275
else:
278276
kwargs = {}
279-
_warnings.warn(
280-
"Unclosed connector {!r}".format(self), ResourceWarning, **kwargs
281-
)
277+
_warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs)
282278
context = {
283279
"connector": self,
284280
"connections": conns,
@@ -640,7 +636,7 @@ def _release(
640636
key: "ConnectionKey",
641637
protocol: ResponseHandler,
642638
*,
643-
should_close: bool = False
639+
should_close: bool = False,
644640
) -> None:
645641
if self._closed:
646642
# acquired connection is already released on connector closing
@@ -757,7 +753,7 @@ def __init__(
757753
limit: int = 100,
758754
limit_per_host: int = 0,
759755
enable_cleanup_closed: bool = False,
760-
loop: Optional[asyncio.AbstractEventLoop] = None
756+
loop: Optional[asyncio.AbstractEventLoop] = None,
761757
):
762758
super().__init__(
763759
keepalive_timeout=keepalive_timeout,
@@ -968,7 +964,7 @@ async def _wrap_create_connection(
968964
req: "ClientRequest",
969965
timeout: "ClientTimeout",
970966
client_error: Type[Exception] = ClientConnectorError,
971-
**kwargs: Any
967+
**kwargs: Any,
972968
) -> Tuple[asyncio.Transport, ResponseHandler]:
973969
try:
974970
with CeilTimeout(timeout.sock_connect):
@@ -986,7 +982,7 @@ async def _create_direct_connection(
986982
traces: List["Trace"],
987983
timeout: "ClientTimeout",
988984
*,
989-
client_error: Type[Exception] = ClientConnectorError
985+
client_error: Type[Exception] = ClientConnectorError,
990986
) -> Tuple[asyncio.Transport, ResponseHandler]:
991987
sslcontext = self._get_ssl_context(req)
992988
fingerprint = self._get_fingerprint(req)

aiohttp/frozenlist.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def insert(self, pos, item):
5858
self._items.insert(pos, item)
5959

6060
def __repr__(self):
61-
return "<FrozenList(frozen={}, {!r})>".format(self._frozen, self._items)
61+
return f"<FrozenList(frozen={self._frozen}, {self._items!r})>"
6262

6363

6464
PyFrozenList = FrozenList

aiohttp/helpers.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,8 @@ def all_tasks(
9494
) # type: bool
9595

9696

97-
CHAR = set(chr(i) for i in range(0, 128))
98-
CTL = set(chr(i) for i in range(0, 32)) | {
97+
CHAR = {chr(i) for i in range(0, 128)}
98+
CTL = {chr(i) for i in range(0, 32)} | {
9999
chr(127),
100100
}
101101
SEPARATORS = {
@@ -184,7 +184,7 @@ def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth"
184184

185185
def encode(self) -> str:
186186
"""Encode credentials."""
187-
creds = ("%s:%s" % (self.login, self.password)).encode(self.encoding)
187+
creds = (f"{self.login}:{self.password}").encode(self.encoding)
188188
return "Basic %s" % base64.b64encode(creds).decode(self.encoding)
189189

190190

@@ -777,4 +777,4 @@ def __bool__(self) -> bool:
777777

778778
def __repr__(self) -> str:
779779
content = ", ".join(map(repr, self._maps))
780-
return "ChainMapProxy({})".format(content)
780+
return f"ChainMapProxy({content})"

aiohttp/http_exceptions.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,10 @@ def __init__(
3535
self.message = message
3636

3737
def __str__(self) -> str:
38-
return "%s, message=%r" % (self.code, self.message)
38+
return f"{self.code}, message={self.message!r}"
3939

4040
def __repr__(self) -> str:
41-
return "<%s: %s>" % (self.__class__.__name__, self)
41+
return f"<{self.__class__.__name__}: {self}>"
4242

4343

4444
class BadHttpMessage(HttpProcessingError):
@@ -78,7 +78,7 @@ def __init__(
7878
self, line: str, limit: str = "Unknown", actual_size: str = "Unknown"
7979
) -> None:
8080
super().__init__(
81-
"Got more than %s bytes (%s) when reading %s." % (limit, actual_size, line)
81+
f"Got more than {limit} bytes ({actual_size}) when reading {line}."
8282
)
8383
self.args = (line, limit, actual_size)
8484

@@ -87,7 +87,7 @@ class InvalidHeader(BadHttpMessage):
8787
def __init__(self, hdr: Union[bytes, str]) -> None:
8888
if isinstance(hdr, bytes):
8989
hdr = hdr.decode("utf-8", "surrogateescape")
90-
super().__init__("Invalid HTTP Header: {}".format(hdr))
90+
super().__init__(f"Invalid HTTP Header: {hdr}")
9191
self.hdr = hdr
9292
self.args = (hdr,)
9393

aiohttp/http_websocket.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]:
298298
if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES:
299299
raise WebSocketError(
300300
WSCloseCode.PROTOCOL_ERROR,
301-
"Invalid close code: {}".format(close_code),
301+
f"Invalid close code: {close_code}",
302302
)
303303
try:
304304
close_message = payload[2:].decode("utf-8")
@@ -310,7 +310,7 @@ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]:
310310
elif payload:
311311
raise WebSocketError(
312312
WSCloseCode.PROTOCOL_ERROR,
313-
"Invalid close frame: {} {} {!r}".format(fin, opcode, payload),
313+
f"Invalid close frame: {fin} {opcode} {payload!r}",
314314
)
315315
else:
316316
msg = WSMessage(WSMsgType.CLOSE, 0, "")
@@ -332,7 +332,7 @@ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]:
332332
and self._opcode is None
333333
):
334334
raise WebSocketError(
335-
WSCloseCode.PROTOCOL_ERROR, "Unexpected opcode={!r}".format(opcode)
335+
WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}"
336336
)
337337
else:
338338
# load text/binary
@@ -577,7 +577,7 @@ def __init__(
577577
limit: int = DEFAULT_LIMIT,
578578
random: Any = random.Random(),
579579
compress: int = 0,
580-
notakeover: bool = False
580+
notakeover: bool = False,
581581
) -> None:
582582
self.protocol = protocol
583583
self.transport = transport

0 commit comments

Comments
 (0)