Skip to content

Apply more ruff rules #12980

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

Closed
wants to merge 30 commits into from
Closed
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
e2b2cb9
Disable ruff/pyupgrade rule UP027
DimitriPapadopoulos Sep 28, 2024
c3ec9fe
Apply ruff/pyupgrade preview rule UP031
DimitriPapadopoulos Oct 3, 2024
03a459c
Disable ruff/pyupgrade rule UP038
DimitriPapadopoulos Sep 28, 2024
5d09fe9
Sort entries in TOML config file
DimitriPapadopoulos Sep 28, 2024
23aa730
Apply ruff rule RUF010
DimitriPapadopoulos Sep 28, 2024
1a2e4a1
Apply ruff rule RUF012
DimitriPapadopoulos Sep 28, 2024
ab5e818
Apply ruff rule RUF019
DimitriPapadopoulos Sep 28, 2024
445f23b
Enforce ruff rules (RUF)
DimitriPapadopoulos Sep 28, 2024
119c012
Apply ruff/flake8-executable rule EXE002
DimitriPapadopoulos Sep 28, 2024
464b013
Apply ruff/flake8-pie rule PIE810
DimitriPapadopoulos Sep 28, 2024
a99ce4f
Enforce ruff/flake8-pie rules (PIE)
DimitriPapadopoulos Sep 28, 2024
8c49d19
Apply ruff/flake8-pyi rule PYI032
DimitriPapadopoulos Sep 28, 2024
19c2957
Apply ruff/flake8-pyi rule PYI036
DimitriPapadopoulos Sep 28, 2024
31eb8f3
Enforce ruff/flake8-pyi rules (PYI)
DimitriPapadopoulos Sep 28, 2024
415c47c
Apply ruff/flake8-raise rule RSE102
DimitriPapadopoulos Sep 28, 2024
787ff00
Apply ruff/flake8-return rule RET501
DimitriPapadopoulos Sep 28, 2024
9d2ca1a
Apply ruff/flake8-return rule RET503
DimitriPapadopoulos Sep 28, 2024
952aa73
Apply ruff/flake8-slots rule SLOT000
DimitriPapadopoulos Sep 28, 2024
1e855a0
Enforce ruff/flake8-slots rules (SLOT)
DimitriPapadopoulos Sep 28, 2024
6c9a8c5
Apply ruff/flake8-simplify rule SIM103
DimitriPapadopoulos Sep 28, 2024
7adbec6
Apply ruff/flake8-simplify rule SIM110
DimitriPapadopoulos Sep 28, 2024
c60e20b
Apply ruff/flake8-simplify rule SIM118
DimitriPapadopoulos Sep 28, 2024
5c354a6
Apply ruff/flake8-type-checking rule TCH001
DimitriPapadopoulos Sep 28, 2024
d66831d
Apply ruff/flake8-type-checking rule TCH002
DimitriPapadopoulos Sep 28, 2024
033dde8
Apply ruff/flake8-type-checking rule TCH003
DimitriPapadopoulos Sep 28, 2024
b19669f
Apply ruff/pygrep-hooks rule PGH003
DimitriPapadopoulos Sep 28, 2024
65833a9
Apply ruff/pygrep-hooks rule PGH004
DimitriPapadopoulos Sep 28, 2024
27670e9
Enforce ruff/pygrep-hooks rule (PGH)
DimitriPapadopoulos Sep 28, 2024
ae41609
Apply ruff/flake8-comprehensions preview rule C419
DimitriPapadopoulos Oct 3, 2024
0b45393
Improve fixes for ruff/flake8-simplify rule SIM103
DimitriPapadopoulos Oct 3, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions docs/pip_sphinxext.py
Original file line number Diff line number Diff line change
@@ -37,13 +37,11 @@ def _is_version_section_title_underline(
self, prev: Optional[str], curr: str
) -> bool:
"""Find a ==== line that marks the version section title."""
if prev is None:
return False
if re.match(r"^=+$", curr) is None:
return False
if len(curr) < len(prev):
return False
return True
return (
prev is not None
and re.match(r"^=+$", curr) is not None
and len(curr) >= len(prev)
)

def _iter_lines_with_refs(self, lines: Iterable[str]) -> Iterator[str]:
"""Transform the input lines to add a ref before each section title.
19 changes: 15 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -163,8 +163,15 @@ extend-exclude = [
ignore = [
"B019",
"B020",
"B904", # Ruff enables opinionated warnings by default
"B905", # Ruff enables opinionated warnings by default
"B904", # Ruff enables opinionated warnings by default
"B905", # Ruff enables opinionated warnings by default
"PYI019",
"PYI024",
"RUF001",
"RUF005",
"RUF015",
"UP027", # deprecated
"UP038", # https://github.com/astral-sh/ruff/issues/7871
]
select = [
"ASYNC",
@@ -177,11 +184,15 @@ select = [
"I",
"ISC",
"PERF",
"PGH",
"PIE",
"PLE",
"PLR0",
"W",
"RUF100",
"PYI",
"RUF",
"SLOT",
"UP",
"W",
]

[tool.ruff.lint.isort]
4 changes: 2 additions & 2 deletions src/pip/__pip-runner__.py
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@
PYTHON_REQUIRES = (3, 8)


def version_str(version): # type: ignore
def version_str(version): # type: ignore[no-untyped-def]
return ".".join(str(v) for v in version)


@@ -35,7 +35,7 @@ def version_str(version): # type: ignore

class PipImportRedirectingFinder:
@classmethod
def find_spec(self, fullname, path=None, target=None): # type: ignore
def find_spec(self, fullname, path=None, target=None): # type: ignore[no-untyped-def]
if fullname != "pip":
return None

Empty file modified src/pip/_internal/__init__.py
100755 → 100644
Empty file.
2 changes: 1 addition & 1 deletion src/pip/_internal/build_env.py
Original file line number Diff line number Diff line change
@@ -316,4 +316,4 @@ def install_requirements(
*,
kind: str,
) -> None:
raise NotImplementedError()
raise NotImplementedError
4 changes: 2 additions & 2 deletions src/pip/_internal/cache.py
Original file line number Diff line number Diff line change
@@ -85,7 +85,7 @@ def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]:

def get_path_for_link(self, link: Link) -> str:
"""Return a directory to store cached items in for link."""
raise NotImplementedError()
raise NotImplementedError

def get(
self,
@@ -96,7 +96,7 @@ def get(
"""Returns a link to a cached item if it exists, otherwise returns the
passed link.
"""
raise NotImplementedError()
raise NotImplementedError


class SimpleWheelCache(Cache):
2 changes: 1 addition & 1 deletion src/pip/_internal/cli/main_parser.py
Original file line number Diff line number Diff line change
@@ -35,7 +35,7 @@ def create_main_parser() -> ConfigOptionParser:
parser.add_option_group(gen_opts)

# so the help formatter knows
parser.main = True # type: ignore
parser.main = True # type: ignore[attr-defined]

# create command listing for description
description = [""] + [
2 changes: 1 addition & 1 deletion src/pip/_internal/cli/progress_bars.py
Original file line number Diff line number Diff line change
@@ -63,7 +63,7 @@ def _raw_progress_bar(
size: Optional[int],
) -> Generator[bytes, None, None]:
def write_progress(current: int, total: int) -> None:
sys.stdout.write("Progress %d of %d\n" % (current, total))
sys.stdout.write(f"Progress {current} of {total}\n")
sys.stdout.flush()

current = 0
4 changes: 2 additions & 2 deletions src/pip/_internal/cli/spinners.py
Original file line number Diff line number Diff line change
@@ -13,10 +13,10 @@

class SpinnerInterface:
def spin(self) -> None:
raise NotImplementedError()
raise NotImplementedError

def finish(self, final_status: str) -> None:
raise NotImplementedError()
raise NotImplementedError


class InteractiveSpinner(SpinnerInterface):
7 changes: 4 additions & 3 deletions src/pip/_internal/commands/index.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import logging
from optparse import Values
from typing import Any, Iterable, List, Optional

from pip._vendor.packaging.version import Version
from typing import TYPE_CHECKING, Any, Iterable, List, Optional

from pip._internal.cli import cmdoptions
from pip._internal.cli.req_command import IndexGroupCommand
@@ -16,6 +14,9 @@
from pip._internal.network.session import PipSession
from pip._internal.utils.misc import write_output

if TYPE_CHECKING:
from pip._vendor.packaging.version import Version

logger = logging.getLogger(__name__)


2 changes: 1 addition & 1 deletion src/pip/_internal/commands/install.py
Original file line number Diff line number Diff line change
@@ -434,7 +434,7 @@ def run(self, options: Values, args: List[str]) -> int:
raise InstallationError(
"ERROR: Failed to build installable wheels for some "
"pyproject.toml based projects ({})".format(
", ".join(r.name for r in build_failures) # type: ignore
", ".join(r.name for r in build_failures) # type: ignore[misc]
)
)

3 changes: 2 additions & 1 deletion src/pip/_internal/commands/list.py
Original file line number Diff line number Diff line change
@@ -4,7 +4,6 @@
from typing import TYPE_CHECKING, Generator, List, Optional, Sequence, Tuple, cast

from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.packaging.version import Version

from pip._internal.cli import cmdoptions
from pip._internal.cli.index_command import IndexGroupCommand
@@ -16,6 +15,8 @@
from pip._internal.utils.misc import tabulate, write_output

if TYPE_CHECKING:
from pip._vendor.packaging.version import Version

from pip._internal.index.package_finder import PackageFinder
from pip._internal.network.session import PipSession

8 changes: 3 additions & 5 deletions src/pip/_internal/commands/search.py
Original file line number Diff line number Diff line change
@@ -95,7 +95,7 @@ def transform_hits(hits: List[Dict[str, str]]) -> List["TransformedHit"]:
summary = hit["summary"]
version = hit["version"]

if name not in packages.keys():
if name not in packages:
packages[name] = {
"name": name,
"summary": summary,
@@ -140,10 +140,8 @@ def print_results(
if name_column_width is None:
name_column_width = (
max(
[
len(hit["name"]) + len(highest_version(hit.get("versions", ["-"])))
for hit in hits
]
len(hit["name"]) + len(highest_version(hit.get("versions", ["-"])))
for hit in hits
)
+ 4
)
6 changes: 3 additions & 3 deletions src/pip/_internal/distributions/base.py
Original file line number Diff line number Diff line change
@@ -37,11 +37,11 @@ def build_tracker_id(self) -> Optional[str]:
If None, then this dist has no work to do in the build tracker, and
``.prepare_distribution_metadata()`` will not be called."""
raise NotImplementedError()
raise NotImplementedError

@abc.abstractmethod
def get_metadata_distribution(self) -> BaseDistribution:
raise NotImplementedError()
raise NotImplementedError

@abc.abstractmethod
def prepare_distribution_metadata(
@@ -50,4 +50,4 @@ def prepare_distribution_metadata(
build_isolation: bool,
check_build_deps: bool,
) -> None:
raise NotImplementedError()
raise NotImplementedError
2 changes: 1 addition & 1 deletion src/pip/_internal/index/collector.py
Original file line number Diff line number Diff line change
@@ -102,7 +102,7 @@ def _ensure_api_response(url: str, session: PipSession) -> None:
"""
scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
if scheme not in {"http", "https"}:
raise _NotHTTP()
raise _NotHTTP

resp = session.head(url, allow_redirects=True)
raise_for_status(resp)
10 changes: 5 additions & 5 deletions src/pip/_internal/index/sources.py
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@
import mimetypes
import os
from collections import defaultdict
from typing import Callable, Dict, Iterable, List, Optional, Tuple
from typing import Callable, ClassVar, Dict, Iterable, List, Optional, Tuple

from pip._vendor.packaging.utils import (
InvalidSdistFilename,
@@ -30,15 +30,15 @@ class LinkSource:
@property
def link(self) -> Optional[Link]:
"""Returns the underlying link, if there's one."""
raise NotImplementedError()
raise NotImplementedError

def page_candidates(self) -> FoundCandidates:
"""Candidates found by parsing an archive listing HTML file."""
raise NotImplementedError()
raise NotImplementedError

def file_links(self) -> FoundLinks:
"""Links found by specifying archives directly."""
raise NotImplementedError()
raise NotImplementedError


def _is_html_file(file_url: str) -> bool:
@@ -101,7 +101,7 @@ class _FlatDirectorySource(LinkSource):
* ``file_candidates``: Archives in the directory.
"""

_paths_to_urls: Dict[str, _FlatDirectoryToUrls] = {}
_paths_to_urls: ClassVar[Dict[str, _FlatDirectoryToUrls]] = {}

def __init__(
self,
4 changes: 1 addition & 3 deletions src/pip/_internal/locations/__init__.py
Original file line number Diff line number Diff line change
@@ -421,9 +421,7 @@ def _looks_like_deb_system_dist_packages(value: str) -> bool:
"""
if not _looks_like_debian_scheme():
return False
if value == "/usr/lib/python3/dist-packages":
return True
return False
return value == "/usr/lib/python3/dist-packages"


def get_purelib() -> str:
6 changes: 4 additions & 2 deletions src/pip/_internal/locations/_distutils.py
Original file line number Diff line number Diff line change
@@ -17,18 +17,20 @@
import logging
import os
import sys
from distutils.cmd import Command as DistutilsCommand
from distutils.command.install import SCHEME_KEYS
from distutils.command.install import install as distutils_install_command
from distutils.sysconfig import get_python_lib
from typing import Dict, List, Optional, Union, cast
from typing import TYPE_CHECKING, Dict, List, Optional, Union, cast

from pip._internal.models.scheme import Scheme
from pip._internal.utils.compat import WINDOWS
from pip._internal.utils.virtualenv import running_under_virtualenv

from .base import get_major_minor_version

if TYPE_CHECKING:
from distutils.cmd import Command as DistutilsCommand

logger = logging.getLogger(__name__)


2 changes: 1 addition & 1 deletion src/pip/_internal/locations/_sysconfig.py
Original file line number Diff line number Diff line change
@@ -94,7 +94,7 @@ def _infer_user() -> str:
if suffixed in _AVAILABLE_SCHEMES:
return suffixed
if "posix_user" not in _AVAILABLE_SCHEMES: # User scheme unavailable.
raise UserInstallationInvalid()
raise UserInstallationInvalid
return "posix_user"


4 changes: 2 additions & 2 deletions src/pip/_internal/metadata/_json.py
Original file line number Diff line number Diff line change
@@ -64,10 +64,10 @@ def sanitise_header(h: Union[Header, str]) -> str:
key = json_name(field)
if multi:
value: Union[str, List[str]] = [
sanitise_header(v) for v in msg.get_all(field) # type: ignore
sanitise_header(v) for v in msg.get_all(field) # type: ignore[union-attr]
]
else:
value = sanitise_header(msg.get(field)) # type: ignore
value = sanitise_header(msg.get(field)) # type: ignore[arg-type]
if key == "keywords":
# Accept both comma-separated and space-separated
# forms, for better compatibility with old data.
Loading