Skip to content

Commit 270ddd3

Browse files
authored
Merge pull request #9404 from jdufresne/mypy-fixup
Handle several mypy TODO comments and exceptions
2 parents f4f35ba + 63ea2e8 commit 270ddd3

File tree

12 files changed

+165
-55
lines changed

12 files changed

+165
-55
lines changed

news/40711960-12d9-4e58-8322-21e5975a804e.trivial.rst

Whitespace-only changes.

setup.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
# The following comment should be removed at some point in the future.
2-
# mypy: disallow-untyped-defs=False
3-
41
import os
52
import sys
63

74
from setuptools import find_packages, setup
85

96

107
def read(rel_path):
8+
# type: (str) -> str
119
here = os.path.abspath(os.path.dirname(__file__))
1210
# intentionally *not* adding an encoding option to open, See:
1311
# https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690
@@ -16,6 +14,7 @@ def read(rel_path):
1614

1715

1816
def get_version(rel_path):
17+
# type: (str) -> str
1918
for line in read(rel_path).splitlines():
2019
if line.startswith('__version__'):
2120
# __version__ = "0.9"

src/pip/_internal/cli/parser.py

+27-5
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,12 @@
11
"""Base option parser setup"""
22

3-
# The following comment should be removed at some point in the future.
4-
# mypy: disallow-untyped-defs=False
5-
63
import logging
74
import optparse
85
import shutil
96
import sys
107
import textwrap
118
from contextlib import suppress
12-
from typing import Any
9+
from typing import Any, Dict, Iterator, List, Tuple
1310

1411
from pip._internal.cli.status_codes import UNKNOWN_ERROR
1512
from pip._internal.configuration import Configuration, ConfigurationError
@@ -22,16 +19,19 @@ class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
2219
"""A prettier/less verbose help formatter for optparse."""
2320

2421
def __init__(self, *args, **kwargs):
22+
# type: (*Any, **Any) -> None
2523
# help position must be aligned with __init__.parseopts.description
2624
kwargs["max_help_position"] = 30
2725
kwargs["indent_increment"] = 1
2826
kwargs["width"] = shutil.get_terminal_size()[0] - 2
2927
super().__init__(*args, **kwargs)
3028

3129
def format_option_strings(self, option):
30+
# type: (optparse.Option) -> str
3231
return self._format_option_strings(option)
3332

3433
def _format_option_strings(self, option, mvarfmt=" <{}>", optsep=", "):
34+
# type: (optparse.Option, str, str) -> str
3535
"""
3636
Return a comma-separated list of option strings and metavars.
3737
@@ -49,17 +49,20 @@ def _format_option_strings(self, option, mvarfmt=" <{}>", optsep=", "):
4949
opts.insert(1, optsep)
5050

5151
if option.takes_value():
52+
assert option.dest is not None
5253
metavar = option.metavar or option.dest.lower()
5354
opts.append(mvarfmt.format(metavar.lower()))
5455

5556
return "".join(opts)
5657

5758
def format_heading(self, heading):
59+
# type: (str) -> str
5860
if heading == "Options":
5961
return ""
6062
return heading + ":\n"
6163

6264
def format_usage(self, usage):
65+
# type: (str) -> str
6366
"""
6467
Ensure there is only one newline between usage and the first heading
6568
if there is no description.
@@ -68,6 +71,7 @@ def format_usage(self, usage):
6871
return msg
6972

7073
def format_description(self, description):
74+
# type: (str) -> str
7175
# leave full control over description to us
7276
if description:
7377
if hasattr(self.parser, "main"):
@@ -86,13 +90,15 @@ def format_description(self, description):
8690
return ""
8791

8892
def format_epilog(self, epilog):
93+
# type: (str) -> str
8994
# leave full control over epilog to us
9095
if epilog:
9196
return epilog
9297
else:
9398
return ""
9499

95100
def indent_lines(self, text, indent):
101+
# type: (str, str) -> str
96102
new_lines = [indent + line for line in text.split("\n")]
97103
return "\n".join(new_lines)
98104

@@ -107,9 +113,12 @@ class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
107113
"""
108114

109115
def expand_default(self, option):
116+
# type: (optparse.Option) -> str
110117
default_values = None
111118
if self.parser is not None:
119+
assert isinstance(self.parser, ConfigOptionParser)
112120
self.parser._update_defaults(self.parser.defaults)
121+
assert option.dest is not None
113122
default_values = self.parser.defaults.get(option.dest)
114123
help_text = super().expand_default(option)
115124

@@ -129,6 +138,7 @@ def expand_default(self, option):
129138

130139
class CustomOptionParser(optparse.OptionParser):
131140
def insert_option_group(self, idx, *args, **kwargs):
141+
# type: (int, Any, Any) -> optparse.OptionGroup
132142
"""Insert an OptionGroup at a given position."""
133143
group = self.add_option_group(*args, **kwargs)
134144

@@ -139,6 +149,7 @@ def insert_option_group(self, idx, *args, **kwargs):
139149

140150
@property
141151
def option_list_all(self):
152+
# type: () -> List[optparse.Option]
142153
"""Get a list of all options, including those in option groups."""
143154
res = self.option_list[:]
144155
for i in self.option_groups:
@@ -166,18 +177,22 @@ def __init__(
166177
super().__init__(*args, **kwargs)
167178

168179
def check_default(self, option, key, val):
180+
# type: (optparse.Option, str, Any) -> Any
169181
try:
170182
return option.check_value(key, val)
171183
except optparse.OptionValueError as exc:
172184
print(f"An error occurred during configuration: {exc}")
173185
sys.exit(3)
174186

175187
def _get_ordered_configuration_items(self):
188+
# type: () -> Iterator[Tuple[str, Any]]
176189
# Configuration gives keys in an unordered manner. Order them.
177190
override_order = ["global", self.name, ":env:"]
178191

179192
# Pool the options into different groups
180-
section_items = {name: [] for name in override_order}
193+
section_items = {
194+
name: [] for name in override_order
195+
} # type: Dict[str, List[Tuple[str, Any]]]
181196
for section_key, val in self.config.items():
182197
# ignore empty values
183198
if not val:
@@ -197,6 +212,7 @@ def _get_ordered_configuration_items(self):
197212
yield key, val
198213

199214
def _update_defaults(self, defaults):
215+
# type: (Dict[str, Any]) -> Dict[str, Any]
200216
"""Updates the given defaults with values from the config files and
201217
the environ. Does a little special handling for certain types of
202218
options (lists)."""
@@ -215,6 +231,8 @@ def _update_defaults(self, defaults):
215231
if option is None:
216232
continue
217233

234+
assert option.dest is not None
235+
218236
if option.action in ("store_true", "store_false"):
219237
try:
220238
val = strtobool(val)
@@ -240,6 +258,7 @@ def _update_defaults(self, defaults):
240258
val = val.split()
241259
val = [self.check_default(option, key, v) for v in val]
242260
elif option.action == "callback":
261+
assert option.callback is not None
243262
late_eval.add(option.dest)
244263
opt_str = option.get_opt_string()
245264
val = option.convert_value(opt_str, val)
@@ -258,6 +277,7 @@ def _update_defaults(self, defaults):
258277
return defaults
259278

260279
def get_default_values(self):
280+
# type: () -> optparse.Values
261281
"""Overriding to make updating the defaults after instantiation of
262282
the option parser possible, _update_defaults() does the dirty work."""
263283
if not self.process_default_values:
@@ -272,12 +292,14 @@ def get_default_values(self):
272292

273293
defaults = self._update_defaults(self.defaults.copy()) # ours
274294
for option in self._get_all_options():
295+
assert option.dest is not None
275296
default = defaults.get(option.dest)
276297
if isinstance(default, str):
277298
opt_str = option.get_opt_string()
278299
defaults[option.dest] = option.check_value(opt_str, default)
279300
return optparse.Values(defaults)
280301

281302
def error(self, msg):
303+
# type: (str) -> None
282304
self.print_usage(sys.stderr)
283305
self.exit(UNKNOWN_ERROR, f"{msg}\n")

src/pip/_internal/network/auth.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737

3838

3939
def get_keyring_auth(url, username):
40-
# type: (str, str) -> Optional[AuthInfo]
40+
# type: (Optional[str], Optional[str]) -> Optional[AuthInfo]
4141
"""Return the tuple auth for a given url from keyring."""
4242
global keyring
4343
if not url or not keyring:

src/pip/_internal/network/session.py

+49-14
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,15 @@
22
network request configuration and behavior.
33
"""
44

5-
# The following comment should be removed at some point in the future.
6-
# mypy: disallow-untyped-defs=False
5+
# When mypy runs on Windows the call to distro.linux_distribution() is skipped
6+
# resulting in the failure:
7+
#
8+
# error: unused 'type: ignore' comment
9+
#
10+
# If the upstream module adds typing, this comment should be removed. See
11+
# https://github.com/nir0s/distro/pull/269
12+
#
13+
# mypy: warn-unused-ignores=False
714

815
import email.utils
916
import ipaddress
@@ -15,13 +22,14 @@
1522
import sys
1623
import urllib.parse
1724
import warnings
18-
from typing import Any, Iterator, List, Optional, Sequence, Tuple, Union
25+
from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union
1926

2027
from pip._vendor import requests, urllib3
2128
from pip._vendor.cachecontrol import CacheControlAdapter
2229
from pip._vendor.requests.adapters import BaseAdapter, HTTPAdapter
23-
from pip._vendor.requests.models import Response
30+
from pip._vendor.requests.models import PreparedRequest, Response
2431
from pip._vendor.requests.structures import CaseInsensitiveDict
32+
from pip._vendor.urllib3.connectionpool import ConnectionPool
2533
from pip._vendor.urllib3.exceptions import InsecureRequestWarning
2634

2735
from pip import __version__
@@ -89,6 +97,7 @@ def looks_like_ci():
8997

9098

9199
def user_agent():
100+
# type: () -> str
92101
"""
93102
Return a string representing the user agent.
94103
"""
@@ -98,15 +107,14 @@ def user_agent():
98107
"implementation": {
99108
"name": platform.python_implementation(),
100109
},
101-
}
110+
} # type: Dict[str, Any]
102111

103112
if data["implementation"]["name"] == 'CPython':
104113
data["implementation"]["version"] = platform.python_version()
105114
elif data["implementation"]["name"] == 'PyPy':
106-
if sys.pypy_version_info.releaselevel == 'final':
107-
pypy_version_info = sys.pypy_version_info[:3]
108-
else:
109-
pypy_version_info = sys.pypy_version_info
115+
pypy_version_info = sys.pypy_version_info # type: ignore
116+
if pypy_version_info.releaselevel == 'final':
117+
pypy_version_info = pypy_version_info[:3]
110118
data["implementation"]["version"] = ".".join(
111119
[str(x) for x in pypy_version_info]
112120
)
@@ -119,9 +127,12 @@ def user_agent():
119127

120128
if sys.platform.startswith("linux"):
121129
from pip._vendor import distro
130+
131+
# https://github.com/nir0s/distro/pull/269
132+
linux_distribution = distro.linux_distribution() # type: ignore
122133
distro_infos = dict(filter(
123134
lambda x: x[1],
124-
zip(["name", "version", "id"], distro.linux_distribution()),
135+
zip(["name", "version", "id"], linux_distribution),
125136
))
126137
libc = dict(filter(
127138
lambda x: x[1],
@@ -170,8 +181,16 @@ def user_agent():
170181

171182
class LocalFSAdapter(BaseAdapter):
172183

173-
def send(self, request, stream=None, timeout=None, verify=None, cert=None,
174-
proxies=None):
184+
def send(
185+
self,
186+
request, # type: PreparedRequest
187+
stream=False, # type: bool
188+
timeout=None, # type: Optional[Union[float, Tuple[float, float]]]
189+
verify=True, # type: Union[bool, str]
190+
cert=None, # type: Optional[Union[str, Tuple[str, str]]]
191+
proxies=None, # type:Optional[Mapping[str, str]]
192+
):
193+
# type: (...) -> Response
175194
pathname = url_to_path(request.url)
176195

177196
resp = Response()
@@ -198,18 +217,33 @@ def send(self, request, stream=None, timeout=None, verify=None, cert=None,
198217
return resp
199218

200219
def close(self):
220+
# type: () -> None
201221
pass
202222

203223

204224
class InsecureHTTPAdapter(HTTPAdapter):
205225

206-
def cert_verify(self, conn, url, verify, cert):
226+
def cert_verify(
227+
self,
228+
conn, # type: ConnectionPool
229+
url, # type: str
230+
verify, # type: Union[bool, str]
231+
cert, # type: Optional[Union[str, Tuple[str, str]]]
232+
):
233+
# type: (...) -> None
207234
super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
208235

209236

210237
class InsecureCacheControlAdapter(CacheControlAdapter):
211238

212-
def cert_verify(self, conn, url, verify, cert):
239+
def cert_verify(
240+
self,
241+
conn, # type: ConnectionPool
242+
url, # type: str
243+
verify, # type: Union[bool, str]
244+
cert, # type: Optional[Union[str, Tuple[str, str]]]
245+
):
246+
# type: (...) -> None
213247
super().cert_verify(conn=conn, url=url, verify=False, cert=cert)
214248

215249

@@ -407,6 +441,7 @@ def is_secure_origin(self, location):
407441
return False
408442

409443
def request(self, method, url, *args, **kwargs):
444+
# type: (str, str, *Any, **Any) -> Response
410445
# Allow setting a default timeout on a session
411446
kwargs.setdefault("timeout", self.timeout)
412447

src/pip/_internal/resolution/legacy/resolver.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,12 @@
1212

1313
# The following comment should be removed at some point in the future.
1414
# mypy: strict-optional=False
15-
# mypy: disallow-untyped-defs=False
1615

1716
import logging
1817
import sys
1918
from collections import defaultdict
2019
from itertools import chain
21-
from typing import DefaultDict, List, Optional, Set, Tuple
20+
from typing import DefaultDict, Iterable, List, Optional, Set, Tuple
2221

2322
from pip._vendor.packaging import specifiers
2423
from pip._vendor.pkg_resources import Distribution
@@ -388,6 +387,7 @@ def _resolve_one(
388387
more_reqs = [] # type: List[InstallRequirement]
389388

390389
def add_req(subreq, extras_requested):
390+
# type: (Distribution, Iterable[str]) -> None
391391
sub_install_req = self._make_install_req(
392392
str(subreq),
393393
req_to_install,
@@ -447,6 +447,7 @@ def get_installation_order(self, req_set):
447447
ordered_reqs = set() # type: Set[InstallRequirement]
448448

449449
def schedule(req):
450+
# type: (InstallRequirement) -> None
450451
if req.satisfied_by or req in ordered_reqs:
451452
return
452453
if req.constraint:

src/pip/_internal/utils/compat.py

-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
"""Stuff that differs in different Python versions and platform
22
distributions."""
33

4-
# The following comment should be removed at some point in the future.
5-
# mypy: disallow-untyped-defs=False
6-
74
import logging
85
import os
96
import sys

0 commit comments

Comments
 (0)