Skip to content

Add another docstring formatter in pre-commit #5629

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

Merged
merged 2 commits into from
Jan 2, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,8 @@ repos:
- id: prettier
args: [--prose-wrap=always, --print-width=88]
exclude: tests(/.*)*/data
- repo: https://github.com/DanielNoord/pydocstringformatter
rev: v0.2.0
hooks:
- id: pydocstringformatter
exclude: *fixtures
3 changes: 2 additions & 1 deletion examples/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ class MyAstroidChecker(BaseChecker):
def visit_call(self, node: nodes.Call) -> None:
"""Called when a :class:`.nodes.Call` node is visited.

See :mod:`astroid` for the description of available nodes."""
See :mod:`astroid` for the description of available nodes.
"""
if not (
isinstance(node.func, nodes.Attribute)
and isinstance(node.func.expr, nodes.Name)
Expand Down
3 changes: 1 addition & 2 deletions examples/deprecation_checker.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
Example checker detecting deprecated functions/methods. Following example searches for usages of
"""Example checker detecting deprecated functions/methods. Following example searches for usages of
deprecated function `deprecated_function` and deprecated method `MyClass.deprecated_method`
from module mymodule:

Expand Down
15 changes: 7 additions & 8 deletions pylint/checkers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@
class NamingStyle:
"""It may seem counterintuitive that single naming style has multiple "accepted"
forms of regular expressions, but we need to special-case stuff like dunder names
in method names."""
in method names.
"""

ANY: Pattern[str] = re.compile(".*")
CLASS_NAME_RGX: Pattern[str] = ANY
Expand Down Expand Up @@ -278,8 +279,7 @@ def in_nested_list(nested_list, obj):


def _get_break_loop_node(break_node):
"""
Returns the loop node that holds the break node in arguments.
"""Returns the loop node that holds the break node in arguments.

Args:
break_node (astroid.Break): the break node of interest.
Expand All @@ -300,8 +300,7 @@ def _get_break_loop_node(break_node):


def _loop_exits_early(loop):
"""
Returns true if a loop may end with a break statement.
"""Returns true if a loop may end with a break statement.

Args:
loop (astroid.For, astroid.While): the loop node inspected.
Expand Down Expand Up @@ -389,8 +388,7 @@ def _determine_function_name_type(node: nodes.FunctionDef, config=None):


def _has_abstract_methods(node):
"""
Determine if the given `node` has abstract methods.
"""Determine if the given `node` has abstract methods.

The methods should be made abstract by decorating them
with `abc` decorators.
Expand Down Expand Up @@ -1496,7 +1494,8 @@ def _check_not_in_finally(self, node, node_name, breaker_classes=()):
"""check that a node is not inside a 'finally' clause of a
'try...finally' statement.
If we find a parent which type is in breaker_classes before
a 'try...finally' block we skip the whole check."""
a 'try...finally' block we skip the whole check.
"""
# if self._tryfinallys is empty, we're not an in try...finally block
if not self._tryfinallys:
return
Expand Down
9 changes: 6 additions & 3 deletions pylint/checkers/base_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ class BaseChecker(OptionsProviderMixIn):
def __init__(self, linter=None):
"""checker instances should have the linter as argument

:param ILinter linter: is an object implementing ILinter."""
:param ILinter linter: is an object implementing ILinter.
"""
if self.name is not None:
self.name = self.name.lower()
super().__init__()
Expand All @@ -67,7 +68,8 @@ def __repr__(self):

def __str__(self):
"""This might be incomplete because multiple class inheriting BaseChecker
can have the same name. Cf MessageHandlerMixIn.get_full_documentation()"""
can have the same name. Cf MessageHandlerMixIn.get_full_documentation()
"""
return self.get_full_documentation(
msgs=self.msgs, options=self.options_and_values(), reports=self.reports
)
Expand Down Expand Up @@ -132,7 +134,8 @@ def check_consistency(self):
checker.

:raises InvalidMessageError: If the checker id in the messages are not
always the same."""
always the same.
"""
checker_id = None
existing_ids = []
for message in self.messages:
Expand Down
10 changes: 3 additions & 7 deletions pylint/checkers/classes/class_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,7 @@ class _DefaultMissing:


def _has_different_parameters_default_value(original, overridden):
"""
Check if original and overridden methods arguments have different default values
"""Check if original and overridden methods arguments have different default values

Return True if one of the overridden arguments has a default
value different from the default value of the original argument
Expand Down Expand Up @@ -821,8 +820,7 @@ def _check_consistent_mro(self, node):
pass

def _check_proper_bases(self, node):
"""
Detect that a class inherits something which is not
"""Detect that a class inherits something which is not
a class or a type.
"""
for base in node.bases:
Expand Down Expand Up @@ -1655,9 +1653,7 @@ def _check_protected_attribute_access(self, node: nodes.Attribute):

@staticmethod
def _is_called_inside_special_method(node: nodes.NodeNG) -> bool:
"""
Returns true if the node is located inside a special (aka dunder) method
"""
"""Returns true if the node is located inside a special (aka dunder) method"""
try:
frame_name = node.frame().name
except AttributeError:
Expand Down
3 changes: 1 addition & 2 deletions pylint/checkers/classes/special_methods_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@


def _safe_infer_call_result(node, caller, context=None):
"""
Safely infer the return value of a function.
"""Safely infer the return value of a function.

Returns None if inference failed or if there is some ambiguity (more than
one node has been inferred). Otherwise, returns inferred value.
Expand Down
3 changes: 1 addition & 2 deletions pylint/checkers/ellipsis_checker.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Ellipsis checker for Python code
"""
"""Ellipsis checker for Python code"""
from typing import TYPE_CHECKING

from astroid import nodes
Expand Down
3 changes: 1 addition & 2 deletions pylint/checkers/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ def predicate(obj):


def _annotated_unpack_infer(stmt, context=None):
"""
Recursively generate nodes inferred by the given statement.
"""Recursively generate nodes inferred by the given statement.
If the inferred value is a list or a tuple, recurse on the elements.
Returns an iterator which yields tuples in the format
('original node', 'inferred node').
Expand Down
29 changes: 9 additions & 20 deletions pylint/checkers/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -669,9 +669,7 @@ def _check_multi_statement_line(self, node, line):
self._visited_lines[line] = 2

def check_line_ending(self, line: str, i: int) -> None:
"""
Check that the final newline is not missing and that there is no trailing whitespace.
"""
"""Check that the final newline is not missing and that there is no trailing whitespace."""
if not line.endswith("\n"):
self.add_message("missing-final-newline", line=i)
return
Expand All @@ -683,9 +681,7 @@ def check_line_ending(self, line: str, i: int) -> None:
)

def check_line_length(self, line: str, i: int, checker_off: bool) -> None:
"""
Check that the line length is less than the authorized value
"""
"""Check that the line length is less than the authorized value"""
max_chars = self.config.max_line_length
ignore_long_line = self.config.ignore_long_lines
line = line.rstrip()
Expand All @@ -697,9 +693,7 @@ def check_line_length(self, line: str, i: int, checker_off: bool) -> None:

@staticmethod
def remove_pylint_option_from_lines(options_pattern_obj) -> str:
"""
Remove the `# pylint ...` pattern from lines
"""
"""Remove the `# pylint ...` pattern from lines"""
lines = options_pattern_obj.string
purged_lines = (
lines[: options_pattern_obj.start(1)].rstrip()
Expand All @@ -709,9 +703,7 @@ def remove_pylint_option_from_lines(options_pattern_obj) -> str:

@staticmethod
def is_line_length_check_activated(pylint_pattern_match_object) -> bool:
"""
Return true if the line length check is activated
"""
"""Return true if the line length check is activated"""
try:
for pragma in parse_pragma(pylint_pattern_match_object.group(2)):
if pragma.action == "disable" and "line-too-long" in pragma.messages:
Expand All @@ -723,9 +715,7 @@ def is_line_length_check_activated(pylint_pattern_match_object) -> bool:

@staticmethod
def specific_splitlines(lines: str) -> List[str]:
"""
Split lines according to universal newlines except those in a specific sets
"""
"""Split lines according to universal newlines except those in a specific sets"""
unsplit_ends = {
"\v",
"\x0b",
Expand All @@ -749,11 +739,10 @@ def specific_splitlines(lines: str) -> List[str]:
return res

def check_lines(self, lines: str, lineno: int) -> None:
"""
Check lines have :
- a final newline
- no trailing whitespace
- less than a maximum number of characters
"""Check lines have :
- a final newline
- no trailing whitespace
- less than a maximum number of characters
"""
# we're first going to do a rough check whether any lines in this set
# go over the line limit. If none of them do, then we don't need to
Expand Down
7 changes: 2 additions & 5 deletions pylint/checkers/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE

"""checker for use of Python logging
"""
"""checker for use of Python logging"""
import string
from typing import TYPE_CHECKING, Set

Expand Down Expand Up @@ -295,9 +294,7 @@ def _helper_string(self, node):

@staticmethod
def _is_operand_literal_str(operand):
"""
Return True if the operand in argument is a literal string
"""
"""Return True if the operand in argument is a literal string"""
return isinstance(operand, nodes.Const) and operand.name == "str"

def _check_call_func(self, node: nodes.Call):
Expand Down
3 changes: 1 addition & 2 deletions pylint/checkers/newstyle.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE

"""check for new / old style related problems
"""
"""check for new / old style related problems"""
from typing import TYPE_CHECKING

import astroid
Expand Down
3 changes: 2 additions & 1 deletion pylint/checkers/refactoring/implicit_booleaness_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ def instance_has_bool(class_def: nodes.ClassDef) -> bool:
def visit_unaryop(self, node: nodes.UnaryOp) -> None:
"""`not len(S)` must become `not S` regardless if the parent block
is a test condition or something else (boolean expression)
e.g. `if not len(S):`"""
e.g. `if not len(S):`
"""
if (
isinstance(node, nodes.UnaryOp)
and node.op == "not"
Expand Down
3 changes: 2 additions & 1 deletion pylint/checkers/refactoring/recommendation_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,8 @@ def visit_const(self, node: nodes.Const) -> None:

def _detect_replacable_format_call(self, node: nodes.Const) -> None:
"""Check whether a string is used in a call to format() or '%' and whether it
can be replaced by an f-string"""
can be replaced by an f-string
"""
if (
isinstance(node.parent, nodes.Attribute)
and node.parent.attrname == "format"
Expand Down
28 changes: 14 additions & 14 deletions pylint/checkers/refactoring/refactoring_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ def _is_a_return_statement(node: nodes.Call) -> bool:


def _is_part_of_with_items(node: nodes.Call) -> bool:
"""
Checks if one of the node's parents is a ``nodes.With`` node and that the node itself is located
"""Checks if one of the node's parents is a ``nodes.With`` node and that the node itself is located
somewhere under its ``items``.
"""
frame = node.frame()
Expand All @@ -135,7 +134,8 @@ def _is_part_of_with_items(node: nodes.Call) -> bool:

def _will_be_released_automatically(node: nodes.Call) -> bool:
"""Checks if a call that could be used in a ``with`` statement is used in an alternative
construct which would ensure that its __exit__ method is called."""
construct which would ensure that its __exit__ method is called.
"""
callables_taking_care_of_exit = frozenset(
(
"contextlib._BaseExitStack.enter_context",
Expand All @@ -152,7 +152,8 @@ def _will_be_released_automatically(node: nodes.Call) -> bool:

class ConsiderUsingWithStack(NamedTuple):
"""Stack for objects that may potentially trigger a R1732 message
if they are not used in a ``with`` block later on."""
if they are not used in a ``with`` block later on.
"""

module_scope: Dict[str, nodes.NodeNG] = {}
class_scope: Dict[str, nodes.NodeNG] = {}
Expand Down Expand Up @@ -1278,7 +1279,8 @@ def _apply_boolean_simplification_rules(operator, values):
reverse for AND

2) False values in OR expressions are only relevant if all values are
false, and the reverse for AND"""
false, and the reverse for AND
"""
simplified_values = []

for subnode in values:
Expand All @@ -1299,7 +1301,8 @@ def _simplify_boolean_operation(self, bool_op):
"""Attempts to simplify a boolean operation

Recursively applies simplification on the operator terms,
and keeps track of whether reductions have been made."""
and keeps track of whether reductions have been made.
"""
children = list(bool_op.get_children())
intermediate = [
self._simplify_boolean_operation(child)
Expand All @@ -1320,7 +1323,8 @@ def _check_simplifiable_condition(self, node):
"""Check if a boolean condition can be simplified.

Variables will not be simplified, even in the value can be inferred,
and expressions like '3 + 4' will remain expanded."""
and expressions like '3 + 4' will remain expanded.
"""
if not utils.is_test_condition(node):
return

Expand Down Expand Up @@ -1506,8 +1510,7 @@ def _check_use_list_or_dict_literal(self, node: nodes.Call) -> None:
self.add_message("use-dict-literal", node=node)

def _check_consider_using_join(self, aug_assign):
"""
We start with the augmented assignment and work our way upwards.
"""We start with the augmented assignment and work our way upwards.
Names of variables for nodes if match successful:
result = '' # assign
for number in ['1', '2', '3'] # for_loop
Expand Down Expand Up @@ -1630,8 +1633,7 @@ def _check_unnecessary_comprehension(self, node: nodes.Comprehension) -> None:

@staticmethod
def _is_and_or_ternary(node):
"""
Returns true if node is 'condition and true_value or false_value' form.
"""Returns true if node is 'condition and true_value or false_value' form.

All of: condition, true_value and false_value should not be a complex boolean expression
"""
Expand Down Expand Up @@ -1793,9 +1795,7 @@ def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:

@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool:
"""
Returns True if there is at least one return in the node's siblings
"""
"""Returns True if there is at least one return in the node's siblings"""
next_sibling = node.next_sibling()
while next_sibling:
if isinstance(next_sibling, nodes.Return):
Expand Down
Loading