Skip to content

Commit 6a6561c

Browse files
committed
Move many type comments to annotations
Use the tool com2ann to automatically convert most type comments to type annotations. Some type comments continue to exist where any work beyond the automatic conversion was required (for example, additional formatting or circular references). For additional information on the com2ann tool, see: https://github.com/ilevkivskyi/com2ann
1 parent c9a07b4 commit 6a6561c

33 files changed

+327
-491
lines changed

news/fb85e56c-2761-4d08-b0c2-8c1130841508.trivial.rst

Whitespace-only changes.

noxfile.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,7 @@ def docs(session: nox.Session) -> None:
123123
session.install("-e", ".")
124124
session.install("-r", REQUIREMENTS["docs"])
125125

126-
def get_sphinx_build_command(kind):
127-
# type: (str) -> List[str]
126+
def get_sphinx_build_command(kind: str) -> List[str]:
128127
# Having the conf.py in the docs/html is weird but needed because we
129128
# can not use a different configuration directory vs source directory
130129
# on RTD currently. So, we'll pass "-c docs/html" here.
@@ -180,8 +179,7 @@ def vendoring(session: nox.Session) -> None:
180179
session.run("vendoring", "sync", ".", "-v")
181180
return
182181

183-
def pinned_requirements(path):
184-
# type: (Path) -> Iterator[Tuple[str, str]]
182+
def pinned_requirements(path: Path) -> Iterator[Tuple[str, str]]:
185183
for line in path.read_text().splitlines(keepends=False):
186184
one, sep, two = line.partition("==")
187185
if not sep:

src/pip/_internal/main.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
from typing import List, Optional
22

33

4-
def main(args=None):
5-
# type: (Optional[List[str]]) -> int
4+
def main(args: Optional[List[str]] = None) -> int:
65
"""This is preserved for old console scripts that may still be referencing
76
it.
87

src/pip/_internal/pyproject.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,14 @@
88
from pip._internal.exceptions import InstallationError
99

1010

11-
def _is_list_of_str(obj):
12-
# type: (Any) -> bool
11+
def _is_list_of_str(obj: Any) -> bool:
1312
return (
1413
isinstance(obj, list) and
1514
all(isinstance(item, str) for item in obj)
1615
)
1716

1817

19-
def make_pyproject_path(unpacked_source_directory):
20-
# type: (str) -> str
18+
def make_pyproject_path(unpacked_source_directory: str) -> str:
2119
return os.path.join(unpacked_source_directory, 'pyproject.toml')
2220

2321

@@ -27,12 +25,11 @@ def make_pyproject_path(unpacked_source_directory):
2725

2826

2927
def load_pyproject_toml(
30-
use_pep517, # type: Optional[bool]
31-
pyproject_toml, # type: str
32-
setup_py, # type: str
33-
req_name # type: str
34-
):
35-
# type: (...) -> Optional[BuildSystemDetails]
28+
use_pep517: Optional[bool],
29+
pyproject_toml: str,
30+
setup_py: str,
31+
req_name: str
32+
) -> Optional[BuildSystemDetails]:
3633
"""Load the pyproject.toml file.
3734
3835
Parameters:
@@ -163,7 +160,7 @@ def load_pyproject_toml(
163160

164161
backend = build_system.get("build-backend")
165162
backend_path = build_system.get("backend-path", [])
166-
check = [] # type: List[str]
163+
check: List[str] = []
167164
if backend is None:
168165
# If the user didn't specify a backend, we assume they want to use
169166
# the setuptools backend. But we can't be sure they have included

src/pip/_internal/self_outdated_check.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,15 @@
2323
logger = logging.getLogger(__name__)
2424

2525

26-
def _get_statefile_name(key):
27-
# type: (str) -> str
26+
def _get_statefile_name(key: str) -> str:
2827
key_bytes = key.encode()
2928
name = hashlib.sha224(key_bytes).hexdigest()
3029
return name
3130

3231

3332
class SelfCheckState:
34-
def __init__(self, cache_dir):
35-
# type: (str) -> None
36-
self.state = {} # type: Dict[str, Any]
33+
def __init__(self, cache_dir: str) -> None:
34+
self.state: Dict[str, Any] = {}
3735
self.statefile_path = None
3836

3937
# Try to load the existing state
@@ -50,12 +48,10 @@ def __init__(self, cache_dir):
5048
pass
5149

5250
@property
53-
def key(self):
54-
# type: () -> str
51+
def key(self) -> str:
5552
return sys.prefix
5653

57-
def save(self, pypi_version, current_time):
58-
# type: (str, datetime.datetime) -> None
54+
def save(self, pypi_version: str, current_time: datetime.datetime) -> None:
5955
# If we do not have a path to cache in, don't bother saving.
6056
if not self.statefile_path:
6157
return
@@ -90,8 +86,7 @@ def save(self, pypi_version, current_time):
9086
pass
9187

9288

93-
def was_installed_by_pip(pkg):
94-
# type: (str) -> bool
89+
def was_installed_by_pip(pkg: str) -> bool:
9590
"""Checks whether pkg was installed by pip
9691
9792
This is used not to display the upgrade message when pip is in fact
@@ -101,8 +96,7 @@ def was_installed_by_pip(pkg):
10196
return dist is not None and "pip" == dist.installer
10297

10398

104-
def pip_self_version_check(session, options):
105-
# type: (PipSession, optparse.Values) -> None
99+
def pip_self_version_check(session: PipSession, options: optparse.Values) -> None:
106100
"""Check for an update for pip.
107101
108102
Limit the frequency of checks to once per week. State is stored either in

src/pip/_internal/utils/filetypes.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,20 @@
66
from pip._internal.utils.misc import splitext
77

88
WHEEL_EXTENSION = ".whl"
9-
BZ2_EXTENSIONS = (".tar.bz2", ".tbz") # type: Tuple[str, ...]
10-
XZ_EXTENSIONS = (
9+
BZ2_EXTENSIONS: Tuple[str, ...] = (".tar.bz2", ".tbz")
10+
XZ_EXTENSIONS: Tuple[str, ...] = (
1111
".tar.xz",
1212
".txz",
1313
".tlz",
1414
".tar.lz",
1515
".tar.lzma",
16-
) # type: Tuple[str, ...]
17-
ZIP_EXTENSIONS = (".zip", WHEEL_EXTENSION) # type: Tuple[str, ...]
18-
TAR_EXTENSIONS = (".tar.gz", ".tgz", ".tar") # type: Tuple[str, ...]
16+
)
17+
ZIP_EXTENSIONS: Tuple[str, ...] = (".zip", WHEEL_EXTENSION)
18+
TAR_EXTENSIONS: Tuple[str, ...] = (".tar.gz", ".tgz", ".tar")
1919
ARCHIVE_EXTENSIONS = ZIP_EXTENSIONS + BZ2_EXTENSIONS + TAR_EXTENSIONS + XZ_EXTENSIONS
2020

2121

22-
def is_archive_file(name):
23-
# type: (str) -> bool
22+
def is_archive_file(name: str) -> bool:
2423
"""Return True if `name` is a considered as an archive file."""
2524
ext = splitext(name)[1].lower()
2625
if ext in ARCHIVE_EXTENSIONS:

src/pip/_internal/utils/glibc.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,12 @@
66
from typing import Optional, Tuple
77

88

9-
def glibc_version_string():
10-
# type: () -> Optional[str]
9+
def glibc_version_string() -> Optional[str]:
1110
"Returns glibc version string, or None if not using glibc."
1211
return glibc_version_string_confstr() or glibc_version_string_ctypes()
1312

1413

15-
def glibc_version_string_confstr():
16-
# type: () -> Optional[str]
14+
def glibc_version_string_confstr() -> Optional[str]:
1715
"Primary implementation of glibc_version_string using os.confstr."
1816
# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
1917
# to be broken or missing. This strategy is used in the standard library
@@ -30,8 +28,7 @@ def glibc_version_string_confstr():
3028
return version
3129

3230

33-
def glibc_version_string_ctypes():
34-
# type: () -> Optional[str]
31+
def glibc_version_string_ctypes() -> Optional[str]:
3532
"Fallback implementation of glibc_version_string using ctypes."
3633

3734
try:
@@ -78,8 +75,7 @@ def glibc_version_string_ctypes():
7875
# versions that was generated by pip 8.1.2 and earlier is useless and
7976
# misleading. Solution: instead of using platform, use our code that actually
8077
# works.
81-
def libc_ver():
82-
# type: () -> Tuple[str, str]
78+
def libc_ver() -> Tuple[str, str]:
8379
"""Try to determine the glibc version
8480
8581
Returns a tuple of strings (lib, version) which default to empty strings

src/pip/_internal/utils/inject_securetransport.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@
1010
import sys
1111

1212

13-
def inject_securetransport():
14-
# type: () -> None
13+
def inject_securetransport() -> None:
1514
# Only relevant on macOS
1615
if sys.platform != "darwin":
1716
return

src/pip/_internal/utils/logging.py

Lines changed: 26 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,9 @@ class BrokenStdoutLoggingError(Exception):
4343
# In Windows, a broken pipe can show up as EINVAL rather than EPIPE:
4444
# https://bugs.python.org/issue19612
4545
# https://bugs.python.org/issue30418
46-
def _is_broken_pipe_error(exc_class, exc):
47-
# type: (Type[BaseException], BaseException) -> bool
46+
def _is_broken_pipe_error(
47+
exc_class: Type[BaseException], exc: BaseException
48+
) -> bool:
4849
"""See the docstring for non-Windows below."""
4950
return (exc_class is BrokenPipeError) or (
5051
isinstance(exc, OSError) and exc.errno in (errno.EINVAL, errno.EPIPE)
@@ -53,8 +54,9 @@ def _is_broken_pipe_error(exc_class, exc):
5354

5455
else:
5556
# Then we are in the non-Windows case.
56-
def _is_broken_pipe_error(exc_class, exc):
57-
# type: (Type[BaseException], BaseException) -> bool
57+
def _is_broken_pipe_error(
58+
exc_class: Type[BaseException], exc: BaseException
59+
) -> bool:
5860
"""
5961
Return whether an exception is a broken pipe error.
6062
@@ -66,8 +68,7 @@ def _is_broken_pipe_error(exc_class, exc):
6668

6769

6870
@contextlib.contextmanager
69-
def indent_log(num=2):
70-
# type: (int) -> Iterator[None]
71+
def indent_log(num: int = 2) -> Iterator[None]:
7172
"""
7273
A context manager which will cause the log output to be indented for any
7374
log messages emitted inside it.
@@ -81,8 +82,7 @@ def indent_log(num=2):
8182
_log_state.indentation -= num
8283

8384

84-
def get_indentation():
85-
# type: () -> int
85+
def get_indentation() -> int:
8686
return getattr(_log_state, "indentation", 0)
8787

8888

@@ -91,11 +91,10 @@ class IndentingFormatter(logging.Formatter):
9191

9292
def __init__(
9393
self,
94-
*args, # type: Any
95-
add_timestamp=False, # type: bool
96-
**kwargs, # type: Any
97-
):
98-
# type: (...) -> None
94+
*args: Any,
95+
add_timestamp: bool = False,
96+
**kwargs: Any,
97+
) -> None:
9998
"""
10099
A logging.Formatter that obeys the indent_log() context manager.
101100
@@ -105,8 +104,7 @@ def __init__(
105104
self.add_timestamp = add_timestamp
106105
super().__init__(*args, **kwargs)
107106

108-
def get_message_start(self, formatted, levelno):
109-
# type: (str, int) -> str
107+
def get_message_start(self, formatted: str, levelno: int) -> str:
110108
"""
111109
Return the start of the formatted log message (not counting the
112110
prefix to add to each line).
@@ -122,8 +120,7 @@ def get_message_start(self, formatted, levelno):
122120

123121
return "ERROR: "
124122

125-
def format(self, record):
126-
# type: (logging.LogRecord) -> str
123+
def format(self, record: logging.LogRecord) -> str:
127124
"""
128125
Calls the standard formatter, but will indent all of the log message
129126
lines by our current indentation level.
@@ -140,10 +137,8 @@ def format(self, record):
140137
return formatted
141138

142139

143-
def _color_wrap(*colors):
144-
# type: (*str) -> Callable[[str], str]
145-
def wrapped(inp):
146-
# type: (str) -> str
140+
def _color_wrap(*colors: str) -> Callable[[str], str]:
141+
def wrapped(inp: str) -> str:
147142
return "".join(list(colors) + [inp, colorama.Style.RESET_ALL])
148143

149144
return wrapped
@@ -161,16 +156,14 @@ class ColorizedStreamHandler(logging.StreamHandler):
161156
else:
162157
COLORS = []
163158

164-
def __init__(self, stream=None, no_color=None):
165-
# type: (Optional[TextIO], bool) -> None
159+
def __init__(self, stream: Optional[TextIO] = None, no_color: bool = None) -> None:
166160
super().__init__(stream)
167161
self._no_color = no_color
168162

169163
if WINDOWS and colorama:
170164
self.stream = colorama.AnsiToWin32(self.stream)
171165

172-
def _using_stdout(self):
173-
# type: () -> bool
166+
def _using_stdout(self) -> bool:
174167
"""
175168
Return whether the handler is using sys.stdout.
176169
"""
@@ -181,8 +174,7 @@ def _using_stdout(self):
181174

182175
return self.stream is sys.stdout
183176

184-
def should_color(self):
185-
# type: () -> bool
177+
def should_color(self) -> bool:
186178
# Don't colorize things if we do not have colorama or if told not to
187179
if not colorama or self._no_color:
188180
return False
@@ -204,8 +196,7 @@ def should_color(self):
204196
# If anything else we should not color it
205197
return False
206198

207-
def format(self, record):
208-
# type: (logging.LogRecord) -> str
199+
def format(self, record: logging.LogRecord) -> str:
209200
msg = super().format(record)
210201

211202
if self.should_color():
@@ -217,8 +208,7 @@ def format(self, record):
217208
return msg
218209

219210
# The logging module says handleError() can be customized.
220-
def handleError(self, record):
221-
# type: (logging.LogRecord) -> None
211+
def handleError(self, record: logging.LogRecord) -> None:
222212
exc_class, exc = sys.exc_info()[:2]
223213
# If a broken pipe occurred while calling write() or flush() on the
224214
# stdout stream in logging's Handler.emit(), then raise our special
@@ -236,19 +226,16 @@ def handleError(self, record):
236226

237227

238228
class BetterRotatingFileHandler(logging.handlers.RotatingFileHandler):
239-
def _open(self):
240-
# type: () -> IO[Any]
229+
def _open(self) -> IO[Any]:
241230
ensure_dir(os.path.dirname(self.baseFilename))
242231
return super()._open()
243232

244233

245234
class MaxLevelFilter(Filter):
246-
def __init__(self, level):
247-
# type: (int) -> None
235+
def __init__(self, level: int) -> None:
248236
self.level = level
249237

250-
def filter(self, record):
251-
# type: (logging.LogRecord) -> bool
238+
def filter(self, record: logging.LogRecord) -> bool:
252239
return record.levelno < self.level
253240

254241

@@ -258,15 +245,13 @@ class ExcludeLoggerFilter(Filter):
258245
A logging Filter that excludes records from a logger (or its children).
259246
"""
260247

261-
def filter(self, record):
262-
# type: (logging.LogRecord) -> bool
248+
def filter(self, record: logging.LogRecord) -> bool:
263249
# The base Filter class allows only records from a logger (or its
264250
# children).
265251
return not super().filter(record)
266252

267253

268-
def setup_logging(verbosity, no_color, user_log_file):
269-
# type: (int, bool, Optional[str]) -> int
254+
def setup_logging(verbosity: int, no_color: bool, user_log_file: Optional[str]) -> int:
270255
"""Configures and sets up all of the logging
271256
272257
Returns the requested logging level, as its integer value.

0 commit comments

Comments
 (0)