Skip to content

Commit

Permalink
Use flake8 simplify (#4798)
Browse files Browse the repository at this point in the history
* Fix SIM102: Use a single if-statement instead of nested if-statements

* Fix SIM105: Use 'contextlib.suppress(...)' instead of try-except-pass

* Fix SIM110: Use 'return any(...)'

* Fix SIM113: Use enumerate instead of manually incrementing a counter

* Fix SIM114: Combine conditions via a logical or to prevent duplicating code

* Fix SIM211: Use 'not a' instead of 'False if a else True'

* Fix SIM300: Use 'age == 42' instead of '42 == age' (Yoda-conditions)

* Fix SIM119: Use dataclasses for data containers

* Ignore "SIM106: Handle error-cases first" for now
  • Loading branch information
radoering authored Nov 21, 2021
1 parent 5c328a3 commit 7aefbd6
Show file tree
Hide file tree
Showing 48 changed files with 349 additions and 366 deletions.
2 changes: 2 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ extend-ignore =
E501,
# E203: Whitespace before ':' (pycqa/pycodestyle#373)
E203,
# SIM106: Handle error-cases first
SIM106,
per-file-ignores =
# F401: Module imported by unused (non-implicit modules)
# TC002: Move third-party import '...' into a type-checking block
Expand Down
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ repos:
- flake8-comprehensions==3.7.0
- flake8-no-pep420==1.2.0
- flake8-quotes==3.3.1
- flake8-simplify==0.14.2
- flake8-tidy-imports==4.5.0
- flake8-type-checking==1.1.0
- flake8-typing-imports==1.11.0
Expand Down
4 changes: 2 additions & 2 deletions get-poetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ def is_decorated():
if platform.system().lower() == "windows":
return (
os.getenv("ANSICON") is not None
or "ON" == os.getenv("ConEmuANSI")
or "xterm" == os.getenv("Term")
or os.getenv("ConEmuANSI") == "ON"
or os.getenv("Term") == "xterm"
)

if not hasattr(sys.stdout, "fileno"):
Expand Down
4 changes: 2 additions & 2 deletions install-poetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ def is_decorated():
if WINDOWS:
return (
os.getenv("ANSICON") is not None
or "ON" == os.getenv("ConEmuANSI")
or "xterm" == os.getenv("Term")
or os.getenv("ConEmuANSI") == "ON"
or os.getenv("Term") == "xterm"
)

if not hasattr(sys.stdout, "fileno"):
Expand Down
9 changes: 3 additions & 6 deletions src/poetry/console/application.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
import re

from contextlib import suppress
from importlib import import_module
from typing import TYPE_CHECKING
from typing import Any
Expand Down Expand Up @@ -195,10 +196,8 @@ def _configure_io(self, io: "IO") -> None:
# We need to check if the command being run
# is the "run" command.
definition = self.definition
try:
with suppress(CleoException):
io.input.bind(definition)
except CleoException:
pass

name = io.input.first_argument
if name == "run":
Expand All @@ -218,10 +217,8 @@ def _configure_io(self, io: "IO") -> None:
for shortcut in shortcuts:
run_input.add_parameter_option("-" + shortcut.lstrip("-"))

try:
with suppress(CleoException):
run_input.bind(definition)
except CleoException:
pass

for option_name, value in input.options.items():
if value:
Expand Down
18 changes: 8 additions & 10 deletions src/poetry/console/commands/new.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import sys

from contextlib import suppress

from cleo.helpers import argument
from cleo.helpers import option

Expand Down Expand Up @@ -44,13 +46,11 @@ def handle(self) -> None:
if not name:
name = path.name

if path.exists():
if list(path.glob("*")):
# Directory is not empty. Aborting.
raise RuntimeError(
"Destination <fg=yellow>{}</> "
"exists and is not empty".format(path)
)
if path.exists() and list(path.glob("*")):
# Directory is not empty. Aborting.
raise RuntimeError(
"Destination <fg=yellow>{}</> " "exists and is not empty".format(path)
)

readme_format = self.option("readme") or "md"

Expand Down Expand Up @@ -78,10 +78,8 @@ def handle(self) -> None:

path = path.resolve()

try:
with suppress(ValueError):
path = path.relative_to(Path.cwd())
except ValueError:
pass

self.line(
"Created package <info>{}</> in <fg=blue>{}</>".format(
Expand Down
15 changes: 7 additions & 8 deletions src/poetry/console/commands/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,13 @@ def handle(self) -> Optional[int]:

# Building package first, if told
if self.option("build"):
if publisher.files:
if not self.confirm(
"There are <info>{}</info> files ready for publishing. "
"Build anyway?".format(len(publisher.files))
):
self.line_error("<error>Aborted!</error>")

return 1
if publisher.files and not self.confirm(
"There are <info>{}</info> files ready for publishing. "
"Build anyway?".format(len(publisher.files))
):
self.line_error("<error>Aborted!</error>")

return 1

self.call("build")

Expand Down
10 changes: 3 additions & 7 deletions src/poetry/console/commands/show.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,11 +359,9 @@ def display_package_tree(
dependencies = package.requires
dependencies = sorted(dependencies, key=lambda x: x.name)
tree_bar = "├"
j = 0
total = len(dependencies)
for dependency in dependencies:
j += 1
if j == total:
for i, dependency in enumerate(dependencies, 1):
if i == total:
tree_bar = "└"

level = 1
Expand Down Expand Up @@ -403,10 +401,8 @@ def _display_tree(

dependencies = sorted(dependencies, key=lambda x: x.name)
tree_bar = previous_tree_bar + " ├"
i = 0
total = len(dependencies)
for dependency in dependencies:
i += 1
for i, dependency in enumerate(dependencies, 1):
current_tree = packages_in_tree
if i == total:
tree_bar = previous_tree_bar + " └"
Expand Down
5 changes: 2 additions & 3 deletions src/poetry/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,8 @@ def create_poetry(
for source in base_poetry.pyproject.poetry_config.get("source", []):
name = source.get("name")
url = source.get("url")
if name and url:
if name not in existing_repositories:
repositories[name] = {"url": url}
if name and url and name not in existing_repositories:
repositories[name] = {"url": url}

config.merge({"repositories": repositories})

Expand Down
19 changes: 10 additions & 9 deletions src/poetry/installation/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,15 +211,16 @@ def _write(self, operation: "OperationTypes", line: str) -> None:
def _execute_operation(self, operation: "OperationTypes") -> None:
try:
if self.supports_fancy_output():
if id(operation) not in self._sections:
if self._should_write_operation(operation):
with self._lock:
self._sections[id(operation)] = self._io.section()
self._sections[id(operation)].write_line(
" <fg=blue;options=bold>•</> {message}: <fg=blue>Pending...</>".format(
message=self.get_operation_message(operation),
),
)
if id(operation) not in self._sections and self._should_write_operation(
operation
):
with self._lock:
self._sections[id(operation)] = self._io.section()
self._sections[id(operation)].write_line(
" <fg=blue;options=bold>•</> {message}: <fg=blue>Pending...</>".format(
message=self.get_operation_message(operation),
),
)
else:
if self._should_write_operation(operation):
if not operation.skipped:
Expand Down
5 changes: 2 additions & 3 deletions src/poetry/installation/installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -569,9 +569,8 @@ def _filter_operations(self, ops: Sequence["Operation"], repo: Repository) -> No

# If a package is optional and not requested
# in any extra we skip it
if package.optional:
if package.name not in extra_packages:
op.skip("Not required")
if package.optional and package.name not in extra_packages:
op.skip("Not required")

def _get_extra_packages(self, repo: Repository) -> List[str]:
"""
Expand Down
14 changes: 8 additions & 6 deletions src/poetry/installation/pip_installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,14 @@ def install(self, package: "Package", update: bool = False) -> None:
index_url = repository.authenticated_url

args += ["--index-url", index_url]
if self._pool.has_default():
if repository.name != self._pool.repositories[0].name:
args += [
"--extra-index-url",
self._pool.repositories[0].authenticated_url,
]
if (
self._pool.has_default()
and repository.name != self._pool.repositories[0].name
):
args += [
"--extra-index-url",
self._pool.repositories[0].authenticated_url,
]

if update:
args.append("-U")
Expand Down
10 changes: 6 additions & 4 deletions src/poetry/puzzle/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,12 +507,14 @@ def complete_package(self, package: DependencyPackage) -> DependencyPackage:
if self._env and not dep.marker.validate(self._env.marker_env):
continue

if not package.is_root():
if (dep.is_optional() and dep.name not in optional_dependencies) or (
if not package.is_root() and (
(dep.is_optional() and dep.name not in optional_dependencies)
or (
dep.in_extras
and not set(dep.in_extras).intersection(package.dependency.extras)
):
continue
)
):
continue

_dependencies.append(dep)

Expand Down
13 changes: 6 additions & 7 deletions src/poetry/puzzle/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,13 @@ def calculate_operations(
if result_package.name == installed_package.name:
installed = True

if result_package.version != installed_package.version:
operations.append(
Update(installed_package, result_package, priority=priority)
if result_package.version != installed_package.version or (
(
installed_package.source_type
or result_package.source_type != "legacy"
)
elif (
installed_package.source_type
or result_package.source_type != "legacy"
) and not result_package.is_same_package_as(installed_package):
and not result_package.is_same_package_as(installed_package)
):
operations.append(
Update(installed_package, result_package, priority=priority)
)
Expand Down
15 changes: 7 additions & 8 deletions src/poetry/repositories/legacy_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,14 +237,13 @@ def find_packages(self, dependency: "Dependency") -> List[Package]:
constraint = parse_constraint(constraint)

allow_prereleases = dependency.allows_prereleases()
if isinstance(constraint, VersionRange):
if (
constraint.max is not None
and constraint.max.is_unstable()
or constraint.min is not None
and constraint.min.is_unstable()
):
allow_prereleases = True
if isinstance(constraint, VersionRange) and (
constraint.max is not None
and constraint.max.is_unstable()
or constraint.min is not None
and constraint.min.is_unstable()
):
allow_prereleases = True

key = dependency.name
if not constraint.is_any():
Expand Down
5 changes: 2 additions & 3 deletions src/poetry/repositories/pool.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from contextlib import suppress
from typing import TYPE_CHECKING
from typing import Dict
from typing import List
Expand Down Expand Up @@ -135,10 +136,8 @@ def package(
raise ValueError(f'Repository "{repository}" does not exist.')

if repository is not None and not self._ignore_repository_names:
try:
with suppress(PackageNotFound):
return self.repository(repository).package(name, version, extras=extras)
except PackageNotFound:
pass
else:
for repo in self._repositories:
try:
Expand Down
15 changes: 7 additions & 8 deletions src/poetry/repositories/pypi_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,13 @@ def find_packages(self, dependency: Dependency) -> List[Package]:
constraint = parse_constraint(constraint)

allow_prereleases = dependency.allows_prereleases()
if isinstance(constraint, VersionRange):
if (
constraint.max is not None
and constraint.max.is_unstable()
or constraint.min is not None
and constraint.min.is_unstable()
):
allow_prereleases = True
if isinstance(constraint, VersionRange) and (
constraint.max is not None
and constraint.max.is_unstable()
or constraint.min is not None
and constraint.min.is_unstable()
):
allow_prereleases = True

try:
info = self.get_package_info(dependency.name)
Expand Down
24 changes: 10 additions & 14 deletions src/poetry/repositories/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,13 @@ def find_packages(self, dependency: "Dependency") -> List["Package"]:
constraint = parse_constraint(constraint)

allow_prereleases = dependency.allows_prereleases()
if isinstance(constraint, VersionRange):
if (
constraint.max is not None
and constraint.max.is_unstable()
or constraint.min is not None
and constraint.min.is_unstable()
):
allow_prereleases = True
if isinstance(constraint, VersionRange) and (
constraint.max is not None
and constraint.max.is_unstable()
or constraint.min is not None
and constraint.min.is_unstable()
):
allow_prereleases = True

for package in self.packages:
if dependency.name == package.name:
Expand All @@ -85,12 +84,9 @@ def find_packages(self, dependency: "Dependency") -> List["Package"]:

def has_package(self, package: "Package") -> bool:
package_id = package.unique_name

for repo_package in self.packages:
if package_id == repo_package.unique_name:
return True

return False
return any(
package_id == repo_package.unique_name for repo_package in self.packages
)

def add_package(self, package: "Package") -> None:
self._packages.append(package)
Expand Down
9 changes: 3 additions & 6 deletions src/poetry/utils/_compat.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import sys

from contextlib import suppress
from typing import List
from typing import Optional

Expand All @@ -20,10 +21,8 @@ def decode(string: str, encodings: Optional[List[str]] = None) -> str:
encodings = encodings or ["utf-8", "latin1", "ascii"]

for encoding in encodings:
try:
with suppress(UnicodeEncodeError, UnicodeDecodeError):
return string.decode(encoding)
except (UnicodeEncodeError, UnicodeDecodeError):
pass

return string.decode(encodings[0], errors="ignore")

Expand All @@ -35,10 +34,8 @@ def encode(string: str, encodings: Optional[List[str]] = None) -> bytes:
encodings = encodings or ["utf-8", "latin1", "ascii"]

for encoding in encodings:
try:
with suppress(UnicodeEncodeError, UnicodeDecodeError):
return string.encode(encoding)
except (UnicodeEncodeError, UnicodeDecodeError):
pass

return string.encode(encodings[0], errors="ignore")

Expand Down
Loading

0 comments on commit 7aefbd6

Please sign in to comment.