Skip to content

Commit 3820b0e

Browse files
q0wuranusjr
andauthored
Replace Iterator[T] with Generator[T,None, None] (#11007)
Co-authored-by: Tzu-ping Chung <[email protected]>
1 parent e679df4 commit 3820b0e

26 files changed

+84
-68
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Replace ``Iterator[T]`` with ``Generator[T, None, None]``.

src/pip/_internal/build_env.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from collections import OrderedDict
1212
from sysconfig import get_paths
1313
from types import TracebackType
14-
from typing import TYPE_CHECKING, Iterable, Iterator, List, Optional, Set, Tuple, Type
14+
from typing import TYPE_CHECKING, Generator, Iterable, List, Optional, Set, Tuple, Type
1515

1616
from pip._vendor.certifi import where
1717
from pip._vendor.packaging.requirements import Requirement
@@ -42,7 +42,7 @@ def __init__(self, path: str) -> None:
4242

4343

4444
@contextlib.contextmanager
45-
def _create_standalone_pip() -> Iterator[str]:
45+
def _create_standalone_pip() -> Generator[str, None, None]:
4646
"""Create a "standalone pip" zip file.
4747
4848
The zip file's content is identical to the currently-running pip.

src/pip/_internal/cli/command_context.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from contextlib import ExitStack, contextmanager
2-
from typing import ContextManager, Iterator, TypeVar
2+
from typing import ContextManager, Generator, TypeVar
33

44
_T = TypeVar("_T", covariant=True)
55

@@ -11,7 +11,7 @@ def __init__(self) -> None:
1111
self._main_context = ExitStack()
1212

1313
@contextmanager
14-
def main_context(self) -> Iterator[None]:
14+
def main_context(self) -> Generator[None, None, None]:
1515
assert not self._in_main_context
1616

1717
self._in_main_context = True

src/pip/_internal/cli/parser.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import sys
77
import textwrap
88
from contextlib import suppress
9-
from typing import Any, Dict, Iterator, List, Tuple
9+
from typing import Any, Dict, Generator, List, Tuple
1010

1111
from pip._internal.cli.status_codes import UNKNOWN_ERROR
1212
from pip._internal.configuration import Configuration, ConfigurationError
@@ -175,7 +175,9 @@ def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:
175175
print(f"An error occurred during configuration: {exc}")
176176
sys.exit(3)
177177

178-
def _get_ordered_configuration_items(self) -> Iterator[Tuple[str, Any]]:
178+
def _get_ordered_configuration_items(
179+
self,
180+
) -> Generator[Tuple[str, Any], None, None]:
179181
# Configuration gives keys in an unordered manner. Order them.
180182
override_order = ["global", self.name, ":env:"]
181183

src/pip/_internal/cli/progress_bars.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import functools
2-
from typing import Callable, Iterator, Optional, Tuple
2+
from typing import Callable, Generator, Iterable, Iterator, Optional, Tuple
33

44
from pip._vendor.rich.progress import (
55
BarColumn,
@@ -16,15 +16,15 @@
1616

1717
from pip._internal.utils.logging import get_indentation
1818

19-
DownloadProgressRenderer = Callable[[Iterator[bytes]], Iterator[bytes]]
19+
DownloadProgressRenderer = Callable[[Iterable[bytes]], Iterator[bytes]]
2020

2121

2222
def _rich_progress_bar(
23-
iterable: Iterator[bytes],
23+
iterable: Iterable[bytes],
2424
*,
2525
bar_type: str,
2626
size: int,
27-
) -> Iterator[bytes]:
27+
) -> Generator[bytes, None, None]:
2828
assert bar_type == "on", "This should only be used in the default mode."
2929

3030
if not size:

src/pip/_internal/cli/spinners.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
import sys
55
import time
6-
from typing import IO, Iterator
6+
from typing import IO, Generator
77

88
from pip._internal.utils.compat import WINDOWS
99
from pip._internal.utils.logging import get_indentation
@@ -113,7 +113,7 @@ def reset(self) -> None:
113113

114114

115115
@contextlib.contextmanager
116-
def open_spinner(message: str) -> Iterator[SpinnerInterface]:
116+
def open_spinner(message: str) -> Generator[SpinnerInterface, None, None]:
117117
# Interactive spinner goes directly to sys.stdout rather than being routed
118118
# through the logging system, but it acts like it has level INFO,
119119
# i.e. it's only displayed if we're at level INFO or better.
@@ -141,7 +141,7 @@ def open_spinner(message: str) -> Iterator[SpinnerInterface]:
141141

142142

143143
@contextlib.contextmanager
144-
def hidden_cursor(file: IO[str]) -> Iterator[None]:
144+
def hidden_cursor(file: IO[str]) -> Generator[None, None, None]:
145145
# The Windows terminal does not support the hide/show cursor ANSI codes,
146146
# even via colorama. So don't even try.
147147
if WINDOWS:

src/pip/_internal/commands/list.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
22
import logging
33
from optparse import Values
4-
from typing import TYPE_CHECKING, Iterator, List, Optional, Sequence, Tuple, cast
4+
from typing import TYPE_CHECKING, Generator, List, Optional, Sequence, Tuple, cast
55

66
from pip._vendor.packaging.utils import canonicalize_name
77

@@ -222,7 +222,7 @@ def get_not_required(
222222

223223
def iter_packages_latest_infos(
224224
self, packages: "_ProcessedDists", options: Values
225-
) -> Iterator["_DistWithLatestInfo"]:
225+
) -> Generator["_DistWithLatestInfo", None, None]:
226226
with self._build_session(options) as session:
227227
finder = self._build_package_finder(options, session)
228228

src/pip/_internal/commands/show.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import logging
22
from optparse import Values
3-
from typing import Iterator, List, NamedTuple, Optional
3+
from typing import Generator, Iterable, Iterator, List, NamedTuple, Optional
44

55
from pip._vendor.packaging.utils import canonicalize_name
66

@@ -67,7 +67,7 @@ class _PackageInfo(NamedTuple):
6767
files: Optional[List[str]]
6868

6969

70-
def search_packages_info(query: List[str]) -> Iterator[_PackageInfo]:
70+
def search_packages_info(query: List[str]) -> Generator[_PackageInfo, None, None]:
7171
"""
7272
Gather details from installed distributions. Print distribution name,
7373
version, location, and installed files. Installed files requires a
@@ -135,7 +135,7 @@ def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]:
135135

136136

137137
def print_results(
138-
distributions: Iterator[_PackageInfo],
138+
distributions: Iterable[_PackageInfo],
139139
list_files: bool,
140140
verbose: bool,
141141
) -> bool:

src/pip/_internal/locations/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import pathlib
55
import sys
66
import sysconfig
7-
from typing import Any, Dict, Iterator, List, Optional, Tuple
7+
from typing import Any, Dict, Generator, List, Optional, Tuple
88

99
from pip._internal.models.scheme import SCHEME_KEYS, Scheme
1010
from pip._internal.utils.compat import WINDOWS
@@ -169,7 +169,7 @@ def _looks_like_msys2_mingw_scheme() -> bool:
169169
)
170170

171171

172-
def _fix_abiflags(parts: Tuple[str]) -> Iterator[str]:
172+
def _fix_abiflags(parts: Tuple[str]) -> Generator[str, None, None]:
173173
ldversion = sysconfig.get_config_var("LDVERSION")
174174
abiflags = getattr(sys, "abiflags", None)
175175

src/pip/_internal/metadata/base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
TYPE_CHECKING,
1111
Collection,
1212
Container,
13+
Generator,
1314
Iterable,
1415
Iterator,
1516
List,
@@ -470,7 +471,7 @@ def _iter_distributions(self) -> Iterator["BaseDistribution"]:
470471
"""
471472
raise NotImplementedError()
472473

473-
def iter_distributions(self) -> Iterator["BaseDistribution"]:
474+
def iter_distributions(self) -> Generator["BaseDistribution", None, None]:
474475
"""Iterate through installed distributions."""
475476
for dist in self._iter_distributions():
476477
# Make sure the distribution actually comes from a valid Python

src/pip/_internal/metadata/pkg_resources.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import os
55
import pathlib
66
import zipfile
7-
from typing import Collection, Iterable, Iterator, List, Mapping, NamedTuple, Optional
7+
from typing import Collection, Generator, Iterable, List, Mapping, NamedTuple, Optional
88

99
from pip._vendor import pkg_resources
1010
from pip._vendor.packaging.requirements import Requirement
@@ -149,7 +149,7 @@ def version(self) -> DistributionVersion:
149149
def is_file(self, path: InfoPath) -> bool:
150150
return self._dist.has_metadata(str(path))
151151

152-
def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:
152+
def iterdir(self, path: InfoPath) -> Generator[pathlib.PurePosixPath, None, None]:
153153
name = str(path)
154154
if not self._dist.has_metadata(name):
155155
raise FileNotFoundError(name)
@@ -251,6 +251,6 @@ def get_distribution(self, name: str) -> Optional[BaseDistribution]:
251251
return None
252252
return self._search_distribution(name)
253253

254-
def _iter_distributions(self) -> Iterator[BaseDistribution]:
254+
def _iter_distributions(self) -> Generator[BaseDistribution, None, None]:
255255
for dist in self._ws:
256256
yield Distribution(dist)

src/pip/_internal/network/cache.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import os
55
from contextlib import contextmanager
6-
from typing import Iterator, Optional
6+
from typing import Generator, Optional
77

88
from pip._vendor.cachecontrol.cache import BaseCache
99
from pip._vendor.cachecontrol.caches import FileCache
@@ -18,7 +18,7 @@ def is_from_cache(response: Response) -> bool:
1818

1919

2020
@contextmanager
21-
def suppressed_cache_errors() -> Iterator[None]:
21+
def suppressed_cache_errors() -> Generator[None, None, None]:
2222
"""If we can't access the cache then we can just skip caching and process
2323
requests as if caching wasn't enabled.
2424
"""

src/pip/_internal/network/lazy_wheel.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from bisect import bisect_left, bisect_right
66
from contextlib import contextmanager
77
from tempfile import NamedTemporaryFile
8-
from typing import Any, Dict, Iterator, List, Optional, Tuple
8+
from typing import Any, Dict, Generator, List, Optional, Tuple
99
from zipfile import BadZipfile, ZipFile
1010

1111
from pip._vendor.packaging.utils import canonicalize_name
@@ -139,7 +139,7 @@ def __exit__(self, *exc: Any) -> Optional[bool]:
139139
return self._file.__exit__(*exc)
140140

141141
@contextmanager
142-
def _stay(self) -> Iterator[None]:
142+
def _stay(self) -> Generator[None, None, None]:
143143
"""Return a context manager keeping the position.
144144
145145
At the end of the block, seek back to original position.
@@ -177,8 +177,8 @@ def _stream_response(
177177

178178
def _merge(
179179
self, start: int, end: int, left: int, right: int
180-
) -> Iterator[Tuple[int, int]]:
181-
"""Return an iterator of intervals to be fetched.
180+
) -> Generator[Tuple[int, int], None, None]:
181+
"""Return a generator of intervals to be fetched.
182182
183183
Args:
184184
start (int): Start of needed interval

src/pip/_internal/network/session.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import sys
1616
import urllib.parse
1717
import warnings
18-
from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union
18+
from typing import Any, Dict, Generator, List, Mapping, Optional, Sequence, Tuple, Union
1919

2020
from pip._vendor import requests, urllib3
2121
from pip._vendor.cachecontrol import CacheControlAdapter
@@ -374,7 +374,7 @@ def add_trusted_host(
374374
# Mount wildcard ports for the same host.
375375
self.mount(build_url_from_netloc(host) + ":", self._trusted_host_adapter)
376376

377-
def iter_secure_origins(self) -> Iterator[SecureOrigin]:
377+
def iter_secure_origins(self) -> Generator[SecureOrigin, None, None]:
378378
yield from SECURE_ORIGINS
379379
for host, port in self.pip_trusted_origins:
380380
yield ("*", host, "*" if port is None else port)

src/pip/_internal/network/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Dict, Iterator
1+
from typing import Dict, Generator
22

33
from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
44

@@ -56,7 +56,7 @@ def raise_for_status(resp: Response) -> None:
5656

5757
def response_chunks(
5858
response: Response, chunk_size: int = CONTENT_CHUNK_SIZE
59-
) -> Iterator[bytes]:
59+
) -> Generator[bytes, None, None]:
6060
"""Given a requests Response, provide the data chunks."""
6161
try:
6262
# Special case for urllib3.

src/pip/_internal/operations/build/build_tracker.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
import os
55
from types import TracebackType
6-
from typing import Dict, Iterator, Optional, Set, Type, Union
6+
from typing import Dict, Generator, Optional, Set, Type, Union
77

88
from pip._internal.models.link import Link
99
from pip._internal.req.req_install import InstallRequirement
@@ -13,7 +13,7 @@
1313

1414

1515
@contextlib.contextmanager
16-
def update_env_context_manager(**changes: str) -> Iterator[None]:
16+
def update_env_context_manager(**changes: str) -> Generator[None, None, None]:
1717
target = os.environ
1818

1919
# Save values from the target and change them.
@@ -39,7 +39,7 @@ def update_env_context_manager(**changes: str) -> Iterator[None]:
3939

4040

4141
@contextlib.contextmanager
42-
def get_build_tracker() -> Iterator["BuildTracker"]:
42+
def get_build_tracker() -> Generator["BuildTracker", None, None]:
4343
root = os.environ.get("PIP_BUILD_TRACKER")
4444
with contextlib.ExitStack() as ctx:
4545
if root is None:
@@ -118,7 +118,7 @@ def cleanup(self) -> None:
118118
logger.debug("Removed build tracker: %r", self._root)
119119

120120
@contextlib.contextmanager
121-
def track(self, req: InstallRequirement) -> Iterator[None]:
121+
def track(self, req: InstallRequirement) -> Generator[None, None, None]:
122122
self.add(req)
123123
yield
124124
self.remove(req)

src/pip/_internal/operations/freeze.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import collections
22
import logging
33
import os
4-
from typing import Container, Dict, Iterable, Iterator, List, NamedTuple, Optional, Set
4+
from typing import Container, Dict, Generator, Iterable, List, NamedTuple, Optional, Set
55

66
from pip._vendor.packaging.utils import canonicalize_name
77
from pip._vendor.packaging.version import Version
@@ -31,7 +31,7 @@ def freeze(
3131
isolated: bool = False,
3232
exclude_editable: bool = False,
3333
skip: Container[str] = (),
34-
) -> Iterator[str]:
34+
) -> Generator[str, None, None]:
3535
installations: Dict[str, FrozenRequirement] = {}
3636

3737
dists = get_environment(paths).iter_installed_distributions(

src/pip/_internal/operations/install/wheel.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
BinaryIO,
2323
Callable,
2424
Dict,
25+
Generator,
2526
Iterable,
2627
Iterator,
2728
List,
@@ -589,7 +590,7 @@ def is_entrypoint_wrapper(file: "File") -> bool:
589590
file.save()
590591
record_installed(file.src_record_path, file.dest_path, file.changed)
591592

592-
def pyc_source_file_paths() -> Iterator[str]:
593+
def pyc_source_file_paths() -> Generator[str, None, None]:
593594
# We de-duplicate installation paths, since there can be overlap (e.g.
594595
# file in .data maps to same location as file in wheel root).
595596
# Sorting installation paths makes it easier to reproduce and debug
@@ -656,7 +657,7 @@ def pyc_output_path(path: str) -> str:
656657
generated_file_mode = 0o666 & ~current_umask()
657658

658659
@contextlib.contextmanager
659-
def _generate_file(path: str, **kwargs: Any) -> Iterator[BinaryIO]:
660+
def _generate_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:
660661
with adjacent_tmp_file(path, **kwargs) as f:
661662
yield f
662663
os.chmod(f.name, generated_file_mode)
@@ -706,7 +707,7 @@ def _generate_file(path: str, **kwargs: Any) -> Iterator[BinaryIO]:
706707

707708

708709
@contextlib.contextmanager
709-
def req_error_context(req_description: str) -> Iterator[None]:
710+
def req_error_context(req_description: str) -> Generator[None, None, None]:
710711
try:
711712
yield
712713
except InstallationError as e:

src/pip/_internal/req/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import collections
22
import logging
3-
from typing import Iterator, List, Optional, Sequence, Tuple
3+
from typing import Generator, List, Optional, Sequence, Tuple
44

55
from pip._internal.utils.logging import indent_log
66

@@ -28,7 +28,7 @@ def __repr__(self) -> str:
2828

2929
def _validate_requirements(
3030
requirements: List[InstallRequirement],
31-
) -> Iterator[Tuple[str, InstallRequirement]]:
31+
) -> Generator[Tuple[str, InstallRequirement], None, None]:
3232
for req in requirements:
3333
assert req.name, f"invalid to-be-installed requirement: {req}"
3434
yield req.name, req

0 commit comments

Comments
 (0)