Skip to content

Commit 8b507f9

Browse files
authored
Merge pull request #13371 from pradyunsg/modernise-type-annotations
Enable and enforce modern type annotations across the codebase
2 parents 3a8d079 + 65fe65b commit 8b507f9

File tree

211 files changed

+2069
-1965
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

211 files changed

+2069
-1965
lines changed

docs/html/conf.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import pathlib
66
import re
77
import sys
8-
from typing import List, Tuple
98

109
# Add the docs/ directory to sys.path, because pip_sphinxext.py is there.
1110
docs_dir = os.path.dirname(os.path.dirname(__file__))
@@ -101,7 +100,7 @@
101100

102101

103102
# List of manual pages generated
104-
def determine_man_pages() -> List[Tuple[str, str, str, str, int]]:
103+
def determine_man_pages() -> list[tuple[str, str, str, str, int]]:
105104
"""Determine which man pages need to be generated."""
106105

107106
def to_document_name(path: str, base_dir: str) -> str:

docs/pip_sphinxext.py

+14-14
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
"""pip sphinx extensions"""
22

3+
from __future__ import annotations
4+
35
import optparse
46
import pathlib
57
import re
68
import sys
9+
from collections.abc import Iterable, Iterator
710
from textwrap import dedent
8-
from typing import Dict, Iterable, Iterator, List, Optional, Union
911

1012
from docutils import nodes, statemachine
1113
from docutils.parsers import rst
@@ -24,7 +26,7 @@ def convert_cli_option_to_envvar(opt_name: str) -> str:
2426
return f"PIP_{normalized_opt_name}"
2527

2628

27-
def convert_cli_opt_names_to_envvars(original_cli_opt_names: List[str]) -> List[str]:
29+
def convert_cli_opt_names_to_envvars(original_cli_opt_names: list[str]) -> list[str]:
2830
return [
2931
convert_cli_option_to_envvar(opt_name) for opt_name in original_cli_opt_names
3032
]
@@ -33,9 +35,7 @@ def convert_cli_opt_names_to_envvars(original_cli_opt_names: List[str]) -> List[
3335
class PipNewsInclude(rst.Directive):
3436
required_arguments = 1
3537

36-
def _is_version_section_title_underline(
37-
self, prev: Optional[str], curr: str
38-
) -> bool:
38+
def _is_version_section_title_underline(self, prev: str | None, curr: str) -> bool:
3939
"""Find a ==== line that marks the version section title."""
4040
if prev is None:
4141
return False
@@ -69,7 +69,7 @@ def _iter_lines_with_refs(self, lines: Iterable[str]) -> Iterator[str]:
6969
if prev is not None:
7070
yield prev
7171

72-
def run(self) -> List[nodes.Node]:
72+
def run(self) -> list[nodes.Node]:
7373
source = self.state_machine.input_lines.source(
7474
self.lineno - self.state_machine.input_offset - 1,
7575
)
@@ -90,7 +90,7 @@ class PipCommandUsage(rst.Directive):
9090
required_arguments = 1
9191
optional_arguments = 3
9292

93-
def run(self) -> List[nodes.Node]:
93+
def run(self) -> list[nodes.Node]:
9494
cmd = create_command(self.arguments[0])
9595
cmd_prefix = "python -m pip"
9696
if len(self.arguments) > 1:
@@ -105,7 +105,7 @@ def run(self) -> List[nodes.Node]:
105105
class PipCommandDescription(rst.Directive):
106106
required_arguments = 1
107107

108-
def run(self) -> List[nodes.Node]:
108+
def run(self) -> list[nodes.Node]:
109109
node = nodes.paragraph()
110110
node.document = self.state.document
111111
desc = ViewList()
@@ -120,8 +120,8 @@ def run(self) -> List[nodes.Node]:
120120

121121
class PipOptions(rst.Directive):
122122
def _format_option(
123-
self, option: optparse.Option, cmd_name: Optional[str] = None
124-
) -> List[str]:
123+
self, option: optparse.Option, cmd_name: str | None = None
124+
) -> list[str]:
125125
bookmark_line = (
126126
f".. _`{cmd_name}_{option._long_opts[0]}`:"
127127
if cmd_name
@@ -157,15 +157,15 @@ def _format_option(
157157
]
158158

159159
def _format_options(
160-
self, options: Iterable[optparse.Option], cmd_name: Optional[str] = None
160+
self, options: Iterable[optparse.Option], cmd_name: str | None = None
161161
) -> None:
162162
for option in options:
163163
if option.help == optparse.SUPPRESS_HELP:
164164
continue
165165
for line in self._format_option(option, cmd_name):
166166
self.view_list.append(line, "")
167167

168-
def run(self) -> List[nodes.Node]:
168+
def run(self) -> list[nodes.Node]:
169169
node = nodes.paragraph()
170170
node.document = self.state.document
171171
self.view_list = ViewList()
@@ -242,7 +242,7 @@ class PipCLIDirective(rst.Directive):
242242
has_content = True
243243
optional_arguments = 1
244244

245-
def run(self) -> List[nodes.Node]:
245+
def run(self) -> list[nodes.Node]:
246246
node = nodes.paragraph()
247247
node.document = self.state.document
248248

@@ -310,7 +310,7 @@ def run(self) -> List[nodes.Node]:
310310
return [node]
311311

312312

313-
def setup(app: Sphinx) -> Dict[str, Union[bool, str]]:
313+
def setup(app: Sphinx) -> dict[str, bool | str]:
314314
app.add_directive("pip-command-usage", PipCommandUsage)
315315
app.add_directive("pip-command-description", PipCommandDescription)
316316
app.add_directive("pip-command-options", PipCommandOptions)

noxfile.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
import os
66
import shutil
77
import sys
8+
from collections.abc import Iterator
89
from pathlib import Path
9-
from typing import Iterator, List, Tuple
1010

1111
import nox
1212

@@ -136,7 +136,7 @@ def test(session: nox.Session) -> None:
136136
def docs(session: nox.Session) -> None:
137137
session.install("-r", REQUIREMENTS["docs"])
138138

139-
def get_sphinx_build_command(kind: str) -> List[str]:
139+
def get_sphinx_build_command(kind: str) -> list[str]:
140140
# Having the conf.py in the docs/html is weird but needed because we
141141
# can not use a different configuration directory vs source directory
142142
# on RTD currently. So, we'll pass "-c docs/html" here.
@@ -214,7 +214,7 @@ def vendoring(session: nox.Session) -> None:
214214
session.run("vendoring", "sync", "-v")
215215
return
216216

217-
def pinned_requirements(path: Path) -> Iterator[Tuple[str, str]]:
217+
def pinned_requirements(path: Path) -> Iterator[tuple[str, str]]:
218218
for line in path.read_text().splitlines(keepends=False):
219219
one, sep, two = line.partition("==")
220220
if not sep:
@@ -357,7 +357,7 @@ def build_release(session: nox.Session) -> None:
357357
shutil.copy(dist, final)
358358

359359

360-
def build_dists(session: nox.Session) -> List[str]:
360+
def build_dists(session: nox.Session) -> list[str]:
361361
"""Return dists with valid metadata."""
362362
session.log(
363363
"# Check if there's any Git-untracked files before building the wheel",

pyproject.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ distlib = "https://bitbucket.org/pypa/distlib/raw/master/LICENSE.txt"
154154

155155
[tool.ruff]
156156
# Pinned to delay pyupgrade changes (https://github.com/pypa/pip/issues/13236)
157-
target-version = "py38" # Pin Ruff to Python 3.8
157+
target-version = "py39" # Pin Ruff to Python 3.9
158158
src = ["src"]
159159
line-length = 88
160160
extend-exclude = [
@@ -187,7 +187,7 @@ select = [
187187
"W",
188188
"RUF100",
189189
"UP",
190-
"FA102", # future-required-type-annotation
190+
"FA",
191191
]
192192

193193
[tool.ruff.lint.isort]

src/pip/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
from typing import List, Optional
1+
from __future__ import annotations
22

33
__version__ = "25.2.dev0"
44

55

6-
def main(args: Optional[List[str]] = None) -> int:
6+
def main(args: list[str] | None = None) -> int:
77
"""This is an internal API only meant for use by pip's own console scripts.
88
99
For additional details, see https://github.com/pypa/pip/issues/7498.

src/pip/_internal/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import List, Optional
1+
from __future__ import annotations
22

33
from pip._internal.utils import _log
44

@@ -7,7 +7,7 @@
77
_log.init_logging()
88

99

10-
def main(args: Optional[List[str]] = None) -> int:
10+
def main(args: list[str] | None = None) -> int:
1111
"""This is preserved for old console scripts that may still be referencing
1212
it.
1313

src/pip/_internal/build_env.py

+19-16
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
"""Build Environment used for isolation during sdist building"""
22

3+
from __future__ import annotations
4+
35
import logging
46
import os
57
import pathlib
68
import site
79
import sys
810
import textwrap
911
from collections import OrderedDict
12+
from collections.abc import Iterable
1013
from types import TracebackType
11-
from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type, Union
14+
from typing import TYPE_CHECKING
1215

1316
from pip._vendor.packaging.version import Version
1417

@@ -27,7 +30,7 @@
2730
logger = logging.getLogger(__name__)
2831

2932

30-
def _dedup(a: str, b: str) -> Union[Tuple[str], Tuple[str, str]]:
33+
def _dedup(a: str, b: str) -> tuple[str] | tuple[str, str]:
3134
return (a, b) if a != b else (a,)
3235

3336

@@ -56,7 +59,7 @@ def get_runnable_pip() -> str:
5659
return os.fsdecode(source / "__pip-runner__.py")
5760

5861

59-
def _get_system_sitepackages() -> Set[str]:
62+
def _get_system_sitepackages() -> set[str]:
6063
"""Get system site packages
6164
6265
Usually from site.getsitepackages,
@@ -87,8 +90,8 @@ def __init__(self) -> None:
8790
for name in ("normal", "overlay")
8891
)
8992

90-
self._bin_dirs: List[str] = []
91-
self._lib_dirs: List[str] = []
93+
self._bin_dirs: list[str] = []
94+
self._lib_dirs: list[str] = []
9295
for prefix in reversed(list(self._prefixes.values())):
9396
self._bin_dirs.append(prefix.bin_dir)
9497
self._lib_dirs.extend(prefix.lib_dirs)
@@ -156,9 +159,9 @@ def __enter__(self) -> None:
156159

157160
def __exit__(
158161
self,
159-
exc_type: Optional[Type[BaseException]],
160-
exc_val: Optional[BaseException],
161-
exc_tb: Optional[TracebackType],
162+
exc_type: type[BaseException] | None,
163+
exc_val: BaseException | None,
164+
exc_tb: TracebackType | None,
162165
) -> None:
163166
for varname, old_value in self._save_env.items():
164167
if old_value is None:
@@ -168,7 +171,7 @@ def __exit__(
168171

169172
def check_requirements(
170173
self, reqs: Iterable[str]
171-
) -> Tuple[Set[Tuple[str, str]], Set[str]]:
174+
) -> tuple[set[tuple[str, str]], set[str]]:
172175
"""Return 2 sets:
173176
- conflicting requirements: set of (installed, wanted) reqs tuples
174177
- missing requirements: set of reqs
@@ -202,7 +205,7 @@ def check_requirements(
202205

203206
def install_requirements(
204207
self,
205-
finder: "PackageFinder",
208+
finder: PackageFinder,
206209
requirements: Iterable[str],
207210
prefix_as_string: str,
208211
*,
@@ -224,13 +227,13 @@ def install_requirements(
224227
@staticmethod
225228
def _install_requirements(
226229
pip_runnable: str,
227-
finder: "PackageFinder",
230+
finder: PackageFinder,
228231
requirements: Iterable[str],
229232
prefix: _Prefix,
230233
*,
231234
kind: str,
232235
) -> None:
233-
args: List[str] = [
236+
args: list[str] = [
234237
sys.executable,
235238
pip_runnable,
236239
"install",
@@ -305,9 +308,9 @@ def __enter__(self) -> None:
305308

306309
def __exit__(
307310
self,
308-
exc_type: Optional[Type[BaseException]],
309-
exc_val: Optional[BaseException],
310-
exc_tb: Optional[TracebackType],
311+
exc_type: type[BaseException] | None,
312+
exc_val: BaseException | None,
313+
exc_tb: TracebackType | None,
311314
) -> None:
312315
pass
313316

@@ -316,7 +319,7 @@ def cleanup(self) -> None:
316319

317320
def install_requirements(
318321
self,
319-
finder: "PackageFinder",
322+
finder: PackageFinder,
320323
requirements: Iterable[str],
321324
prefix_as_string: str,
322325
*,

0 commit comments

Comments
 (0)