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/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 555 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 563 | check_messages | ref | function | @check_messages(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 570 | leave_functiondef | def | function | def leave_functiondef(self, node: nodes.FunctionDef) -> None:
"""Most of the work is done here on close:
checks for max returns, branch, return in __init__
"""
returns = self._returns.pop()
if returns > self.config.max_returns:
self.add_message(
"too-many-return-statements",
node=node,
args=(returns, self.config.max_returns),
)
branches = self._branches[node]
if branches > self.config.max_branches:
self.add_message(
"too-many-branches",
node=node,
args=(branches, self.config.max_branches),
)
# check number of statements
stmts = self._stmts.pop()
if stmts > self.config.max_statements:
self.add_message(
"too-many-statements",
node=node,
args=(stmts, self.config.max_statements),
)
leave_asyncfunctiondef = leave_functiondef
def visit_return(self, _: nodes.Return) -> None:
"""Count number of returns."""
if not self._returns:
return # return outside function, reported by the base checker
self._returns[-1] += 1
def visit_default(self, node: nodes.NodeNG) -> None:
"""Default visit method -> increments the statements counter if
necessary
"""
if node.is_statement:
self._inc_all_stmts(1)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Increments the branches counter."""
branches = len(node.handlers)
if node.orelse:
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def visit_tryfinally(self, node: nodes.TryFinally) -> None:
"""Increments the branches counter."""
self._inc_branch(node, 2)
self._inc_all_stmts(2)
@check_messages("too-many-boolean-expressions")
def visit_if(self, node: nodes.If) -> None:
"""Increments the branches counter and checks boolean expressions."""
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
if node.orelse and (
len(node.orelse) > 1 or not isinstance(node.orelse[0], astroid.If)
):
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def _check_boolean_expressions(self, node):
"""Go through "if" node `node` and count its boolean expressions
if the 'if' node test is a BoolOp node
"""
condition = node.test
if not isinstance(condition, astroid.BoolOp):
return
nb_bool_expr = _count_boolean_expressions(condition)
if nb_bool_expr > self.config.max_bool_expr:
self.add_message(
"too-many-boolean-expressions",
node=condition,
args=(nb_bool_expr, self.config.max_bool_expr),
)
def visit_while(self, node: nodes.While) -> None:
"""Increments the branches counter."""
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches)
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
"""Increments the branches counter."""
self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 576 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 583 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 591 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 599 | visit_return | def | function | def visit_return(self, _: nodes.Return) -> None:
"""Count number of returns."""
if not self._returns:
return # return outside function, reported by the base checker
self._returns[-1] += 1
def visit_default(self, node: nodes.NodeNG) -> None:
"""Default visit method -> increments the statements counter if
necessary
"""
if node.is_statement:
self._inc_all_stmts(1)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Increments the branches counter."""
branches = len(node.handlers)
if node.orelse:
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def visit_tryfinally(self, node: nodes.TryFinally) -> None:
"""Increments the branches counter."""
self._inc_branch(node, 2)
self._inc_all_stmts(2)
@check_messages("too-many-boolean-expressions")
def visit_if(self, node: nodes.If) -> None:
"""Increments the branches counter and checks boolean expressions."""
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
if node.orelse and (
len(node.orelse) > 1 or not isinstance(node.orelse[0], astroid.If)
):
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def _check_boolean_expressions(self, node):
"""Go through "if" node `node` and count its boolean expressions
if the 'if' node test is a BoolOp node
"""
condition = node.test
if not isinstance(condition, astroid.BoolOp):
return
nb_bool_expr = _count_boolean_expressions(condition)
if nb_bool_expr > self.config.max_bool_expr:
self.add_message(
"too-many-boolean-expressions",
node=condition,
args=(nb_bool_expr, self.config.max_bool_expr),
)
def visit_while(self, node: nodes.While) -> None:
"""Increments the branches counter."""
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches)
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
"""Increments the branches counter."""
self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 605 | visit_default | def | function | def visit_default(self, node: nodes.NodeNG) -> None:
"""Default visit method -> increments the statements counter if
necessary
"""
if node.is_statement:
self._inc_all_stmts(1)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Increments the branches counter."""
branches = len(node.handlers)
if node.orelse:
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def visit_tryfinally(self, node: nodes.TryFinally) -> None:
"""Increments the branches counter."""
self._inc_branch(node, 2)
self._inc_all_stmts(2)
@check_messages("too-many-boolean-expressions")
def visit_if(self, node: nodes.If) -> None:
"""Increments the branches counter and checks boolean expressions."""
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
if node.orelse and (
len(node.orelse) > 1 or not isinstance(node.orelse[0], astroid.If)
):
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def _check_boolean_expressions(self, node):
"""Go through "if" node `node` and count its boolean expressions
if the 'if' node test is a BoolOp node
"""
condition = node.test
if not isinstance(condition, astroid.BoolOp):
return
nb_bool_expr = _count_boolean_expressions(condition)
if nb_bool_expr > self.config.max_bool_expr:
self.add_message(
"too-many-boolean-expressions",
node=condition,
args=(nb_bool_expr, self.config.max_bool_expr),
)
def visit_while(self, node: nodes.While) -> None:
"""Increments the branches counter."""
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches)
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
"""Increments the branches counter."""
self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 610 | _inc_all_stmts | ref | function | self._inc_all_stmts(1)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 612 | visit_tryexcept | def | function | def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Increments the branches counter."""
branches = len(node.handlers)
if node.orelse:
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def visit_tryfinally(self, node: nodes.TryFinally) -> None:
"""Increments the branches counter."""
self._inc_branch(node, 2)
self._inc_all_stmts(2)
@check_messages("too-many-boolean-expressions")
def visit_if(self, node: nodes.If) -> None:
"""Increments the branches counter and checks boolean expressions."""
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
if node.orelse and (
len(node.orelse) > 1 or not isinstance(node.orelse[0], astroid.If)
):
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def _check_boolean_expressions(self, node):
"""Go through "if" node `node` and count its boolean expressions
if the 'if' node test is a BoolOp node
"""
condition = node.test
if not isinstance(condition, astroid.BoolOp):
return
nb_bool_expr = _count_boolean_expressions(condition)
if nb_bool_expr > self.config.max_bool_expr:
self.add_message(
"too-many-boolean-expressions",
node=condition,
args=(nb_bool_expr, self.config.max_bool_expr),
)
def visit_while(self, node: nodes.While) -> None:
"""Increments the branches counter."""
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches)
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
"""Increments the branches counter."""
self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 617 | _inc_branch | ref | function | self._inc_branch(node, branches)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 618 | _inc_all_stmts | ref | function | self._inc_all_stmts(branches)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 620 | visit_tryfinally | def | function | def visit_tryfinally(self, node: nodes.TryFinally) -> None:
"""Increments the branches counter."""
self._inc_branch(node, 2)
self._inc_all_stmts(2)
@check_messages("too-many-boolean-expressions")
def visit_if(self, node: nodes.If) -> None:
"""Increments the branches counter and checks boolean expressions."""
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
if node.orelse and (
len(node.orelse) > 1 or not isinstance(node.orelse[0], astroid.If)
):
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def _check_boolean_expressions(self, node):
"""Go through "if" node `node` and count its boolean expressions
if the 'if' node test is a BoolOp node
"""
condition = node.test
if not isinstance(condition, astroid.BoolOp):
return
nb_bool_expr = _count_boolean_expressions(condition)
if nb_bool_expr > self.config.max_bool_expr:
self.add_message(
"too-many-boolean-expressions",
node=condition,
args=(nb_bool_expr, self.config.max_bool_expr),
)
def visit_while(self, node: nodes.While) -> None:
"""Increments the branches counter."""
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches)
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
"""Increments the branches counter."""
self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 622 | _inc_branch | ref | function | self._inc_branch(node, 2)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 623 | _inc_all_stmts | ref | function | self._inc_all_stmts(2)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 625 | check_messages | ref | function | @check_messages("too-many-boolean-expressions")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 626 | visit_if | def | function | def visit_if(self, node: nodes.If) -> None:
"""Increments the branches counter and checks boolean expressions."""
self._check_boolean_expressions(node)
branches = 1
# don't double count If nodes coming from some 'elif'
if node.orelse and (
len(node.orelse) > 1 or not isinstance(node.orelse[0], astroid.If)
):
branches += 1
self._inc_branch(node, branches)
self._inc_all_stmts(branches)
def _check_boolean_expressions(self, node):
"""Go through "if" node `node` and count its boolean expressions
if the 'if' node test is a BoolOp node
"""
condition = node.test
if not isinstance(condition, astroid.BoolOp):
return
nb_bool_expr = _count_boolean_expressions(condition)
if nb_bool_expr > self.config.max_bool_expr:
self.add_message(
"too-many-boolean-expressions",
node=condition,
args=(nb_bool_expr, self.config.max_bool_expr),
)
def visit_while(self, node: nodes.While) -> None:
"""Increments the branches counter."""
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches)
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
"""Increments the branches counter."""
self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 628 | _check_boolean_expressions | ref | function | self._check_boolean_expressions(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 635 | _inc_branch | ref | function | self._inc_branch(node, branches)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 636 | _inc_all_stmts | ref | function | self._inc_all_stmts(branches)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 638 | _check_boolean_expressions | def | function | def _check_boolean_expressions(self, node):
"""Go through "if" node `node` and count its boolean expressions
if the 'if' node test is a BoolOp node
"""
condition = node.test
if not isinstance(condition, astroid.BoolOp):
return
nb_bool_expr = _count_boolean_expressions(condition)
if nb_bool_expr > self.config.max_bool_expr:
self.add_message(
"too-many-boolean-expressions",
node=condition,
args=(nb_bool_expr, self.config.max_bool_expr),
)
def visit_while(self, node: nodes.While) -> None:
"""Increments the branches counter."""
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches)
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
"""Increments the branches counter."""
self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 645 | _count_boolean_expressions | ref | function | nb_bool_expr = _count_boolean_expressions(condition)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 647 | add_message | ref | function | self.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 653 | visit_while | def | function | def visit_while(self, node: nodes.While) -> None:
"""Increments the branches counter."""
branches = 1
if node.orelse:
branches += 1
self._inc_branch(node, branches)
visit_for = visit_while
def _inc_branch(self, node, branchesnum=1):
"""Increments the branches counter."""
self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 658 | _inc_branch | ref | function | self._inc_branch(node, branches)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 662 | _inc_branch | def | function | def _inc_branch(self, node, branchesnum=1):
"""Increments the branches counter."""
self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 664 | scope | ref | function | self._branches[node.scope()] += branchesnum
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 667 | register | def | function | def register(linter: "PyLinter") -> None:
linter.register_checker(MisdesignChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 668 | register_checker | ref | function | linter.register_checker(MisdesignChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/design_analysis.py | pylint/checkers/design_analysis.py | 668 | MisdesignChecker | ref | function | linter.register_checker(MisdesignChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/ellipsis_checker.py | pylint/checkers/ellipsis_checker.py | 13 | EllipsisChecker | def | class | visit_const |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/ellipsis_checker.py | pylint/checkers/ellipsis_checker.py | 27 | check_messages | ref | function | @check_messages("unnecessary-ellipsis")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/ellipsis_checker.py | pylint/checkers/ellipsis_checker.py | 28 | visit_const | def | function | def visit_const(self, node: nodes.Const) -> None:
"""Check if the ellipsis constant is used unnecessarily.
Emit a warning when:
- A line consisting of an ellipsis is preceded by a docstring.
- A statement exists in the same scope as the ellipsis.
For example: A function consisting of an ellipsis followed by a
return statement on the next line.
"""
if (
node.pytype() == "builtins.Ellipsis"
and not isinstance(node.parent, (nodes.Assign, nodes.AnnAssign, nodes.Call))
and (
len(node.parent.parent.child_sequence(node.parent)) > 1
or (
isinstance(node.parent.parent, (nodes.ClassDef, nodes.FunctionDef))
and (node.parent.parent.doc is not None)
)
)
):
self.add_message("unnecessary-ellipsis", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/ellipsis_checker.py | pylint/checkers/ellipsis_checker.py | 37 | pytype | ref | function | node.pytype() == "builtins.Ellipsis"
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/ellipsis_checker.py | pylint/checkers/ellipsis_checker.py | 40 | child_sequence | ref | function | len(node.parent.parent.child_sequence(node.parent)) > 1
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/ellipsis_checker.py | pylint/checkers/ellipsis_checker.py | 47 | add_message | ref | function | self.add_message("unnecessary-ellipsis", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/ellipsis_checker.py | pylint/checkers/ellipsis_checker.py | 50 | register | def | function | def register(linter: "PyLinter") -> None:
linter.register_checker(EllipsisChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/ellipsis_checker.py | pylint/checkers/ellipsis_checker.py | 51 | register_checker | ref | function | linter.register_checker(EllipsisChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/ellipsis_checker.py | pylint/checkers/ellipsis_checker.py | 51 | EllipsisChecker | ref | function | linter.register_checker(EllipsisChecker(linter))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 50 | _builtin_exceptions | def | function | def _builtin_exceptions():
def predicate(obj):
return isinstance(obj, type) and issubclass(obj, BaseException)
members = inspect.getmembers(builtins, predicate)
return {exc.__name__ for (_, exc) in members}
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 51 | predicate | def | function | def predicate(obj):
return isinstance(obj, type) and issubclass(obj, BaseException)
members = inspect.getmembers(builtins, predicate)
return {exc.__name__ for (_, exc) in members}
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 58 | _annotated_unpack_infer | def | function | def _annotated_unpack_infer(stmt, context=None):
"""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').
"""
if isinstance(stmt, (nodes.List, nodes.Tuple)):
for elt in stmt.elts:
inferred = utils.safe_infer(elt)
if inferred and inferred is not astroid.Uninferable:
yield elt, inferred
return
for inferred in stmt.infer(context):
if inferred is astroid.Uninferable:
continue
yield stmt, inferred
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 66 | safe_infer | ref | function | inferred = utils.safe_infer(elt)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 70 | infer | ref | function | for inferred in stmt.infer(context):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 76 | _is_raising | def | function | def _is_raising(body: List) -> bool:
"""Return whether the given statement node raises an exception."""
return any(isinstance(node, nodes.Raise) for node in body)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 189 | BaseVisitor | def | class | __init__ visit visit_default |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 196 | visit | def | function | def visit(self, node):
name = node.__class__.__name__.lower()
dispatch_meth = getattr(self, "visit_" + name, None)
if dispatch_meth:
dispatch_meth(node)
else:
self.visit_default(node)
def visit_default(self, _: nodes.NodeNG) -> None:
"""Default implementation for all the nodes."""
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 200 | dispatch_meth | ref | function | dispatch_meth(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 202 | visit_default | ref | function | self.visit_default(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 204 | visit_default | def | function | def visit_default(self, _: nodes.NodeNG) -> None:
"""Default implementation for all the nodes."""
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 208 | ExceptionRaiseRefVisitor | def | class | visit_name visit_call |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 211 | visit_name | def | function | def visit_name(self, node: nodes.Name) -> None:
if node.name == "NotImplemented":
self._checker.add_message("notimplemented-raised", node=self._node)
def visit_call(self, node: nodes.Call) -> None:
if isinstance(node.func, nodes.Name):
self.visit_name(node.func)
if (
len(node.args) > 1
and isinstance(node.args[0], nodes.Const)
and isinstance(node.args[0].value, str)
):
msg = node.args[0].value
if "%" in msg or ("{" in msg and "}" in msg):
self._checker.add_message("raising-format-tuple", node=self._node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 213 | add_message | ref | function | self._checker.add_message("notimplemented-raised", node=self._node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 215 | visit_call | def | function | def visit_call(self, node: nodes.Call) -> None:
if isinstance(node.func, nodes.Name):
self.visit_name(node.func)
if (
len(node.args) > 1
and isinstance(node.args[0], nodes.Const)
and isinstance(node.args[0].value, str)
):
msg = node.args[0].value
if "%" in msg or ("{" in msg and "}" in msg):
self._checker.add_message("raising-format-tuple", node=self._node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 217 | visit_name | ref | function | self.visit_name(node.func)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 225 | add_message | ref | function | self._checker.add_message("raising-format-tuple", node=self._node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 228 | ExceptionRaiseLeafVisitor | def | class | visit_const visit_instance visit_classdef visit_tuple visit_default |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 231 | visit_const | def | function | def visit_const(self, node: nodes.Const) -> None:
self._checker.add_message(
"raising-bad-type", node=self._node, args=node.value.__class__.__name__
)
def visit_instance(self, instance: objects.ExceptionInstance) -> None:
cls = instance._proxied
self.visit_classdef(cls)
# Exception instances have a particular class type
visit_exceptioninstance = visit_instance
def visit_classdef(self, node: nodes.ClassDef) -> None:
if not utils.inherit_from_std_ex(node) and utils.has_known_bases(node):
if node.newstyle:
self._checker.add_message("raising-non-exception", node=self._node)
def visit_tuple(self, _: nodes.Tuple) -> None:
self._checker.add_message("raising-bad-type", node=self._node, args="tuple")
def visit_default(self, node: nodes.NodeNG) -> None:
name = getattr(node, "name", node.__class__.__name__)
self._checker.add_message("raising-bad-type", node=self._node, args=name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 232 | add_message | ref | function | self._checker.add_message(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 236 | visit_instance | def | function | def visit_instance(self, instance: objects.ExceptionInstance) -> None:
cls = instance._proxied
self.visit_classdef(cls)
# Exception instances have a particular class type
visit_exceptioninstance = visit_instance
def visit_classdef(self, node: nodes.ClassDef) -> None:
if not utils.inherit_from_std_ex(node) and utils.has_known_bases(node):
if node.newstyle:
self._checker.add_message("raising-non-exception", node=self._node)
def visit_tuple(self, _: nodes.Tuple) -> None:
self._checker.add_message("raising-bad-type", node=self._node, args="tuple")
def visit_default(self, node: nodes.NodeNG) -> None:
name = getattr(node, "name", node.__class__.__name__)
self._checker.add_message("raising-bad-type", node=self._node, args=name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 238 | visit_classdef | ref | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 243 | visit_classdef | def | class | |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 244 | inherit_from_std_ex | ref | function | if not utils.inherit_from_std_ex(node) and utils.has_known_bases(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 244 | has_known_bases | ref | function | if not utils.inherit_from_std_ex(node) and utils.has_known_bases(node):
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 246 | add_message | ref | function | self._checker.add_message("raising-non-exception", node=self._node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 248 | visit_tuple | def | function | def visit_tuple(self, _: nodes.Tuple) -> None:
self._checker.add_message("raising-bad-type", node=self._node, args="tuple")
def visit_default(self, node: nodes.NodeNG) -> None:
name = getattr(node, "name", node.__class__.__name__)
self._checker.add_message("raising-bad-type", node=self._node, args=name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 249 | add_message | ref | function | self._checker.add_message("raising-bad-type", node=self._node, args="tuple")
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 251 | visit_default | def | function | def visit_default(self, node: nodes.NodeNG) -> None:
name = getattr(node, "name", node.__class__.__name__)
self._checker.add_message("raising-bad-type", node=self._node, args=name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 253 | add_message | ref | function | self._checker.add_message("raising-bad-type", node=self._node, args=name)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 256 | ExceptionsChecker | def | class | open visit_raise _check_misplaced_bare_raise _check_bad_exception_context _check_raise_missing_from _check_catching_non_exception _check_try_except_raise visit_binop visit_compare visit_tryexcept |
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 279 | _builtin_exceptions | ref | function | self._builtin_exceptions = _builtin_exceptions()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 282 | check_messages | ref | function | @utils.check_messages(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 291 | visit_raise | def | function | def visit_raise(self, node: nodes.Raise) -> None:
if node.exc is None:
self._check_misplaced_bare_raise(node)
return
if node.cause is None:
self._check_raise_missing_from(node)
else:
self._check_bad_exception_context(node)
expr = node.exc
ExceptionRaiseRefVisitor(self, node).visit(expr)
try:
inferred_value = expr.inferred()[-1]
except astroid.InferenceError:
pass
else:
if inferred_value:
ExceptionRaiseLeafVisitor(self, node).visit(inferred_value)
def _check_misplaced_bare_raise(self, node):
# Filter out if it's present in __exit__.
scope = node.scope()
if (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and scope.name == "__exit__"
):
return
current = node
# Stop when a new scope is generated or when the raise
# statement is found inside a TryFinally.
ignores = (nodes.ExceptHandler, nodes.FunctionDef)
while current and not isinstance(current.parent, ignores):
current = current.parent
expected = (nodes.ExceptHandler,)
if not current or not isinstance(current.parent, expected):
self.add_message("misplaced-bare-raise", node=node)
def _check_bad_exception_context(self, node: nodes.Raise) -> None:
"""Verify that the exception context is properly set.
An exception context can be only `None` or an exception.
"""
cause = utils.safe_infer(node.cause)
if cause in (astroid.Uninferable, None):
return
if isinstance(cause, nodes.Const):
if cause.value is not None:
self.add_message("bad-exception-context", node=node)
elif not isinstance(cause, nodes.ClassDef) and not utils.inherit_from_std_ex(
cause
):
self.add_message("bad-exception-context", node=node)
def _check_raise_missing_from(self, node: nodes.Raise) -> None:
if node.exc is None:
# This is a plain `raise`, raising the previously-caught exception. No need for a
# cause.
return
# We'd like to check whether we're inside an `except` clause:
containing_except_node = utils.find_except_wrapper_node_in_scope(node)
if not containing_except_node:
return
# We found a surrounding `except`! We're almost done proving there's a
# `raise-missing-from` here. The only thing we need to protect against is that maybe
# the `raise` is raising the exception that was caught, possibly with some shenanigans
# like `exc.with_traceback(whatever)`. We won't analyze these, we'll just assume
# there's a violation on two simple cases: `raise SomeException(whatever)` and `raise
# SomeException`.
if containing_except_node.name is None:
# The `except` doesn't have an `as exception:` part, meaning there's no way that
# the `raise` is raising the same exception.
self.add_message("raise-missing-from", node=node)
elif isinstance(node.exc, nodes.Call) and isinstance(node.exc.func, nodes.Name):
# We have a `raise SomeException(whatever)`.
self.add_message("raise-missing-from", node=node)
elif (
isinstance(node.exc, nodes.Name)
and node.exc.name != containing_except_node.name.name
):
# We have a `raise SomeException`.
self.add_message("raise-missing-from", node=node)
def _check_catching_non_exception(self, handler, exc, part):
if isinstance(exc, nodes.Tuple):
# Check if it is a tuple of exceptions.
inferred = [utils.safe_infer(elt) for elt in exc.elts]
if any(node is astroid.Uninferable for node in inferred):
# Don't emit if we don't know every component.
return
if all(
node
and (utils.inherit_from_std_ex(node) or not utils.has_known_bases(node))
for node in inferred
):
return
if not isinstance(exc, nodes.ClassDef):
# Don't emit the warning if the inferred stmt
# is None, but the exception handler is something else,
# maybe it was redefined.
if isinstance(exc, nodes.Const) and exc.value is None:
if (
isinstance(handler.type, nodes.Const) and handler.type.value is None
) or handler.type.parent_of(exc):
# If the exception handler catches None or
# the exception component, which is None, is
# defined by the entire exception handler, then
# emit a warning.
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
else:
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
return
if (
not utils.inherit_from_std_ex(exc)
and exc.name not in self._builtin_exceptions
):
if utils.has_known_bases(exc):
self.add_message(
"catching-non-exception", node=handler.type, args=(exc.name,)
)
def _check_try_except_raise(self, node):
def gather_exceptions_from_handler(
handler,
) -> Optional[List[nodes.NodeNG]]:
exceptions: List[nodes.NodeNG] = []
if handler.type:
exceptions_in_handler = utils.safe_infer(handler.type)
if isinstance(exceptions_in_handler, nodes.Tuple):
exceptions = list(
{
exception
for exception in exceptions_in_handler.elts
if isinstance(exception, nodes.Name)
}
)
elif exceptions_in_handler:
exceptions = [exceptions_in_handler]
else:
# Break when we cannot infer anything reliably.
return None
return exceptions
bare_raise = _False
handler_having_bare_raise = None
exceptions_in_bare_handler = []
for handler in node.handlers:
if bare_raise:
# check that subsequent handler is not parent of handler which had bare raise.
# since utils.safe_infer can fail for bare except, check it before.
# also break early if bare except is followed by bare except.
excs_in_current_handler = gather_exceptions_from_handler(handler)
if not excs_in_current_handler:
break
if exceptions_in_bare_handler is None:
# It can be `None` when the inference failed
break
for exc_in_current_handler in excs_in_current_handler:
inferred_current = utils.safe_infer(exc_in_current_handler)
if any(
utils.is_subclass_of(utils.safe_infer(e), inferred_current)
for e in exceptions_in_bare_handler
):
bare_raise = _False
break
# `raise` as the first operator inside the except handler
if _is_raising([handler.body[0]]):
# flags when there is a bare raise
if handler.body[0].exc is None:
bare_raise = _True
handler_having_bare_raise = handler
exceptions_in_bare_handler = gather_exceptions_from_handler(handler)
else:
if bare_raise:
self.add_message("try-except-raise", node=handler_having_bare_raise)
@utils.check_messages("wrong-exception-operation")
def visit_binop(self, node: nodes.BinOp) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V | A)
suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages("wrong-exception-operation")
def visit_compare(self, node: nodes.Compare) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V < A)
suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages(
"bare-except",
"broad-except",
"try-except-raise",
"binary-op-exception",
"bad-except-order",
"catching-non-exception",
"duplicate-except",
)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Check for empty except."""
self._check_try_except_raise(node)
exceptions_classes: List[Any] = []
nb_handlers = len(node.handlers)
for index, handler in enumerate(node.handlers):
if handler.type is None:
if not _is_raising(handler.body):
self.add_message("bare-except", node=handler)
# check if an "except:" is followed by some other
# except
if index < (nb_handlers - 1):
msg = "empty except clause should always appear last"
self.add_message("bad-except-order", node=node, args=msg)
elif isinstance(handler.type, nodes.BoolOp):
self.add_message(
"binary-op-exception", node=handler, args=handler.type.op
)
else:
try:
exceptions = list(_annotated_unpack_infer(handler.type))
except astroid.InferenceError:
continue
for part, exception in exceptions:
if exception is astroid.Uninferable:
continue
if isinstance(
exception, astroid.Instance
) and utils.inherit_from_std_ex(exception):
exception = exception._proxied
self._check_catching_non_exception(handler, exception, part)
if not isinstance(exception, nodes.ClassDef):
continue
exc_ancestors = [
anc
for anc in exception.ancestors()
if isinstance(anc, nodes.ClassDef)
]
for previous_exc in exceptions_classes:
if previous_exc in exc_ancestors:
msg = f"{previous_exc.name} is an ancestor class of {exception.name}"
self.add_message(
"bad-except-order", node=handler.type, args=msg
)
if (
exception.name in self.config.overgeneral_exceptions
and exception.root().name == utils.EXCEPTIONS_MODULE
and not _is_raising(handler.body)
):
self.add_message(
"broad-except", args=exception.name, node=handler.type
)
if exception in exceptions_classes:
self.add_message(
"duplicate-except", args=exception.name, node=handler.type
)
exceptions_classes += [exc for _, exc in exceptions]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 293 | _check_misplaced_bare_raise | ref | function | self._check_misplaced_bare_raise(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 297 | _check_raise_missing_from | ref | function | self._check_raise_missing_from(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 299 | _check_bad_exception_context | ref | function | self._check_bad_exception_context(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 302 | ExceptionRaiseRefVisitor | ref | function | ExceptionRaiseRefVisitor(self, node).visit(expr)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 302 | visit | ref | function | ExceptionRaiseRefVisitor(self, node).visit(expr)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 305 | inferred | ref | function | inferred_value = expr.inferred()[-1]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 310 | ExceptionRaiseLeafVisitor | ref | function | ExceptionRaiseLeafVisitor(self, node).visit(inferred_value)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 310 | visit | ref | function | ExceptionRaiseLeafVisitor(self, node).visit(inferred_value)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 312 | _check_misplaced_bare_raise | def | function | def _check_misplaced_bare_raise(self, node):
# Filter out if it's present in __exit__.
scope = node.scope()
if (
isinstance(scope, nodes.FunctionDef)
and scope.is_method()
and scope.name == "__exit__"
):
return
current = node
# Stop when a new scope is generated or when the raise
# statement is found inside a TryFinally.
ignores = (nodes.ExceptHandler, nodes.FunctionDef)
while current and not isinstance(current.parent, ignores):
current = current.parent
expected = (nodes.ExceptHandler,)
if not current or not isinstance(current.parent, expected):
self.add_message("misplaced-bare-raise", node=node)
def _check_bad_exception_context(self, node: nodes.Raise) -> None:
"""Verify that the exception context is properly set.
An exception context can be only `None` or an exception.
"""
cause = utils.safe_infer(node.cause)
if cause in (astroid.Uninferable, None):
return
if isinstance(cause, nodes.Const):
if cause.value is not None:
self.add_message("bad-exception-context", node=node)
elif not isinstance(cause, nodes.ClassDef) and not utils.inherit_from_std_ex(
cause
):
self.add_message("bad-exception-context", node=node)
def _check_raise_missing_from(self, node: nodes.Raise) -> None:
if node.exc is None:
# This is a plain `raise`, raising the previously-caught exception. No need for a
# cause.
return
# We'd like to check whether we're inside an `except` clause:
containing_except_node = utils.find_except_wrapper_node_in_scope(node)
if not containing_except_node:
return
# We found a surrounding `except`! We're almost done proving there's a
# `raise-missing-from` here. The only thing we need to protect against is that maybe
# the `raise` is raising the exception that was caught, possibly with some shenanigans
# like `exc.with_traceback(whatever)`. We won't analyze these, we'll just assume
# there's a violation on two simple cases: `raise SomeException(whatever)` and `raise
# SomeException`.
if containing_except_node.name is None:
# The `except` doesn't have an `as exception:` part, meaning there's no way that
# the `raise` is raising the same exception.
self.add_message("raise-missing-from", node=node)
elif isinstance(node.exc, nodes.Call) and isinstance(node.exc.func, nodes.Name):
# We have a `raise SomeException(whatever)`.
self.add_message("raise-missing-from", node=node)
elif (
isinstance(node.exc, nodes.Name)
and node.exc.name != containing_except_node.name.name
):
# We have a `raise SomeException`.
self.add_message("raise-missing-from", node=node)
def _check_catching_non_exception(self, handler, exc, part):
if isinstance(exc, nodes.Tuple):
# Check if it is a tuple of exceptions.
inferred = [utils.safe_infer(elt) for elt in exc.elts]
if any(node is astroid.Uninferable for node in inferred):
# Don't emit if we don't know every component.
return
if all(
node
and (utils.inherit_from_std_ex(node) or not utils.has_known_bases(node))
for node in inferred
):
return
if not isinstance(exc, nodes.ClassDef):
# Don't emit the warning if the inferred stmt
# is None, but the exception handler is something else,
# maybe it was redefined.
if isinstance(exc, nodes.Const) and exc.value is None:
if (
isinstance(handler.type, nodes.Const) and handler.type.value is None
) or handler.type.parent_of(exc):
# If the exception handler catches None or
# the exception component, which is None, is
# defined by the entire exception handler, then
# emit a warning.
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
else:
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
return
if (
not utils.inherit_from_std_ex(exc)
and exc.name not in self._builtin_exceptions
):
if utils.has_known_bases(exc):
self.add_message(
"catching-non-exception", node=handler.type, args=(exc.name,)
)
def _check_try_except_raise(self, node):
def gather_exceptions_from_handler(
handler,
) -> Optional[List[nodes.NodeNG]]:
exceptions: List[nodes.NodeNG] = []
if handler.type:
exceptions_in_handler = utils.safe_infer(handler.type)
if isinstance(exceptions_in_handler, nodes.Tuple):
exceptions = list(
{
exception
for exception in exceptions_in_handler.elts
if isinstance(exception, nodes.Name)
}
)
elif exceptions_in_handler:
exceptions = [exceptions_in_handler]
else:
# Break when we cannot infer anything reliably.
return None
return exceptions
bare_raise = _False
handler_having_bare_raise = None
exceptions_in_bare_handler = []
for handler in node.handlers:
if bare_raise:
# check that subsequent handler is not parent of handler which had bare raise.
# since utils.safe_infer can fail for bare except, check it before.
# also break early if bare except is followed by bare except.
excs_in_current_handler = gather_exceptions_from_handler(handler)
if not excs_in_current_handler:
break
if exceptions_in_bare_handler is None:
# It can be `None` when the inference failed
break
for exc_in_current_handler in excs_in_current_handler:
inferred_current = utils.safe_infer(exc_in_current_handler)
if any(
utils.is_subclass_of(utils.safe_infer(e), inferred_current)
for e in exceptions_in_bare_handler
):
bare_raise = _False
break
# `raise` as the first operator inside the except handler
if _is_raising([handler.body[0]]):
# flags when there is a bare raise
if handler.body[0].exc is None:
bare_raise = _True
handler_having_bare_raise = handler
exceptions_in_bare_handler = gather_exceptions_from_handler(handler)
else:
if bare_raise:
self.add_message("try-except-raise", node=handler_having_bare_raise)
@utils.check_messages("wrong-exception-operation")
def visit_binop(self, node: nodes.BinOp) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V | A)
suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages("wrong-exception-operation")
def visit_compare(self, node: nodes.Compare) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V < A)
suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages(
"bare-except",
"broad-except",
"try-except-raise",
"binary-op-exception",
"bad-except-order",
"catching-non-exception",
"duplicate-except",
)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Check for empty except."""
self._check_try_except_raise(node)
exceptions_classes: List[Any] = []
nb_handlers = len(node.handlers)
for index, handler in enumerate(node.handlers):
if handler.type is None:
if not _is_raising(handler.body):
self.add_message("bare-except", node=handler)
# check if an "except:" is followed by some other
# except
if index < (nb_handlers - 1):
msg = "empty except clause should always appear last"
self.add_message("bad-except-order", node=node, args=msg)
elif isinstance(handler.type, nodes.BoolOp):
self.add_message(
"binary-op-exception", node=handler, args=handler.type.op
)
else:
try:
exceptions = list(_annotated_unpack_infer(handler.type))
except astroid.InferenceError:
continue
for part, exception in exceptions:
if exception is astroid.Uninferable:
continue
if isinstance(
exception, astroid.Instance
) and utils.inherit_from_std_ex(exception):
exception = exception._proxied
self._check_catching_non_exception(handler, exception, part)
if not isinstance(exception, nodes.ClassDef):
continue
exc_ancestors = [
anc
for anc in exception.ancestors()
if isinstance(anc, nodes.ClassDef)
]
for previous_exc in exceptions_classes:
if previous_exc in exc_ancestors:
msg = f"{previous_exc.name} is an ancestor class of {exception.name}"
self.add_message(
"bad-except-order", node=handler.type, args=msg
)
if (
exception.name in self.config.overgeneral_exceptions
and exception.root().name == utils.EXCEPTIONS_MODULE
and not _is_raising(handler.body)
):
self.add_message(
"broad-except", args=exception.name, node=handler.type
)
if exception in exceptions_classes:
self.add_message(
"duplicate-except", args=exception.name, node=handler.type
)
exceptions_classes += [exc for _, exc in exceptions]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 314 | scope | ref | function | scope = node.scope()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 317 | is_method | ref | function | and scope.is_method()
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 331 | add_message | ref | function | self.add_message("misplaced-bare-raise", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 333 | _check_bad_exception_context | def | function | def _check_bad_exception_context(self, node: nodes.Raise) -> None:
"""Verify that the exception context is properly set.
An exception context can be only `None` or an exception.
"""
cause = utils.safe_infer(node.cause)
if cause in (astroid.Uninferable, None):
return
if isinstance(cause, nodes.Const):
if cause.value is not None:
self.add_message("bad-exception-context", node=node)
elif not isinstance(cause, nodes.ClassDef) and not utils.inherit_from_std_ex(
cause
):
self.add_message("bad-exception-context", node=node)
def _check_raise_missing_from(self, node: nodes.Raise) -> None:
if node.exc is None:
# This is a plain `raise`, raising the previously-caught exception. No need for a
# cause.
return
# We'd like to check whether we're inside an `except` clause:
containing_except_node = utils.find_except_wrapper_node_in_scope(node)
if not containing_except_node:
return
# We found a surrounding `except`! We're almost done proving there's a
# `raise-missing-from` here. The only thing we need to protect against is that maybe
# the `raise` is raising the exception that was caught, possibly with some shenanigans
# like `exc.with_traceback(whatever)`. We won't analyze these, we'll just assume
# there's a violation on two simple cases: `raise SomeException(whatever)` and `raise
# SomeException`.
if containing_except_node.name is None:
# The `except` doesn't have an `as exception:` part, meaning there's no way that
# the `raise` is raising the same exception.
self.add_message("raise-missing-from", node=node)
elif isinstance(node.exc, nodes.Call) and isinstance(node.exc.func, nodes.Name):
# We have a `raise SomeException(whatever)`.
self.add_message("raise-missing-from", node=node)
elif (
isinstance(node.exc, nodes.Name)
and node.exc.name != containing_except_node.name.name
):
# We have a `raise SomeException`.
self.add_message("raise-missing-from", node=node)
def _check_catching_non_exception(self, handler, exc, part):
if isinstance(exc, nodes.Tuple):
# Check if it is a tuple of exceptions.
inferred = [utils.safe_infer(elt) for elt in exc.elts]
if any(node is astroid.Uninferable for node in inferred):
# Don't emit if we don't know every component.
return
if all(
node
and (utils.inherit_from_std_ex(node) or not utils.has_known_bases(node))
for node in inferred
):
return
if not isinstance(exc, nodes.ClassDef):
# Don't emit the warning if the inferred stmt
# is None, but the exception handler is something else,
# maybe it was redefined.
if isinstance(exc, nodes.Const) and exc.value is None:
if (
isinstance(handler.type, nodes.Const) and handler.type.value is None
) or handler.type.parent_of(exc):
# If the exception handler catches None or
# the exception component, which is None, is
# defined by the entire exception handler, then
# emit a warning.
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
else:
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
return
if (
not utils.inherit_from_std_ex(exc)
and exc.name not in self._builtin_exceptions
):
if utils.has_known_bases(exc):
self.add_message(
"catching-non-exception", node=handler.type, args=(exc.name,)
)
def _check_try_except_raise(self, node):
def gather_exceptions_from_handler(
handler,
) -> Optional[List[nodes.NodeNG]]:
exceptions: List[nodes.NodeNG] = []
if handler.type:
exceptions_in_handler = utils.safe_infer(handler.type)
if isinstance(exceptions_in_handler, nodes.Tuple):
exceptions = list(
{
exception
for exception in exceptions_in_handler.elts
if isinstance(exception, nodes.Name)
}
)
elif exceptions_in_handler:
exceptions = [exceptions_in_handler]
else:
# Break when we cannot infer anything reliably.
return None
return exceptions
bare_raise = _False
handler_having_bare_raise = None
exceptions_in_bare_handler = []
for handler in node.handlers:
if bare_raise:
# check that subsequent handler is not parent of handler which had bare raise.
# since utils.safe_infer can fail for bare except, check it before.
# also break early if bare except is followed by bare except.
excs_in_current_handler = gather_exceptions_from_handler(handler)
if not excs_in_current_handler:
break
if exceptions_in_bare_handler is None:
# It can be `None` when the inference failed
break
for exc_in_current_handler in excs_in_current_handler:
inferred_current = utils.safe_infer(exc_in_current_handler)
if any(
utils.is_subclass_of(utils.safe_infer(e), inferred_current)
for e in exceptions_in_bare_handler
):
bare_raise = _False
break
# `raise` as the first operator inside the except handler
if _is_raising([handler.body[0]]):
# flags when there is a bare raise
if handler.body[0].exc is None:
bare_raise = _True
handler_having_bare_raise = handler
exceptions_in_bare_handler = gather_exceptions_from_handler(handler)
else:
if bare_raise:
self.add_message("try-except-raise", node=handler_having_bare_raise)
@utils.check_messages("wrong-exception-operation")
def visit_binop(self, node: nodes.BinOp) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V | A)
suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages("wrong-exception-operation")
def visit_compare(self, node: nodes.Compare) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V < A)
suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages(
"bare-except",
"broad-except",
"try-except-raise",
"binary-op-exception",
"bad-except-order",
"catching-non-exception",
"duplicate-except",
)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Check for empty except."""
self._check_try_except_raise(node)
exceptions_classes: List[Any] = []
nb_handlers = len(node.handlers)
for index, handler in enumerate(node.handlers):
if handler.type is None:
if not _is_raising(handler.body):
self.add_message("bare-except", node=handler)
# check if an "except:" is followed by some other
# except
if index < (nb_handlers - 1):
msg = "empty except clause should always appear last"
self.add_message("bad-except-order", node=node, args=msg)
elif isinstance(handler.type, nodes.BoolOp):
self.add_message(
"binary-op-exception", node=handler, args=handler.type.op
)
else:
try:
exceptions = list(_annotated_unpack_infer(handler.type))
except astroid.InferenceError:
continue
for part, exception in exceptions:
if exception is astroid.Uninferable:
continue
if isinstance(
exception, astroid.Instance
) and utils.inherit_from_std_ex(exception):
exception = exception._proxied
self._check_catching_non_exception(handler, exception, part)
if not isinstance(exception, nodes.ClassDef):
continue
exc_ancestors = [
anc
for anc in exception.ancestors()
if isinstance(anc, nodes.ClassDef)
]
for previous_exc in exceptions_classes:
if previous_exc in exc_ancestors:
msg = f"{previous_exc.name} is an ancestor class of {exception.name}"
self.add_message(
"bad-except-order", node=handler.type, args=msg
)
if (
exception.name in self.config.overgeneral_exceptions
and exception.root().name == utils.EXCEPTIONS_MODULE
and not _is_raising(handler.body)
):
self.add_message(
"broad-except", args=exception.name, node=handler.type
)
if exception in exceptions_classes:
self.add_message(
"duplicate-except", args=exception.name, node=handler.type
)
exceptions_classes += [exc for _, exc in exceptions]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 338 | safe_infer | ref | function | cause = utils.safe_infer(node.cause)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 344 | add_message | ref | function | self.add_message("bad-exception-context", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 345 | inherit_from_std_ex | ref | function | elif not isinstance(cause, nodes.ClassDef) and not utils.inherit_from_std_ex(
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 348 | add_message | ref | function | self.add_message("bad-exception-context", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 350 | _check_raise_missing_from | def | function | def _check_raise_missing_from(self, node: nodes.Raise) -> None:
if node.exc is None:
# This is a plain `raise`, raising the previously-caught exception. No need for a
# cause.
return
# We'd like to check whether we're inside an `except` clause:
containing_except_node = utils.find_except_wrapper_node_in_scope(node)
if not containing_except_node:
return
# We found a surrounding `except`! We're almost done proving there's a
# `raise-missing-from` here. The only thing we need to protect against is that maybe
# the `raise` is raising the exception that was caught, possibly with some shenanigans
# like `exc.with_traceback(whatever)`. We won't analyze these, we'll just assume
# there's a violation on two simple cases: `raise SomeException(whatever)` and `raise
# SomeException`.
if containing_except_node.name is None:
# The `except` doesn't have an `as exception:` part, meaning there's no way that
# the `raise` is raising the same exception.
self.add_message("raise-missing-from", node=node)
elif isinstance(node.exc, nodes.Call) and isinstance(node.exc.func, nodes.Name):
# We have a `raise SomeException(whatever)`.
self.add_message("raise-missing-from", node=node)
elif (
isinstance(node.exc, nodes.Name)
and node.exc.name != containing_except_node.name.name
):
# We have a `raise SomeException`.
self.add_message("raise-missing-from", node=node)
def _check_catching_non_exception(self, handler, exc, part):
if isinstance(exc, nodes.Tuple):
# Check if it is a tuple of exceptions.
inferred = [utils.safe_infer(elt) for elt in exc.elts]
if any(node is astroid.Uninferable for node in inferred):
# Don't emit if we don't know every component.
return
if all(
node
and (utils.inherit_from_std_ex(node) or not utils.has_known_bases(node))
for node in inferred
):
return
if not isinstance(exc, nodes.ClassDef):
# Don't emit the warning if the inferred stmt
# is None, but the exception handler is something else,
# maybe it was redefined.
if isinstance(exc, nodes.Const) and exc.value is None:
if (
isinstance(handler.type, nodes.Const) and handler.type.value is None
) or handler.type.parent_of(exc):
# If the exception handler catches None or
# the exception component, which is None, is
# defined by the entire exception handler, then
# emit a warning.
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
else:
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
return
if (
not utils.inherit_from_std_ex(exc)
and exc.name not in self._builtin_exceptions
):
if utils.has_known_bases(exc):
self.add_message(
"catching-non-exception", node=handler.type, args=(exc.name,)
)
def _check_try_except_raise(self, node):
def gather_exceptions_from_handler(
handler,
) -> Optional[List[nodes.NodeNG]]:
exceptions: List[nodes.NodeNG] = []
if handler.type:
exceptions_in_handler = utils.safe_infer(handler.type)
if isinstance(exceptions_in_handler, nodes.Tuple):
exceptions = list(
{
exception
for exception in exceptions_in_handler.elts
if isinstance(exception, nodes.Name)
}
)
elif exceptions_in_handler:
exceptions = [exceptions_in_handler]
else:
# Break when we cannot infer anything reliably.
return None
return exceptions
bare_raise = _False
handler_having_bare_raise = None
exceptions_in_bare_handler = []
for handler in node.handlers:
if bare_raise:
# check that subsequent handler is not parent of handler which had bare raise.
# since utils.safe_infer can fail for bare except, check it before.
# also break early if bare except is followed by bare except.
excs_in_current_handler = gather_exceptions_from_handler(handler)
if not excs_in_current_handler:
break
if exceptions_in_bare_handler is None:
# It can be `None` when the inference failed
break
for exc_in_current_handler in excs_in_current_handler:
inferred_current = utils.safe_infer(exc_in_current_handler)
if any(
utils.is_subclass_of(utils.safe_infer(e), inferred_current)
for e in exceptions_in_bare_handler
):
bare_raise = _False
break
# `raise` as the first operator inside the except handler
if _is_raising([handler.body[0]]):
# flags when there is a bare raise
if handler.body[0].exc is None:
bare_raise = _True
handler_having_bare_raise = handler
exceptions_in_bare_handler = gather_exceptions_from_handler(handler)
else:
if bare_raise:
self.add_message("try-except-raise", node=handler_having_bare_raise)
@utils.check_messages("wrong-exception-operation")
def visit_binop(self, node: nodes.BinOp) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V | A)
suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages("wrong-exception-operation")
def visit_compare(self, node: nodes.Compare) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V < A)
suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages(
"bare-except",
"broad-except",
"try-except-raise",
"binary-op-exception",
"bad-except-order",
"catching-non-exception",
"duplicate-except",
)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Check for empty except."""
self._check_try_except_raise(node)
exceptions_classes: List[Any] = []
nb_handlers = len(node.handlers)
for index, handler in enumerate(node.handlers):
if handler.type is None:
if not _is_raising(handler.body):
self.add_message("bare-except", node=handler)
# check if an "except:" is followed by some other
# except
if index < (nb_handlers - 1):
msg = "empty except clause should always appear last"
self.add_message("bad-except-order", node=node, args=msg)
elif isinstance(handler.type, nodes.BoolOp):
self.add_message(
"binary-op-exception", node=handler, args=handler.type.op
)
else:
try:
exceptions = list(_annotated_unpack_infer(handler.type))
except astroid.InferenceError:
continue
for part, exception in exceptions:
if exception is astroid.Uninferable:
continue
if isinstance(
exception, astroid.Instance
) and utils.inherit_from_std_ex(exception):
exception = exception._proxied
self._check_catching_non_exception(handler, exception, part)
if not isinstance(exception, nodes.ClassDef):
continue
exc_ancestors = [
anc
for anc in exception.ancestors()
if isinstance(anc, nodes.ClassDef)
]
for previous_exc in exceptions_classes:
if previous_exc in exc_ancestors:
msg = f"{previous_exc.name} is an ancestor class of {exception.name}"
self.add_message(
"bad-except-order", node=handler.type, args=msg
)
if (
exception.name in self.config.overgeneral_exceptions
and exception.root().name == utils.EXCEPTIONS_MODULE
and not _is_raising(handler.body)
):
self.add_message(
"broad-except", args=exception.name, node=handler.type
)
if exception in exceptions_classes:
self.add_message(
"duplicate-except", args=exception.name, node=handler.type
)
exceptions_classes += [exc for _, exc in exceptions]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 356 | find_except_wrapper_node_in_scope | ref | function | containing_except_node = utils.find_except_wrapper_node_in_scope(node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 368 | add_message | ref | function | self.add_message("raise-missing-from", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 371 | add_message | ref | function | self.add_message("raise-missing-from", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 377 | add_message | ref | function | self.add_message("raise-missing-from", node=node)
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 379 | _check_catching_non_exception | def | function | def _check_catching_non_exception(self, handler, exc, part):
if isinstance(exc, nodes.Tuple):
# Check if it is a tuple of exceptions.
inferred = [utils.safe_infer(elt) for elt in exc.elts]
if any(node is astroid.Uninferable for node in inferred):
# Don't emit if we don't know every component.
return
if all(
node
and (utils.inherit_from_std_ex(node) or not utils.has_known_bases(node))
for node in inferred
):
return
if not isinstance(exc, nodes.ClassDef):
# Don't emit the warning if the inferred stmt
# is None, but the exception handler is something else,
# maybe it was redefined.
if isinstance(exc, nodes.Const) and exc.value is None:
if (
isinstance(handler.type, nodes.Const) and handler.type.value is None
) or handler.type.parent_of(exc):
# If the exception handler catches None or
# the exception component, which is None, is
# defined by the entire exception handler, then
# emit a warning.
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
else:
self.add_message(
"catching-non-exception",
node=handler.type,
args=(part.as_string(),),
)
return
if (
not utils.inherit_from_std_ex(exc)
and exc.name not in self._builtin_exceptions
):
if utils.has_known_bases(exc):
self.add_message(
"catching-non-exception", node=handler.type, args=(exc.name,)
)
def _check_try_except_raise(self, node):
def gather_exceptions_from_handler(
handler,
) -> Optional[List[nodes.NodeNG]]:
exceptions: List[nodes.NodeNG] = []
if handler.type:
exceptions_in_handler = utils.safe_infer(handler.type)
if isinstance(exceptions_in_handler, nodes.Tuple):
exceptions = list(
{
exception
for exception in exceptions_in_handler.elts
if isinstance(exception, nodes.Name)
}
)
elif exceptions_in_handler:
exceptions = [exceptions_in_handler]
else:
# Break when we cannot infer anything reliably.
return None
return exceptions
bare_raise = _False
handler_having_bare_raise = None
exceptions_in_bare_handler = []
for handler in node.handlers:
if bare_raise:
# check that subsequent handler is not parent of handler which had bare raise.
# since utils.safe_infer can fail for bare except, check it before.
# also break early if bare except is followed by bare except.
excs_in_current_handler = gather_exceptions_from_handler(handler)
if not excs_in_current_handler:
break
if exceptions_in_bare_handler is None:
# It can be `None` when the inference failed
break
for exc_in_current_handler in excs_in_current_handler:
inferred_current = utils.safe_infer(exc_in_current_handler)
if any(
utils.is_subclass_of(utils.safe_infer(e), inferred_current)
for e in exceptions_in_bare_handler
):
bare_raise = _False
break
# `raise` as the first operator inside the except handler
if _is_raising([handler.body[0]]):
# flags when there is a bare raise
if handler.body[0].exc is None:
bare_raise = _True
handler_having_bare_raise = handler
exceptions_in_bare_handler = gather_exceptions_from_handler(handler)
else:
if bare_raise:
self.add_message("try-except-raise", node=handler_having_bare_raise)
@utils.check_messages("wrong-exception-operation")
def visit_binop(self, node: nodes.BinOp) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V | A)
suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages("wrong-exception-operation")
def visit_compare(self, node: nodes.Compare) -> None:
if isinstance(node.parent, nodes.ExceptHandler):
# except (V < A)
suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?"
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
@utils.check_messages(
"bare-except",
"broad-except",
"try-except-raise",
"binary-op-exception",
"bad-except-order",
"catching-non-exception",
"duplicate-except",
)
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
"""Check for empty except."""
self._check_try_except_raise(node)
exceptions_classes: List[Any] = []
nb_handlers = len(node.handlers)
for index, handler in enumerate(node.handlers):
if handler.type is None:
if not _is_raising(handler.body):
self.add_message("bare-except", node=handler)
# check if an "except:" is followed by some other
# except
if index < (nb_handlers - 1):
msg = "empty except clause should always appear last"
self.add_message("bad-except-order", node=node, args=msg)
elif isinstance(handler.type, nodes.BoolOp):
self.add_message(
"binary-op-exception", node=handler, args=handler.type.op
)
else:
try:
exceptions = list(_annotated_unpack_infer(handler.type))
except astroid.InferenceError:
continue
for part, exception in exceptions:
if exception is astroid.Uninferable:
continue
if isinstance(
exception, astroid.Instance
) and utils.inherit_from_std_ex(exception):
exception = exception._proxied
self._check_catching_non_exception(handler, exception, part)
if not isinstance(exception, nodes.ClassDef):
continue
exc_ancestors = [
anc
for anc in exception.ancestors()
if isinstance(anc, nodes.ClassDef)
]
for previous_exc in exceptions_classes:
if previous_exc in exc_ancestors:
msg = f"{previous_exc.name} is an ancestor class of {exception.name}"
self.add_message(
"bad-except-order", node=handler.type, args=msg
)
if (
exception.name in self.config.overgeneral_exceptions
and exception.root().name == utils.EXCEPTIONS_MODULE
and not _is_raising(handler.body)
):
self.add_message(
"broad-except", args=exception.name, node=handler.type
)
if exception in exceptions_classes:
self.add_message(
"duplicate-except", args=exception.name, node=handler.type
)
exceptions_classes += [exc for _, exc in exceptions]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 382 | safe_infer | ref | function | inferred = [utils.safe_infer(elt) for elt in exc.elts]
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 388 | inherit_from_std_ex | ref | function | and (utils.inherit_from_std_ex(node) or not utils.has_known_bases(node))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 388 | has_known_bases | ref | function | and (utils.inherit_from_std_ex(node) or not utils.has_known_bases(node))
|
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py | pylint/checkers/exceptions.py | 400 | parent_of | ref | function | ) or handler.type.parent_of(exc):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.