Skip to content

Complete type annotations in pip/_internal/cli #10065

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Jun 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
ff6b13a
Complete the annotations in `pip/_internal/cli`
DiddiLeija Jun 14, 2021
ec81b09
Create 10065.trivial.rst
DiddiLeija Jun 14, 2021
7a79567
Update the annotations in `progress_bars.py`
DiddiLeija Jun 14, 2021
0a5e30f
Update the annotations in req_command.py
DiddiLeija Jun 14, 2021
f003863
Update req_command.py
DiddiLeija Jun 14, 2021
19a6e96
Fix an annotation mistake
DiddiLeija Jun 14, 2021
0fb5a61
Merge branch 'pypa:main' into pip/_internal/cli-annotations-fixes-1
DiddiLeija Jun 15, 2021
37f3ff1
Fix the annotation structure
DiddiLeija Jun 15, 2021
7b68bd0
Remove a trailing whitespace
DiddiLeija Jun 15, 2021
72881b4
Remove the whitespaces
DiddiLeija Jun 15, 2021
0a2b24f
Update the spinners.py annotations
DiddiLeija Jun 15, 2021
9d2ee1f
Update src/pip/_internal/cli/progress_bars.py
DiddiLeija Jun 16, 2021
411f49f
Update `pip/_internal/cli/progress_bars.py`
DiddiLeija Jun 16, 2021
d582d91
Annotate a variable definition
DiddiLeija Jun 16, 2021
0bceddb
Don't import `typing.List` and `typing.Dict`
DiddiLeija Jun 16, 2021
0431a18
Fix the annotations
DiddiLeija Jun 16, 2021
ced58b5
Update src/pip/_internal/cli/spinners.py
DiddiLeija Jun 16, 2021
3e8be35
Merge branch 'pypa:main' into pip/_internal/cli-annotations-fixes-1
DiddiLeija Jun 21, 2021
7d24066
Merge branch 'pypa:main' into pip/_internal/cli-annotations-fixes-1
DiddiLeija Jun 24, 2021
43baccd
Merge branch 'pypa:main' into pip/_internal/cli-annotations-fixes-1
DiddiLeija Jun 25, 2021
ed5a809
Merge branch 'pypa:main' into pip/_internal/cli-annotations-fixes-1
DiddiLeija Jun 26, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/10065.trivial.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed all the annotations from ``pip/_internal/cli``.
35 changes: 12 additions & 23 deletions src/pip/_internal/cli/progress_bars.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import itertools
import sys
from signal import SIGINT, default_int_handler, signal
from typing import Any, Dict, List
from typing import Any

from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar
from pip._vendor.progress.spinner import Spinner
Expand All @@ -18,8 +18,7 @@
colorama = None


def _select_progress_class(preferred, fallback):
# type: (Bar, Bar) -> Bar
def _select_progress_class(preferred: Bar, fallback: Bar) -> Bar:
encoding = getattr(preferred.file, "encoding", None)

# If we don't know what encoding this file is in, then we'll just assume
Expand Down Expand Up @@ -67,8 +66,7 @@ class InterruptibleMixin:
download has already completed, for example.
"""

def __init__(self, *args, **kwargs):
# type: (List[Any], Dict[Any, Any]) -> None
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""
Save the original SIGINT handler for later.
"""
Expand All @@ -85,8 +83,7 @@ def __init__(self, *args, **kwargs):
if self.original_handler is None:
self.original_handler = default_int_handler

def finish(self):
# type: () -> None
def finish(self) -> None:
"""
Restore the original SIGINT handler after finishing.

Expand All @@ -108,8 +105,7 @@ def handle_sigint(self, signum, frame): # type: ignore


class SilentBar(Bar):
def update(self):
# type: () -> None
def update(self) -> None:
pass


Expand All @@ -122,28 +118,24 @@ class BlueEmojiBar(IncrementalBar):


class DownloadProgressMixin:
def __init__(self, *args, **kwargs):
# type: (List[Any], Dict[Any, Any]) -> None
def __init__(self, *args: Any, **kwargs: Any) -> None:
# https://github.com/python/mypy/issues/5887
super().__init__(*args, **kwargs) # type: ignore
self.message = (" " * (get_indentation() + 2)) + self.message # type: str

@property
def downloaded(self):
# type: () -> str
def downloaded(self) -> str:
return format_size(self.index) # type: ignore

@property
def download_speed(self):
# type: () -> str
def download_speed(self) -> str:
# Avoid zero division errors...
if self.avg == 0.0: # type: ignore
return "..."
return format_size(1 / self.avg) + "/s" # type: ignore

@property
def pretty_eta(self):
# type: () -> str
def pretty_eta(self) -> str:
if self.eta: # type: ignore
return f"eta {self.eta_td}" # type: ignore
return ""
Expand All @@ -158,8 +150,7 @@ def iter(self, it): # type: ignore


class WindowsMixin:
def __init__(self, *args, **kwargs):
# type: (List[Any], Dict[Any, Any]) -> None
def __init__(self, *args: Any, **kwargs: Any) -> None:
# The Windows terminal does not support the hide/show cursor ANSI codes
# even with colorama. So we'll ensure that hide_cursor is False on
# Windows.
Expand Down Expand Up @@ -221,14 +212,12 @@ class DownloadProgressSpinner(
file = sys.stdout
suffix = "%(downloaded)s %(download_speed)s"

def next_phase(self):
# type: () -> str
def next_phase(self) -> str:
if not hasattr(self, "_phaser"):
self._phaser = itertools.cycle(self.phases)
return next(self._phaser)

def update(self):
# type: () -> None
def update(self) -> None:
message = self.message % self
phase = self.next_phase()
suffix = self.suffix % self
Expand Down
109 changes: 50 additions & 59 deletions src/pip/_internal/cli/req_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,12 @@ class SessionCommandMixin(CommandContextMixIn):
A class mixin for command classes needing _build_session().
"""

def __init__(self):
# type: () -> None
def __init__(self) -> None:
super().__init__()
self._session = None # Optional[PipSession]
self._session: Optional[PipSession] = None

@classmethod
def _get_index_urls(cls, options):
# type: (Values) -> Optional[List[str]]
def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
"""Return a list of index urls from user-provided options."""
index_urls = []
if not getattr(options, "no_index", False):
Expand All @@ -70,8 +68,7 @@ def _get_index_urls(cls, options):
# Return None rather than an empty list
return index_urls or None

def get_default_session(self, options):
# type: (Values) -> PipSession
def get_default_session(self, options: Values) -> PipSession:
"""Get a default-managed session."""
if self._session is None:
self._session = self.enter_context(self._build_session(options))
Expand All @@ -81,8 +78,12 @@ def get_default_session(self, options):
assert self._session is not None
return self._session

def _build_session(self, options, retries=None, timeout=None):
# type: (Values, Optional[int], Optional[int]) -> PipSession
def _build_session(
self,
options: Values,
retries: Optional[int] = None,
timeout: Optional[int] = None,
) -> PipSession:
assert not options.cache_dir or os.path.isabs(options.cache_dir)
session = PipSession(
cache=(
Expand Down Expand Up @@ -126,8 +127,7 @@ class IndexGroupCommand(Command, SessionCommandMixin):
This also corresponds to the commands that permit the pip version check.
"""

def handle_pip_version_check(self, options):
# type: (Values) -> None
def handle_pip_version_check(self, options: Values) -> None:
"""
Do the pip version check if not disabled.

Expand All @@ -154,8 +154,7 @@ def handle_pip_version_check(self, options):
]


def warn_if_run_as_root():
# type: () -> None
def warn_if_run_as_root() -> None:
"""Output a warning for sudo users on Unix.

In a virtual environment, sudo pip still writes to virtualenv.
Expand Down Expand Up @@ -184,19 +183,18 @@ def warn_if_run_as_root():
)


def with_cleanup(func):
# type: (Any) -> Any
def with_cleanup(func: Any) -> Any:
"""Decorator for common logic related to managing temporary
directories.
"""

def configure_tempdir_registry(registry):
# type: (TempDirectoryTypeRegistry) -> None
def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
for t in KEEPABLE_TEMPDIR_TYPES:
registry.set_delete(t, False)

def wrapper(self, options, args):
# type: (RequirementCommand, Values, List[Any]) -> Optional[int]
def wrapper(
self: RequirementCommand, options: Values, args: List[Any]
) -> Optional[int]:
assert self.tempdir_registry is not None
if options.no_clean:
configure_tempdir_registry(self.tempdir_registry)
Expand All @@ -214,15 +212,13 @@ def wrapper(self, options, args):


class RequirementCommand(IndexGroupCommand):
def __init__(self, *args, **kw):
# type: (Any, Any) -> None
def __init__(self, *args: Any, **kw: Any) -> None:
super().__init__(*args, **kw)

self.cmd_opts.add_option(cmdoptions.no_clean())

@staticmethod
def determine_resolver_variant(options):
# type: (Values) -> str
def determine_resolver_variant(options: Values) -> str:
"""Determines which resolver should be used, based on the given options."""
if "legacy-resolver" in options.deprecated_features_enabled:
return "legacy"
Expand All @@ -232,15 +228,14 @@ def determine_resolver_variant(options):
@classmethod
def make_requirement_preparer(
cls,
temp_build_dir, # type: TempDirectory
options, # type: Values
req_tracker, # type: RequirementTracker
session, # type: PipSession
finder, # type: PackageFinder
use_user_site, # type: bool
download_dir=None, # type: str
):
# type: (...) -> RequirementPreparer
temp_build_dir: TempDirectory,
options: Values,
req_tracker: RequirementTracker,
session: PipSession,
finder: PackageFinder,
use_user_site: bool,
download_dir: Optional[str] = None,
) -> RequirementPreparer:
"""
Create a RequirementPreparer instance for the given parameters.
"""
Expand Down Expand Up @@ -283,19 +278,18 @@ def make_requirement_preparer(
@classmethod
def make_resolver(
cls,
preparer, # type: RequirementPreparer
finder, # type: PackageFinder
options, # type: Values
wheel_cache=None, # type: Optional[WheelCache]
use_user_site=False, # type: bool
ignore_installed=True, # type: bool
ignore_requires_python=False, # type: bool
force_reinstall=False, # type: bool
upgrade_strategy="to-satisfy-only", # type: str
use_pep517=None, # type: Optional[bool]
py_version_info=None, # type: Optional[Tuple[int, ...]]
):
# type: (...) -> BaseResolver
preparer: RequirementPreparer,
finder: PackageFinder,
options: Values,
wheel_cache: Optional[WheelCache] = None,
use_user_site: bool = False,
ignore_installed: bool = True,
ignore_requires_python: bool = False,
force_reinstall: bool = False,
upgrade_strategy: str = "to-satisfy-only",
use_pep517: Optional[bool] = None,
py_version_info: Optional[Tuple[int, ...]] = None,
) -> BaseResolver:
"""
Create a Resolver instance for the given parameters.
"""
Expand Down Expand Up @@ -342,12 +336,11 @@ def make_resolver(

def get_requirements(
self,
args, # type: List[str]
options, # type: Values
finder, # type: PackageFinder
session, # type: PipSession
):
# type: (...) -> List[InstallRequirement]
args: List[str],
options: Values,
finder: PackageFinder,
session: PipSession,
) -> List[InstallRequirement]:
"""
Parse command-line arguments into the corresponding requirements.
"""
Expand Down Expand Up @@ -421,8 +414,7 @@ def get_requirements(
return requirements

@staticmethod
def trace_basic_info(finder):
# type: (PackageFinder) -> None
def trace_basic_info(finder: PackageFinder) -> None:
"""
Trace basic information about the provided objects.
"""
Expand All @@ -434,12 +426,11 @@ def trace_basic_info(finder):

def _build_package_finder(
self,
options, # type: Values
session, # type: PipSession
target_python=None, # type: Optional[TargetPython]
ignore_requires_python=None, # type: Optional[bool]
):
# type: (...) -> PackageFinder
options: Values,
session: PipSession,
target_python: Optional[TargetPython] = None,
ignore_requires_python: Optional[bool] = None,
) -> PackageFinder:
"""
Create a package finder appropriate to this requirement command.

Expand Down
Loading