Skip to content

Commit

Permalink
Apply pyupgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
asvetlov committed Oct 25, 2020
1 parent 5b59f2c commit fa56a44
Show file tree
Hide file tree
Showing 51 changed files with 317 additions and 326 deletions.
14 changes: 7 additions & 7 deletions aiohttp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def __init__(
trust_env: bool = False,
requote_redirect_url: bool = True,
trace_configs: Optional[List[TraceConfig]] = None,
read_bufsize: int = 2 ** 16
read_bufsize: int = 2 ** 16,
) -> None:

if loop is None:
Expand Down Expand Up @@ -336,7 +336,7 @@ def __del__(self, _warnings: Any = warnings) -> None:
else:
kwargs = {}
_warnings.warn(
"Unclosed client session {!r}".format(self), ResourceWarning, **kwargs
f"Unclosed client session {self!r}", ResourceWarning, **kwargs
)
context = {"client_session": self, "message": "Unclosed client session"}
if self._source_traceback is not None:
Expand Down Expand Up @@ -377,7 +377,7 @@ async def _request(
ssl: Optional[Union[SSLContext, bool, Fingerprint]] = None,
proxy_headers: Optional[LooseHeaders] = None,
trace_request_ctx: Optional[SimpleNamespace] = None,
read_bufsize: Optional[int] = None
read_bufsize: Optional[int] = None,
) -> ClientResponse:

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

assert conn.transport is not None
Expand Down Expand Up @@ -677,7 +677,7 @@ def ws_connect(
ssl_context: Optional[SSLContext] = None,
proxy_headers: Optional[LooseHeaders] = None,
compress: int = 0,
max_msg_size: int = 4 * 1024 * 1024
max_msg_size: int = 4 * 1024 * 1024,
) -> "_WSRequestContextManager":
"""Initiate websocket connection."""
return _WSRequestContextManager(
Expand Down Expand Up @@ -727,7 +727,7 @@ async def _ws_connect(
ssl_context: Optional[SSLContext] = None,
proxy_headers: Optional[LooseHeaders] = None,
compress: int = 0,
max_msg_size: int = 4 * 1024 * 1024
max_msg_size: int = 4 * 1024 * 1024,
) -> ClientWebSocketResponse:

if headers is None:
Expand Down Expand Up @@ -1207,7 +1207,7 @@ def request(
version: HttpVersion = http.HttpVersion11,
connector: Optional[BaseConnector] = None,
read_bufsize: Optional[int] = None,
loop: Optional[asyncio.AbstractEventLoop] = None
loop: Optional[asyncio.AbstractEventLoop] = None,
) -> _SessionRequestContextManager:
"""Constructs and sends a request. Returns response object.
method - HTTP method
Expand Down
16 changes: 8 additions & 8 deletions aiohttp/client_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def __init__(
code: Optional[int] = None,
status: Optional[int] = None,
message: str = "",
headers: Optional[LooseHeaders] = None
headers: Optional[LooseHeaders] = None,
) -> None:
self.request_info = request_info
if code is not None:
Expand All @@ -90,21 +90,21 @@ def __init__(
self.args = (request_info, history)

def __str__(self) -> str:
return "%s, message=%r, url=%r" % (
return "{}, message={!r}, url={!r}".format(
self.status,
self.message,
self.request_info.real_url,
)

def __repr__(self) -> str:
args = "%r, %r" % (self.request_info, self.history)
args = f"{self.request_info!r}, {self.history!r}"
if self.status != 0:
args += ", status=%r" % (self.status,)
args += f", status={self.status!r}"
if self.message != "":
args += ", message=%r" % (self.message,)
args += f", message={self.message!r}"
if self.headers is not None:
args += ", headers=%r" % (self.headers,)
return "%s(%s)" % (type(self).__name__, args)
args += f", headers={self.headers!r}"
return "{}({})".format(type(self).__name__, args)

@property
def code(self) -> int:
Expand Down Expand Up @@ -257,7 +257,7 @@ def url(self) -> Any:
return self.args[0]

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


class ClientSSLError(ClientConnectorError):
Expand Down
18 changes: 8 additions & 10 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ def __init__(
session: Optional["ClientSession"] = None,
ssl: Union[SSLContext, bool, Fingerprint, None] = None,
proxy_headers: Optional[LooseHeaders] = None,
traces: Optional[List["Trace"]] = None
traces: Optional[List["Trace"]] = None,
):

if loop is None:
Expand Down Expand Up @@ -381,7 +381,7 @@ def update_version(self, version: Union[http.HttpVersion, str]) -> None:
version = http.HttpVersion(int(v[0]), int(v[1]))
except ValueError:
raise ValueError(
"Can not parse http version number: {}".format(version)
f"Can not parse http version number: {version}"
) from None
self.version = version

Expand All @@ -392,7 +392,7 @@ def update_headers(self, headers: Optional[LooseHeaders]) -> None:
# add host
netloc = cast(str, self.url.raw_host)
if helpers.is_ipv6_address(netloc):
netloc = "[{}]".format(netloc)
netloc = f"[{netloc}]"
if self.url.port is not None and not self.url.is_default_port():
netloc += ":" + str(self.url.port)
self.headers[hdrs.HOST] = netloc
Expand Down Expand Up @@ -615,8 +615,8 @@ async def send(self, conn: "Connection") -> "ClientResponse":
connect_host = self.url.raw_host
assert connect_host is not None
if helpers.is_ipv6_address(connect_host):
connect_host = "[{}]".format(connect_host)
path = "{}:{}".format(connect_host, self.url.port)
connect_host = f"[{connect_host}]"
path = f"{connect_host}:{self.url.port}"
elif self.proxy and not self.is_ssl():
path = str(self.url)
else:
Expand Down Expand Up @@ -731,7 +731,7 @@ def __init__(
request_info: RequestInfo,
traces: List["Trace"],
loop: asyncio.AbstractEventLoop,
session: "ClientSession"
session: "ClientSession",
) -> None:
assert isinstance(url, URL)

Expand Down Expand Up @@ -808,9 +808,7 @@ def __del__(self, _warnings: Any = warnings) -> None:
kwargs = {"source": self}
else:
kwargs = {}
_warnings.warn(
"Unclosed response {!r}".format(self), ResourceWarning, **kwargs
)
_warnings.warn(f"Unclosed response {self!r}", ResourceWarning, **kwargs)
context = {"client_response": self, "message": "Unclosed response"}
if self._source_traceback:
context["source_traceback"] = self._source_traceback
Expand Down Expand Up @@ -1087,7 +1085,7 @@ async def json(
*,
encoding: Optional[str] = None,
loads: JSONDecoder = DEFAULT_JSON_DECODER,
content_type: Optional[str] = "application/json"
content_type: Optional[str] = "application/json",
) -> Any:
"""Read and decodes JSON response."""
if self._body is None:
Expand Down
14 changes: 5 additions & 9 deletions aiohttp/client_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(
receive_timeout: Optional[float] = None,
heartbeat: Optional[float] = None,
compress: int = 0,
client_notakeover: bool = False
client_notakeover: bool = False,
) -> None:
self._response = response
self._conn = response.connection
Expand Down Expand Up @@ -159,7 +159,7 @@ async def send_json(
data: Any,
compress: Optional[int] = None,
*,
dumps: JSONEncoder = DEFAULT_JSON_ENCODER
dumps: JSONEncoder = DEFAULT_JSON_ENCODER,
) -> None:
await self.send_str(dumps(data), compress=compress)

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

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

async def receive_json(
self,
*,
loads: JSONDecoder = DEFAULT_JSON_DECODER,
timeout: Optional[float] = None
timeout: Optional[float] = None,
) -> Any:
data = await self.receive_str(timeout=timeout)
return loads(data)
Expand Down
20 changes: 8 additions & 12 deletions aiohttp/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,17 +109,15 @@ def __init__(
self._source_traceback = traceback.extract_stack(sys._getframe(1))

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

def __del__(self, _warnings: Any = warnings) -> None:
if self._protocol is not None:
if PY_36:
kwargs = {"source": self}
else:
kwargs = {}
_warnings.warn(
"Unclosed connection {!r}".format(self), ResourceWarning, **kwargs
)
_warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs)
if self._loop.is_closed():
return

Expand Down Expand Up @@ -213,7 +211,7 @@ def __init__(
limit: int = 100,
limit_per_host: int = 0,
enable_cleanup_closed: bool = False,
loop: Optional[asyncio.AbstractEventLoop] = None
loop: Optional[asyncio.AbstractEventLoop] = None,
) -> None:

if force_close:
Expand Down Expand Up @@ -276,9 +274,7 @@ def __del__(self, _warnings: Any = warnings) -> None:
kwargs = {"source": self}
else:
kwargs = {}
_warnings.warn(
"Unclosed connector {!r}".format(self), ResourceWarning, **kwargs
)
_warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs)
context = {
"connector": self,
"connections": conns,
Expand Down Expand Up @@ -640,7 +636,7 @@ def _release(
key: "ConnectionKey",
protocol: ResponseHandler,
*,
should_close: bool = False
should_close: bool = False,
) -> None:
if self._closed:
# acquired connection is already released on connector closing
Expand Down Expand Up @@ -757,7 +753,7 @@ def __init__(
limit: int = 100,
limit_per_host: int = 0,
enable_cleanup_closed: bool = False,
loop: Optional[asyncio.AbstractEventLoop] = None
loop: Optional[asyncio.AbstractEventLoop] = None,
):
super().__init__(
keepalive_timeout=keepalive_timeout,
Expand Down Expand Up @@ -968,7 +964,7 @@ async def _wrap_create_connection(
req: "ClientRequest",
timeout: "ClientTimeout",
client_error: Type[Exception] = ClientConnectorError,
**kwargs: Any
**kwargs: Any,
) -> Tuple[asyncio.Transport, ResponseHandler]:
try:
with CeilTimeout(timeout.sock_connect):
Expand All @@ -986,7 +982,7 @@ async def _create_direct_connection(
traces: List["Trace"],
timeout: "ClientTimeout",
*,
client_error: Type[Exception] = ClientConnectorError
client_error: Type[Exception] = ClientConnectorError,
) -> Tuple[asyncio.Transport, ResponseHandler]:
sslcontext = self._get_ssl_context(req)
fingerprint = self._get_fingerprint(req)
Expand Down
2 changes: 1 addition & 1 deletion aiohttp/frozenlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def insert(self, pos, item):
self._items.insert(pos, item)

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


PyFrozenList = FrozenList
Expand Down
8 changes: 4 additions & 4 deletions aiohttp/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ def all_tasks(
) # type: bool


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

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


Expand Down Expand Up @@ -777,4 +777,4 @@ def __bool__(self) -> bool:

def __repr__(self) -> str:
content = ", ".join(map(repr, self._maps))
return "ChainMapProxy({})".format(content)
return f"ChainMapProxy({content})"
8 changes: 4 additions & 4 deletions aiohttp/http_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ def __init__(
self.message = message

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

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


class BadHttpMessage(HttpProcessingError):
Expand Down Expand Up @@ -78,7 +78,7 @@ def __init__(
self, line: str, limit: str = "Unknown", actual_size: str = "Unknown"
) -> None:
super().__init__(
"Got more than %s bytes (%s) when reading %s." % (limit, actual_size, line)
f"Got more than {limit} bytes ({actual_size}) when reading {line}."
)
self.args = (line, limit, actual_size)

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

Expand Down
8 changes: 4 additions & 4 deletions aiohttp/http_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]:
if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES:
raise WebSocketError(
WSCloseCode.PROTOCOL_ERROR,
"Invalid close code: {}".format(close_code),
f"Invalid close code: {close_code}",
)
try:
close_message = payload[2:].decode("utf-8")
Expand All @@ -310,7 +310,7 @@ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]:
elif payload:
raise WebSocketError(
WSCloseCode.PROTOCOL_ERROR,
"Invalid close frame: {} {} {!r}".format(fin, opcode, payload),
f"Invalid close frame: {fin} {opcode} {payload!r}",
)
else:
msg = WSMessage(WSMsgType.CLOSE, 0, "")
Expand All @@ -332,7 +332,7 @@ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]:
and self._opcode is None
):
raise WebSocketError(
WSCloseCode.PROTOCOL_ERROR, "Unexpected opcode={!r}".format(opcode)
WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}"
)
else:
# load text/binary
Expand Down Expand Up @@ -577,7 +577,7 @@ def __init__(
limit: int = DEFAULT_LIMIT,
random: Any = random.Random(),
compress: int = 0,
notakeover: bool = False
notakeover: bool = False,
) -> None:
self.protocol = protocol
self.transport = transport
Expand Down
Loading

0 comments on commit fa56a44

Please sign in to comment.