Skip to content

Commit f8a7439

Browse files
authored
Complete type annotations in pip/_internal/network (#10184)
1 parent 0fb0e3b commit f8a7439

File tree

7 files changed

+130
-168
lines changed

7 files changed

+130
-168
lines changed

src/pip/_internal/network/auth.py

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,7 @@
3636
keyring = None
3737

3838

39-
def get_keyring_auth(url, username):
40-
# type: (Optional[str], Optional[str]) -> Optional[AuthInfo]
39+
def get_keyring_auth(url: Optional[str], username: Optional[str]) -> Optional[AuthInfo]:
4140
"""Return the tuple auth for a given url from keyring."""
4241
global keyring
4342
if not url or not keyring:
@@ -71,20 +70,20 @@ def get_keyring_auth(url, username):
7170

7271
class MultiDomainBasicAuth(AuthBase):
7372

74-
def __init__(self, prompting=True, index_urls=None):
75-
# type: (bool, Optional[List[str]]) -> None
73+
def __init__(
74+
self, prompting: bool = True, index_urls: Optional[List[str]] = None
75+
) -> None:
7676
self.prompting = prompting
7777
self.index_urls = index_urls
78-
self.passwords = {} # type: Dict[str, AuthInfo]
78+
self.passwords: Dict[str, AuthInfo] = {}
7979
# When the user is prompted to enter credentials and keyring is
8080
# available, we will offer to save them. If the user accepts,
8181
# this value is set to the credentials they entered. After the
8282
# request authenticates, the caller should call
8383
# ``save_credentials`` to save these.
84-
self._credentials_to_save = None # type: Optional[Credentials]
84+
self._credentials_to_save: Optional[Credentials] = None
8585

86-
def _get_index_url(self, url):
87-
# type: (str) -> Optional[str]
86+
def _get_index_url(self, url: str) -> Optional[str]:
8887
"""Return the original index URL matching the requested URL.
8988
9089
Cached or dynamically generated credentials may work against
@@ -106,9 +105,8 @@ def _get_index_url(self, url):
106105
return u
107106
return None
108107

109-
def _get_new_credentials(self, original_url, allow_netrc=True,
110-
allow_keyring=False):
111-
# type: (str, bool, bool) -> AuthInfo
108+
def _get_new_credentials(self, original_url: str, allow_netrc: bool = True,
109+
allow_keyring: bool = False) -> AuthInfo:
112110
"""Find and return credentials for the specified URL."""
113111
# Split the credentials and netloc from the url.
114112
url, netloc, url_user_password = split_auth_netloc_from_url(
@@ -157,8 +155,9 @@ def _get_new_credentials(self, original_url, allow_netrc=True,
157155

158156
return username, password
159157

160-
def _get_url_and_credentials(self, original_url):
161-
# type: (str) -> Tuple[str, Optional[str], Optional[str]]
158+
def _get_url_and_credentials(
159+
self, original_url: str
160+
) -> Tuple[str, Optional[str], Optional[str]]:
162161
"""Return the credentials to use for the provided URL.
163162
164163
If allowed, netrc and keyring may be used to obtain the
@@ -197,8 +196,7 @@ def _get_url_and_credentials(self, original_url):
197196

198197
return url, username, password
199198

200-
def __call__(self, req):
201-
# type: (Request) -> Request
199+
def __call__(self, req: Request) -> Request:
202200
# Get credentials for this request
203201
url, username, password = self._get_url_and_credentials(req.url)
204202

@@ -215,8 +213,9 @@ def __call__(self, req):
215213
return req
216214

217215
# Factored out to allow for easy patching in tests
218-
def _prompt_for_password(self, netloc):
219-
# type: (str) -> Tuple[Optional[str], Optional[str], bool]
216+
def _prompt_for_password(
217+
self, netloc: str
218+
) -> Tuple[Optional[str], Optional[str], bool]:
220219
username = ask_input(f"User for {netloc}: ")
221220
if not username:
222221
return None, None, False
@@ -227,14 +226,12 @@ def _prompt_for_password(self, netloc):
227226
return username, password, True
228227

229228
# Factored out to allow for easy patching in tests
230-
def _should_save_password_to_keyring(self):
231-
# type: () -> bool
229+
def _should_save_password_to_keyring(self) -> bool:
232230
if not keyring:
233231
return False
234232
return ask("Save credentials to keyring [y/N]: ", ["y", "n"]) == "y"
235233

236-
def handle_401(self, resp, **kwargs):
237-
# type: (Response, **Any) -> Response
234+
def handle_401(self, resp: Response, **kwargs: Any) -> Response:
238235
# We only care about 401 responses, anything else we want to just
239236
# pass through the actual response
240237
if resp.status_code != 401:
@@ -286,16 +283,14 @@ def handle_401(self, resp, **kwargs):
286283

287284
return new_resp
288285

289-
def warn_on_401(self, resp, **kwargs):
290-
# type: (Response, **Any) -> None
286+
def warn_on_401(self, resp: Response, **kwargs: Any) -> None:
291287
"""Response callback to warn about incorrect credentials."""
292288
if resp.status_code == 401:
293289
logger.warning(
294290
'401 Error, Credentials not correct for %s', resp.request.url,
295291
)
296292

297-
def save_credentials(self, resp, **kwargs):
298-
# type: (Response, **Any) -> None
293+
def save_credentials(self, resp: Response, **kwargs: Any) -> None:
299294
"""Response callback to save credentials on success."""
300295
assert keyring is not None, "should never reach here without keyring"
301296
if not keyring:

src/pip/_internal/network/cache.py

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,12 @@
1313
from pip._internal.utils.misc import ensure_dir
1414

1515

16-
def is_from_cache(response):
17-
# type: (Response) -> bool
16+
def is_from_cache(response: Response) -> bool:
1817
return getattr(response, "from_cache", False)
1918

2019

2120
@contextmanager
22-
def suppressed_cache_errors():
23-
# type: () -> Iterator[None]
21+
def suppressed_cache_errors() -> Iterator[None]:
2422
"""If we can't access the cache then we can just skip caching and process
2523
requests as if caching wasn't enabled.
2624
"""
@@ -36,30 +34,26 @@ class SafeFileCache(BaseCache):
3634
not be accessible or writable.
3735
"""
3836

39-
def __init__(self, directory):
40-
# type: (str) -> None
37+
def __init__(self, directory: str) -> None:
4138
assert directory is not None, "Cache directory must not be None."
4239
super().__init__()
4340
self.directory = directory
4441

45-
def _get_cache_path(self, name):
46-
# type: (str) -> str
42+
def _get_cache_path(self, name: str) -> str:
4743
# From cachecontrol.caches.file_cache.FileCache._fn, brought into our
4844
# class for backwards-compatibility and to avoid using a non-public
4945
# method.
5046
hashed = FileCache.encode(name)
5147
parts = list(hashed[:5]) + [hashed]
5248
return os.path.join(self.directory, *parts)
5349

54-
def get(self, key):
55-
# type: (str) -> Optional[bytes]
50+
def get(self, key: str) -> Optional[bytes]:
5651
path = self._get_cache_path(key)
5752
with suppressed_cache_errors():
5853
with open(path, 'rb') as f:
5954
return f.read()
6055

61-
def set(self, key, value):
62-
# type: (str, bytes) -> None
56+
def set(self, key: str, value: bytes) -> None:
6357
path = self._get_cache_path(key)
6458
with suppressed_cache_errors():
6559
ensure_dir(os.path.dirname(path))
@@ -69,8 +63,7 @@ def set(self, key, value):
6963

7064
replace(f.name, path)
7165

72-
def delete(self, key):
73-
# type: (str) -> None
66+
def delete(self, key: str) -> None:
7467
path = self._get_cache_path(key)
7568
with suppressed_cache_errors():
7669
os.remove(path)

src/pip/_internal/network/download.py

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,18 @@
2020
logger = logging.getLogger(__name__)
2121

2222

23-
def _get_http_response_size(resp):
24-
# type: (Response) -> Optional[int]
23+
def _get_http_response_size(resp: Response) -> Optional[int]:
2524
try:
2625
return int(resp.headers['content-length'])
2726
except (ValueError, KeyError, TypeError):
2827
return None
2928

3029

3130
def _prepare_download(
32-
resp, # type: Response
33-
link, # type: Link
34-
progress_bar # type: str
35-
):
36-
# type: (...) -> Iterable[bytes]
31+
resp: Response,
32+
link: Link,
33+
progress_bar: str
34+
) -> Iterable[bytes]:
3735
total_length = _get_http_response_size(resp)
3836

3937
if link.netloc == PyPI.file_storage_domain:
@@ -72,16 +70,14 @@ def _prepare_download(
7270
)(chunks)
7371

7472

75-
def sanitize_content_filename(filename):
76-
# type: (str) -> str
73+
def sanitize_content_filename(filename: str) -> str:
7774
"""
7875
Sanitize the "filename" value from a Content-Disposition header.
7976
"""
8077
return os.path.basename(filename)
8178

8279

83-
def parse_content_disposition(content_disposition, default_filename):
84-
# type: (str, str) -> str
80+
def parse_content_disposition(content_disposition: str, default_filename: str) -> str:
8581
"""
8682
Parse the "filename" value from a Content-Disposition header, and
8783
return the default filename if the result is empty.
@@ -95,8 +91,7 @@ def parse_content_disposition(content_disposition, default_filename):
9591
return filename or default_filename
9692

9793

98-
def _get_http_response_filename(resp, link):
99-
# type: (Response, Link) -> str
94+
def _get_http_response_filename(resp: Response, link: Link) -> str:
10095
"""Get an ideal filename from the given HTTP response, falling back to
10196
the link filename if not provided.
10297
"""
@@ -105,7 +100,7 @@ def _get_http_response_filename(resp, link):
105100
content_disposition = resp.headers.get('content-disposition')
106101
if content_disposition:
107102
filename = parse_content_disposition(content_disposition, filename)
108-
ext = splitext(filename)[1] # type: Optional[str]
103+
ext: Optional[str] = splitext(filename)[1]
109104
if not ext:
110105
ext = mimetypes.guess_extension(
111106
resp.headers.get('content-type', '')
@@ -119,8 +114,7 @@ def _get_http_response_filename(resp, link):
119114
return filename
120115

121116

122-
def _http_get_download(session, link):
123-
# type: (PipSession, Link) -> Response
117+
def _http_get_download(session: PipSession, link: Link) -> Response:
124118
target_url = link.url.split('#', 1)[0]
125119
resp = session.get(target_url, headers=HEADERS, stream=True)
126120
raise_for_status(resp)
@@ -130,15 +124,13 @@ def _http_get_download(session, link):
130124
class Downloader:
131125
def __init__(
132126
self,
133-
session, # type: PipSession
134-
progress_bar, # type: str
135-
):
136-
# type: (...) -> None
127+
session: PipSession,
128+
progress_bar: str,
129+
) -> None:
137130
self._session = session
138131
self._progress_bar = progress_bar
139132

140-
def __call__(self, link, location):
141-
# type: (Link, str) -> Tuple[str, str]
133+
def __call__(self, link: Link, location: str) -> Tuple[str, str]:
142134
"""Download the file given by link into location."""
143135
try:
144136
resp = _http_get_download(self._session, link)
@@ -164,15 +156,15 @@ class BatchDownloader:
164156

165157
def __init__(
166158
self,
167-
session, # type: PipSession
168-
progress_bar, # type: str
169-
):
170-
# type: (...) -> None
159+
session: PipSession,
160+
progress_bar: str,
161+
) -> None:
171162
self._session = session
172163
self._progress_bar = progress_bar
173164

174-
def __call__(self, links, location):
175-
# type: (Iterable[Link], str) -> Iterable[Tuple[Link, Tuple[str, str]]]
165+
def __call__(
166+
self, links: Iterable[Link], location: str
167+
) -> Iterable[Tuple[Link, Tuple[str, str]]]:
176168
"""Download the files given by links into location."""
177169
for link in links:
178170
try:

0 commit comments

Comments
 (0)