Skip to content

Commit

Permalink
Convert type comments to type annotations (#6412)
Browse files Browse the repository at this point in the history
  • Loading branch information
asvetlov committed Dec 13, 2021
1 parent 535c58e commit 3001f96
Show file tree
Hide file tree
Showing 34 changed files with 240 additions and 256 deletions.
2 changes: 1 addition & 1 deletion aiohttp/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ class AbstractStreamWriter(ABC):

buffer_size = 0
output_size = 0
length = 0 # type: Optional[int]
length: Optional[int] = 0

@abstractmethod
async def write(self, chunk: bytes) -> None:
Expand Down
6 changes: 3 additions & 3 deletions aiohttp/base_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ class BaseProtocol(asyncio.Protocol):
)

def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop = loop # type: asyncio.AbstractEventLoop
self._loop: asyncio.AbstractEventLoop = loop
self._paused = False
self._drain_waiter = None # type: Optional[asyncio.Future[None]]
self._drain_waiter: Optional[asyncio.Future[None]] = None
self._connection_lost = False
self._reading_paused = False

self.transport = None # type: Optional[asyncio.Transport]
self.transport: Optional[asyncio.Transport] = None

def pause_writing(self) -> None:
assert not self._paused
Expand Down
18 changes: 9 additions & 9 deletions aiohttp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ def __init__(
if cookies is not None:
self._cookie_jar.update_cookies(cookies)

self._connector = connector # type: Optional[BaseConnector]
self._connector: Optional[BaseConnector] = connector
self._connector_owner = connector_owner
self._default_auth = auth
self._version = version
Expand Down Expand Up @@ -295,10 +295,10 @@ def __init__(

# Convert to list of tuples
if headers:
real_headers = CIMultiDict(headers) # type: CIMultiDict[str]
real_headers: CIMultiDict[str] = CIMultiDict(headers)
else:
real_headers = CIMultiDict()
self._default_headers = real_headers # type: CIMultiDict[str]
self._default_headers: CIMultiDict[str] = real_headers
if skip_auto_headers is not None:
self._skip_auto_headers = frozenset(istr(i) for i in skip_auto_headers)
else:
Expand Down Expand Up @@ -435,7 +435,7 @@ async def _request(
raise InvalidURL(proxy) from e

if timeout is sentinel:
real_timeout = self._timeout # type: ClientTimeout
real_timeout: ClientTimeout = self._timeout
else:
if not isinstance(timeout, ClientTimeout):
real_timeout = ClientTimeout(total=timeout) # type: ignore[arg-type]
Expand Down Expand Up @@ -746,7 +746,7 @@ async def _ws_connect(
) -> ClientWebSocketResponse:

if headers is None:
real_headers = CIMultiDict() # type: CIMultiDict[str]
real_headers: CIMultiDict[str] = CIMultiDict()
else:
real_headers = CIMultiDict(headers)

Expand Down Expand Up @@ -865,9 +865,9 @@ async def _ws_connect(
assert conn_proto is not None
transport = conn.transport
assert transport is not None
reader = FlowControlDataQueue(
reader: FlowControlDataQueue[WSMessage] = FlowControlDataQueue(
conn_proto, 2 ** 16, loop=self._loop
) # type: FlowControlDataQueue[WSMessage]
)
conn_proto.set_parser(WebSocketReader(reader, max_msg_size), reader)
writer = WebSocketWriter(
conn_proto,
Expand Down Expand Up @@ -902,7 +902,7 @@ def _prepare_headers(self, headers: Optional[LooseHeaders]) -> "CIMultiDict[str]
if headers:
if not isinstance(headers, (MultiDictProxy, MultiDict)):
headers = CIMultiDict(headers)
added_names = set() # type: Set[str]
added_names: Set[str] = set()
for key, value in headers.items():
if key in added_names:
result.add(key, value)
Expand Down Expand Up @@ -1178,7 +1178,7 @@ def __init__(
session: ClientSession,
) -> None:
self._coro = coro
self._resp = None # type: Optional[ClientResponse]
self._resp: Optional[ClientResponse] = None
self._session = session

async def __aenter__(self) -> ClientResponse:
Expand Down
6 changes: 3 additions & 3 deletions aiohttp/client_proto.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:

self._tail = b""
self._upgraded = False
self._parser = None # type: Optional[HttpResponseParser]
self._parser: Optional[HttpResponseParser] = None

self._read_timeout = None # type: Optional[float]
self._read_timeout_handle = None # type: Optional[asyncio.TimerHandle]
self._read_timeout: Optional[float] = None
self._read_timeout_handle: Optional[asyncio.TimerHandle] = None

@property
def upgraded(self) -> bool:
Expand Down
36 changes: 17 additions & 19 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ def __init__(
real_response_class = ClientResponse
else:
real_response_class = response_class
self.response_class = real_response_class # type: Type[ClientResponse]
self.response_class: Type[ClientResponse] = real_response_class
self._timer = timer if timer is not None else TimerNoop()
self._ssl = ssl

Expand Down Expand Up @@ -329,9 +329,7 @@ def ssl(self) -> Union["SSLContext", None, bool, Fingerprint]:
def connection_key(self) -> ConnectionKey:
proxy_headers = self.proxy_headers
if proxy_headers:
h = hash(
tuple((k, v) for k, v in proxy_headers.items())
) # type: Optional[int]
h: Optional[int] = hash(tuple((k, v) for k, v in proxy_headers.items()))
else:
h = None
return ConnectionKey(
Expand All @@ -356,7 +354,7 @@ def port(self) -> Optional[int]:

@property
def request_info(self) -> RequestInfo:
headers = CIMultiDictProxy(self.headers) # type: CIMultiDictProxy[str]
headers: CIMultiDictProxy[str] = CIMultiDictProxy(self.headers)
return RequestInfo(self.url, self.method, headers, self.original_url)

def update_host(self, url: URL) -> None:
Expand Down Expand Up @@ -387,7 +385,7 @@ def update_version(self, version: Union[http.HttpVersion, str]) -> None:

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

# add host
netloc = cast(str, self.url.raw_host)
Expand Down Expand Up @@ -427,7 +425,7 @@ def update_cookies(self, cookies: Optional[LooseCookies]) -> None:
if not cookies:
return

c = SimpleCookie() # type: SimpleCookie[str]
c: SimpleCookie[str] = SimpleCookie()
if hdrs.COOKIE in self.headers:
c.load(self.headers.get(hdrs.COOKIE, ""))
del self.headers[hdrs.COOKIE]
Expand Down Expand Up @@ -713,12 +711,12 @@ class ClientResponse(HeadersMixin):

# from the Status-Line of the response
version = None # HTTP-Version
status = None # type: int # Status-Code
status: int = None # type: ignore[assignment] # Status-Code
reason = None # Reason-Phrase

content = None # type: StreamReader # Payload stream
_headers = None # type: CIMultiDictProxy[str] # Response headers
_raw_headers = None # type: RawHeaders # Response raw headers
content: StreamReader = None # type: ignore[assignment] # Payload stream
_headers: "CIMultiDictProxy[str]" = None # type: ignore[assignment]
_raw_headers: RawHeaders = None # type: ignore[assignment] # Response raw headers

_connection = None # current connection
_source_traceback = None
Expand All @@ -743,22 +741,22 @@ def __init__(
assert isinstance(url, URL)

self.method = method
self.cookies = SimpleCookie() # type: SimpleCookie[str]
self.cookies: SimpleCookie[str] = SimpleCookie()

self._real_url = url
self._url = url.with_fragment(None)
self._body = None # type: Any
self._writer = writer # type: Optional[asyncio.Task[None]]
self._body: Any = None
self._writer: Optional[asyncio.Task[None]] = writer
self._continue = continue100 # None by default
self._closed = True
self._history = () # type: Tuple[ClientResponse, ...]
self._history: Tuple[ClientResponse, ...] = ()
self._request_info = request_info
self._timer = timer if timer is not None else TimerNoop()
self._cache = {} # type: Dict[str, Any]
self._cache: Dict[str, Any] = {}
self._traces = traces
self._loop = loop
# store a reference to session #1985
self._session = session # type: Optional[ClientSession]
self._session: Optional[ClientSession] = session
if loop.get_debug():
self._source_traceback = traceback.extract_stack(sys._getframe(1))

Expand Down Expand Up @@ -855,7 +853,7 @@ def links(self) -> "MultiDictProxy[MultiDictProxy[Union[str, URL]]]":
if not links_str:
return MultiDictProxy(MultiDict())

links = MultiDict() # type: MultiDict[MultiDictProxy[Union[str, URL]]]
links: MultiDict[MultiDictProxy[Union[str, URL]]] = MultiDict()

for val in re.split(r",(?=\s*<)", links_str):
match = re.match(r"\s*<(.*)>(.*)", val)
Expand All @@ -865,7 +863,7 @@ def links(self) -> "MultiDictProxy[MultiDictProxy[Union[str, URL]]]":
url, params_str = match.groups()
params = params_str.split(";")[1:]

link = MultiDict() # type: MultiDict[Union[str, URL]]
link: MultiDict[Union[str, URL]] = MultiDict()

for param in params:
match = re.match(r"^\s*(\S*)\s*=\s*(['\"]?)(.*?)(\2)\s*$", param, re.M)
Expand Down
6 changes: 3 additions & 3 deletions aiohttp/client_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__(
self._protocol = protocol
self._closed = False
self._closing = False
self._close_code = None # type: Optional[int]
self._close_code: Optional[int] = None
self._timeout = timeout
self._receive_timeout = receive_timeout
self._autoclose = autoclose
Expand All @@ -62,8 +62,8 @@ def __init__(
self._pong_heartbeat = heartbeat / 2.0
self._pong_response_cb: Optional[asyncio.TimerHandle] = None
self._loop = loop
self._waiting = None # type: Optional[asyncio.Future[bool]]
self._exception = None # type: Optional[BaseException]
self._waiting: Optional[asyncio.Future[bool]] = None
self._exception: Optional[BaseException] = None
self._compress = compress
self._client_notakeover = client_notakeover

Expand Down
34 changes: 14 additions & 20 deletions aiohttp/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ def __init__(
self._key = key
self._connector = connector
self._loop = loop
self._protocol = protocol # type: Optional[ResponseHandler]
self._callbacks = [] # type: List[Callable[[], None]]
self._protocol: Optional[ResponseHandler] = protocol
self._callbacks: List[Callable[[], None]] = []

if loop.get_debug():
self._source_traceback = traceback.extract_stack(sys._getframe(1))
Expand Down Expand Up @@ -237,15 +237,13 @@ def __init__(
if loop.get_debug():
self._source_traceback = traceback.extract_stack(sys._getframe(1))

self._conns = (
{}
) # type: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]]
self._conns: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]] = {}
self._limit = limit
self._limit_per_host = limit_per_host
self._acquired = set() # type: Set[ResponseHandler]
self._acquired_per_host = defaultdict(
set
) # type: DefaultDict[ConnectionKey, Set[ResponseHandler]]
self._acquired: Set[ResponseHandler] = set()
self._acquired_per_host: DefaultDict[
ConnectionKey, Set[ResponseHandler]
] = defaultdict(set)
self._keepalive_timeout = cast(float, keepalive_timeout)
self._force_close = force_close

Expand All @@ -255,15 +253,15 @@ def __init__(
self._loop = loop
self._factory = functools.partial(ResponseHandler, loop=loop)

self.cookies = SimpleCookie() # type: SimpleCookie[str]
self.cookies: SimpleCookie[str] = SimpleCookie()

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

# start cleanup closed transports task
self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None
self._cleanup_closed_disabled = not enable_cleanup_closed
self._cleanup_closed_transports = [] # type: List[Optional[asyncio.Transport]]
self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []
self._cleanup_closed()

def __del__(self, _warnings: Any = warnings) -> None:
Expand Down Expand Up @@ -685,10 +683,8 @@ async def _create_connection(

class _DNSCacheTable:
def __init__(self, ttl: Optional[float] = None) -> None:
self._addrs_rr = (
{}
) # type: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]]
self._timestamps = {} # type: Dict[Tuple[str, int], float]
self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]] = {}
self._timestamps: Dict[Tuple[str, int], float] = {}
self._ttl = ttl

def __contains__(self, host: object) -> bool:
Expand Down Expand Up @@ -784,9 +780,7 @@ def __init__(

self._use_dns_cache = use_dns_cache
self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)
self._throttle_dns_events = (
{}
) # type: Dict[Tuple[str, int], EventResultOrError]
self._throttle_dns_events: Dict[Tuple[str, int], EventResultOrError] = {}
self._family = family
self._local_addr = local_addr

Expand Down Expand Up @@ -1165,7 +1159,7 @@ def drop_exception(fut: "asyncio.Future[List[Dict[str, Any]]]") -> None:
# it is problem of resolving proxy ip itself
raise ClientConnectorError(req.connection_key, exc) from exc

last_exc = None # type: Optional[Exception]
last_exc: Optional[Exception] = None

for hinfo in hosts:
host = hinfo["host"]
Expand Down Expand Up @@ -1211,7 +1205,7 @@ async def _create_proxy_connection(
self._fail_on_no_start_tls(req)
runtime_has_start_tls = self._loop_supports_start_tls()

headers = {} # type: Dict[str, str]
headers: Dict[str, str] = {}
if req.proxy_headers is not None:
headers = req.proxy_headers # type: ignore[assignment]
headers[hdrs.HOST] = req.headers[hdrs.HOST]
Expand Down
10 changes: 4 additions & 6 deletions aiohttp/cookiejar.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,8 @@ def __init__(
loop: Optional[asyncio.AbstractEventLoop] = None,
) -> None:
super().__init__(loop=loop)
self._cookies = defaultdict(
SimpleCookie
) # type: DefaultDict[str, SimpleCookie[str]]
self._host_only_cookies = set() # type: Set[Tuple[str, str]]
self._cookies: DefaultDict[str, SimpleCookie[str]] = defaultdict(SimpleCookie)
self._host_only_cookies: Set[Tuple[str, str]] = set()
self._unsafe = unsafe
self._quote_cookie = quote_cookie
if treat_as_secure_origin is None:
Expand All @@ -84,7 +82,7 @@ def __init__(
]
self._treat_as_secure_origin = treat_as_secure_origin
self._next_expiration = next_whole_second()
self._expirations = {} # type: Dict[Tuple[str, str], datetime.datetime]
self._expirations: Dict[Tuple[str, str], datetime.datetime] = {}
# #4515: datetime.max may not be representable on 32-bit platforms
self._max_time = self.MAX_TIME
try:
Expand Down Expand Up @@ -166,7 +164,7 @@ def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> No

for name, cookie in cookies:
if not isinstance(cookie, Morsel):
tmp = SimpleCookie() # type: SimpleCookie[str]
tmp: SimpleCookie[str] = SimpleCookie()
tmp[name] = cookie # type: ignore[assignment]
cookie = tmp[name]

Expand Down
4 changes: 2 additions & 2 deletions aiohttp/formdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __init__(
charset: Optional[str] = None,
) -> None:
self._writer = multipart.MultipartWriter("form-data")
self._fields = [] # type: List[Any]
self._fields: List[Any] = []
self._is_multipart = False
self._is_processed = False
self._quote_fields = quote_fields
Expand Down Expand Up @@ -56,7 +56,7 @@ def add_field(
if filename is None and content_transfer_encoding is None:
filename = name

type_options = MultiDict({"name": name}) # type: MultiDict[str]
type_options: MultiDict[str] = MultiDict({"name": name})
if filename is not None and not isinstance(filename, str):
raise TypeError(
"filename must be an instance of str. " "Got: %s" % filename
Expand Down

0 comments on commit 3001f96

Please sign in to comment.