Skip to content

Commit 7d78fd0

Browse files
asvetlovDreamsorcererpre-commit-ci[bot]
authored
Convert type comments to type annotations (#6410)
Co-authored-by: Sam Bull <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent c3356ac commit 7d78fd0

34 files changed

+252
-265
lines changed

aiohttp/abc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ class AbstractStreamWriter(ABC):
161161

162162
buffer_size = 0
163163
output_size = 0
164-
length = 0 # type: Optional[int]
164+
length: Optional[int] = 0
165165

166166
@abstractmethod
167167
async def write(self, chunk: bytes) -> None:

aiohttp/base_protocol.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@ class BaseProtocol(asyncio.Protocol):
1515
)
1616

1717
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
18-
self._loop = loop # type: asyncio.AbstractEventLoop
18+
self._loop: asyncio.AbstractEventLoop = loop
1919
self._paused = False
20-
self._drain_waiter = None # type: Optional[asyncio.Future[None]]
20+
self._drain_waiter: Optional[asyncio.Future[None]] = None
2121
self._connection_lost = False
2222
self._reading_paused = False
2323

24-
self.transport = None # type: Optional[asyncio.Transport]
24+
self.transport: Optional[asyncio.Transport] = None
2525

2626
def pause_writing(self) -> None:
2727
assert not self._paused

aiohttp/client.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -234,12 +234,12 @@ def __init__(
234234

235235
# Initialize these three attrs before raising any exception,
236236
# they are used in __del__
237-
self._connector = connector # type: Optional[BaseConnector]
237+
self._connector: Optional[BaseConnector] = connector
238238
self._loop = loop
239239
if loop.get_debug():
240-
self._source_traceback = traceback.extract_stack(
241-
sys._getframe(1)
242-
) # type: Optional[traceback.StackSummary]
240+
self._source_traceback: Optional[
241+
traceback.StackSummary
242+
] = traceback.extract_stack(sys._getframe(1))
243243
else:
244244
self._source_traceback = None
245245

@@ -269,10 +269,10 @@ def __init__(
269269

270270
# Convert to list of tuples
271271
if headers:
272-
real_headers = CIMultiDict(headers) # type: CIMultiDict[str]
272+
real_headers: CIMultiDict[str] = CIMultiDict(headers)
273273
else:
274274
real_headers = CIMultiDict()
275-
self._default_headers = real_headers # type: CIMultiDict[str]
275+
self._default_headers: CIMultiDict[str] = real_headers
276276
if skip_auto_headers is not None:
277277
self._skip_auto_headers = frozenset(istr(i) for i in skip_auto_headers)
278278
else:
@@ -741,7 +741,7 @@ async def _ws_connect(
741741
ws_timeout = dataclasses.replace(ws_timeout, ws_receive=receive_timeout)
742742

743743
if headers is None:
744-
real_headers = CIMultiDict() # type: CIMultiDict[str]
744+
real_headers: CIMultiDict[str] = CIMultiDict()
745745
else:
746746
real_headers = CIMultiDict(headers)
747747

@@ -864,9 +864,9 @@ async def _ws_connect(
864864
assert conn_proto is not None
865865
transport = conn.transport
866866
assert transport is not None
867-
reader = FlowControlDataQueue(
867+
reader: FlowControlDataQueue[WSMessage] = FlowControlDataQueue(
868868
conn_proto, 2 ** 16, loop=self._loop
869-
) # type: FlowControlDataQueue[WSMessage]
869+
)
870870
conn_proto.set_parser(WebSocketReader(reader, max_msg_size), reader)
871871
writer = WebSocketWriter(
872872
conn_proto,
@@ -900,7 +900,7 @@ def _prepare_headers(self, headers: Optional[LooseHeaders]) -> "CIMultiDict[str]
900900
if headers:
901901
if not isinstance(headers, (MultiDictProxy, MultiDict)):
902902
headers = CIMultiDict(headers)
903-
added_names = set() # type: Set[str]
903+
added_names: Set[str] = set()
904904
for key, value in headers.items():
905905
if key in added_names:
906906
result.add(key, value)
@@ -1146,7 +1146,7 @@ def __init__(
11461146
session: ClientSession,
11471147
) -> None:
11481148
self._coro = coro
1149-
self._resp = None # type: Optional[ClientResponse]
1149+
self._resp: Optional[ClientResponse] = None
11501150
self._session = session
11511151

11521152
async def __aenter__(self) -> ClientResponse:

aiohttp/client_proto.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,14 @@ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
3131

3232
self._tail = b""
3333
self._upgraded = False
34-
self._parser = None # type: Optional[HttpResponseParser]
34+
self._parser: Optional[HttpResponseParser] = None
3535

36-
self._read_timeout = None # type: Optional[float]
37-
self._read_timeout_handle = None # type: Optional[asyncio.TimerHandle]
36+
self._read_timeout: Optional[float] = None
37+
self._read_timeout_handle: Optional[asyncio.TimerHandle] = None
3838

39-
self._timeout_ceil_threshold = 5 # type: Optional[float]
39+
self._timeout_ceil_threshold: Optional[float] = 5
4040

41-
self.closed = self._loop.create_future() # type: asyncio.Future[None]
41+
self.closed: asyncio.Future[None] = self._loop.create_future()
4242

4343
@property
4444
def upgraded(self) -> bool:

aiohttp/client_reqrep.py

+20-19
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ def __init__(
230230
real_response_class = ClientResponse
231231
else:
232232
real_response_class = response_class
233-
self.response_class = real_response_class # type: Type[ClientResponse]
233+
self.response_class: Type[ClientResponse] = real_response_class
234234
self._timer = timer if timer is not None else TimerNoop()
235235
self._ssl = ssl
236236

@@ -265,9 +265,7 @@ def ssl(self) -> Union["SSLContext", None, bool, Fingerprint]:
265265
def connection_key(self) -> ConnectionKey:
266266
proxy_headers = self.proxy_headers
267267
if proxy_headers:
268-
h = hash(
269-
tuple((k, v) for k, v in proxy_headers.items())
270-
) # type: Optional[int]
268+
h: Optional[int] = hash(tuple((k, v) for k, v in proxy_headers.items()))
271269
else:
272270
h = None
273271
return ConnectionKey(
@@ -292,7 +290,7 @@ def port(self) -> Optional[int]:
292290

293291
@property
294292
def request_info(self) -> RequestInfo:
295-
headers = CIMultiDictProxy(self.headers) # type: CIMultiDictProxy[str]
293+
headers: CIMultiDictProxy[str] = CIMultiDictProxy(self.headers)
296294
return RequestInfo(self.url, self.method, headers, self.original_url)
297295

298296
def update_host(self, url: URL) -> None:
@@ -323,7 +321,7 @@ def update_version(self, version: Union[http.HttpVersion, str]) -> None:
323321

324322
def update_headers(self, headers: Optional[LooseHeaders]) -> None:
325323
"""Update request headers."""
326-
self.headers = CIMultiDict() # type: CIMultiDict[str]
324+
self.headers: CIMultiDict[str] = CIMultiDict()
327325

328326
# add host
329327
netloc = cast(str, self.url.raw_host)
@@ -363,7 +361,7 @@ def update_cookies(self, cookies: Optional[LooseCookies]) -> None:
363361
if not cookies:
364362
return
365363

366-
c = SimpleCookie() # type: SimpleCookie[str]
364+
c: SimpleCookie[str] = SimpleCookie()
367365
if hdrs.COOKIE in self.headers:
368366
c.load(self.headers.get(hdrs.COOKIE, ""))
369367
del self.headers[hdrs.COOKIE]
@@ -652,14 +650,17 @@ async def _on_headers_request_sent(
652650

653651
class ClientResponse(HeadersMixin):
654652

653+
# Some of these attributes are None when created,
654+
# but will be set by the start() method.
655+
# As the end user will likely never see the None values, we cheat the types below.
655656
# from the Status-Line of the response
656657
version = None # HTTP-Version
657-
status = None # type: int # Status-Code
658+
status: int = None # type: ignore[assignment] # Status-Code
658659
reason = None # Reason-Phrase
659660

660-
content = None # type: StreamReader # Payload stream
661-
_headers = None # type: CIMultiDictProxy[str] # Response headers
662-
_raw_headers = None # type: RawHeaders # Response raw headers
661+
content: StreamReader = None # type: ignore[assignment] # Payload stream
662+
_headers: CIMultiDictProxy[str] = None # type: ignore[assignment]
663+
_raw_headers: RawHeaders = None # type: ignore[assignment]
663664

664665
_connection = None # current connection
665666
_source_traceback = None
@@ -685,22 +686,22 @@ def __init__(
685686
super().__init__()
686687

687688
self.method = method
688-
self.cookies = SimpleCookie() # type: SimpleCookie[str]
689+
self.cookies: SimpleCookie[str] = SimpleCookie()
689690

690691
self._real_url = url
691692
self._url = url.with_fragment(None)
692-
self._body = None # type: Optional[bytes]
693-
self._writer = writer # type: Optional[asyncio.Task[None]]
693+
self._body: Optional[bytes] = None
694+
self._writer: Optional[asyncio.Task[None]] = writer
694695
self._continue = continue100 # None by default
695696
self._closed = True
696-
self._history = () # type: Tuple[ClientResponse, ...]
697+
self._history: Tuple[ClientResponse, ...] = ()
697698
self._request_info = request_info
698699
self._timer = timer if timer is not None else TimerNoop()
699-
self._cache = {} # type: Dict[str, Any]
700+
self._cache: Dict[str, Any] = {}
700701
self._traces = traces
701702
self._loop = loop
702703
# store a reference to session #1985
703-
self._session = session # type: Optional[ClientSession]
704+
self._session: Optional[ClientSession] = session
704705
if loop.get_debug():
705706
self._source_traceback = traceback.extract_stack(sys._getframe(1))
706707

@@ -790,7 +791,7 @@ def links(self) -> "MultiDictProxy[MultiDictProxy[Union[str, URL]]]":
790791
if not links_str:
791792
return MultiDictProxy(MultiDict())
792793

793-
links = MultiDict() # type: MultiDict[MultiDictProxy[Union[str, URL]]]
794+
links: MultiDict[MultiDictProxy[Union[str, URL]]] = MultiDict()
794795

795796
for val in re.split(r",(?=\s*<)", links_str):
796797
match = re.match(r"\s*<(.*)>(.*)", val)
@@ -800,7 +801,7 @@ def links(self) -> "MultiDictProxy[MultiDictProxy[Union[str, URL]]]":
800801
url, params_str = match.groups()
801802
params = params_str.split(";")[1:]
802803

803-
link = MultiDict() # type: MultiDict[Union[str, URL]]
804+
link: MultiDict[Union[str, URL]] = MultiDict()
804805

805806
for param in params:
806807
match = re.match(r"^\s*(\S*)\s*=\s*(['\"]?)(.*?)(\2)\s*$", param, re.M)

aiohttp/client_ws.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,8 @@ def __init__(
6363
self._protocol = protocol
6464
self._closed = False
6565
self._closing = False
66-
self._close_code = None # type: Optional[int]
67-
self._timeout = timeout # type: ClientWSTimeout
66+
self._close_code: Optional[int] = None
67+
self._timeout: ClientWSTimeout = timeout
6868
self._autoclose = autoclose
6969
self._autoping = autoping
7070
self._heartbeat = heartbeat
@@ -73,8 +73,8 @@ def __init__(
7373
self._pong_heartbeat = heartbeat / 2.0
7474
self._pong_response_cb: Optional[asyncio.TimerHandle] = None
7575
self._loop = loop
76-
self._waiting = None # type: Optional[asyncio.Future[bool]]
77-
self._exception = None # type: Optional[BaseException]
76+
self._waiting: Optional[asyncio.Future[bool]] = None
77+
self._exception: Optional[BaseException] = None
7878
self._compress = compress
7979
self._client_notakeover = client_notakeover
8080

aiohttp/connector.py

+16-22
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,8 @@ def __init__(
8383
self._key = key
8484
self._connector = connector
8585
self._loop = loop
86-
self._protocol = protocol # type: Optional[ResponseHandler]
87-
self._callbacks = [] # type: List[Callable[[], None]]
86+
self._protocol: Optional[ResponseHandler] = protocol
87+
self._callbacks: List[Callable[[], None]] = []
8888

8989
if loop.get_debug():
9090
self._source_traceback = traceback.extract_stack(sys._getframe(1))
@@ -155,7 +155,7 @@ class _TransportPlaceholder:
155155
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
156156
fut = loop.create_future()
157157
fut.set_result(None)
158-
self.closed = fut # type: asyncio.Future[Optional[Exception]]
158+
self.closed: asyncio.Future[Optional[Exception]] = fut
159159

160160
def close(self) -> None:
161161
pass
@@ -210,15 +210,13 @@ def __init__(
210210
if loop.get_debug():
211211
self._source_traceback = traceback.extract_stack(sys._getframe(1))
212212

213-
self._conns = (
214-
{}
215-
) # type: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]]
213+
self._conns: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]] = {}
216214
self._limit = limit
217215
self._limit_per_host = limit_per_host
218-
self._acquired = set() # type: Set[ResponseHandler]
219-
self._acquired_per_host = defaultdict(
220-
set
221-
) # type: DefaultDict[ConnectionKey, Set[ResponseHandler]]
216+
self._acquired: Set[ResponseHandler] = set()
217+
self._acquired_per_host: DefaultDict[
218+
ConnectionKey, Set[ResponseHandler]
219+
] = defaultdict(set)
222220
self._keepalive_timeout = cast(float, keepalive_timeout)
223221
self._force_close = force_close
224222

@@ -228,15 +226,15 @@ def __init__(
228226
self._loop = loop
229227
self._factory = functools.partial(ResponseHandler, loop=loop)
230228

231-
self.cookies = SimpleCookie() # type: SimpleCookie[str]
229+
self.cookies: SimpleCookie[str] = SimpleCookie()
232230

233231
# start keep-alive connection cleanup task
234232
self._cleanup_handle: Optional[asyncio.TimerHandle] = None
235233

236234
# start cleanup closed transports task
237235
self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None
238236
self._cleanup_closed_disabled = not enable_cleanup_closed
239-
self._cleanup_closed_transports = [] # type: List[Optional[asyncio.Transport]]
237+
self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []
240238
self._cleanup_closed()
241239

242240
def __del__(self, _warnings: Any = warnings) -> None:
@@ -383,7 +381,7 @@ async def close(self) -> None:
383381
logging.error(err_msg)
384382

385383
def _close_immediately(self) -> List["asyncio.Future[None]"]:
386-
waiters = [] # type: List['asyncio.Future[None]']
384+
waiters: List["asyncio.Future[None]"] = []
387385

388386
if self._closed:
389387
return waiters
@@ -667,10 +665,8 @@ async def _create_connection(
667665

668666
class _DNSCacheTable:
669667
def __init__(self, ttl: Optional[float] = None) -> None:
670-
self._addrs_rr = (
671-
{}
672-
) # type: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]]
673-
self._timestamps = {} # type: Dict[Tuple[str, int], float]
668+
self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]] = {}
669+
self._timestamps: Dict[Tuple[str, int], float] = {}
674670
self._ttl = ttl
675671

676672
def __contains__(self, host: object) -> bool:
@@ -768,9 +764,7 @@ def __init__(
768764

769765
self._use_dns_cache = use_dns_cache
770766
self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)
771-
self._throttle_dns_events = (
772-
{}
773-
) # type: Dict[Tuple[str, int], EventResultOrError]
767+
self._throttle_dns_events: Dict[Tuple[str, int], EventResultOrError] = {}
774768
self._family = family
775769
self._local_addr = local_addr
776770

@@ -1107,7 +1101,7 @@ def drop_exception(fut: "asyncio.Future[List[Dict[str, Any]]]") -> None:
11071101
# it is problem of resolving proxy ip itself
11081102
raise ClientConnectorError(req.connection_key, exc) from exc
11091103

1110-
last_exc = None # type: Optional[Exception]
1104+
last_exc: Optional[Exception] = None
11111105

11121106
for hinfo in hosts:
11131107
host = hinfo["host"]
@@ -1149,7 +1143,7 @@ def drop_exception(fut: "asyncio.Future[List[Dict[str, Any]]]") -> None:
11491143
async def _create_proxy_connection(
11501144
self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout"
11511145
) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
1152-
headers = {} # type: Dict[str, str]
1146+
headers: Dict[str, str] = {}
11531147
if req.proxy_headers is not None:
11541148
headers = req.proxy_headers # type: ignore[assignment]
11551149
headers[hdrs.HOST] = req.headers[hdrs.HOST]

aiohttp/cookiejar.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,8 @@ def __init__(
6565
treat_as_secure_origin: Union[StrOrURL, List[StrOrURL], None] = None
6666
) -> None:
6767
self._loop = asyncio.get_running_loop()
68-
self._cookies = defaultdict(
69-
SimpleCookie
70-
) # type: DefaultDict[str, SimpleCookie[str]]
71-
self._host_only_cookies = set() # type: Set[Tuple[str, str]]
68+
self._cookies: DefaultDict[str, SimpleCookie[str]] = defaultdict(SimpleCookie)
69+
self._host_only_cookies: Set[Tuple[str, str]] = set()
7270
self._unsafe = unsafe
7371
self._quote_cookie = quote_cookie
7472
if treat_as_secure_origin is None:
@@ -84,7 +82,7 @@ def __init__(
8482
]
8583
self._treat_as_secure_origin = treat_as_secure_origin
8684
self._next_expiration = next_whole_second()
87-
self._expirations = {} # type: Dict[Tuple[str, str], datetime.datetime]
85+
self._expirations: Dict[Tuple[str, str], datetime.datetime] = {}
8886
# #4515: datetime.max may not be representable on 32-bit platforms
8987
self._max_time = self.MAX_TIME
9088
try:
@@ -166,7 +164,7 @@ def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> No
166164

167165
for name, cookie in cookies:
168166
if not isinstance(cookie, Morsel):
169-
tmp = SimpleCookie() # type: SimpleCookie[str]
167+
tmp: SimpleCookie[str] = SimpleCookie()
170168
tmp[name] = cookie # type: ignore[assignment]
171169
cookie = tmp[name]
172170

0 commit comments

Comments
 (0)