Skip to content
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

enable strictness flags for mypy #5531

Merged
merged 7 commits into from
May 8, 2022
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
3 changes: 0 additions & 3 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ ban-relative-imports = true
# flake8-use-fstring: https://github.com/MichaelKim0407/flake8-use-fstring#--percent-greedy-and---format-greedy
format-greedy = 1
inline-quotes = double
# Allow omission of a return type hint for __init__ if at least one argument is annotated
# used by flake8-annotations
mypy-init-return = true
enable-extensions = TC, TC1
type-checking-exempt-modules = typing, typing-extensions
eradicate-whitelist-extend = ^-.*;
Expand Down
23 changes: 17 additions & 6 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,9 @@ force-exclude = '''


[tool.mypy]
check_untyped_defs = true
ignore_missing_imports = true
show_error_codes = true
warn_redundant_casts = true
warn_unused_configs = true
warn_unused_ignores = true
files = "src"
show_error_codes = true
strict = true

# The following whitelist is used to allow for incremental adoption
# of Mypy. Modules should be removed from this whitelist as and when
Expand All @@ -131,6 +127,21 @@ module = [
]
ignore_errors = true

[[tool.mypy.overrides]]
module = [
'cachecontrol.*',
'cachy.*',
'cleo.*',
'crashtest.*',
'entrypoints.*',
'html5lib.*',
'jsonschema.*',
'pexpect.*',
'poetry.core.*',
'requests_toolbelt.*',
'shellingham.*',
]
ignore_missing_imports = true

[tool.coverage.report]
exclude_lines = [
Expand Down
8 changes: 7 additions & 1 deletion src/poetry/__version__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from __future__ import annotations

from typing import Callable

from poetry.utils._compat import metadata


__version__ = metadata.version("poetry")
# The metadata.version that we import for Python 3.7 is untyped, work around
# that.
version: Callable[[str], str] = metadata.version

__version__ = version("poetry")
12 changes: 8 additions & 4 deletions src/poetry/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__(
self._auth_config_source: ConfigSource = DictConfigSource()

@property
def config(self) -> dict:
def config(self) -> dict[str, Any]:
return self._config

@property
Expand All @@ -90,7 +90,7 @@ def merge(self, config: dict[str, Any]) -> None:
merge_dicts(self._config, config)

def all(self) -> dict[str, Any]:
def _all(config: dict, parent_key: str = "") -> dict:
def _all(config: dict[str, Any], parent_key: str = "") -> dict[str, Any]:
all_ = {}

for key in config:
Expand Down Expand Up @@ -159,10 +159,14 @@ def process(self, value: Any) -> Any:
if not isinstance(value, str):
return value

return re.sub(r"{(.+?)}", lambda m: self.get(m.group(1)), value)
return re.sub(
r"{(.+?)}",
lambda m: self.get(m.group(1)), # type: ignore[no-any-return]
value,
)

@staticmethod
def _get_normalizer(name: str) -> Callable:
def _get_normalizer(name: str) -> Callable[[str], Any]:
if name in {
"virtualenvs.create",
"virtualenvs.in-project",
Expand Down
18 changes: 11 additions & 7 deletions src/poetry/console/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@
from poetry.poetry import Poetry


def load_command(name: str) -> Callable:
def load_command(name: str) -> Callable[[], type[Command]]:
def _load() -> type[Command]:
words = name.split(" ")
module = import_module("poetry.console.commands." + ".".join(words))
command_class = getattr(module, "".join(c.title() for c in words) + "Command")
return command_class()
command_type: type[Command] = command_class()
return command_type

return _load

Expand Down Expand Up @@ -89,7 +90,7 @@ def _load() -> type[Command]:
]


class Application(BaseApplication):
class Application(BaseApplication): # type: ignore[misc]
def __init__(self) -> None:
super().__init__("poetry", __version__)

Expand Down Expand Up @@ -128,7 +129,8 @@ def poetry(self) -> Poetry:

@property
def command_loader(self) -> CommandLoader:
return self._command_loader
command_loader: CommandLoader = self._command_loader
return command_loader

def reset_poetry(self) -> None:
self._poetry = None
Expand Down Expand Up @@ -176,7 +178,8 @@ def _run(self, io: IO) -> int:

self._load_plugins(io)

return super()._run(io)
exit_code: int = super()._run(io)
return exit_code

def _configure_io(self, io: IO) -> None:
# We need to check if the command being run
Expand Down Expand Up @@ -212,7 +215,7 @@ def _configure_io(self, io: IO) -> None:

io.set_input(run_input)

return super()._configure_io(io)
super()._configure_io(io)

def register_command_loggers(
self, event: ConsoleCommandEvent, event_name: str, _: Any
Expand Down Expand Up @@ -376,7 +379,8 @@ def _get_solution_provider_repository(self) -> SolutionProviderRepository:


def main() -> int:
return Application().run()
exit_code: int = Application().run()
return exit_code


if __name__ == "__main__":
Expand Down
11 changes: 9 additions & 2 deletions src/poetry/console/command_loader.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
from __future__ import annotations

from typing import TYPE_CHECKING
from typing import Callable

from cleo.exceptions import LogicException
from cleo.loaders.factory_command_loader import FactoryCommandLoader


class CommandLoader(FactoryCommandLoader):
def register_factory(self, command_name: str, factory: Callable) -> None:
if TYPE_CHECKING:
from poetry.console.commands.command import Command


class CommandLoader(FactoryCommandLoader): # type: ignore[misc]
def register_factory(
self, command_name: str, factory: Callable[[], Command]
) -> None:
if command_name in self._factories:
raise LogicException(f'The command "{command_name}" already exists.')

Expand Down
10 changes: 8 additions & 2 deletions src/poetry/console/commands/about.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from typing import Callable

from poetry.console.commands.command import Command


Expand All @@ -12,12 +14,16 @@ class AboutCommand(Command):
def handle(self) -> None:
from poetry.utils._compat import metadata

# The metadata.version that we import for Python 3.7 is untyped, work around
# that.
version: Callable[[str], str] = metadata.version

self.line(
f"""\
<info>Poetry - Package Management for Python

Version: {metadata.version('poetry')}
Poetry-Core Version: {metadata.version('poetry-core')}</info>
Version: {version('poetry')}
Poetry-Core Version: {version('poetry-core')}</info>

<comment>Poetry is a dependency manager tracking local dependencies of your projects\
and libraries.
Expand Down
2 changes: 1 addition & 1 deletion src/poetry/console/commands/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ def handle(self) -> int:
return status

def get_existing_packages_from_input(
self, packages: list[str], section: dict
self, packages: list[str], section: dict[str, Any]
) -> list[str]:
existing_packages = []

Expand Down
5 changes: 3 additions & 2 deletions src/poetry/console/commands/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from poetry.poetry import Poetry


class Command(BaseCommand):
class Command(BaseCommand): # type: ignore[misc]
loggers: list[str] = []

_poetry: Poetry | None = None
Expand All @@ -28,7 +28,8 @@ def set_poetry(self, poetry: Poetry) -> None:
self._poetry = poetry

def get_application(self) -> Application:
return self.application
application: Application = self.application
return application

def reset_poetry(self) -> None:
self.get_application().reset_poetry()
Expand Down
50 changes: 2 additions & 48 deletions src/poetry/console/commands/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,8 @@ def _list_configuration(

if isinstance(value, dict):
k += f"{key}."
self._list_configuration(value, cast(dict, raw_val), k=k)
raw_val = cast("dict[str, Any]", raw_val)
self._list_configuration(value, raw_val, k=k)
k = orig_k

continue
Expand All @@ -338,50 +339,3 @@ def _list_configuration(
message = f"<c1>{k + key}</c1> = <c2>{json.dumps(value)}</c2>"

self.line(message)

def _get_setting(
self,
contents: dict,
setting: str | None = None,
k: str | None = None,
default: Any | None = None,
) -> list[tuple[str, str]]:
orig_k = k

if setting and setting.split(".")[0] not in contents:
value = json.dumps(default)

return [((k or "") + setting, value)]
else:
values = []
for key, value in contents.items():
if setting and key != setting.split(".")[0]:
continue

if isinstance(value, dict) or key == "repositories" and k is None:
if k is None:
k = ""

k += re.sub(r"^config\.", "", key + ".")
if setting and len(setting) > 1:
setting = ".".join(setting.split(".")[1:])

values += self._get_setting(
cast(dict, value), k=k, setting=setting, default=default
)
k = orig_k

continue

if isinstance(value, list):
value = ", ".join(
json.dumps(val) if isinstance(val, list) else val
for val in value
)
value = f"[{value}]"

value = json.dumps(value)

values.append(((k or "") + key, value))

return values
3 changes: 2 additions & 1 deletion src/poetry/console/commands/debug/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ def handle(self) -> int:
)
command = self.application.get("env info")

return command.run(self._io)
exit_code: int = command.run(self._io)
return exit_code
2 changes: 1 addition & 1 deletion src/poetry/console/commands/debug/resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def handle(self) -> int:
from poetry.core.packages.project_package import ProjectPackage

from poetry.factory import Factory
from poetry.puzzle import Solver
from poetry.puzzle.solver import Solver
from poetry.repositories.pool import Pool
from poetry.repositories.repository import Repository
from poetry.utils.env import EnvManager
Expand Down
2 changes: 1 addition & 1 deletion src/poetry/console/commands/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class InstallCommand(InstallerCommand):
def handle(self) -> int:
from poetry.core.masonry.utils.module import ModuleOrPackageNotFound

from poetry.masonry.builders import EditableBuilder
from poetry.masonry.builders.editable import EditableBuilder

self._installer.use_executor(
self.poetry.config.get("experimental.new-installer", False)
Expand Down
5 changes: 3 additions & 2 deletions src/poetry/console/commands/plugin/add.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,16 +170,17 @@ def handle(self) -> int:
if self.option("dry-run"):
argv.append("--dry-run")

return update_command.run(
exit_code: int = update_command.run(
IO(
StringInput(" ".join(argv)),
self._io.output,
self._io.error_output,
)
)
return exit_code

def get_existing_packages_from_input(
self, packages: list[str], poetry_content: dict, target_section: str
self, packages: list[str], poetry_content: dict[str, Any], target_section: str
) -> list[str]:
existing_packages = []

Expand Down
3 changes: 2 additions & 1 deletion src/poetry/console/commands/plugin/remove.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,11 @@ def handle(self) -> int:
if self.option("dry-run"):
argv.append("--dry-run")

return remove_command.run(
exit_code: int = remove_command.run(
IO(
StringInput(" ".join(argv)),
self._io.output,
self._io.error_output,
)
)
return exit_code
10 changes: 8 additions & 2 deletions src/poetry/console/commands/show.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,10 @@ def display_package_tree(
io.write_line(f" <b>{package.pretty_version}</b>{description}")

dependencies = package.requires
dependencies = sorted(dependencies, key=lambda x: x.name)
dependencies = sorted(
dependencies,
key=lambda x: x.name, # type: ignore[no-any-return]
)
tree_bar = "├"
total = len(dependencies)
for i, dependency in enumerate(dependencies, 1):
Expand Down Expand Up @@ -338,7 +341,10 @@ def _display_tree(

break

dependencies = sorted(dependencies, key=lambda x: x.name)
dependencies = sorted(
dependencies,
key=lambda x: x.name, # type: ignore[no-any-return]
)
tree_bar = previous_tree_bar + " ├"
total = len(dependencies)
for i, dependency in enumerate(dependencies, 1):
Expand Down
2 changes: 1 addition & 1 deletion src/poetry/console/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
from cleo.exceptions import CleoSimpleException


class PoetrySimpleConsoleException(CleoSimpleException):
class PoetrySimpleConsoleException(CleoSimpleException): # type: ignore[misc]

pass
2 changes: 1 addition & 1 deletion src/poetry/console/io/inputs/run_argv_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from cleo.io.inputs.definition import Definition


class RunArgvInput(ArgvInput):
class RunArgvInput(ArgvInput): # type: ignore[misc]
def __init__(
self,
argv: list[str] | None = None,
Expand Down
Loading