Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ruff] Fix some configuration warnings, activate flake8-pie, flake8-pyi, and pydocstyle #9593

Merged
merged 6 commits into from
May 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/test_messages_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def get_expected_messages(stream: TextIO) -> MessageCounter:
line = match.group("line")
if line is None:
lineno = i + 1
elif line.startswith("+") or line.startswith("-"):
elif line.startswith(("+", "-")):
lineno = i + 1 + int(line)
else:
lineno = int(line)
Expand Down
4 changes: 2 additions & 2 deletions examples/custom_raw.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@


class MyRawChecker(BaseRawFileChecker):
"""Check for line continuations with '\' instead of using triple
quoted string or parenthesis
r"""Check for line continuations with '\' instead of using triple
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ironic update to use raw docstring in the MyRawChecker class πŸ˜„

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you know it was twice voted "most likely place to see dangerous raw characters in the doc" ?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No :) what is that (doc)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just joking πŸ˜„ The doc would be the docstring in the raw checker where you explain about raw string and why you need them sometime.

quoted string or parenthesis.
"""

name = "custom_raw"
Expand Down
1 change: 0 additions & 1 deletion pylint/checkers/base/comparison_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ def _check_singleton_comparison(
checking_for_absence: bool = False,
) -> None:
"""Check if == or != is being used to compare a singleton value."""

if utils.is_singleton_const(left_value):
singleton, other_value = left_value.value, right_value
elif utils.is_singleton_const(right_value):
Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/base/name_checker/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ def _check_typevar(self, name: str, node: nodes.AssignName) -> None:
confidence=interfaces.INFERENCE,
)
elif variance == TypeVarVariance.invariant and (
name.endswith("_co") or name.endswith("_contra")
name.endswith(("_co", "_contra"))
):
suggest_name = re.sub("_contra$|_co$", "", name)
self.add_message(
Expand Down
2 changes: 1 addition & 1 deletion pylint/checkers/base_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __gt__(self, other: Any) -> bool:
return not self_is_builtin
return self.name > other.name

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
"""Permit to assert Checkers are equal."""
if not isinstance(other, BaseChecker):
return False
Expand Down
3 changes: 0 additions & 3 deletions pylint/checkers/classes/class_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,6 @@ def _is_attribute_property(name: str, klass: nodes.ClassDef) -> bool:
Returns ``True`` if the name is a property in the given klass,
``False`` otherwise.
"""

try:
attributes = klass.getattr(name)
except astroid.NotFoundError:
Expand Down Expand Up @@ -748,7 +747,6 @@ def __init__(self) -> None:

def set_accessed(self, node: _AccessNodes) -> None:
"""Set the given node as accessed."""

frame = node_frame_class(node)
if frame is None:
# The node does not live in a class.
Expand Down Expand Up @@ -1946,7 +1944,6 @@ def _is_class_or_instance_attribute(name: str, klass: nodes.ClassDef) -> bool:
Returns ``True`` if the name is a property in the given klass,
``False`` otherwise.
"""

if utils.is_class_attr(name, klass):
return True

Expand Down
3 changes: 0 additions & 3 deletions pylint/checkers/deprecated.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,6 @@ def check_deprecated_method(self, node: nodes.Call, inferred: nodes.NodeNG) -> N

This method should be called from the checker implementing this mixin.
"""

# Reject nodes which aren't of interest to us.
if not isinstance(inferred, ACCEPTABLE_NODES):
return
Expand Down Expand Up @@ -272,7 +271,6 @@ def check_deprecated_class(
self, node: nodes.NodeNG, mod_name: str, class_names: Iterable[str]
) -> None:
"""Checks if the class is deprecated."""

for class_name in class_names:
if class_name in self.deprecated_classes(mod_name):
self.add_message(
Expand All @@ -281,7 +279,6 @@ def check_deprecated_class(

def check_deprecated_class_in_call(self, node: nodes.Call) -> None:
"""Checks if call the deprecated class."""

if isinstance(node.func, nodes.Attribute) and isinstance(
node.func.expr, nodes.Name
):
Expand Down
1 change: 0 additions & 1 deletion pylint/checkers/design_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,6 @@

def _is_exempt_from_public_methods(node: astroid.ClassDef) -> bool:
"""Check if a class is exempt from too-few-public-methods."""

# If it's a typing.Namedtuple, typing.TypedDict or an Enum
for ancestor in node.ancestors():
if is_enum(ancestor):
Expand Down
1 change: 0 additions & 1 deletion pylint/checkers/imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -1076,7 +1076,6 @@ def _add_imported_module(self, node: ImportNode, importedmodname: str) -> None:

def _check_preferred_module(self, node: ImportNode, mod_path: str) -> None:
"""Check if the module has a preferred replacement."""

mod_compare = [mod_path]
# build a comparison list of possible names using importfrom
if isinstance(node, astroid.nodes.node_classes.ImportFrom):
Expand Down
1 change: 0 additions & 1 deletion pylint/checkers/non_ascii_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ class NonAsciiNameChecker(base_checker.BaseChecker):

def _check_name(self, node_type: str, name: str | None, node: nodes.NodeNG) -> None:
"""Check whether a name is using non-ASCII characters."""

if name is None:
# For some nodes i.e. *kwargs from a dict, the name will be empty
return
Expand Down
1 change: 0 additions & 1 deletion pylint/checkers/refactoring/recommendation_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ def _check_use_maxsplit_arg(self, node: nodes.Call) -> None:
"""Add message when accessing first or last elements of a str.split() or
str.rsplit().
"""

# Check if call is split() or rsplit()
if not (
isinstance(node.func, nodes.Attribute)
Expand Down
1 change: 0 additions & 1 deletion pylint/checkers/refactoring/refactoring_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,6 @@ def _check_simplifiable_if(self, node: nodes.If) -> None:
the result of the statement's test, then this can be reduced
to `bool(test)` without losing any functionality.
"""

if self._is_actual_elif(node):
# Not interested in if statements with multiple branches.
return
Expand Down
12 changes: 5 additions & 7 deletions pylint/checkers/similar.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
NamedTuple,
Expand Down Expand Up @@ -136,7 +135,7 @@ def __init__(self, fileid: str, num_line: int, *lines: Iterable[str]) -> None:
self._hash: int = sum(hash(lin) for lin in lines)
"""The hash of some consecutive lines."""

def __eq__(self, o: Any) -> bool:
def __eq__(self, o: object) -> bool:
if not isinstance(o, LinesChunk):
return NotImplemented
return self._hash == o._hash
Expand Down Expand Up @@ -195,7 +194,7 @@ def __repr__(self) -> str:
f"<LineSetStartCouple <{self.fst_lineset_index};{self.snd_lineset_index}>>"
)

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
if not isinstance(other, LineSetStartCouple):
return NotImplemented
return (
Expand Down Expand Up @@ -612,7 +611,6 @@ def _get_functions(
"""Recursively get all functions including nested in the classes from the
tree.
"""

for node in tree.body:
if isinstance(node, (nodes.FunctionDef, nodes.AsyncFunctionDef)):
functions.append(node)
Expand Down Expand Up @@ -648,10 +646,10 @@ def _get_functions(
line = line.strip()
if ignore_docstrings:
if not docstring:
if line.startswith('"""') or line.startswith("'''"):
if line.startswith(('"""', "'''")):
docstring = line[:3]
line = line[3:]
elif line.startswith('r"""') or line.startswith("r'''"):
elif line.startswith(('r"""', "r'''")):
docstring = line[1:4]
line = line[4:]
if docstring:
Expand Down Expand Up @@ -717,7 +715,7 @@ def __lt__(self, other: LineSet) -> bool:
def __hash__(self) -> int:
return id(self)

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
if not isinstance(other, LineSet):
return False
return self.__dict__ == other.__dict__
Expand Down
3 changes: 0 additions & 3 deletions pylint/checkers/typecheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -1228,7 +1228,6 @@ def _get_nomember_msgid_hint(
)
def visit_assign(self, node: nodes.Assign) -> None:
"""Process assignments in the AST."""

self._check_assignment_from_function_call(node)
self._check_dundername_is_string(node)

Expand Down Expand Up @@ -1309,7 +1308,6 @@ def _is_builtin_no_return(node: nodes.Assign) -> bool:

def _check_dundername_is_string(self, node: nodes.Assign) -> None:
"""Check a string is assigned to self.__name__."""

# Check the left-hand side of the assignment is <something>.__name__
lhs = node.targets[0]
if not isinstance(lhs, nodes.AssignAttr):
Expand Down Expand Up @@ -1926,7 +1924,6 @@ def visit_with(self, node: nodes.With) -> None:
@only_required_for_messages("invalid-unary-operand-type")
def visit_unaryop(self, node: nodes.UnaryOp) -> None:
"""Detect TypeErrors for unary operands."""

for error in node.type_errors():
# Let the error customize its output.
self.add_message("invalid-unary-operand-type", args=str(error), node=node)
Expand Down
5 changes: 2 additions & 3 deletions pylint/checkers/unicode.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,6 @@ def _map_positions_to_result(
Also takes care of encodings for which the length of an encoded code point does not
default to 8 Bit.
"""

result: dict[int, _BadChar] = {}

for search_for, char in search_dict.items():
Expand Down Expand Up @@ -248,7 +247,7 @@ def _cached_encode_search(string: str, encoding: str) -> bytes:


def _fix_utf16_32_line_stream(steam: Iterable[bytes], codec: str) -> Iterable[bytes]:
"""Handle line ending for UTF16 and UTF32 correctly.
r"""Handle line ending for UTF16 and UTF32 correctly.

Currently, Python simply strips the required zeros after \n after the
line ending. Leading to lines that can't be decoded properly
Expand Down Expand Up @@ -375,7 +374,7 @@ class UnicodeChecker(checkers.BaseRawFileChecker):

@staticmethod
def _is_invalid_codec(codec: str) -> bool:
return codec.startswith("utf-16") or codec.startswith("utf-32")
return codec.startswith(("utf-16", "utf-32"))

@staticmethod
def _is_unicode(codec: str) -> bool:
Expand Down
3 changes: 0 additions & 3 deletions pylint/checkers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1484,7 +1484,6 @@ def node_type(node: nodes.NodeNG) -> SuccessfulInferenceResult | None:

def is_registered_in_singledispatch_function(node: nodes.FunctionDef) -> bool:
"""Check if the given function node is a singledispatch function."""

singledispatch_qnames = (
"functools.singledispatch",
"singledispatch.singledispatch",
Expand Down Expand Up @@ -1540,7 +1539,6 @@ def find_inferred_fn_from_register(node: nodes.NodeNG) -> nodes.FunctionDef | No

def is_registered_in_singledispatchmethod_function(node: nodes.FunctionDef) -> bool:
"""Check if the given function node is a singledispatchmethod function."""

singledispatchmethod_qnames = (
"functools.singledispatchmethod",
"singledispatch.singledispatchmethod",
Expand Down Expand Up @@ -2276,7 +2274,6 @@ def is_enum_member(node: nodes.AssignName) -> bool:
"""Return `True` if `node` is an Enum member (is an item of the
`__members__` container).
"""

frame = node.frame()
if (
not isinstance(frame, nodes.ClassDef)
Expand Down
1 change: 0 additions & 1 deletion pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1017,7 +1017,6 @@ def _check_loop_finishes_via_except(
the loop can depend on it being assigned.

Example:

for _ in range(3):
try:
do_something()
Expand Down
2 changes: 1 addition & 1 deletion pylint/config/config_initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def _order_all_first(config_args: list[str], *, joined: bool) -> list[str]:
all_action = ""

for i, arg in enumerate(config_args):
if joined and (arg.startswith("--enable=") or arg.startswith("--disable=")):
if joined and arg.startswith(("--enable=", "--disable=")):
value = arg.split("=")[1]
elif arg in {"--enable", "--disable"}:
value = config_args[i + 1]
Expand Down
2 changes: 0 additions & 2 deletions pylint/extensions/empty_comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

def is_line_commented(line: bytes) -> bool:
"""Checks if a `# symbol that is not part of a string was found in line."""

comment_idx = line.find(b"#")
if comment_idx == -1:
return False
Expand All @@ -27,7 +26,6 @@ def is_line_commented(line: bytes) -> bool:

def comment_part_of_string(line: bytes, comment_idx: int) -> bool:
"""Checks if the symbol at comment_idx is part of a string."""

if (
line[:comment_idx].count(b"'") % 2 == 1
and line[comment_idx:].count(b"'") % 2 == 1
Expand Down
10 changes: 5 additions & 5 deletions pylint/lint/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@

"""Pylint [options] modules_or_packages.

Check that module(s) satisfy a coding standard (and more !).
Check that module(s) satisfy a coding standard (and more !).

pylint --help
pylint --help

Display this help message and exit.
Display this help message and exit.

pylint --help-msg <msg-id>[,<msg-id>]
pylint --help-msg <msg-id>[,<msg-id>]

Display help messages about given message identifiers and exit.
Display help messages about given message identifiers and exit.
"""
import sys

Expand Down
4 changes: 2 additions & 2 deletions pylint/message/message_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from __future__ import annotations

import sys
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING

from astroid import nodes

Expand Down Expand Up @@ -59,7 +59,7 @@ def check_msgid(msgid: str) -> None:
if msgid[0] not in MSG_TYPES:
raise InvalidMessageError(f"Bad message type {msgid[0]} in {msgid!r}")

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
return (
isinstance(other, MessageDefinition)
and self.msgid == other.msgid
Expand Down
1 change: 0 additions & 1 deletion pylint/pyreverse/diadefslib.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,6 @@ def get_diadefs(self, project: Project, linker: Linker) -> list[ClassDiagram]:
:returns: The list of diagram definitions
:rtype: list(:class:`pylint.pyreverse.diagrams.ClassDiagram`)
"""

# read and interpret diagram definitions (Diadefs)
diagrams = []
generator = ClassDiadefGenerator(linker, self)
Expand Down
1 change: 0 additions & 1 deletion pylint/pyreverse/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,6 @@ def infer_node(node: nodes.AssignAttr | nodes.AssignName) -> set[InferenceResult
"""Return a set containing the node annotation if it exists
otherwise return a set of the inferred types using the NodeNG.infer method.
"""

ann = get_annotation(node)
try:
if ann:
Expand Down
2 changes: 1 addition & 1 deletion pylint/testutils/lint_module_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def get_expected_messages(stream: TextIO) -> MessageCounter:
line = match.group("line")
if line is None:
lineno = i + 1
elif line.startswith("+") or line.startswith("-"):
elif line.startswith(("+", "-")):
lineno = i + 1 + int(line)
else:
lineno = int(line)
Expand Down
13 changes: 6 additions & 7 deletions pylint/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,12 @@ def normalize_text(


# py3k has no more cmp builtin
def cmp(a: int | float, b: int | float) -> int:
def cmp(a: float, b: float) -> int:
return (a > b) - (a < b)


def diff_string(old: int | float, new: int | float) -> str:
"""Given an old and new int value, return a string representing the
difference.
"""
def diff_string(old: float, new: float) -> str:
"""Given an old and new value, return a string representing the difference."""
diff = abs(old - new)
diff_str = f"{CMPS[cmp(old, new)]}{diff and f'{diff:.2f}' or ''}"
return diff_str
Expand Down Expand Up @@ -211,7 +209,7 @@ def register_plugins(linter: PyLinter, directory: str) -> None:


def _splitstrip(string: str, sep: str = ",") -> list[str]:
"""Return a list of stripped string by splitting the string given as
r"""Return a list of stripped string by splitting the string given as
argument on `sep` (',' by default), empty strings are discarded.

>>> _splitstrip('a, b, c , 4,,')
Expand Down Expand Up @@ -256,7 +254,8 @@ def _check_csv(value: list[str] | tuple[str] | str) -> Sequence[str]:

def _check_regexp_csv(value: list[str] | tuple[str] | str) -> Iterable[str]:
r"""Split a comma-separated list of regexps, taking care to avoid splitting
a regex employing a comma as quantifier, as in `\d{1,2}`."""
a regex employing a comma as quantifier, as in `\d{1,2}`.
"""
if isinstance(value, (list, tuple)):
yield from value
else:
Expand Down