Skip to content

Commit

Permalink
Used pyupgrade to remove compatibility code (#3861)
Browse files Browse the repository at this point in the history
* Used pyupgrade to remove compatibility code

May fix #3860
  • Loading branch information
ThatXliner authored Apr 2, 2021
1 parent 45a9b8f commit b753aaf
Show file tree
Hide file tree
Showing 44 changed files with 198 additions and 258 deletions.
4 changes: 1 addition & 3 deletions poetry/config/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import absolute_import

import os
import re

Expand Down Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion poetry/config/config_source.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Any


class ConfigSource(object):
class ConfigSource:
def add_property(self, key: str, value: Any) -> None:
raise NotImplementedError()

Expand Down
6 changes: 3 additions & 3 deletions poetry/console/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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: <comment>{}</>".format(env.path))
io.write_line(f"Using virtualenv: <comment>{env.path}</>")

command.set_env(env)

Expand Down
20 changes: 7 additions & 13 deletions poetry/inspection/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)("<debug>{}:</debug> {}".format(cls.__name__, msg))
getattr(logger, level)(f"<debug>{cls.__name__}:</debug> {msg}")

def to_package(
self,
Expand All @@ -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,
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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",
Expand All @@ -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(
Expand All @@ -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
Expand Down
10 changes: 3 additions & 7 deletions poetry/installation/authenticator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion poetry/installation/chef.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 4 additions & 8 deletions poetry/installation/chooser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("_", "-")
Expand Down Expand Up @@ -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

Expand Down
13 changes: 4 additions & 9 deletions poetry/installation/executor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import division

import itertools
import os
import threading
Expand Down Expand Up @@ -44,7 +41,7 @@
from .operations import OperationTypes


class Executor(object):
class Executor:
def __init__(
self,
env: "Env",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -431,9 +428,7 @@ def _display_summary(self, operations: List["OperationTypes"]) -> None:
"" if updates == 1 else "s",
uninstalls,
"" if uninstalls == 1 else "s",
", <info>{}</> skipped".format(skipped)
if skipped and self._verbose
else "",
f", <info>{skipped}</> skipped" if skipped and self._verbose else "",
)
)
self._io.write_line("")
Expand Down Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions poetry/installation/installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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("<info>Updating dependencies</>")
solver = Solver(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -378,7 +378,7 @@ def _execute(self, operations: List["OperationTypes"]) -> int:
"" if updates == 1 else "s",
uninstalls,
"" if uninstalls == 1 else "s",
", <info>{}</> skipped".format(skipped)
f", <info>{skipped}</> skipped"
if skipped and self.is_verbose()
else "",
)
Expand All @@ -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:
Expand Down
12 changes: 5 additions & 7 deletions poetry/installation/pip_installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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)))
Expand Down
5 changes: 2 additions & 3 deletions poetry/json/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import json
import os

from io import open
from typing import List

import jsonschema
Expand All @@ -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())
Expand Down
6 changes: 3 additions & 3 deletions poetry/layouts/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -51,7 +51,7 @@ def test_version():
BUILD_SYSTEM_MAX_VERSION: Optional[str] = None


class Layout(object):
class Layout:
def __init__(
self,
project: str,
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 1 addition & 3 deletions poetry/layouts/src.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

from typing import TYPE_CHECKING

from .layout import Layout
Expand All @@ -8,7 +6,7 @@
if TYPE_CHECKING:
from pathlib import Path

DEFAULT = u"""__version__ = '{version}'
DEFAULT = """__version__ = '{version}'
"""


Expand Down
4 changes: 1 addition & 3 deletions poetry/layouts/standard.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
# -*- coding: utf-8 -*-

from typing import TYPE_CHECKING

from .layout import Layout


if TYPE_CHECKING:
from pathlib import Path
DEFAULT = u"""__version__ = '{version}'
DEFAULT = """__version__ = '{version}'
"""


Expand Down
Loading

0 comments on commit b753aaf

Please sign in to comment.