class documentation

class RefactoringChecker(checkers.BaseTokenChecker): (source)

View In Hierarchy

Looks for code which can be refactored. This checker also mixes the astroid and the token approaches in order to create knowledge about whether an "else if" node is a true "else if" node, or an "elif" node.

Method __init__ Checker instances should have the linter as argument.
Method leave_classdef Undocumented
Method leave_functiondef Undocumented
Method leave_module Undocumented
Method open Called before visiting project (i.e. set of modules).
Method process_tokens Should be overridden by subclasses.
Method visit_assign Undocumented
Method visit_augassign Undocumented
Method visit_boolop Undocumented
Method visit_call Undocumented
Method visit_comprehension Undocumented
Method visit_excepthandler Undocumented
Method visit_for Undocumented
Method visit_functiondef Undocumented
Method visit_if Undocumented
Method visit_ifexp Undocumented
Method visit_raise Undocumented
Method visit_return Undocumented
Method visit_tryexcept Undocumented
Method visit_with Undocumented
Class Variable msgs Undocumented
Class Variable name Name of the provider.
Class Variable options Options provided by this provider.
Static Method _and_or_ternary_arguments Undocumented
Static Method _apply_boolean_simplification_rules Removes irrelevant values or returns short-circuiting values.
Static Method _check_exception_inherit_from_stopiteration Return True if the exception node in argument inherit from StopIteration.
Static Method _dict_literal_suggestion Return a suggestion of reasonable length.
Static Method _duplicated_isinstance_types Get the duplicated types from the underlying isinstance calls.
Static Method _has_exit_in_scope Undocumented
Static Method _has_return_in_siblings Returns True if there is at least one return in the node's siblings.
Static Method _is_and_or_ternary Returns true if node is 'condition and true_value or false_value' form.
Static Method _is_bool_const Undocumented
Static Method _is_simple_assignment Undocumented
Static Method _name_to_concatenate Try to extract the name used in a concatenation loop.
Static Method _type_and_name_are_equal Undocumented
Method _append_context_managers_to_stack Undocumented
Method _check_chained_comparison Check if there is any chained comparison in the expression.
Method _check_consider_get Undocumented
Method _check_consider_merging_isinstance Check isinstance calls which can be merged together.
Method _check_consider_using_comprehension_constructor Undocumented
Method _check_consider_using_generator Undocumented
Method _check_consider_using_in Undocumented
Method _check_consider_using_join We start with the augmented assignment and work our way upwards.
Method _check_consider_using_min_max_builtin Check if the given if node can be refactored as a min/max python builtin.
Method _check_consider_using_with Undocumented
Method _check_consistent_returns Check that all return statements inside a function are consistent.
Method _check_nested_blocks Update and check the number of nested blocks.
Method _check_quit_exit_call Undocumented
Method _check_raising_stopiteration_in_generator_next_call Check if a StopIteration exception is raised by the call to next function.
Method _check_redefined_argument_from_local Undocumented
Method _check_return_at_the_end Check for presence of a *single* return statement at the end of a function.
Method _check_simplifiable_condition Check if a boolean condition can be simplified.
Method _check_simplifiable_if Check if the given if node can be simplified.
Method _check_simplifiable_ifexp Undocumented
Method _check_stop_iteration_inside_generator Check if an exception of type StopIteration is raised inside a generator.
Method _check_super_with_arguments Undocumented
Method _check_superfluous_else Undocumented
Method _check_superfluous_else_break Undocumented
Method _check_superfluous_else_continue Undocumented
Method _check_superfluous_else_raise Undocumented
Method _check_superfluous_else_return Undocumented
Method _check_swap_variables Undocumented
Method _check_unnecessary_comprehension Undocumented
Method _check_unnecessary_dict_index_lookup Add message when accessing dict values by index lookup.
Method _check_unnecessary_list_index_lookup Undocumented
Method _check_use_dict_literal Check if dict is created by using the literal {}.
Method _check_use_list_literal Check if empty list is created by using the literal [].
Method _emit_consider_using_with_if_needed Undocumented
Method _emit_nested_blocks_message_if_needed Undocumented
Method _enumerate_with_start Check presence of `start` kwarg or second argument to enumerate.
Method _get_start_value Undocumented
Method _init Undocumented
Method _is_actual_elif Check if the given node is an actual elif.
Method _is_dict_get_block Undocumented
Method _is_function_def_never_returning Return True if the function never returns, False otherwise.
Method _is_if_node_return_ended Check if the If node ends with an explicit return statement.
Method _is_node_return_ended Check if the node ends with an explicit return statement.
Method _is_raise_node_return_ended Check if the Raise node ends with an explicit return statement.
Method _simplify_boolean_operation Attempts to simplify a boolean operation.
Instance Variable _can_simplify_bool_op Undocumented
Instance Variable _consider_using_with_stack Undocumented
Instance Variable _elifs Undocumented
Instance Variable _nested_blocks Undocumented
Instance Variable _never_returning_functions Undocumented
Instance Variable _reported_swap_nodes Undocumented
Instance Variable _return_nodes Undocumented
Property _dummy_rgx Undocumented

Inherited from BaseChecker (via BaseTokenChecker):

Method __eq__ Permit to assert Checkers are equal.
Method __gt__ Sorting of checkers.
Method __hash__ Make Checker hashable.
Method __repr__ Undocumented
Method __str__ This might be incomplete because multiple classes inheriting BaseChecker can have the same name.
Method add_message Undocumented
Method check_consistency Check the consistency of msgid.
Method close Called after visiting project (i.e set of modules).
Method create_message_definition_from_tuple Undocumented
Method get_full_documentation Undocumented
Method get_map_data Undocumented
Method get_message_definition Undocumented
Method reduce_map_data Undocumented
Class Variable enabled Undocumented
Class Variable reports Undocumented
Instance Variable linter Undocumented
Property messages Undocumented

Inherited from _ArgumentsProvider (via BaseTokenChecker, BaseChecker):

Method get_option_def DEPRECATED: Return the dictionary defining an option given its name.
Method level.setter Undocumented
Method load_defaults DEPRECATED: Initialize the provider using default values.
Method option_attrname DEPRECATED: Get the config attribute corresponding to opt.
Method option_value DEPRECATED: Get the current value for the given option.
Method options_and_values DEPRECATED.
Method options_by_section DEPRECATED: Return an iterator on options grouped by section.
Method set_option DEPRECATED: Method called to set an option (registered in the options list).
Class Variable option_groups_descs Option groups of this provider and their descriptions.
Property config Undocumented
Property level Undocumented
Instance Variable _arguments_manager The manager that will parse and register any options provided.
Instance Variable _level Undocumented
def __init__(self, linter: PyLinter): (source)

Checker instances should have the linter as argument.

@utils.only_required_for_messages('consider-using-with')
def leave_classdef(self, _: nodes.ClassDef): (source)

Undocumented

@utils.only_required_for_messages('too-many-nested-blocks', 'inconsistent-return-statements', 'useless-return', 'consider-using-with')
def leave_functiondef(self, node: nodes.FunctionDef): (source)

Undocumented

@utils.only_required_for_messages('consider-using-with')
def leave_module(self, _: nodes.Module): (source)

Undocumented

def open(self): (source)

Called before visiting project (i.e. set of modules).

def process_tokens(self, tokens: list[tokenize.TokenInfo]): (source)

Should be overridden by subclasses.

@utils.only_required_for_messages('simplify-boolean-expression', 'consider-using-ternary', 'consider-swap-variables', 'consider-using-with')
def visit_assign(self, node: nodes.Assign): (source)

Undocumented

@utils.only_required_for_messages('consider-using-join')
def visit_augassign(self, node: nodes.AugAssign): (source)

Undocumented

@utils.only_required_for_messages('consider-merging-isinstance', 'consider-using-in', 'chained-comparison', 'simplifiable-condition', 'condition-evals-to-constant')
def visit_boolop(self, node: nodes.BoolOp): (source)

Undocumented

@utils.only_required_for_messages('stop-iteration-return', 'consider-using-dict-comprehension', 'consider-using-set-comprehension', 'consider-using-sys-exit', 'super-with-arguments', 'consider-using-generator', 'consider-using-with', 'use-list-literal', 'use-dict-literal', 'use-a-generator')
def visit_call(self, node: nodes.Call): (source)

Undocumented

@utils.only_required_for_messages('unnecessary-comprehension', 'unnecessary-dict-index-lookup', 'unnecessary-list-index-lookup')
def visit_comprehension(self, node: nodes.Comprehension): (source)

Undocumented

@utils.only_required_for_messages('redefined-argument-from-local')
def visit_excepthandler(self, node: nodes.ExceptHandler): (source)

Undocumented

@utils.only_required_for_messages('redefined-argument-from-local', 'too-many-nested-blocks', 'unnecessary-dict-index-lookup', 'unnecessary-list-index-lookup')
def visit_for(self, node: nodes.For): (source)

Undocumented

def visit_functiondef(self, node: nodes.FunctionDef): (source)

Undocumented

@utils.only_required_for_messages('too-many-nested-blocks', 'simplifiable-if-statement', 'no-else-return', 'no-else-raise', 'no-else-break', 'no-else-continue', 'consider-using-get', 'consider-using-min-builtin', 'consider-using-max-builtin')
def visit_if(self, node: nodes.If): (source)

Undocumented

@utils.only_required_for_messages('simplifiable-if-expression')
def visit_ifexp(self, node: nodes.IfExp): (source)

Undocumented

@utils.only_required_for_messages('stop-iteration-return')
def visit_raise(self, node: nodes.Raise): (source)

Undocumented

@utils.only_required_for_messages('simplify-boolean-expression', 'consider-using-ternary', 'consider-swap-variables')
def visit_return(self, node: nodes.Return|nodes.Assign): (source)

Undocumented

@utils.only_required_for_messages('too-many-nested-blocks', 'no-else-return')
def visit_tryexcept(self, node: nodes.TryExcept|nodes.TryFinally): (source)

Undocumented

@utils.only_required_for_messages('redefined-argument-from-local', 'consider-using-with')
def visit_with(self, node: nodes.With): (source)

Undocumented

Name of the provider.

options: tuple[tuple, ...] = (source)

Options provided by this provider.

@staticmethod
def _and_or_ternary_arguments(node: nodes.BoolOp) -> tuple[nodes.NodeNG, nodes.NodeNG, nodes.NodeNG]: (source)

Undocumented

@staticmethod
def _apply_boolean_simplification_rules(operator: str, values: list[nodes.NodeNG]) -> list[nodes.NodeNG]: (source)

Removes irrelevant values or returns short-circuiting values. This function applies the following two rules: 1) an OR expression with True in it will always be true, and the reverse for AND 2) False values in OR expressions are only relevant if all values are false, and the reverse for AND

@staticmethod
def _check_exception_inherit_from_stopiteration(exc: nodes.ClassDef|bases.Instance) -> bool: (source)

Return True if the exception node in argument inherit from StopIteration.

@staticmethod
def _dict_literal_suggestion(node: nodes.Call) -> str: (source)

Return a suggestion of reasonable length.

@staticmethod
def _duplicated_isinstance_types(node: nodes.BoolOp) -> dict[str, set[str]]: (source)

Get the duplicated types from the underlying isinstance calls. :param nodes.BoolOp node: Node which should contain a bunch of isinstance calls. :returns: Dictionary of the comparison objects from the isinstance calls, to duplicate values from consecutive calls. :rtype: dict

@staticmethod
def _has_exit_in_scope(scope: nodes.LocalsDictNodeNG) -> bool: (source)

Undocumented

@staticmethod
def _has_return_in_siblings(node: nodes.NodeNG) -> bool: (source)

Returns True if there is at least one return in the node's siblings.

@staticmethod
def _is_and_or_ternary(node: nodes.NodeNG|None) -> bool: (source)

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

@staticmethod
def _is_bool_const(node: nodes.Return|nodes.Assign) -> bool: (source)

Undocumented

@staticmethod
def _is_simple_assignment(node: nodes.NodeNG|None) -> bool: (source)

Undocumented

@staticmethod
def _name_to_concatenate(node: nodes.NodeNG) -> str|None: (source)

Try to extract the name used in a concatenation loop.

@staticmethod
def _type_and_name_are_equal(node_a: Any, node_b: Any) -> bool: (source)

Undocumented

def _append_context_managers_to_stack(self, node: nodes.Assign): (source)

Undocumented

def _check_chained_comparison(self, node: nodes.BoolOp): (source)

Check if there is any chained comparison in the expression. Add a refactoring message if a boolOp contains comparison like a < b and b < c, which can be chained as a < b < c. Care is taken to avoid simplifying a < b < c and b < d.

def _check_consider_get(self, node: nodes.If): (source)

Undocumented

def _check_consider_merging_isinstance(self, node: nodes.BoolOp): (source)

Check isinstance calls which can be merged together.

def _check_consider_using_comprehension_constructor(self, node: nodes.Call): (source)

Undocumented

def _check_consider_using_generator(self, node: nodes.Call): (source)

Undocumented

def _check_consider_using_in(self, node: nodes.BoolOp): (source)

Undocumented

def _check_consider_using_join(self, aug_assign: nodes.AugAssign): (source)

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 result += number # aug_assign

def _check_consider_using_min_max_builtin(self, node: nodes.If): (source)

Check if the given if node can be refactored as a min/max python builtin.

def _check_consider_using_with(self, node: nodes.Call): (source)

Undocumented

def _check_consistent_returns(self, node: nodes.FunctionDef): (source)

Check that all return statements inside a function are consistent. Return statements are consistent if: - all returns are explicit and if there is no implicit return; - all returns are empty and if there is, possibly, an implicit return. Args: node (nodes.FunctionDef): the function holding the return statements.

def _check_nested_blocks(self, node: NodesWithNestedBlocks): (source)

Update and check the number of nested blocks.

def _check_quit_exit_call(self, node: nodes.Call): (source)

Undocumented

def _check_raising_stopiteration_in_generator_next_call(self, node: nodes.Call): (source)

Check if a StopIteration exception is raised by the call to next function. If the next value has a default value, then do not add message. :param node: Check to see if this Call node is a next function :type node: :class:`nodes.Call`

def _check_redefined_argument_from_local(self, name_node: nodes.AssignName): (source)

Undocumented

def _check_return_at_the_end(self, node: nodes.FunctionDef): (source)

Check for presence of a *single* return statement at the end of a function. "return" or "return None" are useless because None is the default return type if they are missing. NOTE: produces a message only if there is a single return statement in the function body. Otherwise _check_consistent_returns() is called! Per its implementation and PEP8 we can have a "return None" at the end of the function body if there are other return statements before that!

def _check_simplifiable_condition(self, node: nodes.BoolOp): (source)

Check if a boolean condition can be simplified. Variables will not be simplified, even if the value can be inferred, and expressions like '3 + 4' will remain expanded.

def _check_simplifiable_if(self, node: nodes.If): (source)

Check if the given if node can be simplified. The if statement can be reduced to a boolean expression in some cases. For instance, if there are two branches and both of them return a boolean value that depends on the result of the statement's test, then this can be reduced to `bool(test)` without losing any functionality.

def _check_simplifiable_ifexp(self, node: nodes.IfExp): (source)

Undocumented

def _check_stop_iteration_inside_generator(self, node: nodes.Raise): (source)

Check if an exception of type StopIteration is raised inside a generator.

def _check_super_with_arguments(self, node: nodes.Call): (source)

Undocumented

def _check_superfluous_else(self, node: nodes.If|nodes.TryExcept, msg_id: str, returning_node_class: nodes.NodeNG): (source)

Undocumented

def _check_superfluous_else_break(self, node: nodes.If): (source)

Undocumented

def _check_superfluous_else_continue(self, node: nodes.If): (source)

Undocumented

def _check_superfluous_else_raise(self, node: nodes.If): (source)

Undocumented

def _check_superfluous_else_return(self, node: nodes.If): (source)

Undocumented

def _check_swap_variables(self, node: nodes.Return|nodes.Assign): (source)

Undocumented

def _check_unnecessary_comprehension(self, node: nodes.Comprehension): (source)

Undocumented

def _check_unnecessary_dict_index_lookup(self, node: nodes.For|nodes.Comprehension): (source)

Add message when accessing dict values by index lookup.

def _check_unnecessary_list_index_lookup(self, node: nodes.For|nodes.Comprehension): (source)

Undocumented

def _check_use_dict_literal(self, node: nodes.Call): (source)

Check if dict is created by using the literal {}.

def _check_use_list_literal(self, node: nodes.Call): (source)

Check if empty list is created by using the literal [].

def _emit_consider_using_with_if_needed(self, stack: dict[str, nodes.NodeNG]): (source)

Undocumented

def _emit_nested_blocks_message_if_needed(self, nested_blocks: list[NodesWithNestedBlocks]): (source)

Undocumented

def _enumerate_with_start(self, node: nodes.For|nodes.Comprehension) -> tuple[bool, Confidence]: (source)

Check presence of `start` kwarg or second argument to enumerate. For example: `enumerate([1,2,3], start=1)` `enumerate([1,2,3], 1)` If `start` is assigned to `0`, the default value, this is equivalent to not calling `enumerate` with start.

def _get_start_value(self, node: nodes.NodeNG) -> tuple[int|None, Confidence]: (source)

Undocumented

def _init(self): (source)

Undocumented

def _is_actual_elif(self, node: nodes.If|nodes.TryExcept) -> bool: (source)

Check if the given node is an actual elif. This is a problem we're having with the builtin ast module, which splits `elif` branches into a separate if statement. Unfortunately we need to know the exact type in certain cases.

def _is_dict_get_block(self, node: nodes.If) -> bool: (source)

Undocumented

def _is_function_def_never_returning(self, node: nodes.FunctionDef) -> bool: (source)

Return True if the function never returns, False otherwise. Args: node (nodes.FunctionDef): function definition node to be analyzed. Returns: bool: True if the function never returns, False otherwise.

def _is_if_node_return_ended(self, node: nodes.If) -> bool: (source)

Check if the If node ends with an explicit return statement. Args: node (nodes.If): If node to be checked. Returns: bool: True if the node ends with an explicit statement, False otherwise.

def _is_node_return_ended(self, node: nodes.NodeNG) -> bool: (source)

Check if the node ends with an explicit return statement. Args: node (nodes.NodeNG): node to be checked. Returns: bool: True if the node ends with an explicit statement, False otherwise.

def _is_raise_node_return_ended(self, node: nodes.Raise) -> bool: (source)

Check if the Raise node ends with an explicit return statement. Args: node (nodes.Raise): Raise node to be checked. Returns: bool: True if the node ends with an explicit statement, False otherwise.

def _simplify_boolean_operation(self, bool_op: nodes.BoolOp) -> nodes.BoolOp: (source)

Attempts to simplify a boolean operation. Recursively applies simplification on the operator terms, and keeps track of whether reductions have been made.

_can_simplify_bool_op: bool = (source)

Undocumented

_consider_using_with_stack = (source)

Undocumented

Undocumented

_nested_blocks = (source)

Undocumented

_never_returning_functions = (source)

Undocumented

_reported_swap_nodes: set[nodes.NodeNG] = (source)

Undocumented

_return_nodes: dict[str, list[nodes.Return]] = (source)

Undocumented

@cached_property
_dummy_rgx: Pattern[str] = (source)

Undocumented