fname
stringlengths
63
176
rel_fname
stringclasses
706 values
line
int64
-1
4.5k
name
stringlengths
1
81
kind
stringclasses
2 values
category
stringclasses
2 values
info
stringlengths
0
77.9k
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/bad_builtin.py
pylint/extensions/bad_builtin.py
30
BadBuiltinChecker
def
class
visit_call
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/bad_builtin.py
pylint/extensions/bad_builtin.py
58
check_messages
ref
function
@check_messages("bad-builtin")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/bad_builtin.py
pylint/extensions/bad_builtin.py
59
visit_call
def
function
def visit_call(self, node: nodes.Call) -> None: if isinstance(node.func, nodes.Name): name = node.func.name # ignore the name if it's not a builtin (i.e. not defined in the # locals nor globals scope) if not (name in node.frame(future=_True) or name in node.root()): if name in self.config.bad_functions: hint = BUILTIN_HINTS.get(name) args = f"{name!r}. {hint}" if hint else repr(name) self.add_message("bad-builtin", node=node, args=args)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/bad_builtin.py
pylint/extensions/bad_builtin.py
64
frame
ref
function
if not (name in node.frame(future=True) or name in node.root()):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/bad_builtin.py
pylint/extensions/bad_builtin.py
64
root
ref
function
if not (name in node.frame(future=True) or name in node.root()):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/bad_builtin.py
pylint/extensions/bad_builtin.py
68
add_message
ref
function
self.add_message("bad-builtin", node=node, args=args)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/bad_builtin.py
pylint/extensions/bad_builtin.py
71
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(BadBuiltinChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/bad_builtin.py
pylint/extensions/bad_builtin.py
72
register_checker
ref
function
linter.register_checker(BadBuiltinChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/bad_builtin.py
pylint/extensions/bad_builtin.py
72
BadBuiltinChecker
ref
function
linter.register_checker(BadBuiltinChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
22
BroadTryClauseChecker
def
class
_count_statements visit_tryexcept visit_tryfinally
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
56
_count_statements
def
function
def _count_statements(self, try_node): statement_count = len(try_node.body) for body_node in try_node.body: if isinstance(body_node, (nodes.For, nodes.If, nodes.While, nodes.With)): statement_count += self._count_statements(body_node) return statement_count def visit_tryexcept(self, node: Union[nodes.TryExcept, nodes.TryFinally]) -> None: try_clause_statements = self._count_statements(node) if try_clause_statements > self.config.max_try_statements: msg = f"try clause contains {try_clause_statements} statements, expected at most {self.config.max_try_statements}" self.add_message( "too-many-try-statements", node.lineno, node=node, args=msg ) def visit_tryfinally(self, node: nodes.TryFinally) -> None: self.visit_tryexcept(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
61
_count_statements
ref
function
statement_count += self._count_statements(body_node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
65
visit_tryexcept
def
function
def visit_tryexcept(self, node: Union[nodes.TryExcept, nodes.TryFinally]) -> None: try_clause_statements = self._count_statements(node) if try_clause_statements > self.config.max_try_statements: msg = f"try clause contains {try_clause_statements} statements, expected at most {self.config.max_try_statements}" self.add_message( "too-many-try-statements", node.lineno, node=node, args=msg ) def visit_tryfinally(self, node: nodes.TryFinally) -> None: self.visit_tryexcept(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
66
_count_statements
ref
function
try_clause_statements = self._count_statements(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
69
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
73
visit_tryfinally
def
function
def visit_tryfinally(self, node: nodes.TryFinally) -> None: self.visit_tryexcept(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
74
visit_tryexcept
ref
function
self.visit_tryexcept(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
77
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(BroadTryClauseChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
78
register_checker
ref
function
linter.register_checker(BroadTryClauseChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/broad_try_clause.py
pylint/extensions/broad_try_clause.py
78
BroadTryClauseChecker
ref
function
linter.register_checker(BroadTryClauseChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
26
ElseifUsedChecker
def
class
__init__ _init process_tokens leave_module visit_if
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
43
_init
ref
function
self._init()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
45
_init
def
function
def _init(self): self._elifs = {} def process_tokens(self, tokens): """Process tokens and look for 'if' or 'elif'.""" self._elifs = { begin: token for _, token, begin, _, _ in tokens if token in {"elif", "if"} } def leave_module(self, _: nodes.Module) -> None: self._init() @check_messages("else-if-used") def visit_if(self, node: nodes.If) -> None: """Current if node must directly follow an 'else'.""" if ( isinstance(node.parent, nodes.If) and node.parent.orelse == [node] and (node.lineno, node.col_offset) in self._elifs and self._elifs[(node.lineno, node.col_offset)] == "if" ): self.add_message("else-if-used", node=node, confidence=HIGH)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
48
process_tokens
def
function
def process_tokens(self, tokens): """Process tokens and look for 'if' or 'elif'.""" self._elifs = { begin: token for _, token, begin, _, _ in tokens if token in {"elif", "if"} } def leave_module(self, _: nodes.Module) -> None: self._init() @check_messages("else-if-used") def visit_if(self, node: nodes.If) -> None: """Current if node must directly follow an 'else'.""" if ( isinstance(node.parent, nodes.If) and node.parent.orelse == [node] and (node.lineno, node.col_offset) in self._elifs and self._elifs[(node.lineno, node.col_offset)] == "if" ): self.add_message("else-if-used", node=node, confidence=HIGH)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
54
leave_module
def
function
def leave_module(self, _: nodes.Module) -> None: self._init() @check_messages("else-if-used") def visit_if(self, node: nodes.If) -> None: """Current if node must directly follow an 'else'.""" if ( isinstance(node.parent, nodes.If) and node.parent.orelse == [node] and (node.lineno, node.col_offset) in self._elifs and self._elifs[(node.lineno, node.col_offset)] == "if" ): self.add_message("else-if-used", node=node, confidence=HIGH)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
55
_init
ref
function
self._init()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
57
check_messages
ref
function
@check_messages("else-if-used")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
58
visit_if
def
function
def visit_if(self, node: nodes.If) -> None: """Current if node must directly follow an 'else'.""" if ( isinstance(node.parent, nodes.If) and node.parent.orelse == [node] and (node.lineno, node.col_offset) in self._elifs and self._elifs[(node.lineno, node.col_offset)] == "if" ): self.add_message("else-if-used", node=node, confidence=HIGH)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
66
add_message
ref
function
self.add_message("else-if-used", node=node, confidence=HIGH)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
69
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(ElseifUsedChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
70
register_checker
ref
function
linter.register_checker(ElseifUsedChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/check_elif.py
pylint/extensions/check_elif.py
70
ElseifUsedChecker
ref
function
linter.register_checker(ElseifUsedChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
19
CodeStyleChecker
def
class
__init__ open visit_dict visit_for visit_comprehension visit_if _check_dict_consider_namedtuple_dataclass _check_consider_using_assignment_expr _check_prev_sibling_to_if_stmt _check_ignore_assignment_expr_suggestion
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
81
get_global_option
ref
function
py_version = get_global_option(self, "py-version")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
85
get_global_option
ref
function
or get_global_option(self, "max-line-length")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
88
check_messages
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
89
visit_dict
def
function
def visit_dict(self, node: nodes.Dict) -> None: self._check_dict_consider_namedtuple_dataclass(node) @check_messages("consider-using-tuple") def visit_for(self, node: nodes.For) -> None: if isinstance(node.iter, nodes.List): self.add_message("consider-using-tuple", node=node.iter) @check_messages("consider-using-tuple") def visit_comprehension(self, node: nodes.Comprehension) -> None: if isinstance(node.iter, nodes.List): self.add_message("consider-using-tuple", node=node.iter) @check_messages("consider-using-assignment-expr") def visit_if(self, node: nodes.If) -> None: if self._py38_plus: self._check_consider_using_assignment_expr(node) def _check_dict_consider_namedtuple_dataclass(self, node: nodes.Dict) -> None: """Check if dictionary values can be replaced by Namedtuple or Dataclass.""" if not ( isinstance(node.parent, (nodes.Assign, nodes.AnnAssign)) and isinstance(node.parent.parent, nodes.Module) or isinstance(node.parent, nodes.AnnAssign) and isinstance(node.parent.target, nodes.AssignName) and utils.is_assign_name_annotated_with(node.parent.target, "Final") ): # If dict is not part of an 'Assign' or 'AnnAssign' node in # a module context OR 'AnnAssign' with 'Final' annotation, skip check. return # All dict_values are itself dict nodes if len(node.items) > 1 and all( isinstance(dict_value, nodes.Dict) for _, dict_value in node.items ): KeyTupleT = Tuple[Type[nodes.NodeNG], str] # Makes sure all keys are 'Const' string nodes keys_checked: Set[KeyTupleT] = set() for _, dict_value in node.items: dict_value = cast(nodes.Dict, dict_value) for key, _ in dict_value.items: key_tuple = (type(key), key.as_string()) if key_tuple in keys_checked: continue inferred = safe_infer(key) if not ( isinstance(inferred, nodes.Const) and inferred.pytype() == "builtins.str" ): return keys_checked.add(key_tuple) # Makes sure all subdicts have at least 1 common key key_tuples: List[Tuple[KeyTupleT, ...]] = [] for _, dict_value in node.items: dict_value = cast(nodes.Dict, dict_value) key_tuples.append( tuple((type(key), key.as_string()) for key, _ in dict_value.items) ) keys_intersection: Set[KeyTupleT] = set(key_tuples[0]) for sub_key_tuples in key_tuples[1:]: keys_intersection.intersection_update(sub_key_tuples) if not keys_intersection: return self.add_message("consider-using-namedtuple-or-dataclass", node=node) return # All dict_values are itself either list or tuple nodes if len(node.items) > 1 and all( isinstance(dict_value, (nodes.List, nodes.Tuple)) for _, dict_value in node.items ): # Make sure all sublists have the same length > 0 list_length = len(node.items[0][1].elts) if list_length == 0: return for _, dict_value in node.items[1:]: dict_value = cast(Union[nodes.List, nodes.Tuple], dict_value) if len(dict_value.elts) != list_length: return # Make sure at least one list entry isn't a dict for _, dict_value in node.items: dict_value = cast(Union[nodes.List, nodes.Tuple], dict_value) if all(isinstance(entry, nodes.Dict) for entry in dict_value.elts): return self.add_message("consider-using-namedtuple-or-dataclass", node=node) return def _check_consider_using_assignment_expr(self, node: nodes.If) -> None: """Check if an assignment expression (walrus operator) can be used. For example if an assignment is directly followed by an if statement: >>> x = 2 >>> if x: >>> ... Can be replaced by: >>> if (x := 2): >>> ... Note: Assignment expressions were added in Python 3.8 """ # Check if `node.test` contains a `Name` node node_name: Optional[nodes.Name] = None if isinstance(node.test, nodes.Name): node_name = node.test elif ( isinstance(node.test, nodes.UnaryOp) and node.test.op == "not" and isinstance(node.test.operand, nodes.Name) ): node_name = node.test.operand elif ( isinstance(node.test, nodes.Compare) and isinstance(node.test.left, nodes.Name) and len(node.test.ops) == 1 ): node_name = node.test.left else: return # Make sure the previous node is an assignment to the same name # used in `node.test`. Furthermore, ignore if assignment spans multiple lines. prev_sibling = node.previous_sibling() if CodeStyleChecker._check_prev_sibling_to_if_stmt( prev_sibling, node_name.name ): # Check if match statement would be a better fit. # I.e. multiple ifs that test the same name. if CodeStyleChecker._check_ignore_assignment_expr_suggestion( node, node_name.name ): return # Build suggestion string. Check length of suggestion # does not exceed max-line-length-suggestions test_str = node.test.as_string().replace( node_name.name, f"({node_name.name} := {prev_sibling.value.as_string()})", 1, ) suggestion = f"if {test_str}:" if ( node.col_offset is not None and len(suggestion) + node.col_offset > self._max_length or len(suggestion) > self._max_length ): return self.add_message( "consider-using-assignment-expr", node=node_name, args=(suggestion,), ) @staticmethod def _check_prev_sibling_to_if_stmt( prev_sibling: Optional[nodes.NodeNG], name: Optional[str] ) -> TypeGuard[Union[nodes.Assign, nodes.AnnAssign]]: """Check if previous sibling is an assignment with the same name. Ignore statements which span multiple lines. """ if prev_sibling is None or prev_sibling.tolineno - prev_sibling.fromlineno != 0: return _False if ( isinstance(prev_sibling, nodes.Assign) and len(prev_sibling.targets) == 1 and isinstance(prev_sibling.targets[0], nodes.AssignName) and prev_sibling.targets[0].name == name ): return _True if ( isinstance(prev_sibling, nodes.AnnAssign) and isinstance(prev_sibling.target, nodes.AssignName) and prev_sibling.target.name == name ): return _True return _False @staticmethod def _check_ignore_assignment_expr_suggestion( node: nodes.If, name: Optional[str] ) -> bool: """Return _True if suggestion for assignment expr should be ignored. E.g., in cases where a match statement would be a better fit (multiple conditions). """ if isinstance(node.test, nodes.Compare): next_if_node: Optional[nodes.If] = None next_sibling = node.next_sibling() if len(node.orelse) == 1 and isinstance(node.orelse[0], nodes.If): # elif block next_if_node = node.orelse[0] elif isinstance(next_sibling, nodes.If): # separate if block next_if_node = next_sibling if ( # pylint: disable=too-many-boolean-expressions next_if_node is not None and ( isinstance(next_if_node.test, nodes.Compare) and isinstance(next_if_node.test.left, nodes.Name) and next_if_node.test.left.name == name or isinstance(next_if_node.test, nodes.Name) and next_if_node.test.name == name ) ): return _True return _False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
90
_check_dict_consider_namedtuple_dataclass
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
92
check_messages
ref
function
@check_messages("consider-using-tuple")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
93
visit_for
def
function
def visit_for(self, node: nodes.For) -> None: if isinstance(node.iter, nodes.List): self.add_message("consider-using-tuple", node=node.iter) @check_messages("consider-using-tuple") def visit_comprehension(self, node: nodes.Comprehension) -> None: if isinstance(node.iter, nodes.List): self.add_message("consider-using-tuple", node=node.iter) @check_messages("consider-using-assignment-expr") def visit_if(self, node: nodes.If) -> None: if self._py38_plus: self._check_consider_using_assignment_expr(node) def _check_dict_consider_namedtuple_dataclass(self, node: nodes.Dict) -> None: """Check if dictionary values can be replaced by Namedtuple or Dataclass.""" if not ( isinstance(node.parent, (nodes.Assign, nodes.AnnAssign)) and isinstance(node.parent.parent, nodes.Module) or isinstance(node.parent, nodes.AnnAssign) and isinstance(node.parent.target, nodes.AssignName) and utils.is_assign_name_annotated_with(node.parent.target, "Final") ): # If dict is not part of an 'Assign' or 'AnnAssign' node in # a module context OR 'AnnAssign' with 'Final' annotation, skip check. return # All dict_values are itself dict nodes if len(node.items) > 1 and all( isinstance(dict_value, nodes.Dict) for _, dict_value in node.items ): KeyTupleT = Tuple[Type[nodes.NodeNG], str] # Makes sure all keys are 'Const' string nodes keys_checked: Set[KeyTupleT] = set() for _, dict_value in node.items: dict_value = cast(nodes.Dict, dict_value) for key, _ in dict_value.items: key_tuple = (type(key), key.as_string()) if key_tuple in keys_checked: continue inferred = safe_infer(key) if not ( isinstance(inferred, nodes.Const) and inferred.pytype() == "builtins.str" ): return keys_checked.add(key_tuple) # Makes sure all subdicts have at least 1 common key key_tuples: List[Tuple[KeyTupleT, ...]] = [] for _, dict_value in node.items: dict_value = cast(nodes.Dict, dict_value) key_tuples.append( tuple((type(key), key.as_string()) for key, _ in dict_value.items) ) keys_intersection: Set[KeyTupleT] = set(key_tuples[0]) for sub_key_tuples in key_tuples[1:]: keys_intersection.intersection_update(sub_key_tuples) if not keys_intersection: return self.add_message("consider-using-namedtuple-or-dataclass", node=node) return # All dict_values are itself either list or tuple nodes if len(node.items) > 1 and all( isinstance(dict_value, (nodes.List, nodes.Tuple)) for _, dict_value in node.items ): # Make sure all sublists have the same length > 0 list_length = len(node.items[0][1].elts) if list_length == 0: return for _, dict_value in node.items[1:]: dict_value = cast(Union[nodes.List, nodes.Tuple], dict_value) if len(dict_value.elts) != list_length: return # Make sure at least one list entry isn't a dict for _, dict_value in node.items: dict_value = cast(Union[nodes.List, nodes.Tuple], dict_value) if all(isinstance(entry, nodes.Dict) for entry in dict_value.elts): return self.add_message("consider-using-namedtuple-or-dataclass", node=node) return def _check_consider_using_assignment_expr(self, node: nodes.If) -> None: """Check if an assignment expression (walrus operator) can be used. For example if an assignment is directly followed by an if statement: >>> x = 2 >>> if x: >>> ... Can be replaced by: >>> if (x := 2): >>> ... Note: Assignment expressions were added in Python 3.8 """ # Check if `node.test` contains a `Name` node node_name: Optional[nodes.Name] = None if isinstance(node.test, nodes.Name): node_name = node.test elif ( isinstance(node.test, nodes.UnaryOp) and node.test.op == "not" and isinstance(node.test.operand, nodes.Name) ): node_name = node.test.operand elif ( isinstance(node.test, nodes.Compare) and isinstance(node.test.left, nodes.Name) and len(node.test.ops) == 1 ): node_name = node.test.left else: return # Make sure the previous node is an assignment to the same name # used in `node.test`. Furthermore, ignore if assignment spans multiple lines. prev_sibling = node.previous_sibling() if CodeStyleChecker._check_prev_sibling_to_if_stmt( prev_sibling, node_name.name ): # Check if match statement would be a better fit. # I.e. multiple ifs that test the same name. if CodeStyleChecker._check_ignore_assignment_expr_suggestion( node, node_name.name ): return # Build suggestion string. Check length of suggestion # does not exceed max-line-length-suggestions test_str = node.test.as_string().replace( node_name.name, f"({node_name.name} := {prev_sibling.value.as_string()})", 1, ) suggestion = f"if {test_str}:" if ( node.col_offset is not None and len(suggestion) + node.col_offset > self._max_length or len(suggestion) > self._max_length ): return self.add_message( "consider-using-assignment-expr", node=node_name, args=(suggestion,), ) @staticmethod def _check_prev_sibling_to_if_stmt( prev_sibling: Optional[nodes.NodeNG], name: Optional[str] ) -> TypeGuard[Union[nodes.Assign, nodes.AnnAssign]]: """Check if previous sibling is an assignment with the same name. Ignore statements which span multiple lines. """ if prev_sibling is None or prev_sibling.tolineno - prev_sibling.fromlineno != 0: return _False if ( isinstance(prev_sibling, nodes.Assign) and len(prev_sibling.targets) == 1 and isinstance(prev_sibling.targets[0], nodes.AssignName) and prev_sibling.targets[0].name == name ): return _True if ( isinstance(prev_sibling, nodes.AnnAssign) and isinstance(prev_sibling.target, nodes.AssignName) and prev_sibling.target.name == name ): return _True return _False @staticmethod def _check_ignore_assignment_expr_suggestion( node: nodes.If, name: Optional[str] ) -> bool: """Return _True if suggestion for assignment expr should be ignored. E.g., in cases where a match statement would be a better fit (multiple conditions). """ if isinstance(node.test, nodes.Compare): next_if_node: Optional[nodes.If] = None next_sibling = node.next_sibling() if len(node.orelse) == 1 and isinstance(node.orelse[0], nodes.If): # elif block next_if_node = node.orelse[0] elif isinstance(next_sibling, nodes.If): # separate if block next_if_node = next_sibling if ( # pylint: disable=too-many-boolean-expressions next_if_node is not None and ( isinstance(next_if_node.test, nodes.Compare) and isinstance(next_if_node.test.left, nodes.Name) and next_if_node.test.left.name == name or isinstance(next_if_node.test, nodes.Name) and next_if_node.test.name == name ) ): return _True return _False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
95
add_message
ref
function
self.add_message("consider-using-tuple", node=node.iter)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
97
check_messages
ref
function
@check_messages("consider-using-tuple")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
98
visit_comprehension
def
function
def visit_comprehension(self, node: nodes.Comprehension) -> None: if isinstance(node.iter, nodes.List): self.add_message("consider-using-tuple", node=node.iter) @check_messages("consider-using-assignment-expr") def visit_if(self, node: nodes.If) -> None: if self._py38_plus: self._check_consider_using_assignment_expr(node) def _check_dict_consider_namedtuple_dataclass(self, node: nodes.Dict) -> None: """Check if dictionary values can be replaced by Namedtuple or Dataclass.""" if not ( isinstance(node.parent, (nodes.Assign, nodes.AnnAssign)) and isinstance(node.parent.parent, nodes.Module) or isinstance(node.parent, nodes.AnnAssign) and isinstance(node.parent.target, nodes.AssignName) and utils.is_assign_name_annotated_with(node.parent.target, "Final") ): # If dict is not part of an 'Assign' or 'AnnAssign' node in # a module context OR 'AnnAssign' with 'Final' annotation, skip check. return # All dict_values are itself dict nodes if len(node.items) > 1 and all( isinstance(dict_value, nodes.Dict) for _, dict_value in node.items ): KeyTupleT = Tuple[Type[nodes.NodeNG], str] # Makes sure all keys are 'Const' string nodes keys_checked: Set[KeyTupleT] = set() for _, dict_value in node.items: dict_value = cast(nodes.Dict, dict_value) for key, _ in dict_value.items: key_tuple = (type(key), key.as_string()) if key_tuple in keys_checked: continue inferred = safe_infer(key) if not ( isinstance(inferred, nodes.Const) and inferred.pytype() == "builtins.str" ): return keys_checked.add(key_tuple) # Makes sure all subdicts have at least 1 common key key_tuples: List[Tuple[KeyTupleT, ...]] = [] for _, dict_value in node.items: dict_value = cast(nodes.Dict, dict_value) key_tuples.append( tuple((type(key), key.as_string()) for key, _ in dict_value.items) ) keys_intersection: Set[KeyTupleT] = set(key_tuples[0]) for sub_key_tuples in key_tuples[1:]: keys_intersection.intersection_update(sub_key_tuples) if not keys_intersection: return self.add_message("consider-using-namedtuple-or-dataclass", node=node) return # All dict_values are itself either list or tuple nodes if len(node.items) > 1 and all( isinstance(dict_value, (nodes.List, nodes.Tuple)) for _, dict_value in node.items ): # Make sure all sublists have the same length > 0 list_length = len(node.items[0][1].elts) if list_length == 0: return for _, dict_value in node.items[1:]: dict_value = cast(Union[nodes.List, nodes.Tuple], dict_value) if len(dict_value.elts) != list_length: return # Make sure at least one list entry isn't a dict for _, dict_value in node.items: dict_value = cast(Union[nodes.List, nodes.Tuple], dict_value) if all(isinstance(entry, nodes.Dict) for entry in dict_value.elts): return self.add_message("consider-using-namedtuple-or-dataclass", node=node) return def _check_consider_using_assignment_expr(self, node: nodes.If) -> None: """Check if an assignment expression (walrus operator) can be used. For example if an assignment is directly followed by an if statement: >>> x = 2 >>> if x: >>> ... Can be replaced by: >>> if (x := 2): >>> ... Note: Assignment expressions were added in Python 3.8 """ # Check if `node.test` contains a `Name` node node_name: Optional[nodes.Name] = None if isinstance(node.test, nodes.Name): node_name = node.test elif ( isinstance(node.test, nodes.UnaryOp) and node.test.op == "not" and isinstance(node.test.operand, nodes.Name) ): node_name = node.test.operand elif ( isinstance(node.test, nodes.Compare) and isinstance(node.test.left, nodes.Name) and len(node.test.ops) == 1 ): node_name = node.test.left else: return # Make sure the previous node is an assignment to the same name # used in `node.test`. Furthermore, ignore if assignment spans multiple lines. prev_sibling = node.previous_sibling() if CodeStyleChecker._check_prev_sibling_to_if_stmt( prev_sibling, node_name.name ): # Check if match statement would be a better fit. # I.e. multiple ifs that test the same name. if CodeStyleChecker._check_ignore_assignment_expr_suggestion( node, node_name.name ): return # Build suggestion string. Check length of suggestion # does not exceed max-line-length-suggestions test_str = node.test.as_string().replace( node_name.name, f"({node_name.name} := {prev_sibling.value.as_string()})", 1, ) suggestion = f"if {test_str}:" if ( node.col_offset is not None and len(suggestion) + node.col_offset > self._max_length or len(suggestion) > self._max_length ): return self.add_message( "consider-using-assignment-expr", node=node_name, args=(suggestion,), ) @staticmethod def _check_prev_sibling_to_if_stmt( prev_sibling: Optional[nodes.NodeNG], name: Optional[str] ) -> TypeGuard[Union[nodes.Assign, nodes.AnnAssign]]: """Check if previous sibling is an assignment with the same name. Ignore statements which span multiple lines. """ if prev_sibling is None or prev_sibling.tolineno - prev_sibling.fromlineno != 0: return _False if ( isinstance(prev_sibling, nodes.Assign) and len(prev_sibling.targets) == 1 and isinstance(prev_sibling.targets[0], nodes.AssignName) and prev_sibling.targets[0].name == name ): return _True if ( isinstance(prev_sibling, nodes.AnnAssign) and isinstance(prev_sibling.target, nodes.AssignName) and prev_sibling.target.name == name ): return _True return _False @staticmethod def _check_ignore_assignment_expr_suggestion( node: nodes.If, name: Optional[str] ) -> bool: """Return _True if suggestion for assignment expr should be ignored. E.g., in cases where a match statement would be a better fit (multiple conditions). """ if isinstance(node.test, nodes.Compare): next_if_node: Optional[nodes.If] = None next_sibling = node.next_sibling() if len(node.orelse) == 1 and isinstance(node.orelse[0], nodes.If): # elif block next_if_node = node.orelse[0] elif isinstance(next_sibling, nodes.If): # separate if block next_if_node = next_sibling if ( # pylint: disable=too-many-boolean-expressions next_if_node is not None and ( isinstance(next_if_node.test, nodes.Compare) and isinstance(next_if_node.test.left, nodes.Name) and next_if_node.test.left.name == name or isinstance(next_if_node.test, nodes.Name) and next_if_node.test.name == name ) ): return _True return _False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
100
add_message
ref
function
self.add_message("consider-using-tuple", node=node.iter)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
102
check_messages
ref
function
@check_messages("consider-using-assignment-expr")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
103
visit_if
def
function
def visit_if(self, node: nodes.If) -> None: if self._py38_plus: self._check_consider_using_assignment_expr(node) def _check_dict_consider_namedtuple_dataclass(self, node: nodes.Dict) -> None: """Check if dictionary values can be replaced by Namedtuple or Dataclass.""" if not ( isinstance(node.parent, (nodes.Assign, nodes.AnnAssign)) and isinstance(node.parent.parent, nodes.Module) or isinstance(node.parent, nodes.AnnAssign) and isinstance(node.parent.target, nodes.AssignName) and utils.is_assign_name_annotated_with(node.parent.target, "Final") ): # If dict is not part of an 'Assign' or 'AnnAssign' node in # a module context OR 'AnnAssign' with 'Final' annotation, skip check. return # All dict_values are itself dict nodes if len(node.items) > 1 and all( isinstance(dict_value, nodes.Dict) for _, dict_value in node.items ): KeyTupleT = Tuple[Type[nodes.NodeNG], str] # Makes sure all keys are 'Const' string nodes keys_checked: Set[KeyTupleT] = set() for _, dict_value in node.items: dict_value = cast(nodes.Dict, dict_value) for key, _ in dict_value.items: key_tuple = (type(key), key.as_string()) if key_tuple in keys_checked: continue inferred = safe_infer(key) if not ( isinstance(inferred, nodes.Const) and inferred.pytype() == "builtins.str" ): return keys_checked.add(key_tuple) # Makes sure all subdicts have at least 1 common key key_tuples: List[Tuple[KeyTupleT, ...]] = [] for _, dict_value in node.items: dict_value = cast(nodes.Dict, dict_value) key_tuples.append( tuple((type(key), key.as_string()) for key, _ in dict_value.items) ) keys_intersection: Set[KeyTupleT] = set(key_tuples[0]) for sub_key_tuples in key_tuples[1:]: keys_intersection.intersection_update(sub_key_tuples) if not keys_intersection: return self.add_message("consider-using-namedtuple-or-dataclass", node=node) return # All dict_values are itself either list or tuple nodes if len(node.items) > 1 and all( isinstance(dict_value, (nodes.List, nodes.Tuple)) for _, dict_value in node.items ): # Make sure all sublists have the same length > 0 list_length = len(node.items[0][1].elts) if list_length == 0: return for _, dict_value in node.items[1:]: dict_value = cast(Union[nodes.List, nodes.Tuple], dict_value) if len(dict_value.elts) != list_length: return # Make sure at least one list entry isn't a dict for _, dict_value in node.items: dict_value = cast(Union[nodes.List, nodes.Tuple], dict_value) if all(isinstance(entry, nodes.Dict) for entry in dict_value.elts): return self.add_message("consider-using-namedtuple-or-dataclass", node=node) return def _check_consider_using_assignment_expr(self, node: nodes.If) -> None: """Check if an assignment expression (walrus operator) can be used. For example if an assignment is directly followed by an if statement: >>> x = 2 >>> if x: >>> ... Can be replaced by: >>> if (x := 2): >>> ... Note: Assignment expressions were added in Python 3.8 """ # Check if `node.test` contains a `Name` node node_name: Optional[nodes.Name] = None if isinstance(node.test, nodes.Name): node_name = node.test elif ( isinstance(node.test, nodes.UnaryOp) and node.test.op == "not" and isinstance(node.test.operand, nodes.Name) ): node_name = node.test.operand elif ( isinstance(node.test, nodes.Compare) and isinstance(node.test.left, nodes.Name) and len(node.test.ops) == 1 ): node_name = node.test.left else: return # Make sure the previous node is an assignment to the same name # used in `node.test`. Furthermore, ignore if assignment spans multiple lines. prev_sibling = node.previous_sibling() if CodeStyleChecker._check_prev_sibling_to_if_stmt( prev_sibling, node_name.name ): # Check if match statement would be a better fit. # I.e. multiple ifs that test the same name. if CodeStyleChecker._check_ignore_assignment_expr_suggestion( node, node_name.name ): return # Build suggestion string. Check length of suggestion # does not exceed max-line-length-suggestions test_str = node.test.as_string().replace( node_name.name, f"({node_name.name} := {prev_sibling.value.as_string()})", 1, ) suggestion = f"if {test_str}:" if ( node.col_offset is not None and len(suggestion) + node.col_offset > self._max_length or len(suggestion) > self._max_length ): return self.add_message( "consider-using-assignment-expr", node=node_name, args=(suggestion,), ) @staticmethod def _check_prev_sibling_to_if_stmt( prev_sibling: Optional[nodes.NodeNG], name: Optional[str] ) -> TypeGuard[Union[nodes.Assign, nodes.AnnAssign]]: """Check if previous sibling is an assignment with the same name. Ignore statements which span multiple lines. """ if prev_sibling is None or prev_sibling.tolineno - prev_sibling.fromlineno != 0: return _False if ( isinstance(prev_sibling, nodes.Assign) and len(prev_sibling.targets) == 1 and isinstance(prev_sibling.targets[0], nodes.AssignName) and prev_sibling.targets[0].name == name ): return _True if ( isinstance(prev_sibling, nodes.AnnAssign) and isinstance(prev_sibling.target, nodes.AssignName) and prev_sibling.target.name == name ): return _True return _False @staticmethod def _check_ignore_assignment_expr_suggestion( node: nodes.If, name: Optional[str] ) -> bool: """Return _True if suggestion for assignment expr should be ignored. E.g., in cases where a match statement would be a better fit (multiple conditions). """ if isinstance(node.test, nodes.Compare): next_if_node: Optional[nodes.If] = None next_sibling = node.next_sibling() if len(node.orelse) == 1 and isinstance(node.orelse[0], nodes.If): # elif block next_if_node = node.orelse[0] elif isinstance(next_sibling, nodes.If): # separate if block next_if_node = next_sibling if ( # pylint: disable=too-many-boolean-expressions next_if_node is not None and ( isinstance(next_if_node.test, nodes.Compare) and isinstance(next_if_node.test.left, nodes.Name) and next_if_node.test.left.name == name or isinstance(next_if_node.test, nodes.Name) and next_if_node.test.name == name ) ): return _True return _False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
105
_check_consider_using_assignment_expr
ref
function
self._check_consider_using_assignment_expr(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
107
_check_dict_consider_namedtuple_dataclass
def
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
114
is_assign_name_annotated_with
ref
function
and utils.is_assign_name_annotated_with(node.parent.target, "Final")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
131
as_string
ref
function
key_tuple = (type(key), key.as_string())
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
134
safe_infer
ref
function
inferred = safe_infer(key)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
137
pytype
ref
function
and inferred.pytype() == "builtins.str"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
147
as_string
ref
function
tuple((type(key), key.as_string()) for key, _ in dict_value.items)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
155
add_message
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
178
add_message
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
181
_check_consider_using_assignment_expr
def
function
def _check_consider_using_assignment_expr(self, node: nodes.If) -> None: """Check if an assignment expression (walrus operator) can be used. For example if an assignment is directly followed by an if statement: >>> x = 2 >>> if x: >>> ... Can be replaced by: >>> if (x := 2): >>> ... Note: Assignment expressions were added in Python 3.8 """ # Check if `node.test` contains a `Name` node node_name: Optional[nodes.Name] = None if isinstance(node.test, nodes.Name): node_name = node.test elif ( isinstance(node.test, nodes.UnaryOp) and node.test.op == "not" and isinstance(node.test.operand, nodes.Name) ): node_name = node.test.operand elif ( isinstance(node.test, nodes.Compare) and isinstance(node.test.left, nodes.Name) and len(node.test.ops) == 1 ): node_name = node.test.left else: return # Make sure the previous node is an assignment to the same name # used in `node.test`. Furthermore, ignore if assignment spans multiple lines. prev_sibling = node.previous_sibling() if CodeStyleChecker._check_prev_sibling_to_if_stmt( prev_sibling, node_name.name ): # Check if match statement would be a better fit. # I.e. multiple ifs that test the same name. if CodeStyleChecker._check_ignore_assignment_expr_suggestion( node, node_name.name ): return # Build suggestion string. Check length of suggestion # does not exceed max-line-length-suggestions test_str = node.test.as_string().replace( node_name.name, f"({node_name.name} := {prev_sibling.value.as_string()})", 1, ) suggestion = f"if {test_str}:" if ( node.col_offset is not None and len(suggestion) + node.col_offset > self._max_length or len(suggestion) > self._max_length ): return self.add_message( "consider-using-assignment-expr", node=node_name, args=(suggestion,), ) @staticmethod def _check_prev_sibling_to_if_stmt( prev_sibling: Optional[nodes.NodeNG], name: Optional[str] ) -> TypeGuard[Union[nodes.Assign, nodes.AnnAssign]]: """Check if previous sibling is an assignment with the same name. Ignore statements which span multiple lines. """ if prev_sibling is None or prev_sibling.tolineno - prev_sibling.fromlineno != 0: return _False if ( isinstance(prev_sibling, nodes.Assign) and len(prev_sibling.targets) == 1 and isinstance(prev_sibling.targets[0], nodes.AssignName) and prev_sibling.targets[0].name == name ): return _True if ( isinstance(prev_sibling, nodes.AnnAssign) and isinstance(prev_sibling.target, nodes.AssignName) and prev_sibling.target.name == name ): return _True return _False @staticmethod def _check_ignore_assignment_expr_suggestion( node: nodes.If, name: Optional[str] ) -> bool: """Return _True if suggestion for assignment expr should be ignored. E.g., in cases where a match statement would be a better fit (multiple conditions). """ if isinstance(node.test, nodes.Compare): next_if_node: Optional[nodes.If] = None next_sibling = node.next_sibling() if len(node.orelse) == 1 and isinstance(node.orelse[0], nodes.If): # elif block next_if_node = node.orelse[0] elif isinstance(next_sibling, nodes.If): # separate if block next_if_node = next_sibling if ( # pylint: disable=too-many-boolean-expressions next_if_node is not None and ( isinstance(next_if_node.test, nodes.Compare) and isinstance(next_if_node.test.left, nodes.Name) and next_if_node.test.left.name == name or isinstance(next_if_node.test, nodes.Name) and next_if_node.test.name == name ) ): return _True return _False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
216
previous_sibling
ref
function
prev_sibling = node.previous_sibling()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
217
_check_prev_sibling_to_if_stmt
ref
function
if CodeStyleChecker._check_prev_sibling_to_if_stmt(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
223
_check_ignore_assignment_expr_suggestion
ref
function
if CodeStyleChecker._check_ignore_assignment_expr_suggestion(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
230
as_string
ref
function
test_str = node.test.as_string().replace(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
232
as_string
ref
function
f"({node_name.name} := {prev_sibling.value.as_string()})",
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
243
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
250
_check_prev_sibling_to_if_stmt
def
function
def _check_prev_sibling_to_if_stmt( prev_sibling: Optional[nodes.NodeNG], name: Optional[str] ) -> TypeGuard[Union[nodes.Assign, nodes.AnnAssign]]: """Check if previous sibling is an assignment with the same name. Ignore statements which span multiple lines. """ if prev_sibling is None or prev_sibling.tolineno - prev_sibling.fromlineno != 0: return _False if ( isinstance(prev_sibling, nodes.Assign) and len(prev_sibling.targets) == 1 and isinstance(prev_sibling.targets[0], nodes.AssignName) and prev_sibling.targets[0].name == name ): return _True if ( isinstance(prev_sibling, nodes.AnnAssign) and isinstance(prev_sibling.target, nodes.AssignName) and prev_sibling.target.name == name ): return _True return _False @staticmethod def _check_ignore_assignment_expr_suggestion( node: nodes.If, name: Optional[str] ) -> bool: """Return _True if suggestion for assignment expr should be ignored. E.g., in cases where a match statement would be a better fit (multiple conditions). """ if isinstance(node.test, nodes.Compare): next_if_node: Optional[nodes.If] = None next_sibling = node.next_sibling() if len(node.orelse) == 1 and isinstance(node.orelse[0], nodes.If): # elif block next_if_node = node.orelse[0] elif isinstance(next_sibling, nodes.If): # separate if block next_if_node = next_sibling if ( # pylint: disable=too-many-boolean-expressions next_if_node is not None and ( isinstance(next_if_node.test, nodes.Compare) and isinstance(next_if_node.test.left, nodes.Name) and next_if_node.test.left.name == name or isinstance(next_if_node.test, nodes.Name) and next_if_node.test.name == name ) ): return _True return _False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
275
_check_ignore_assignment_expr_suggestion
def
function
def _check_ignore_assignment_expr_suggestion( node: nodes.If, name: Optional[str] ) -> bool: """Return _True if suggestion for assignment expr should be ignored. E.g., in cases where a match statement would be a better fit (multiple conditions). """ if isinstance(node.test, nodes.Compare): next_if_node: Optional[nodes.If] = None next_sibling = node.next_sibling() if len(node.orelse) == 1 and isinstance(node.orelse[0], nodes.If): # elif block next_if_node = node.orelse[0] elif isinstance(next_sibling, nodes.If): # separate if block next_if_node = next_sibling if ( # pylint: disable=too-many-boolean-expressions next_if_node is not None and ( isinstance(next_if_node.test, nodes.Compare) and isinstance(next_if_node.test.left, nodes.Name) and next_if_node.test.left.name == name or isinstance(next_if_node.test, nodes.Name) and next_if_node.test.name == name ) ): return _True return _False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
285
next_sibling
ref
function
next_sibling = node.next_sibling()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
307
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(CodeStyleChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
308
register_checker
ref
function
linter.register_checker(CodeStyleChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/code_style.py
pylint/extensions/code_style.py
308
CodeStyleChecker
ref
function
linter.register_checker(CodeStyleChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
27
_is_constant_zero
def
function
def _is_constant_zero(node): return isinstance(node, astroid.Const) and node.value == 0
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
31
CompareToZeroChecker
def
class
visit_compare
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
53
check_messages
ref
function
@utils.check_messages("compare-to-zero")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
54
visit_compare
def
function
def visit_compare(self, node: nodes.Compare) -> None: _operators = ["!=", "==", "is not", "is"] # note: astroid.Compare has the left most operand in node.left # while the rest are a list of tuples in node.ops # the format of the tuple is ('compare operator sign', node) # here we squash everything into `ops` to make it easier for processing later ops = [("", node.left)] ops.extend(node.ops) iter_ops: Iterable[Any] = iter(ops) ops = list(itertools.chain(*iter_ops)) for ops_idx in range(len(ops) - 2): op_1 = ops[ops_idx] op_2 = ops[ops_idx + 1] op_3 = ops[ops_idx + 2] error_detected = _False # 0 ?? X if _is_constant_zero(op_1) and op_2 in _operators: error_detected = _True # X ?? 0 elif op_2 in _operators and _is_constant_zero(op_3): error_detected = _True if error_detected: self.add_message("compare-to-zero", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
72
_is_constant_zero
ref
function
if _is_constant_zero(op_1) and op_2 in _operators:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
75
_is_constant_zero
ref
function
elif op_2 in _operators and _is_constant_zero(op_3):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
79
add_message
ref
function
self.add_message("compare-to-zero", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
82
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(CompareToZeroChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
83
register_checker
ref
function
linter.register_checker(CompareToZeroChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparetozero.py
pylint/extensions/comparetozero.py
83
CompareToZeroChecker
ref
function
linter.register_checker(CompareToZeroChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
22
MisplacedComparisonConstantChecker
def
class
_check_misplaced_constant visit_compare
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
42
_check_misplaced_constant
def
function
def _check_misplaced_constant( self, node: nodes.Compare, left: nodes.NodeNG, right: nodes.NodeNG, operator: str, ): if isinstance(right, nodes.Const): return operator = REVERSED_COMPS.get(operator, operator) suggestion = f"{right.as_string()} {operator} {left.value!r}" self.add_message("misplaced-comparison-constant", node=node, args=(suggestion,)) @utils.check_messages("misplaced-comparison-constant") def visit_compare(self, node: nodes.Compare) -> None: # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in COMPARISON_OPERATORS and isinstance(left, nodes.Const): self._check_misplaced_constant(node, left, right, operator)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
52
as_string
ref
function
suggestion = f"{right.as_string()} {operator} {left.value!r}"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
53
add_message
ref
function
self.add_message("misplaced-comparison-constant", node=node, args=(suggestion,))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
55
check_messages
ref
function
@utils.check_messages("misplaced-comparison-constant")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
56
visit_compare
def
function
def visit_compare(self, node: nodes.Compare) -> None: # NOTE: this checker only works with binary comparisons like 'x == 42' # but not 'x == y == 42' if len(node.ops) != 1: return left = node.left operator, right = node.ops[0] if operator in COMPARISON_OPERATORS and isinstance(left, nodes.Const): self._check_misplaced_constant(node, left, right, operator)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
65
_check_misplaced_constant
ref
function
self._check_misplaced_constant(node, left, right, operator)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
68
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(MisplacedComparisonConstantChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
69
register_checker
ref
function
linter.register_checker(MisplacedComparisonConstantChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/comparison_placement.py
pylint/extensions/comparison_placement.py
69
MisplacedComparisonConstantChecker
ref
function
linter.register_checker(MisplacedComparisonConstantChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
21
ConfusingConsecutiveElifChecker
def
class
visit_if _has_no_else_clause
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
38
check_messages
ref
function
@check_messages("confusing-consecutive-elif")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
39
visit_if
def
function
def visit_if(self, node: nodes.If) -> None: body_ends_with_if = isinstance( node.body[-1], nodes.If ) and self._has_no_else_clause(node.body[-1]) if node.has_elif_block() and body_ends_with_if: self.add_message("confusing-consecutive-elif", node=node.orelse[0]) @staticmethod def _has_no_else_clause(node: nodes.If): orelse = node.orelse while orelse and isinstance(orelse[0], nodes.If): orelse = orelse[0].orelse if not orelse or isinstance(orelse[0], nodes.If): return _True return _False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
42
_has_no_else_clause
ref
function
) and self._has_no_else_clause(node.body[-1])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
43
has_elif_block
ref
function
if node.has_elif_block() and body_ends_with_if:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
44
add_message
ref
function
self.add_message("confusing-consecutive-elif", node=node.orelse[0])
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
47
_has_no_else_clause
def
function
def _has_no_else_clause(node: nodes.If): orelse = node.orelse while orelse and isinstance(orelse[0], nodes.If): orelse = orelse[0].orelse if not orelse or isinstance(orelse[0], nodes.If): return _True return _False
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
56
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(ConfusingConsecutiveElifChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
57
register_checker
ref
function
linter.register_checker(ConfusingConsecutiveElifChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/confusing_elif.py
pylint/extensions/confusing_elif.py
57
ConfusingConsecutiveElifChecker
ref
function
linter.register_checker(ConfusingConsecutiveElifChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/consider_ternary_expression.py
pylint/extensions/consider_ternary_expression.py
13
ConsiderTernaryExpressionChecker
def
class
visit_if
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/extensions/consider_ternary_expression.py
pylint/extensions/consider_ternary_expression.py
26
visit_if
def
function
def visit_if(self, node: nodes.If) -> None: if isinstance(node.parent, nodes.If): return if len(node.body) != 1 or len(node.orelse) != 1: return bst = node.body[0] ost = node.orelse[0] if not isinstance(bst, nodes.Assign) or not isinstance(ost, nodes.Assign): return for (bname, oname) in zip(bst.targets, ost.targets): if not isinstance(bname, nodes.AssignName) or not isinstance( oname, nodes.AssignName ): return if bname.name != oname.name: return self.add_message("consider-ternary-expression", node=node)