Skip to content

Complete type annotations in pip/_internal/commands #10182

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 5 commits into from
Jul 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
12 changes: 5 additions & 7 deletions src/pip/_internal/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import importlib
from collections import OrderedDict, namedtuple
from typing import Any, Optional
from typing import Any, Dict, Optional

from pip._internal.cli.base_command import Command

Expand All @@ -18,7 +18,7 @@
# in a test-related module).
# Finally, we need to pass an iterable of pairs here rather than a dict
# so that the ordering won't be lost when using Python 2.7.
commands_dict = OrderedDict([
commands_dict: Dict[str, CommandInfo] = OrderedDict([
('install', CommandInfo(
'pip._internal.commands.install', 'InstallCommand',
'Install packages.',
Expand Down Expand Up @@ -83,11 +83,10 @@
'pip._internal.commands.help', 'HelpCommand',
'Show help for commands.',
)),
]) # type: OrderedDict[str, CommandInfo]
])


def create_command(name, **kwargs):
# type: (str, **Any) -> Command
def create_command(name: str, **kwargs: Any) -> Command:
"""
Create an instance of the Command class with the given name.
"""
Expand All @@ -99,8 +98,7 @@ def create_command(name, **kwargs):
return command


def get_similar_commands(name):
# type: (str) -> Optional[str]
def get_similar_commands(name: str) -> Optional[str]:
"""Command name auto-correct."""
from difflib import get_close_matches

Expand Down
36 changes: 12 additions & 24 deletions src/pip/_internal/commands/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ class CacheCommand(Command):
%prog purge
"""

def add_options(self):
# type: () -> None
def add_options(self) -> None:

self.cmd_opts.add_option(
'--format',
Expand All @@ -50,8 +49,7 @@ def add_options(self):

self.parser.insert_option_group(0, self.cmd_opts)

def run(self, options, args):
# type: (Values, List[Any]) -> int
def run(self, options: Values, args: List[Any]) -> int:
handlers = {
"dir": self.get_cache_dir,
"info": self.get_cache_info,
Expand Down Expand Up @@ -84,15 +82,13 @@ def run(self, options, args):

return SUCCESS

def get_cache_dir(self, options, args):
# type: (Values, List[Any]) -> None
def get_cache_dir(self, options: Values, args: List[Any]) -> None:
if args:
raise CommandError('Too many arguments')

logger.info(options.cache_dir)

def get_cache_info(self, options, args):
# type: (Values, List[Any]) -> None
def get_cache_info(self, options: Values, args: List[Any]) -> None:
if args:
raise CommandError('Too many arguments')

Expand Down Expand Up @@ -124,8 +120,7 @@ def get_cache_info(self, options, args):

logger.info(message)

def list_cache_items(self, options, args):
# type: (Values, List[Any]) -> None
def list_cache_items(self, options: Values, args: List[Any]) -> None:
if len(args) > 1:
raise CommandError('Too many arguments')

Expand All @@ -140,8 +135,7 @@ def list_cache_items(self, options, args):
else:
self.format_for_abspath(files)

def format_for_human(self, files):
# type: (List[str]) -> None
def format_for_human(self, files: List[str]) -> None:
if not files:
logger.info('Nothing cached.')
return
Expand All @@ -154,8 +148,7 @@ def format_for_human(self, files):
logger.info('Cache contents:\n')
logger.info('\n'.join(sorted(results)))

def format_for_abspath(self, files):
# type: (List[str]) -> None
def format_for_abspath(self, files: List[str]) -> None:
if not files:
return

Expand All @@ -165,8 +158,7 @@ def format_for_abspath(self, files):

logger.info('\n'.join(sorted(results)))

def remove_cache_items(self, options, args):
# type: (Values, List[Any]) -> None
def remove_cache_items(self, options: Values, args: List[Any]) -> None:
if len(args) > 1:
raise CommandError('Too many arguments')

Expand All @@ -187,24 +179,20 @@ def remove_cache_items(self, options, args):
logger.verbose("Removed %s", filename)
logger.info("Files removed: %s", len(files))

def purge_cache(self, options, args):
# type: (Values, List[Any]) -> None
def purge_cache(self, options: Values, args: List[Any]) -> None:
if args:
raise CommandError('Too many arguments')

return self.remove_cache_items(options, ['*'])

def _cache_dir(self, options, subdir):
# type: (Values, str) -> str
def _cache_dir(self, options: Values, subdir: str) -> str:
return os.path.join(options.cache_dir, subdir)

def _find_http_files(self, options):
# type: (Values) -> List[str]
def _find_http_files(self, options: Values) -> List[str]:
http_dir = self._cache_dir(options, 'http')
return filesystem.find_files(http_dir, '*')

def _find_wheels(self, options, pattern):
# type: (Values, str) -> List[str]
def _find_wheels(self, options: Values, pattern: str) -> List[str]:
wheel_dir = self._cache_dir(options, 'wheels')

# The wheel filename format, as specified in PEP 427, is:
Expand Down
3 changes: 1 addition & 2 deletions src/pip/_internal/commands/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ class CheckCommand(Command):
usage = """
%prog [options]"""

def run(self, options, args):
# type: (Values, List[Any]) -> int
def run(self, options: Values, args: List[Any]) -> int:

package_set, parsing_probs = create_package_set_from_installed()
missing, conflicting = check_package_set(package_set)
Expand Down
6 changes: 2 additions & 4 deletions src/pip/_internal/commands/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ class CompletionCommand(Command):

ignore_require_venv = True

def add_options(self):
# type: () -> None
def add_options(self) -> None:
self.cmd_opts.add_option(
'--bash', '-b',
action='store_const',
Expand All @@ -74,8 +73,7 @@ def add_options(self):

self.parser.insert_option_group(0, self.cmd_opts)

def run(self, options, args):
# type: (Values, List[str]) -> int
def run(self, options: Values, args: List[str]) -> int:
"""Prints the completion code of the given shell"""
shells = COMPLETION_SCRIPTS.keys()
shell_options = ['--' + shell for shell in sorted(shells)]
Expand Down
42 changes: 14 additions & 28 deletions src/pip/_internal/commands/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ class ConfigurationCommand(Command):
%prog [<file-option>] debug
"""

def add_options(self):
# type: () -> None
def add_options(self) -> None:
self.cmd_opts.add_option(
'--editor',
dest='editor',
Expand Down Expand Up @@ -88,8 +87,7 @@ def add_options(self):

self.parser.insert_option_group(0, self.cmd_opts)

def run(self, options, args):
# type: (Values, List[str]) -> int
def run(self, options: Values, args: List[str]) -> int:
handlers = {
"list": self.list_values,
"edit": self.open_in_editor,
Expand Down Expand Up @@ -134,8 +132,7 @@ def run(self, options, args):

return SUCCESS

def _determine_file(self, options, need_value):
# type: (Values, bool) -> Optional[Kind]
def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]:
file_options = [key for key, value in (
(kinds.USER, options.user_file),
(kinds.GLOBAL, options.global_file),
Expand All @@ -161,36 +158,31 @@ def _determine_file(self, options, need_value):
"(--user, --site, --global) to perform."
)

def list_values(self, options, args):
# type: (Values, List[str]) -> None
def list_values(self, options: Values, args: List[str]) -> None:
self._get_n_args(args, "list", n=0)

for key, value in sorted(self.configuration.items()):
write_output("%s=%r", key, value)

def get_name(self, options, args):
# type: (Values, List[str]) -> None
def get_name(self, options: Values, args: List[str]) -> None:
key = self._get_n_args(args, "get [name]", n=1)
value = self.configuration.get_value(key)

write_output("%s", value)

def set_name_value(self, options, args):
# type: (Values, List[str]) -> None
def set_name_value(self, options: Values, args: List[str]) -> None:
key, value = self._get_n_args(args, "set [name] [value]", n=2)
self.configuration.set_value(key, value)

self._save_configuration()

def unset_name(self, options, args):
# type: (Values, List[str]) -> None
def unset_name(self, options: Values, args: List[str]) -> None:
key = self._get_n_args(args, "unset [name]", n=1)
self.configuration.unset_value(key)

self._save_configuration()

def list_config_values(self, options, args):
# type: (Values, List[str]) -> None
def list_config_values(self, options: Values, args: List[str]) -> None:
"""List config key-value pairs across different config files"""
self._get_n_args(args, "debug", n=0)

Expand All @@ -207,25 +199,22 @@ def list_config_values(self, options, args):
if file_exists:
self.print_config_file_values(variant)

def print_config_file_values(self, variant):
# type: (Kind) -> None
def print_config_file_values(self, variant: Kind) -> None:
"""Get key-value pairs from the file of a variant"""
for name, value in self.configuration.\
get_values_in_config(variant).items():
with indent_log():
write_output("%s: %s", name, value)

def print_env_var_values(self):
# type: () -> None
def print_env_var_values(self) -> None:
"""Get key-values pairs present as environment variables"""
write_output("%s:", 'env_var')
with indent_log():
for key, value in sorted(self.configuration.get_environ_vars()):
env_var = f'PIP_{key.upper()}'
write_output("%s=%r", env_var, value)

def open_in_editor(self, options, args):
# type: (Values, List[str]) -> None
def open_in_editor(self, options: Values, args: List[str]) -> None:
editor = self._determine_editor(options)

fname = self.configuration.get_file_to_edit()
Expand All @@ -240,8 +229,7 @@ def open_in_editor(self, options, args):
.format(e.returncode)
)

def _get_n_args(self, args, example, n):
# type: (List[str], str, int) -> Any
def _get_n_args(self, args: List[str], example: str, n: int) -> Any:
"""Helper to make sure the command got the right number of arguments
"""
if len(args) != n:
Expand All @@ -256,8 +244,7 @@ def _get_n_args(self, args, example, n):
else:
return args

def _save_configuration(self):
# type: () -> None
def _save_configuration(self) -> None:
# We successfully ran a modifying command. Need to save the
# configuration.
try:
Expand All @@ -268,8 +255,7 @@ def _save_configuration(self):
)
raise PipError("Internal Error.")

def _determine_editor(self, options):
# type: (Values) -> str
def _determine_editor(self, options: Values) -> str:
if options.editor is not None:
return options.editor
elif "VISUAL" in os.environ:
Expand Down
Loading