From b753aaf4c3c08ef0e54941a6616fe318fdf4f6e4 Mon Sep 17 00:00:00 2001 From: ThatXliner Date: Fri, 2 Apr 2021 09:13:57 -0700 Subject: [PATCH] Used pyupgrade to remove compatibility code (#3861) * Used pyupgrade to remove compatibility code May fix #3860 --- poetry/config/config.py | 4 +- poetry/config/config_source.py | 2 +- poetry/console/application.py | 6 +- poetry/inspection/info.py | 20 +++--- poetry/installation/authenticator.py | 10 +-- poetry/installation/chef.py | 2 +- poetry/installation/chooser.py | 12 ++-- poetry/installation/executor.py | 13 ++-- poetry/installation/installer.py | 10 +-- poetry/installation/pip_installer.py | 12 ++-- poetry/json/__init__.py | 5 +- poetry/layouts/layout.py | 6 +- poetry/layouts/src.py | 4 +- poetry/layouts/standard.py | 4 +- poetry/mixology/assignment.py | 2 +- poetry/mixology/failure.py | 8 +-- poetry/mixology/incompatibility.py | 36 ++++++----- poetry/mixology/partial_solution.py | 2 +- poetry/mixology/term.py | 10 +-- poetry/mixology/version_solver.py | 10 ++- poetry/packages/dependency_package.py | 4 +- poetry/packages/locker.py | 4 +- poetry/packages/package_collection.py | 4 +- poetry/plugins/base_plugin.py | 2 +- poetry/plugins/plugin_manager.py | 6 +- poetry/publishing/publisher.py | 8 +-- poetry/publishing/uploader.py | 37 ++++-------- poetry/puzzle/exceptions.py | 2 +- poetry/puzzle/provider.py | 8 +-- poetry/puzzle/solver.py | 10 ++- poetry/repositories/base_repository.py | 2 +- poetry/repositories/legacy_repository.py | 8 +-- poetry/repositories/pool.py | 10 +-- poetry/repositories/pypi_repository.py | 30 ++++----- poetry/repositories/remote_repository.py | 2 +- poetry/repositories/repository.py | 2 +- poetry/utils/_compat.py | 2 +- poetry/utils/env.py | 77 ++++++++++++------------ poetry/utils/exporter.py | 18 +++--- poetry/utils/helpers.py | 6 +- poetry/utils/password_manager.py | 26 ++++---- poetry/utils/setup_reader.py | 2 +- poetry/utils/shell.py | 2 +- poetry/version/version_selector.py | 6 +- 44 files changed, 198 insertions(+), 258 deletions(-) diff --git a/poetry/config/config.py b/poetry/config/config.py index c0f794bd004..b1b3b3e61bb 100644 --- a/poetry/config/config.py +++ b/poetry/config/config.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import os import re @@ -27,7 +25,7 @@ def boolean_normalizer(val: str) -> bool: return val in ["true", "1"] -class Config(object): +class Config: default_config = { "cache-dir": str(CACHE_DIR), diff --git a/poetry/config/config_source.py b/poetry/config/config_source.py index 0a6707f28c9..2fc9b585ac6 100644 --- a/poetry/config/config_source.py +++ b/poetry/config/config_source.py @@ -1,7 +1,7 @@ from typing import Any -class ConfigSource(object): +class ConfigSource: def add_property(self, key: str, value: Any) -> None: raise NotImplementedError() diff --git a/poetry/console/application.py b/poetry/console/application.py index d9d9277d274..8dcbced0b73 100644 --- a/poetry/console/application.py +++ b/poetry/console/application.py @@ -88,7 +88,7 @@ def _load() -> Type[Command]: class Application(BaseApplication): def __init__(self) -> None: - super(Application, self).__init__("poetry", __version__) + super().__init__("poetry", __version__) self._poetry = None self._io: Optional[IO] = None @@ -132,7 +132,7 @@ def create_io( output: Optional[Output] = None, error_output: Optional[Output] = None, ) -> IO: - io = super(Application, self).create_io(input, output, error_output) + io = super().create_io(input, output, error_output) # Set our own CLI styles formatter = io.output.formatter @@ -265,7 +265,7 @@ def configure_env( env = env_manager.create_venv(io) if env.is_venv() and io.is_verbose(): - io.write_line("Using virtualenv: {}".format(env.path)) + io.write_line(f"Using virtualenv: {env.path}") command.set_env(env) diff --git a/poetry/inspection/info.py b/poetry/inspection/info.py index fbc96b40015..ae5f59bd63f 100644 --- a/poetry/inspection/info.py +++ b/poetry/inspection/info.py @@ -47,9 +47,7 @@ def __init__( reasons = ( "Unable to determine package info for path: {}".format(str(path)), ) + reasons - super(PackageInfoError, self).__init__( - "\n\n".join(str(msg).strip() for msg in reasons if msg) - ) + super().__init__("\n\n".join(str(msg).strip() for msg in reasons if msg)) class PackageInfo: @@ -119,7 +117,7 @@ def load(cls, data: Dict[str, Optional[Union[str, List[str]]]]) -> "PackageInfo" @classmethod def _log(cls, msg: str, level: str = "info") -> None: """Internal helper method to log information.""" - getattr(logger, level)("{}: {}".format(cls.__name__, msg)) + getattr(logger, level)(f"{cls.__name__}: {msg}") def to_package( self, @@ -139,9 +137,7 @@ def to_package( if not self.version: # The version could not be determined, so we raise an error since it is mandatory. - raise RuntimeError( - "Unable to retrieve the package version for {}".format(name) - ) + raise RuntimeError(f"Unable to retrieve the package version for {name}") package = Package( name=name, @@ -329,7 +325,7 @@ def from_setup_files(cls, path: Path) -> "PackageInfo": requires += "\n" for extra_name, deps in result["extras_require"].items(): - requires += "[{}]\n".format(extra_name) + requires += f"[{extra_name}]\n" for dep in deps: requires += dep + "\n" @@ -462,7 +458,7 @@ def _pep517_metadata(cls, path: Path) -> "PackageInfo": "install", "--disable-pip-version-check", "--ignore-installed", - *PEP517_META_BUILD_DEPS + *PEP517_META_BUILD_DEPS, ) venv.run( "python", @@ -475,7 +471,7 @@ def _pep517_metadata(cls, path: Path) -> "PackageInfo": except EnvCommandError as e: # something went wrong while attempting pep517 metadata build # fallback to egg_info if setup.py available - cls._log("PEP517 build failed: {}".format(e), level="debug") + cls._log(f"PEP517 build failed: {e}", level="debug") setup_py = path / "setup.py" if not setup_py.exists(): raise PackageInfoError( @@ -497,9 +493,7 @@ def _pep517_metadata(cls, path: Path) -> "PackageInfo": os.chdir(cwd.as_posix()) if info: - cls._log( - "Falling back to parsed setup.py file for {}".format(path), "debug" - ) + cls._log(f"Falling back to parsed setup.py file for {path}", "debug") return info # if we reach here, everything has failed and all hope is lost diff --git a/poetry/installation/authenticator.py b/poetry/installation/authenticator.py index 84ba26c027e..8c5e1d01222 100644 --- a/poetry/installation/authenticator.py +++ b/poetry/installation/authenticator.py @@ -24,7 +24,7 @@ logger = logging.getLogger() -class Authenticator(object): +class Authenticator: def __init__(self, config: "Config", io: Optional["IO"] = None) -> None: self._config = config self._io = io @@ -92,9 +92,7 @@ def request(self, method: str, url: str, **kwargs: Any) -> requests.Response: if not is_last_attempt: attempt += 1 delay = 0.5 * attempt - self._log( - "Retrying HTTP request in {} seconds.".format(delay), level="debug" - ) + self._log(f"Retrying HTTP request in {delay} seconds.", level="debug") time.sleep(delay) continue @@ -141,9 +139,7 @@ def _get_credentials_for_netloc_from_config( credentials = (None, None) for repository_name in self._config.get("repositories", []): - repository_config = self._config.get( - "repositories.{}".format(repository_name) - ) + repository_config = self._config.get(f"repositories.{repository_name}") if not repository_config: continue diff --git a/poetry/installation/chef.py b/poetry/installation/chef.py index 4f373b8752a..ce095a03d5c 100644 --- a/poetry/installation/chef.py +++ b/poetry/installation/chef.py @@ -80,7 +80,7 @@ def get_cached_archives_for_link(self, link: Link) -> List[Link]: archive_types = ["whl", "tar.gz", "tar.bz2", "bz2", "zip"] links = [] for archive_type in archive_types: - for archive in cache_dir.glob("*.{}".format(archive_type)): + for archive in cache_dir.glob(f"*.{archive_type}"): links.append(Link(archive.as_uri())) return links diff --git a/poetry/installation/chooser.py b/poetry/installation/chooser.py index 10c89c1ce6d..0069a50a47f 100644 --- a/poetry/installation/chooser.py +++ b/poetry/installation/chooser.py @@ -17,11 +17,11 @@ class InvalidWheelName(Exception): pass -class Wheel(object): +class Wheel: def __init__(self, filename: str) -> None: wheel_info = wheel_file_re.match(filename) if not wheel_info: - raise InvalidWheelName("{} is not a valid wheel filename.".format(filename)) + raise InvalidWheelName(f"{filename} is not a valid wheel filename.") self.filename = filename self.name = wheel_info.group("name").replace("_", "-") @@ -70,16 +70,12 @@ def choose_for(self, package: Package) -> Link: links.append(link) if not links: - raise RuntimeError( - "Unable to find installation candidates for {}".format(package) - ) + raise RuntimeError(f"Unable to find installation candidates for {package}") # Get the best link chosen = max(links, key=lambda link: self._sort_key(package, link)) if not chosen: - raise RuntimeError( - "Unable to find installation candidates for {}".format(package) - ) + raise RuntimeError(f"Unable to find installation candidates for {package}") return chosen diff --git a/poetry/installation/executor.py b/poetry/installation/executor.py index 89ab57a7cf5..5e2daa012eb 100644 --- a/poetry/installation/executor.py +++ b/poetry/installation/executor.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import division - import itertools import os import threading @@ -44,7 +41,7 @@ from .operations import OperationTypes -class Executor(object): +class Executor: def __init__( self, env: "Env", @@ -296,7 +293,7 @@ def _do_execute_operation(self, operation: "OperationTypes") -> int: return 0 - result = getattr(self, "_execute_{}".format(method))(operation) + result = getattr(self, f"_execute_{method}")(operation) if result != 0: return result @@ -431,9 +428,7 @@ def _display_summary(self, operations: List["OperationTypes"]) -> None: "" if updates == 1 else "s", uninstalls, "" if uninstalls == 1 else "s", - ", {} skipped".format(skipped) - if skipped and self._verbose - else "", + f", {skipped} skipped" if skipped and self._verbose else "", ) ) self._io.write_line("") @@ -638,7 +633,7 @@ def _download_link(self, operation: Union[Install, Update], link: Link) -> Link: archive_hash = "sha256:" + FileDependency(package.name, archive).hash() if archive_hash not in {f["hash"] for f in package.files}: raise RuntimeError( - "Invalid hash for {} using archive {}".format(package, archive.name) + f"Invalid hash for {package} using archive {archive.name}" ) return archive diff --git a/poetry/installation/installer.py b/poetry/installation/installer.py index bc254c135e3..0b91efa35f6 100644 --- a/poetry/installation/installer.py +++ b/poetry/installation/installer.py @@ -200,7 +200,7 @@ def _do_refresh(self) -> int: # Checking extras for extra in self._extras: if extra not in self._package.extras: - raise ValueError("Extra [{}] is not specified.".format(extra)) + raise ValueError(f"Extra [{extra}] is not specified.") locked_repository = self._locker.locked_repository(True) solver = Solver( @@ -237,7 +237,7 @@ def _do_install(self, local_repo: Repository) -> int: # Checking extras for extra in self._extras: if extra not in self._package.extras: - raise ValueError("Extra [{}] is not specified.".format(extra)) + raise ValueError(f"Extra [{extra}] is not specified.") self._io.write_line("Updating dependencies") solver = Solver( @@ -267,7 +267,7 @@ def _do_install(self, local_repo: Repository) -> int: for extra in self._extras: if extra not in self._locker.lock_data.get("extras", {}): - raise ValueError("Extra [{}] is not specified.".format(extra)) + raise ValueError(f"Extra [{extra}] is not specified.") # If we are installing from lock # Filter the operations by comparing it with what is @@ -378,7 +378,7 @@ def _execute(self, operations: List["OperationTypes"]) -> int: "" if updates == 1 else "s", uninstalls, "" if uninstalls == 1 else "s", - ", {} skipped".format(skipped) + f", {skipped} skipped" if skipped and self.is_verbose() else "", ) @@ -397,7 +397,7 @@ def _execute_operation(self, operation: Operation) -> None: """ method = operation.job_type - getattr(self, "_execute_{}".format(method))(operation) + getattr(self, f"_execute_{method}")(operation) def _execute_install(self, operation: Install) -> None: if operation.skipped: diff --git a/poetry/installation/pip_installer.py b/poetry/installation/pip_installer.py index bf253367fc3..9c70f338afe 100644 --- a/poetry/installation/pip_installer.py +++ b/poetry/installation/pip_installer.py @@ -134,14 +134,14 @@ def run(self, *args: Any, **kwargs: Any) -> str: def requirement(self, package: "Package", formatted: bool = False) -> str: if formatted and not package.source_type: - req = "{}=={}".format(package.name, package.version) + req = f"{package.name}=={package.version}" for f in package.files: hash_type = "sha256" h = f["hash"] if ":" in h: hash_type, h = h.split(":") - req += " --hash {}:{}".format(hash_type, h) + req += f" --hash {hash_type}:{h}" req += "\n" @@ -169,14 +169,12 @@ def requirement(self, package: "Package", formatted: bool = False) -> str: return req if package.source_type == "url": - return "{}#egg={}".format(package.source_url, package.name) + return f"{package.source_url}#egg={package.name}" - return "{}=={}".format(package.name, package.version) + return f"{package.name}=={package.version}" def create_temporary_requirement(self, package: "Package") -> str: - fd, name = tempfile.mkstemp( - "reqs.txt", "{}-{}".format(package.name, package.version) - ) + fd, name = tempfile.mkstemp("reqs.txt", f"{package.name}-{package.version}") try: os.write(fd, encode(self.requirement(package, formatted=True))) diff --git a/poetry/json/__init__.py b/poetry/json/__init__.py index d65edd6106a..ad4eafed7a9 100644 --- a/poetry/json/__init__.py +++ b/poetry/json/__init__.py @@ -1,7 +1,6 @@ import json import os -from io import open from typing import List import jsonschema @@ -16,10 +15,10 @@ class ValidationError(ValueError): def validate_object(obj: dict, schema_name: str) -> List[str]: - schema = os.path.join(SCHEMA_DIR, "{}.json".format(schema_name)) + schema = os.path.join(SCHEMA_DIR, f"{schema_name}.json") if not os.path.exists(schema): - raise ValueError("Schema {} does not exist.".format(schema_name)) + raise ValueError(f"Schema {schema_name} does not exist.") with open(schema, encoding="utf-8") as f: schema = json.loads(f.read()) diff --git a/poetry/layouts/layout.py b/poetry/layouts/layout.py index ed3b7b45777..dfc2e609c95 100644 --- a/poetry/layouts/layout.py +++ b/poetry/layouts/layout.py @@ -14,7 +14,7 @@ from poetry.core.pyproject.toml import PyProjectTOML -TESTS_DEFAULT = u"""from {package_name} import __version__ +TESTS_DEFAULT = """from {package_name} import __version__ def test_version(): @@ -51,7 +51,7 @@ def test_version(): BUILD_SYSTEM_MAX_VERSION: Optional[str] = None -class Layout(object): +class Layout: def __init__( self, project: str, @@ -146,7 +146,7 @@ def _create_readme(self, path: "Path") -> None: def _create_tests(self, path: "Path") -> None: tests = path / "tests" tests_init = tests / "__init__.py" - tests_default = tests / "test_{}.py".format(self._package_name) + tests_default = tests / f"test_{self._package_name}.py" tests.mkdir() tests_init.touch(exist_ok=False) diff --git a/poetry/layouts/src.py b/poetry/layouts/src.py index 3d844b4a4fc..4f43263ef93 100644 --- a/poetry/layouts/src.py +++ b/poetry/layouts/src.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from typing import TYPE_CHECKING from .layout import Layout @@ -8,7 +6,7 @@ if TYPE_CHECKING: from pathlib import Path -DEFAULT = u"""__version__ = '{version}' +DEFAULT = """__version__ = '{version}' """ diff --git a/poetry/layouts/standard.py b/poetry/layouts/standard.py index e0a1db99204..9971d4aed8d 100644 --- a/poetry/layouts/standard.py +++ b/poetry/layouts/standard.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from typing import TYPE_CHECKING from .layout import Layout @@ -7,7 +5,7 @@ if TYPE_CHECKING: from pathlib import Path -DEFAULT = u"""__version__ = '{version}' +DEFAULT = """__version__ = '{version}' """ diff --git a/poetry/mixology/assignment.py b/poetry/mixology/assignment.py index 836c1895b66..e0079d46b1a 100644 --- a/poetry/mixology/assignment.py +++ b/poetry/mixology/assignment.py @@ -25,7 +25,7 @@ def __init__( index: int, cause: Optional["Incompatibility"] = None, ) -> None: - super(Assignment, self).__init__(dependency, is_positive) + super().__init__(dependency, is_positive) self._decision_level = decision_level self._index = index diff --git a/poetry/mixology/failure.py b/poetry/mixology/failure.py index 55a163c0e5f..bf84348ced1 100644 --- a/poetry/mixology/failure.py +++ b/poetry/mixology/failure.py @@ -65,9 +65,7 @@ def write(self) -> str: if isinstance(self._root.cause, ConflictCause): self._visit(self._root, {}) else: - self._write( - self._root, "Because {}, version solving failed.".format(self._root) - ) + self._write(self._root, f"Because {self._root}, version solving failed.") padding = ( 0 @@ -89,7 +87,7 @@ def write(self) -> str: number = line[-1] if number is not None: - message = "({})".format(number).ljust(padding) + message + message = f"({number})".ljust(padding) + message else: message = " " * padding + message @@ -165,7 +163,7 @@ def _visit( self._visit(second, details_for_cause) self._write( incompatibility, - "Thus, {}.".format(incompatibility_string), + f"Thus, {incompatibility_string}.", numbered=numbered, ) else: diff --git a/poetry/mixology/incompatibility.py b/poetry/mixology/incompatibility.py index 0a848d1374c..e195e08b7ab 100644 --- a/poetry/mixology/incompatibility.py +++ b/poetry/mixology/incompatibility.py @@ -105,11 +105,9 @@ def external_incompatibilities( """ if isinstance(self._cause, ConflictCause): cause: ConflictCause = self._cause - for incompatibility in cause.conflict.external_incompatibilities: - yield incompatibility + yield from cause.conflict.external_incompatibilities - for incompatibility in cause.other.external_incompatibilities: - yield incompatibility + yield from cause.other.external_incompatibilities else: yield self @@ -136,7 +134,7 @@ def __str__(self) -> str: cause: PythonCause = self._cause text = "{} requires ".format(self._terse(self._terms[0], allow_every=True)) - text += "Python {}".format(cause.python_version) + text += f"Python {cause.python_version}" return text elif isinstance(self._cause, PlatformCause): @@ -145,7 +143,7 @@ def __str__(self) -> str: cause: PlatformCause = self._cause text = "{} requires ".format(self._terse(self._terms[0], allow_every=True)) - text += "platform {}".format(cause.platform) + text += f"platform {cause.platform}" return text elif isinstance(self._cause, NoVersionsCause): @@ -201,7 +199,7 @@ def __str__(self) -> str: else self._terse(term2) ) - return "{} is incompatible with {}".format(package1, package2) + return f"{package1} is incompatible with {package2}" else: return "either {} or {}".format( self._terse(term1), self._terse(term2) @@ -305,14 +303,14 @@ def _try_requires_both( else: buffer.append("requires") - buffer.append(" both {}".format(this_negatives)) + buffer.append(f" both {this_negatives}") if this_line is not None: - buffer.append(" ({})".format(this_line)) + buffer.append(f" ({this_line})") - buffer.append(" and {}".format(other_negatives)) + buffer.append(f" and {other_negatives}") if other_line is not None: - buffer.append(" ({})".format(other_line)) + buffer.append(f" ({other_line})") return "".join(buffer) @@ -361,7 +359,7 @@ def _try_requires_through( buffer = [] if len(prior_positives) > 1: prior_string = " or ".join([self._terse(term) for term in prior_positives]) - buffer.append("if {} then ".format(prior_string)) + buffer.append(f"if {prior_string} then ") else: if isinstance(prior.cause, DependencyCause): verb = "depends on" @@ -374,7 +372,7 @@ def _try_requires_through( buffer.append(self._terse(prior_negative)) if prior_line is not None: - buffer.append(" ({})".format(prior_line)) + buffer.append(f" ({prior_line})") buffer.append(" which ") @@ -390,7 +388,7 @@ def _try_requires_through( ) if latter_line is not None: - buffer.append(" ({})".format(latter_line)) + buffer.append(f" ({latter_line})") return "".join(buffer) @@ -423,7 +421,7 @@ def _try_requires_forbidden( buffer = [] if len(positives) > 1: prior_string = " or ".join([self._terse(term) for term in positives]) - buffer.append("if {} then ".format(prior_string)) + buffer.append(f"if {prior_string} then ") else: buffer.append(self._terse(positives[0], allow_every=True)) if isinstance(prior.cause, DependencyCause): @@ -433,11 +431,11 @@ def _try_requires_forbidden( buffer.append(self._terse(latter.terms[0]) + " ") if prior_line is not None: - buffer.append("({}) ".format(prior_line)) + buffer.append(f"({prior_line}) ") if isinstance(latter.cause, PythonCause): cause: PythonCause = latter.cause - buffer.append("which requires Python {}".format(cause.python_version)) + buffer.append(f"which requires Python {cause.python_version}") elif isinstance(latter.cause, NoVersionsCause): buffer.append("which doesn't match any versions") elif isinstance(latter.cause, PackageNotFoundCause): @@ -446,13 +444,13 @@ def _try_requires_forbidden( buffer.append("which is forbidden") if latter_line is not None: - buffer.append(" ({})".format(latter_line)) + buffer.append(f" ({latter_line})") return "".join(buffer) def _terse(self, term: Term, allow_every: bool = False) -> str: if allow_every and term.constraint.is_any(): - return "every version of {}".format(term.dependency.complete_name) + return f"every version of {term.dependency.complete_name}" if term.dependency.is_root: return term.dependency.pretty_name diff --git a/poetry/mixology/partial_solution.py b/poetry/mixology/partial_solution.py index f06c65de792..96a761d4438 100644 --- a/poetry/mixology/partial_solution.py +++ b/poetry/mixology/partial_solution.py @@ -199,7 +199,7 @@ def satisfier(self, term: Term) -> Assignment: if assigned_term.satisfies(term): return assignment - raise RuntimeError("[BUG] {} is not satisfied.".format(term)) + raise RuntimeError(f"[BUG] {term} is not satisfied.") def satisfies(self, term: Term) -> bool: return self.relation(term) == SetRelation.SUBSET diff --git a/poetry/mixology/term.py b/poetry/mixology/term.py index 3b76578ba14..9542689e033 100644 --- a/poetry/mixology/term.py +++ b/poetry/mixology/term.py @@ -10,7 +10,7 @@ from poetry.core.semver.helpers import VersionTypes -class Term(object): +class Term: """ A statement about a package which is true or false for a given selection of package versions. @@ -52,9 +52,7 @@ def relation(self, other: "Term") -> int: allowed by this term and another. """ if self.dependency.complete_name != other.dependency.complete_name: - raise ValueError( - "{} should refer to {}".format(other, self.dependency.complete_name) - ) + raise ValueError(f"{other} should refer to {self.dependency.complete_name}") other_constraint = other.constraint @@ -116,9 +114,7 @@ def intersect(self, other: "Term") -> Optional["Term"]: allowed by both this term and another """ if self.dependency.complete_name != other.dependency.complete_name: - raise ValueError( - "{} should refer to {}".format(other, self.dependency.complete_name) - ) + raise ValueError(f"{other} should refer to {self.dependency.complete_name}") if self._compatible_dependency(other.dependency): if self.is_positive() != other.is_positive(): diff --git a/poetry/mixology/version_solver.py b/poetry/mixology/version_solver.py index beb60c59dd7..c9025964440 100644 --- a/poetry/mixology/version_solver.py +++ b/poetry/mixology/version_solver.py @@ -193,7 +193,7 @@ def _resolve_conflict(self, incompatibility: Incompatibility) -> Incompatibility .. _conflict resolution: https://github.com/dart-lang/pub/tree/master/doc/solver.md#conflict-resolution """ - self._log("conflict: {}".format(incompatibility)) + self._log(f"conflict: {incompatibility}") new_incompatibility = False while not incompatibility.is_failure(): @@ -308,10 +308,8 @@ def _resolve_conflict(self, incompatibility: Incompatibility) -> Incompatibility bang, most_recent_term, partially, most_recent_satisfier ) ) - self._log( - '{} which is caused by "{}"'.format(bang, most_recent_satisfier.cause) - ) - self._log("{} thus: {}".format(bang, incompatibility)) + self._log(f'{bang} which is caused by "{most_recent_satisfier.cause}"') + self._log(f"{bang} thus: {incompatibility}") raise SolveFailure(incompatibility) @@ -429,7 +427,7 @@ def _result(self) -> SolverResult: ) def _add_incompatibility(self, incompatibility: Incompatibility) -> None: - self._log("fact: {}".format(incompatibility)) + self._log(f"fact: {incompatibility}") for term in incompatibility.terms: if term.dependency.complete_name not in self._incompatibilities: diff --git a/poetry/packages/dependency_package.py b/poetry/packages/dependency_package.py index cc50e8d94dc..e215db5b3b2 100644 --- a/poetry/packages/dependency_package.py +++ b/poetry/packages/dependency_package.py @@ -6,7 +6,7 @@ from poetry.core.packages.package import Package -class DependencyPackage(object): +class DependencyPackage: def __init__(self, dependency: Dependency, package: Package) -> None: self._dependency = dependency self._package = package @@ -33,7 +33,7 @@ def __getattr__(self, name: str) -> Any: def __setattr__(self, key: str, value: Any) -> None: if key in {"_dependency", "_package"}: - return super(DependencyPackage, self).__setattr__(key, value) + return super().__setattr__(key, value) setattr(self._package, key, value) diff --git a/poetry/packages/locker.py b/poetry/packages/locker.py index 3b1436bcf52..03f6e677eb9 100644 --- a/poetry/packages/locker.py +++ b/poetry/packages/locker.py @@ -43,7 +43,7 @@ logger = logging.getLogger(__name__) -class Locker(object): +class Locker: _VERSION = "1.1" @@ -471,7 +471,7 @@ def _get_lock_data(self) -> "TOMLDocument": try: lock_data = self._lock.read() except TOMLKitError as e: - raise RuntimeError("Unable to read the lock file ({}).".format(e)) + raise RuntimeError(f"Unable to read the lock file ({e}).") lock_version = Version.parse(lock_data["metadata"].get("lock-version", "1.0")) current_version = Version.parse(self._VERSION) diff --git a/poetry/packages/package_collection.py b/poetry/packages/package_collection.py index 00e271dd6c6..3386aee855b 100644 --- a/poetry/packages/package_collection.py +++ b/poetry/packages/package_collection.py @@ -21,7 +21,7 @@ def __init__( if packages is None: packages = [] - super(PackageCollection, self).__init__() + super().__init__() for package in packages: self.append(package) @@ -32,4 +32,4 @@ def append(self, package: Union["Package", DependencyPackage]) -> None: package = DependencyPackage(self._dependency, package) - return super(PackageCollection, self).append(package) + return super().append(package) diff --git a/poetry/plugins/base_plugin.py b/poetry/plugins/base_plugin.py index 9e287c8178c..de42071b4dc 100644 --- a/poetry/plugins/base_plugin.py +++ b/poetry/plugins/base_plugin.py @@ -1,4 +1,4 @@ -class BasePlugin(object): +class BasePlugin: """ Base class for all plugin types """ diff --git a/poetry/plugins/plugin_manager.py b/poetry/plugins/plugin_manager.py index 6f9e8f49ba2..c24ad2b20c1 100644 --- a/poetry/plugins/plugin_manager.py +++ b/poetry/plugins/plugin_manager.py @@ -11,7 +11,7 @@ logger = logging.getLogger(__name__) -class PluginManager(object): +class PluginManager: """ This class registers and activates plugins. """ @@ -31,7 +31,7 @@ def load_plugins(self): # type: () -> None self._load_plugin_entrypoint(entrypoint) def get_plugin_entry_points(self) -> List[entrypoints.EntryPoint]: - return entrypoints.get_group_all("poetry.{}".format(self._type)) + return entrypoints.get_group_all(f"poetry.{self._type}") def add_plugin(self, plugin): # type: (Plugin) -> None if not isinstance(plugin, (Plugin, ApplicationPlugin)): @@ -48,7 +48,7 @@ def activate(self, *args, **kwargs): def _load_plugin_entrypoint( self, entrypoint ): # type: (entrypoints.EntryPoint) -> None - logger.debug("Loading the {} plugin".format(entrypoint.name)) + logger.debug(f"Loading the {entrypoint.name} plugin") plugin = entrypoint.load() diff --git a/poetry/publishing/publisher.py b/poetry/publishing/publisher.py index 2c9d1e14d8a..cfa5c7d085d 100644 --- a/poetry/publishing/publisher.py +++ b/poetry/publishing/publisher.py @@ -52,17 +52,15 @@ def publish( repository_name = "pypi" else: # Retrieving config information - url = self._poetry.config.get("repositories.{}.url".format(repository_name)) + url = self._poetry.config.get(f"repositories.{repository_name}.url") if url is None: - raise RuntimeError( - "Repository {} is not defined".format(repository_name) - ) + raise RuntimeError(f"Repository {repository_name} is not defined") if not (username and password): # Check if we have a token first token = self._password_manager.get_pypi_token(repository_name) if token: - logger.debug("Found an API token for {}.".format(repository_name)) + logger.debug(f"Found an API token for {repository_name}.") username = "__token__" password = token else: diff --git a/poetry/publishing/uploader.py b/poetry/publishing/uploader.py index 787f112f49c..798b2533af8 100644 --- a/poetry/publishing/uploader.py +++ b/poetry/publishing/uploader.py @@ -39,8 +39,8 @@ class UploadError(Exception): def __init__(self, error: Union[ConnectionError, HTTPError, str]) -> None: if isinstance(error, HTTPError): - message = "HTTP Error {}: {}".format( - error.response.status_code, error.response.reason + message = ( + f"HTTP Error {error.response.status_code}: {error.response.reason}" ) elif isinstance(error, ConnectionError): message = ( @@ -49,7 +49,7 @@ def __init__(self, error: Union[ConnectionError, HTTPError, str]) -> None: ) else: message = str(error) - super(UploadError, self).__init__(message) + super().__init__(message) class Uploader: @@ -82,14 +82,10 @@ def files(self) -> List[Path]: wheels = list( dist.glob( - "{}-{}-*.whl".format( - escape_name(self._package.pretty_name), escape_version(version) - ) + f"{escape_name(self._package.pretty_name)}-{escape_version(version)}-*.whl" ) ) - tars = list( - dist.glob("{}-{}.tar.gz".format(self._package.pretty_name, version)) - ) + tars = list(dist.glob(f"{self._package.pretty_name}-{version}.tar.gz")) return sorted(wheels + tars) @@ -263,9 +259,7 @@ def _upload_file( ) encoder = MultipartEncoder(data_to_send) bar = ProgressBar(self._io, max=encoder.len) - bar.set_format( - " - Uploading {0} %percent%%".format(file.name) - ) + bar.set_format(f" - Uploading {file.name} %percent%%") monitor = MultipartEncoderMonitor( encoder, lambda monitor: bar.set_progress(monitor.bytes_read) ) @@ -284,17 +278,13 @@ def _upload_file( ) if dry_run or 200 <= resp.status_code < 300: bar.set_format( - " - Uploading {0} %percent%%".format( - file.name - ) + f" - Uploading {file.name} %percent%%" ) bar.finish() elif resp.status_code == 301: if self._io.output.is_decorated(): self._io.overwrite( - " - Uploading {0} {1}".format( - file.name, "FAILED" - ) + f" - Uploading {file.name} FAILED" ) raise UploadError( "Redirects are not supported. " @@ -303,9 +293,7 @@ def _upload_file( except (requests.ConnectionError, requests.HTTPError) as e: if self._io.output.is_decorated(): self._io.overwrite( - " - Uploading {0} {1}".format( - file.name, "FAILED" - ) + f" - Uploading {file.name} FAILED" ) raise UploadError(e) finally: @@ -318,12 +306,13 @@ def _register(self, session: requests.Session, url: str) -> requests.Response: Register a package to a repository. """ dist = self._poetry.file.parent / "dist" - file = dist / "{}-{}.tar.gz".format( - self._package.name, normalize_version(self._package.version.text) + file = ( + dist + / f"{self._package.name}-{normalize_version(self._package.version.text)}.tar.gz" ) if not file.exists(): - raise RuntimeError('"{0}" does not exist.'.format(file.name)) + raise RuntimeError(f'"{file.name}" does not exist.') data = self.post_data(file) data.update({":action": "submit", "protocol_version": "1"}) diff --git a/poetry/puzzle/exceptions.py b/poetry/puzzle/exceptions.py index 5c032da5970..4eaf46fda40 100644 --- a/poetry/puzzle/exceptions.py +++ b/poetry/puzzle/exceptions.py @@ -6,7 +6,7 @@ class SolverProblemError(Exception): def __init__(self, error: Exception) -> None: self._error = error - super(SolverProblemError, self).__init__(str(error)) + super().__init__(str(error)) @property def error(self) -> Exception: diff --git a/poetry/puzzle/provider.py b/poetry/puzzle/provider.py index 3d384a6697d..c7427161c2c 100644 --- a/poetry/puzzle/provider.py +++ b/poetry/puzzle/provider.py @@ -49,7 +49,7 @@ class Indicator(ProgressIndicator): def _formatter_elapsed(self) -> str: elapsed = time.time() - self._start_time - return "{:.1f}s".format(elapsed) + return f"{elapsed:.1f}s" class Provider: @@ -199,7 +199,7 @@ def get_package_from_vcs( name: Optional[str] = None, ) -> Package: if vcs != "git": - raise ValueError("Unsupported VCS dependency {}".format(vcs)) + raise ValueError(f"Unsupported VCS dependency {vcs}") tmp_dir = Path( mkdtemp(prefix="pypoetry-git-{}".format(url.split("/")[-1].rstrip(".git"))) @@ -266,7 +266,7 @@ def get_package_from_file(cls, file_path: Path) -> Package: ) except PackageInfoError: raise RuntimeError( - "Unable to determine package info from path: {}".format(file_path) + f"Unable to determine package info from path: {file_path}" ) return package @@ -546,7 +546,7 @@ def complete_package(self, package: DependencyPackage) -> DependencyPackage: dependencies.append(deps[0]) continue - self.debug("Duplicate dependencies for {}".format(dep_name)) + self.debug(f"Duplicate dependencies for {dep_name}") # Regrouping by constraint by_constraint = dict() diff --git a/poetry/puzzle/solver.py b/poetry/puzzle/solver.py index 605eea303b8..b5a413f15e0 100644 --- a/poetry/puzzle/solver.py +++ b/poetry/puzzle/solver.py @@ -85,9 +85,7 @@ def solve(self, use_latest: List[str] = None) -> List["OperationTypes"]: ) ) self._provider.debug( - "Resolved with overrides: {}".format( - ", ".join("({})".format(b) for b in self._overrides) - ) + f"Resolved with overrides: {', '.join(f'({b})' for b in self._overrides)}" ) operations = [] @@ -221,7 +219,7 @@ def solve_in_compatibility_mode( for override in overrides: self._provider.debug( "Retrying dependency resolution " - "with the following overrides ({}).".format(override) + f"with the following overrides ({override})." ) self._provider.set_overrides(override) _packages, _depths = self._solve(use_latest=use_latest) @@ -293,7 +291,7 @@ def _solve(self, use_latest: List[str] = None) -> Tuple[List[Package], List[int] return final_packages, depths -class DFSNode(object): +class DFSNode: def __init__(self, id: Tuple[str, str, bool], name: str, base_name: str) -> None: self.id = id self.name = name @@ -408,7 +406,7 @@ def __init__( self.category = dep.category self.optional = dep.is_optional() - super(PackageNode, self).__init__( + super().__init__( (package.complete_name, self.category, self.optional), package.complete_name, package.name, diff --git a/poetry/repositories/base_repository.py b/poetry/repositories/base_repository.py index 0e03b8446ce..3d5e5c5ebcd 100644 --- a/poetry/repositories/base_repository.py +++ b/poetry/repositories/base_repository.py @@ -8,7 +8,7 @@ from poetry.core.packages.package import Package -class BaseRepository(object): +class BaseRepository: def __init__(self) -> None: self._packages = [] diff --git a/poetry/repositories/legacy_repository.py b/poetry/repositories/legacy_repository.py index 8446b31ee99..60fd8c8b6fa 100644 --- a/poetry/repositories/legacy_repository.py +++ b/poetry/repositories/legacy_repository.py @@ -330,7 +330,7 @@ def package( return self._packages[index] except ValueError: - package = super(LegacyRepository, self).package(name, version, extras) + package = super().package(name, version, extras) package._source_type = "legacy" package._source_url = self._url package._source_reference = self.name @@ -347,7 +347,7 @@ def find_links_for_package(self, package: Package) -> List[Link]: def _get_release_info(self, name: str, version: str) -> dict: page = self._get("/{}/".format(canonicalize_name(name).replace(".", "-"))) if page is None: - raise PackageNotFound('No package named "{}"'.format(name)) + raise PackageNotFound(f'No package named "{name}"') data = PackageInfo( name=name, @@ -377,7 +377,7 @@ def _get_release_info(self, name: str, version: str) -> dict: ): urls["sdist"].append(link.url) - file_hash = "{}:{}".format(link.hash_name, link.hash) if link.hash else None + file_hash = f"{link.hash_name}:{link.hash}" if link.hash else None if not link.hash or ( link.hash_name not in ("sha256", "sha384", "sha512") @@ -425,7 +425,7 @@ def _get(self, endpoint: str) -> Optional[Page]: response = self.session.get(url) if response.status_code in (401, 403): self._log( - "Authorization error accessing {url}".format(url=url), + f"Authorization error accessing {url}", level="warning", ) return diff --git a/poetry/repositories/pool.py b/poetry/repositories/pool.py index 69d933296ac..251ff92506b 100644 --- a/poetry/repositories/pool.py +++ b/poetry/repositories/pool.py @@ -32,7 +32,7 @@ def __init__( self._ignore_repository_names = ignore_repository_names - super(Pool, self).__init__() + super().__init__() @property def repositories(self) -> List[Repository]: @@ -53,7 +53,7 @@ def repository(self, name: str) -> Repository: if name in self._lookup: return self._repositories[self._lookup[name]] - raise ValueError('Repository "{}" does not exist.'.format(name)) + raise ValueError(f'Repository "{name}" does not exist.') def add_repository( self, repository: Repository, default: bool = False, secondary: bool = False @@ -125,7 +125,7 @@ def package( and repository not in self._lookup and not self._ignore_repository_names ): - raise ValueError('Repository "{}" does not exist.'.format(repository)) + raise ValueError(f'Repository "{repository}" does not exist.') if repository is not None and not self._ignore_repository_names: try: @@ -144,7 +144,7 @@ def package( return package - raise PackageNotFound("Package {} ({}) not found.".format(name, version)) + raise PackageNotFound(f"Package {name} ({version}) not found.") def find_packages(self, dependency: "Dependency") -> List["Package"]: repository = dependency.source_name @@ -156,7 +156,7 @@ def find_packages(self, dependency: "Dependency") -> List["Package"]: and repository not in self._lookup and not self._ignore_repository_names ): - raise ValueError('Repository "{}" does not exist.'.format(repository)) + raise ValueError(f'Repository "{repository}" does not exist.') if repository is not None and not self._ignore_repository_names: return self.repository(repository).find_packages(dependency) diff --git a/poetry/repositories/pypi_repository.py b/poetry/repositories/pypi_repository.py index 0a5d02e1f10..1c7b7be316a 100644 --- a/poetry/repositories/pypi_repository.py +++ b/poetry/repositories/pypi_repository.py @@ -54,7 +54,7 @@ def __init__( disable_cache: bool = False, fallback: bool = True, ) -> None: - super(PyPiRepository, self).__init__(url.rstrip("/") + "/simple/") + super().__init__(url.rstrip("/") + "/simple/") self._base_url = url self._disable_cache = disable_cache @@ -211,9 +211,9 @@ def get_package_info(self, name: str) -> dict: ) def _get_package_info(self, name: str) -> dict: - data = self._get("pypi/{}/json".format(name)) + data = self._get(f"pypi/{name}/json") if data is None: - raise PackageNotFound("Package [{}] not found.".format(name)) + raise PackageNotFound(f"Package [{name}] not found.") return data @@ -230,24 +230,24 @@ def get_release_info(self, name: str, version: str) -> "PackageInfo": return PackageInfo.load(self._get_release_info(name, version)) cached = self._cache.remember_forever( - "{}:{}".format(name, version), lambda: self._get_release_info(name, version) + f"{name}:{version}", lambda: self._get_release_info(name, version) ) cache_version = cached.get("_cache_version", "0.0.0") if parse_constraint(cache_version) != self.CACHE_VERSION: # The cache must be updated self._log( - "The cache for {} {} is outdated. Refreshing.".format(name, version), + f"The cache for {name} {version} is outdated. Refreshing.", level="debug", ) cached = self._get_release_info(name, version) - self._cache.forever("{}:{}".format(name, version), cached) + self._cache.forever(f"{name}:{version}", cached) return PackageInfo.load(cached) def find_links_for_package(self, package: Package) -> List[Link]: - json_data = self._get("pypi/{}/{}/json".format(package.name, package.version)) + json_data = self._get(f"pypi/{package.name}/{package.version}/json") if json_data is None: return [] @@ -261,11 +261,11 @@ def find_links_for_package(self, package: Package) -> List[Link]: def _get_release_info(self, name: str, version: str) -> dict: from poetry.inspection.info import PackageInfo - self._log("Getting info for {} ({}) from PyPI".format(name, version), "debug") + self._log(f"Getting info for {name} ({version}) from PyPI", "debug") - json_data = self._get("pypi/{}/{}/json".format(name, version)) + json_data = self._get(f"pypi/{name}/{version}/json") if json_data is None: - raise PackageNotFound("Package [{}] not found.".format(name)) + raise PackageNotFound(f"Package [{name}] not found.") info = json_data["info"] @@ -383,14 +383,14 @@ def _get_info_from_urls(self, urls: Dict[str, List[str]]) -> "PackageInfo": return info - py2_requires_dist = set( + py2_requires_dist = { Dependency.create_from_pep_508(r).to_pep_508() for r in info.requires_dist - ) - py3_requires_dist = set( + } + py3_requires_dist = { Dependency.create_from_pep_508(r).to_pep_508() for r in py3_info.requires_dist - ) + } base_requires_dist = py2_requires_dist & py3_requires_dist py2_only_requires_dist = py2_requires_dist - py3_requires_dist py3_only_requires_dist = py3_requires_dist - py2_requires_dist @@ -469,4 +469,4 @@ def _download(self, url: str, dest: str) -> None: return download_file(url, dest, session=self.session) def _log(self, msg: str, level: str = "info") -> None: - getattr(logger, level)("{}: {}".format(self._name, msg)) + getattr(logger, level)(f"{self._name}: {msg}") diff --git a/poetry/repositories/remote_repository.py b/poetry/repositories/remote_repository.py index a893b31ec4f..b07321dcd66 100644 --- a/poetry/repositories/remote_repository.py +++ b/poetry/repositories/remote_repository.py @@ -5,7 +5,7 @@ class RemoteRepository(Repository): def __init__(self, url: str) -> None: self._url = url - super(RemoteRepository, self).__init__() + super().__init__() @property def url(self) -> str: diff --git a/poetry/repositories/repository.py b/poetry/repositories/repository.py index 43894e4e4d4..c2a36c2dfe1 100644 --- a/poetry/repositories/repository.py +++ b/poetry/repositories/repository.py @@ -13,7 +13,7 @@ class Repository(BaseRepository): def __init__(self, packages: List["Package"] = None, name: str = None) -> None: - super(Repository, self).__init__() + super().__init__() self._name = name diff --git a/poetry/utils/_compat.py b/poetry/utils/_compat.py index 1ede84dcd3f..977c997ede3 100644 --- a/poetry/utils/_compat.py +++ b/poetry/utils/_compat.py @@ -46,6 +46,6 @@ def to_str(string): def list_to_shell_command(cmd): return " ".join( - '"{}"'.format(token) if " " in token and token[0] not in {"'", '"'} else token + f'"{token}"' if " " in token and token[0] not in {"'", '"'} else token for token in cmd ) diff --git a/poetry/utils/env.py b/poetry/utils/env.py index 933f9165210..3df76495acc 100644 --- a/poetry/utils/env.py +++ b/poetry/utils/env.py @@ -225,7 +225,7 @@ def _path_method_wrapper( return result else: results.append(result) - except (IOError, OSError): + except OSError: # TODO: Replace with PermissionError pass @@ -257,7 +257,7 @@ def find(self, path: Path, writable_only: bool = False) -> List[Path]: def __getattr__(self, item: str) -> Any: try: - return super(SitePackages, self).__getattribute__(item) + return super().__getattribute__(item) except AttributeError: return getattr(self.path, item) @@ -275,8 +275,8 @@ def __init__(self, e: CalledProcessError, input: Optional[str] = None) -> None: e.cmd, e.returncode, decode(e.output) ) if input: - message += "input was : {}".format(input) - super(EnvCommandError, self).__init__(message) + message += f"input was : {input}" + super().__init__(message) class NoCompatiblePythonVersionFound(EnvError): @@ -296,10 +296,10 @@ def __init__(self, expected: str, given: Optional[str] = None) -> None: 'via the "env use" command.' ) - super(NoCompatiblePythonVersionFound, self).__init__(message) + super().__init__(message) -class EnvManager(object): +class EnvManager: """ Environments manager """ @@ -324,9 +324,9 @@ def activate(self, python: str, io: IO) -> "Env": try: python_version = Version.parse(python) - python = "python{}".format(python_version.major) + python = f"python{python_version.major}" if python_version.precision > 1: - python += ".{}".format(python_version.minor) + python += f".{python_version.minor}" except ValueError: # Executable in PATH or full executable path pass @@ -348,7 +348,7 @@ def activate(self, python: str, io: IO) -> "Env": raise EnvCommandError(e) python_version = Version.parse(python_version.strip()) - minor = "{}.{}".format(python_version.major, python_version.minor) + minor = f"{python_version.major}.{python_version.minor}" patch = python_version.text create = False @@ -383,7 +383,7 @@ def activate(self, python: str, io: IO) -> "Env": # We need to recreate create = True - name = "{}-py{}".format(base_env_name, minor) + name = f"{base_env_name}-py{minor}" venv = venv_path / name # Create if needed @@ -482,7 +482,7 @@ def get(self, reload: bool = False) -> Union["VirtualEnv", "SystemEnv"]: else: venv_path = Path(venv_path) - name = "{}-py{}".format(base_env_name, python_minor.strip()) + name = f"{base_env_name}-py{python_minor.strip()}" venv = venv_path / name @@ -513,8 +513,7 @@ def list(self, name: Optional[str] = None) -> List["VirtualEnv"]: venv_path = Path(venv_path) env_list = [ - VirtualEnv(Path(p)) - for p in sorted(venv_path.glob("{}-py*".format(venv_name))) + VirtualEnv(Path(p)) for p in sorted(venv_path.glob(f"{venv_name}-py*")) ] venv = self._poetry.file.parent / ".venv" @@ -566,14 +565,14 @@ def remove(self, python: str) -> "Env": return venv raise ValueError( - 'Environment "{}" does not exist.'.format(python) + f'Environment "{python}" does not exist.' ) try: python_version = Version.parse(python) - python = "python{}".format(python_version.major) + python = f"python{python_version.major}" if python_version.precision > 1: - python += ".{}".format(python_version.minor) + python += f".{python_version.minor}" except ValueError: # Executable in PATH or full executable path pass @@ -595,15 +594,13 @@ def remove(self, python: str) -> "Env": raise EnvCommandError(e) python_version = Version.parse(python_version.strip()) - minor = "{}.{}".format(python_version.major, python_version.minor) + minor = f"{python_version.major}.{python_version.minor}" - name = "{}-py{}".format(base_env_name, minor) + name = f"{base_env_name}-py{minor}" venv = venv_path / name if not venv.exists(): - raise ValueError( - 'Environment "{}" does not exist.'.format(name) - ) + raise ValueError(f'Environment "{name}" does not exist.') if envs_file.exists(): envs = envs_file.read() @@ -698,7 +695,7 @@ def create_venv( ) ): if len(python_to_try) == 1: - if not parse_constraint("^{}.0".format(python_to_try)).allows_any( + if not parse_constraint(f"^{python_to_try}.0").allows_any( supported_python ): continue @@ -710,7 +707,7 @@ def create_venv( python = "python" + python_to_try if io.is_debug(): - io.write_line("Trying {}".format(python)) + io.write_line(f"Trying {python}") try: python_patch = decode( @@ -733,7 +730,7 @@ def create_venv( continue if supported_python.allows(Version.parse(python_patch)): - io.write_line("Using {} ({})".format(python, python_patch)) + io.write_line(f"Using {python} ({python_patch})") executable = python python_minor = ".".join(python_patch.split(".")[:2]) break @@ -747,7 +744,7 @@ def create_venv( venv = venv_path else: name = self.generate_env_name(name, str(cwd)) - name = "{}-py{}".format(name, python_minor.strip()) + name = f"{name}-py{python_minor.strip()}" venv = venv_path / name if not venv.exists(): @@ -788,7 +785,7 @@ def create_venv( flags=self._poetry.config.get("virtualenvs.options"), ) elif io.is_very_verbose(): - io.write_line("Virtualenv {} already exists.".format(name)) + io.write_line(f"Virtualenv {name} already exists.") # venv detection: # stdlib venv may symlink sys.executable, so we can't use realpath. @@ -846,7 +843,7 @@ def build_venv( for flag, value in flags.items(): if value is True: - args.append("--{}".format(flag)) + args.append(f"--{flag}") args.append(str(path)) @@ -896,10 +893,10 @@ def generate_env_name(cls, name: str, cwd: str) -> str: h = hashlib.sha256(encode(cwd)).digest() h = base64.urlsafe_b64encode(h).decode()[:8] - return "{}-{}".format(sanitized_name, h) + return f"{sanitized_name}-{h}" -class Env(object): +class Env: """ An abstract Python environment. """ @@ -1196,7 +1193,7 @@ def __eq__(self, other: "Env") -> bool: return other.__class__ == self.__class__ and other.path == self.path def __repr__(self) -> str: - return '{}("{}")'.format(self.__class__.__name__, self._path) + return f'{self.__class__.__name__}("{self._path}")' class SystemEnv(Env): @@ -1244,7 +1241,7 @@ def get_paths(self) -> Dict[str, str]: # headers is not a path returned by sysconfig.get_paths() continue - paths[key] = getattr(obj, "install_{}".format(key)) + paths[key] = getattr(obj, f"install_{key}") if site.check_enableusersite() and hasattr(obj, "install_usersite"): paths["usersite"] = getattr(obj, "install_usersite") @@ -1303,7 +1300,7 @@ class VirtualEnv(Env): """ def __init__(self, path: Path, base: Optional[Path] = None) -> None: - super(VirtualEnv, self).__init__(path, base) + super().__init__(path, base) # If base is None, it probably means this is # a virtualenv created from VIRTUAL_ENV. @@ -1388,7 +1385,7 @@ def is_sane(self) -> bool: def _run(self, cmd: List[str], **kwargs: Any) -> Optional[int]: kwargs["env"] = self.get_temp_environ(environ=kwargs.get("env")) - return super(VirtualEnv, self)._run(cmd, **kwargs) + return super()._run(cmd, **kwargs) def get_temp_environ( self, @@ -1415,7 +1412,7 @@ def get_temp_environ( def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]: kwargs["env"] = self.get_temp_environ(environ=kwargs.get("env")) - return super(VirtualEnv, self).execute(bin, *args, **kwargs) + return super().execute(bin, *args, **kwargs) @contextmanager def temp_environ(self) -> Iterator[None]: @@ -1437,7 +1434,7 @@ def __init__( if path is None: path = Path(sys.prefix) - super(NullEnv, self).__init__(path, base=base) + super().__init__(path, base=base) self._execute = execute self.executed = [] @@ -1449,13 +1446,13 @@ def _run(self, cmd: List[str], **kwargs: Any) -> int: self.executed.append(cmd) if self._execute: - return super(NullEnv, self)._run(cmd, **kwargs) + return super()._run(cmd, **kwargs) def execute(self, bin: str, *args: str, **kwargs: Any) -> Optional[int]: self.executed.append([bin] + list(args)) if self._execute: - return super(NullEnv, self).execute(bin, *args, **kwargs) + return super().execute(bin, *args, **kwargs) def _bin(self, bin: str) -> str: return bin @@ -1497,7 +1494,7 @@ def __init__( supported_tags: List[Tag] = None, **kwargs: Any, ): - super(MockEnv, self).__init__(**kwargs) + super().__init__(**kwargs) self._version_info = version_info self._python_implementation = python_implementation @@ -1524,7 +1521,7 @@ def pip_version(self) -> Version: @property def sys_path(self) -> List[str]: if self._sys_path is None: - return super(MockEnv, self).sys_path + return super().sys_path return self._sys_path @@ -1532,7 +1529,7 @@ def get_marker_env(self) -> Dict[str, Any]: if self._mock_marker_env is not None: return self._mock_marker_env - marker_env = super(MockEnv, self).get_marker_env() + marker_env = super().get_marker_env() marker_env["python_implementation"] = self._python_implementation marker_env["version_info"] = self._version_info marker_env["python_version"] = ".".join(str(v) for v in self._version_info[:2]) diff --git a/poetry/utils/exporter.py b/poetry/utils/exporter.py index b3630aa6184..2ce9c6d19fd 100644 --- a/poetry/utils/exporter.py +++ b/poetry/utils/exporter.py @@ -12,7 +12,7 @@ from poetry.utils._compat import decode -class Exporter(object): +class Exporter: """ Exporter class to export a lock file to alternative formats. """ @@ -36,7 +36,7 @@ def export( with_credentials: bool = False, ) -> None: if fmt not in self.ACCEPTED_FORMATS: - raise ValueError("Invalid export format: {}".format(fmt)) + raise ValueError(f"Invalid export format: {fmt}") getattr(self, "_export_{}".format(fmt.replace(".", "_")))( cwd, @@ -81,15 +81,15 @@ def _export_requirements_txt( line = requirement elif is_direct_local_reference: dependency_uri = path_to_url(dependency.source_url) - line = "{} @ {}".format(dependency.name, dependency_uri) + line = f"{dependency.name} @ {dependency_uri}" else: - line = "{}=={}".format(package.name, package.version) + line = f"{package.name}=={package.version}" if not is_direct_remote_reference: if ";" in requirement: markers = requirement.split(";", 1)[1].strip() if markers: - line += "; {}".format(markers) + line += f"; {markers}" if ( not is_direct_remote_reference @@ -109,7 +109,7 @@ def _export_requirements_txt( if algorithm not in self.ALLOWED_HASH_ALGORITHMS: continue - hashes.append("{}:{}".format(algorithm, h)) + hashes.append(f"{algorithm}:{h}") if hashes: line += " \\\n" @@ -143,7 +143,7 @@ def _export_requirements_txt( if with_credentials else repository.url ) - indexes_header = "--index-url {}\n".format(url) + indexes_header = f"--index-url {url}\n" continue url = ( @@ -151,8 +151,8 @@ def _export_requirements_txt( ) parsed_url = urllib.parse.urlsplit(url) if parsed_url.scheme == "http": - indexes_header += "--trusted-host {}\n".format(parsed_url.netloc) - indexes_header += "--extra-index-url {}\n".format(url) + indexes_header += f"--trusted-host {parsed_url.netloc}\n" + indexes_header += f"--extra-index-url {url}\n" content = indexes_header + "\n" + content diff --git a/poetry/utils/helpers.py b/poetry/utils/helpers.py index 1156b6415db..d81d0f15b3d 100644 --- a/poetry/utils/helpers.py +++ b/poetry/utils/helpers.py @@ -51,7 +51,7 @@ def temporary_directory(*args: Any, **kwargs: Any) -> Iterator[str]: def get_cert(config: Config, repository_name: str) -> Optional[Path]: - cert = config.get("certificates.{}.cert".format(repository_name)) + cert = config.get(f"certificates.{repository_name}.cert") if cert: return Path(cert) else: @@ -59,7 +59,7 @@ def get_cert(config: Config, repository_name: str) -> Optional[Path]: def get_client_cert(config: Config, repository_name: str) -> Optional[Path]: - client_cert = config.get("certificates.{}.client-cert".format(repository_name)) + client_cert = config.get(f"certificates.{repository_name}.client-cert") if client_cert: return Path(client_cert) else: @@ -131,7 +131,7 @@ def is_dir_writable(path: Path, create: bool = False) -> bool: with tempfile.TemporaryFile(dir=str(path)): pass - except (IOError, OSError): + except OSError: return False else: return True diff --git a/poetry/utils/password_manager.py b/poetry/utils/password_manager.py index bbf2a1a210a..e5eb05eab51 100644 --- a/poetry/utils/password_manager.py +++ b/poetry/utils/password_manager.py @@ -44,7 +44,7 @@ def get_password(self, name: str, username: str) -> Optional[str]: return keyring.get_password(name, username) except (RuntimeError, keyring.errors.KeyringError): raise KeyRingError( - "Unable to retrieve the password for {} from the key ring".format(name) + f"Unable to retrieve the password for {name} from the key ring" ) def set_password(self, name: str, username: str, password: str) -> None: @@ -78,11 +78,11 @@ def delete_password(self, name: str, username: str) -> None: keyring.delete_password(name, username) except (RuntimeError, keyring.errors.KeyringError): raise KeyRingError( - "Unable to delete the password for {} from the key ring".format(name) + f"Unable to delete the password for {name} from the key ring" ) def get_entry_name(self, name: str) -> str: - return "{}-{}".format(self._namespace, name) + return f"{self._namespace}-{name}" def _check(self) -> None: try: @@ -137,31 +137,27 @@ def keyring(self) -> KeyRing: def set_pypi_token(self, name: str, token: str) -> None: if not self.keyring.is_available(): - self._config.auth_config_source.add_property( - "pypi-token.{}".format(name), token - ) + self._config.auth_config_source.add_property(f"pypi-token.{name}", token) else: self.keyring.set_password(name, "__token__", token) def get_pypi_token(self, name: str) -> str: if not self.keyring.is_available(): - return self._config.get("pypi-token.{}".format(name)) + return self._config.get(f"pypi-token.{name}") return self.keyring.get_password(name, "__token__") def delete_pypi_token(self, name: str) -> None: if not self.keyring.is_available(): - return self._config.auth_config_source.remove_property( - "pypi-token.{}".format(name) - ) + return self._config.auth_config_source.remove_property(f"pypi-token.{name}") self.keyring.delete_password(name, "__token__") def get_http_auth(self, name: str) -> Optional[Dict[str, str]]: - auth = self._config.get("http-basic.{}".format(name)) + auth = self._config.get(f"http-basic.{name}") if not auth: - username = self._config.get("http-basic.{}.username".format(name)) - password = self._config.get("http-basic.{}.password".format(name)) + username = self._config.get(f"http-basic.{name}.username") + password = self._config.get(f"http-basic.{name}.password") if not username and not password: return None else: @@ -182,7 +178,7 @@ def set_http_password(self, name: str, username: str, password: str) -> None: else: self.keyring.set_password(name, username, password) - self._config.auth_config_source.add_property("http-basic.{}".format(name), auth) + self._config.auth_config_source.add_property(f"http-basic.{name}", auth) def delete_http_password(self, name: str) -> None: auth = self.get_http_auth(name) @@ -194,4 +190,4 @@ def delete_http_password(self, name: str) -> None: except KeyRingError: pass - self._config.auth_config_source.remove_property("http-basic.{}".format(name)) + self._config.auth_config_source.remove_property(f"http-basic.{name}") diff --git a/poetry/utils/setup_reader.py b/poetry/utils/setup_reader.py index da6d844e816..c85f34cdda3 100644 --- a/poetry/utils/setup_reader.py +++ b/poetry/utils/setup_reader.py @@ -13,7 +13,7 @@ from poetry.core.semver.version import Version -class SetupReader(object): +class SetupReader: """ Class that reads a setup.py file without executing it. """ diff --git a/poetry/utils/shell.py b/poetry/utils/shell.py index 544be053c4c..ce91bfba029 100644 --- a/poetry/utils/shell.py +++ b/poetry/utils/shell.py @@ -118,4 +118,4 @@ def _get_source_command(self) -> str: return "." def __repr__(self) -> str: - return '{}("{}", "{}")'.format(self.__class__.__name__, self._name, self._path) + return f'{self.__class__.__name__}("{self._name}", "{self._path}")' diff --git a/poetry/version/version_selector.py b/poetry/version/version_selector.py index 27dd582aaff..94892eb5287 100644 --- a/poetry/version/version_selector.py +++ b/poetry/version/version_selector.py @@ -10,7 +10,7 @@ from poetry.repositories import Pool -class VersionSelector(object): +class VersionSelector: def __init__(self, pool: "Pool") -> None: self._pool = pool @@ -78,6 +78,6 @@ def _transform_version(self, version: str, pretty_version: str) -> str: else: version = ".".join(str(p) for p in parts) if parsed.is_unstable(): - version += "-{}".format(parsed.pre.to_string()) + version += f"-{parsed.pre.to_string()}" - return "^{}".format(version) + return f"^{version}"