Skip to content

Commit 6c383e5

Browse files
cdce8pjacobtylerwalls
authored andcommitted
Use Try node
1 parent 816bea7 commit 6c383e5

20 files changed

+86
-113
lines changed

pylint/checkers/base/basic_checker.py

+11-13
Original file line numberDiff line numberDiff line change
@@ -272,13 +272,13 @@ class BasicChecker(_BasicChecker):
272272

273273
def __init__(self, linter: PyLinter) -> None:
274274
super().__init__(linter)
275-
self._tryfinallys: list[nodes.TryFinally] | None = None
275+
self._trys: list[nodes.Try]
276276

277277
def open(self) -> None:
278278
"""Initialize visit variables and statistics."""
279279
py_version = self.linter.config.py_version
280280
self._py38_plus = py_version >= (3, 8)
281-
self._tryfinallys = []
281+
self._trys = []
282282
self.linter.stats.reset_node_count()
283283

284284
@utils.only_required_for_messages(
@@ -478,7 +478,7 @@ def visit_expr(self, node: nodes.Expr) -> None:
478478
# side effects), else pointless-statement
479479
if (
480480
isinstance(expr, (nodes.Yield, nodes.Await))
481-
or (isinstance(node.parent, nodes.TryExcept) and node.parent.body == [node])
481+
or (isinstance(node.parent, nodes.Try) and node.parent.body == [node])
482482
or (isinstance(expr, nodes.Const) and expr.value is Ellipsis)
483483
):
484484
return
@@ -768,19 +768,17 @@ def visit_set(self, node: nodes.Set) -> None:
768768
)
769769
values.add(value)
770770

771-
def visit_tryfinally(self, node: nodes.TryFinally) -> None:
772-
"""Update try...finally flag."""
773-
assert self._tryfinallys is not None
774-
self._tryfinallys.append(node)
771+
def visit_try(self, node: nodes.Try) -> None:
772+
"""Update try block flag."""
773+
self._trys.append(node)
775774

776775
for final_node in node.finalbody:
777776
for return_node in final_node.nodes_of_class(nodes.Return):
778777
self.add_message("return-in-finally", node=return_node, confidence=HIGH)
779778

780-
def leave_tryfinally(self, _: nodes.TryFinally) -> None:
781-
"""Update try...finally flag."""
782-
assert self._tryfinallys is not None
783-
self._tryfinallys.pop()
779+
def leave_try(self, _: nodes.Try) -> None:
780+
"""Update try block flag."""
781+
self._trys.pop()
784782

785783
def _check_unreachable(
786784
self,
@@ -816,8 +814,8 @@ def _check_not_in_finally(
816814
If we find a parent which type is in breaker_classes before
817815
a 'try...finally' block we skip the whole check.
818816
"""
819-
# if self._tryfinallys is empty, we're not an in try...finally block
820-
if not self._tryfinallys:
817+
# if self._trys is empty, we're not an in try block
818+
if not self._trys:
821819
return
822820
# the node could be a grand-grand...-child of the 'try...finally'
823821
_parent = node.parent

pylint/checkers/base/basic_error_checker.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,7 @@ def _check_in_loop(
496496
if isinstance(parent, (nodes.ClassDef, nodes.FunctionDef)):
497497
break
498498
if (
499-
isinstance(parent, nodes.TryFinally)
499+
isinstance(parent, nodes.Try)
500500
and node in parent.finalbody
501501
and isinstance(node, nodes.Continue)
502502
and not self._py38_plus

pylint/checkers/design_analysis.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -593,19 +593,16 @@ def visit_default(self, node: nodes.NodeNG) -> None:
593593
if node.is_statement:
594594
self._inc_all_stmts(1)
595595

596-
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
596+
def visit_try(self, node: nodes.Try) -> None:
597597
"""Increments the branches counter."""
598598
branches = len(node.handlers)
599599
if node.orelse:
600600
branches += 1
601+
if node.finalbody:
602+
branches += 1
601603
self._inc_branch(node, branches)
602604
self._inc_all_stmts(branches)
603605

604-
def visit_tryfinally(self, node: nodes.TryFinally) -> None:
605-
"""Increments the branches counter."""
606-
self._inc_branch(node, 2)
607-
self._inc_all_stmts(2)
608-
609606
@only_required_for_messages("too-many-boolean-expressions", "too-many-branches")
610607
def visit_if(self, node: nodes.If) -> None:
611608
"""Increments the branches counter and checks boolean expressions."""

pylint/checkers/exceptions.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ def _check_misplaced_bare_raise(self, node: nodes.Raise) -> None:
348348

349349
current = node
350350
# Stop when a new scope is generated or when the raise
351-
# statement is found inside a TryFinally.
351+
# statement is found inside a Try.
352352
ignores = (nodes.ExceptHandler, nodes.FunctionDef)
353353
while current and not isinstance(current.parent, ignores):
354354
current = current.parent
@@ -473,7 +473,7 @@ def _check_catching_non_exception(
473473
"catching-non-exception", node=handler.type, args=(exc.name,)
474474
)
475475

476-
def _check_try_except_raise(self, node: nodes.TryExcept) -> None:
476+
def _check_try_except_raise(self, node: nodes.Try) -> None:
477477
def gather_exceptions_from_handler(
478478
handler: nodes.ExceptHandler,
479479
) -> list[InferenceResult] | None:
@@ -556,7 +556,7 @@ def visit_compare(self, node: nodes.Compare) -> None:
556556
"catching-non-exception",
557557
"duplicate-except",
558558
)
559-
def visit_tryexcept(self, node: nodes.TryExcept) -> None:
559+
def visit_try(self, node: nodes.Try) -> None:
560560
"""Check for empty except."""
561561
self._check_try_except_raise(node)
562562
exceptions_classes: list[Any] = []

pylint/checkers/format.py

-14
Original file line numberDiff line numberDiff line change
@@ -496,14 +496,6 @@ def visit_default(self, node: nodes.NodeNG) -> None:
496496
prev_sibl = node.previous_sibling()
497497
if prev_sibl is not None:
498498
prev_line = prev_sibl.fromlineno
499-
# The line on which a 'finally': occurs in a 'try/finally'
500-
# is not directly represented in the AST. We infer it
501-
# by taking the last line of the body and adding 1, which
502-
# should be the line of finally:
503-
elif (
504-
isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody
505-
):
506-
prev_line = node.parent.body[0].tolineno + 1
507499
elif isinstance(node.parent, nodes.Module):
508500
prev_line = 0
509501
else:
@@ -534,12 +526,6 @@ def _check_multi_statement_line(self, node: nodes.NodeNG, line: int) -> None:
534526
# in with statements.
535527
if isinstance(node, nodes.With):
536528
return
537-
# For try... except... finally..., the two nodes
538-
# appear to be on the same line due to how the AST is built.
539-
if isinstance(node, nodes.TryExcept) and isinstance(
540-
node.parent, nodes.TryFinally
541-
):
542-
return
543529
if (
544530
isinstance(node.parent, nodes.If)
545531
and not node.parent.orelse

pylint/checkers/imports.py

+4-11
Original file line numberDiff line numberDiff line change
@@ -614,8 +614,7 @@ def compute_first_non_import_node(
614614
| nodes.IfExp
615615
| nodes.Assign
616616
| nodes.AssignAttr
617-
| nodes.TryExcept
618-
| nodes.TryFinally,
617+
| nodes.Try,
619618
) -> None:
620619
# if the node does not contain an import instruction, and if it is the
621620
# first node of the module, keep a track of it (all the import positions
@@ -625,11 +624,7 @@ def compute_first_non_import_node(
625624
return
626625
if not isinstance(node.parent, nodes.Module):
627626
return
628-
nested_allowed = [nodes.TryExcept, nodes.TryFinally]
629-
is_nested_allowed = [
630-
allowed for allowed in nested_allowed if isinstance(node, allowed)
631-
]
632-
if is_nested_allowed and any(
627+
if isinstance(node, nodes.Try) and any(
633628
node.nodes_of_class((nodes.Import, nodes.ImportFrom))
634629
):
635630
return
@@ -646,9 +641,7 @@ def compute_first_non_import_node(
646641
return
647642
self._first_non_import_node = node
648643

649-
visit_tryfinally = (
650-
visit_tryexcept
651-
) = (
644+
visit_try = (
652645
visit_assignattr
653646
) = (
654647
visit_assign
@@ -672,7 +665,7 @@ def visit_functiondef(
672665
while not isinstance(root.parent, nodes.Module):
673666
root = root.parent
674667

675-
if isinstance(root, (nodes.If, nodes.TryFinally, nodes.TryExcept)):
668+
if isinstance(root, (nodes.If, nodes.Try)):
676669
if any(root.nodes_of_class((nodes.Import, nodes.ImportFrom))):
677670
return
678671

pylint/checkers/refactoring/refactoring_checker.py

+11-16
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,7 @@
2727
from pylint.lint import PyLinter
2828

2929

30-
NodesWithNestedBlocks = Union[
31-
nodes.TryExcept, nodes.TryFinally, nodes.While, nodes.For, nodes.If
32-
]
30+
NodesWithNestedBlocks = Union[nodes.Try, nodes.While, nodes.For, nodes.If]
3331

3432
KNOWN_INFINITE_ITERATORS = {"itertools.count", "itertools.cycle"}
3533
BUILTIN_EXIT_FUNCS = frozenset(("quit", "exit"))
@@ -71,7 +69,7 @@ def _if_statement_is_always_returning(
7169

7270

7371
def _except_statement_is_always_returning(
74-
node: nodes.TryExcept, returning_node_class: nodes.NodeNG
72+
node: nodes.Try, returning_node_class: nodes.NodeNG
7573
) -> bool:
7674
"""Detect if all except statements return."""
7775
return all(
@@ -653,15 +651,13 @@ def leave_module(self, _: nodes.Module) -> None:
653651
self._init()
654652

655653
@utils.only_required_for_messages("too-many-nested-blocks", "no-else-return")
656-
def visit_tryexcept(self, node: nodes.TryExcept | nodes.TryFinally) -> None:
654+
def visit_try(self, node: nodes.Try) -> None:
657655
self._check_nested_blocks(node)
658656

659-
if isinstance(node, nodes.TryExcept):
660-
self._check_superfluous_else_return(node)
661-
self._check_superfluous_else_raise(node)
657+
self._check_superfluous_else_return(node)
658+
self._check_superfluous_else_raise(node)
662659

663-
visit_tryfinally = visit_tryexcept
664-
visit_while = visit_tryexcept
660+
visit_while = visit_try
665661

666662
def _check_redefined_argument_from_local(self, name_node: nodes.AssignName) -> None:
667663
if self._dummy_rgx and self._dummy_rgx.match(name_node.name):
@@ -723,13 +719,11 @@ def visit_with(self, node: nodes.With) -> None:
723719

724720
def _check_superfluous_else(
725721
self,
726-
node: nodes.If | nodes.TryExcept,
722+
node: nodes.If | nodes.Try,
727723
msg_id: str,
728724
returning_node_class: nodes.NodeNG,
729725
) -> None:
730-
if isinstance(node, nodes.TryExcept) and isinstance(
731-
node.parent, nodes.TryFinally
732-
):
726+
if isinstance(node, nodes.Try) and node.finalbody:
733727
# Not interested in try/except/else/finally statements.
734728
return
735729

@@ -745,7 +739,8 @@ def _check_superfluous_else(
745739
isinstance(node, nodes.If)
746740
and _if_statement_is_always_returning(node, returning_node_class)
747741
) or (
748-
isinstance(node, nodes.TryExcept)
742+
isinstance(node, nodes.Try)
743+
and not node.finalbody
749744
and _except_statement_is_always_returning(node, returning_node_class)
750745
):
751746
orelse = node.orelse[0]
@@ -1962,7 +1957,7 @@ def _is_node_return_ended(self, node: nodes.NodeNG) -> bool:
19621957
return self._is_raise_node_return_ended(node)
19631958
if isinstance(node, nodes.If):
19641959
return self._is_if_node_return_ended(node)
1965-
if isinstance(node, nodes.TryExcept):
1960+
if isinstance(node, nodes.Try):
19661961
handlers = {
19671962
_child
19681963
for _child in node.get_children()

pylint/checkers/utils.py

+9-10
Original file line numberDiff line numberDiff line change
@@ -379,8 +379,7 @@ def is_defined_before(var_node: nodes.Name) -> bool:
379379
nodes.For,
380380
nodes.While,
381381
nodes.With,
382-
nodes.TryExcept,
383-
nodes.TryFinally,
382+
nodes.Try,
384383
nodes.ExceptHandler,
385384
),
386385
):
@@ -988,10 +987,10 @@ def unimplemented_abstract_methods(
988987

989988
def find_try_except_wrapper_node(
990989
node: nodes.NodeNG,
991-
) -> nodes.ExceptHandler | nodes.TryExcept | None:
992-
"""Return the ExceptHandler or the TryExcept node in which the node is."""
990+
) -> nodes.ExceptHandler | nodes.Try | None:
991+
"""Return the ExceptHandler or the Try node in which the node is."""
993992
current = node
994-
ignores = (nodes.ExceptHandler, nodes.TryExcept)
993+
ignores = (nodes.ExceptHandler, nodes.Try)
995994
while current and not isinstance(current.parent, ignores):
996995
current = current.parent
997996

@@ -1002,7 +1001,7 @@ def find_try_except_wrapper_node(
10021001

10031002
def find_except_wrapper_node_in_scope(
10041003
node: nodes.NodeNG,
1005-
) -> nodes.ExceptHandler | nodes.TryExcept | None:
1004+
) -> nodes.ExceptHandler | None:
10061005
"""Return the ExceptHandler in which the node is, without going out of scope."""
10071006
for current in node.node_ancestors():
10081007
if isinstance(current, astroid.scoped_nodes.LocalsDictNodeNG):
@@ -1062,7 +1061,7 @@ def get_exception_handlers(
10621061
list: the collection of handlers that are handling the exception or None.
10631062
"""
10641063
context = find_try_except_wrapper_node(node)
1065-
if isinstance(context, nodes.TryExcept):
1064+
if isinstance(context, nodes.Try):
10661065
return [
10671066
handler for handler in context.handlers if error_of_type(handler, exception)
10681067
]
@@ -1133,13 +1132,13 @@ def is_node_inside_try_except(node: nodes.Raise) -> bool:
11331132
bool: True if the node is inside a try/except statement, False otherwise.
11341133
"""
11351134
context = find_try_except_wrapper_node(node)
1136-
return isinstance(context, nodes.TryExcept)
1135+
return isinstance(context, nodes.Try)
11371136

11381137

11391138
def node_ignores_exception(
11401139
node: nodes.NodeNG, exception: type[Exception] | str = Exception
11411140
) -> bool:
1142-
"""Check if the node is in a TryExcept which handles the given exception.
1141+
"""Check if the node is in a Try which handles the given exception.
11431142
11441143
If the exception is not given, the function is going to look for bare
11451144
excepts.
@@ -1918,7 +1917,7 @@ def get_node_first_ancestor_of_type_and_its_child(
19181917
descendant visited directly before reaching the sought ancestor.
19191918
19201919
Useful for extracting whether a statement is guarded by a try, except, or finally
1921-
when searching for a TryFinally ancestor.
1920+
when searching for a Try ancestor.
19221921
"""
19231922
child = node
19241923
for ancestor in node.node_ancestors():

0 commit comments

Comments
 (0)