Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions personal_python_ast_optimizer/parser/skipper.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,30 @@ def _should_skip_function(
and is_overload_function(node)
)

def visit_Try(self, node: ast.Try) -> ast.AST | list[ast.stmt] | None:
parsed_node = self.generic_visit(node)

if isinstance(
parsed_node, (ast.Try, ast.TryStar)
) and self._is_useless_try_node(parsed_node):
return parsed_node.finalbody or None

return parsed_node

def visit_TryStar(self, node: ast.TryStar) -> ast.AST | list[ast.stmt] | None:
parsed_node = self.generic_visit(node)

if isinstance(
parsed_node, (ast.Try, ast.TryStar)
) and self._is_useless_try_node(parsed_node):
return parsed_node.finalbody or None

return parsed_node

@staticmethod
def _is_useless_try_node(node: ast.Try | ast.TryStar) -> bool:
return all(isinstance(n, ast.Pass) for n in node.body)

def visit_Attribute(self, node: ast.Attribute) -> ast.AST | None:
if isinstance(node.value, ast.Name):
if node.attr in self.optimizations_config.enums_to_fold.get(
Expand Down
37 changes: 35 additions & 2 deletions tests/parser/test_exception.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,48 @@
from tests.utils import BeforeAndAfter, run_minifier_and_assert_correct


def test_raise_same_line():
def test_almost_useful_try():
before_and_after = BeforeAndAfter(
"""
try:
pass
pass
except:
pass
finally:
print(1)
""",
"print(1)",
)

run_minifier_and_assert_correct(before_and_after)


def test_useless_try():
before_and_after = BeforeAndAfter(
"""
try:
pass
except Exception as e:
pass
finally:
pass
""",
"",
)

run_minifier_and_assert_correct(before_and_after)


def test_raise_same_line():
before_and_after = BeforeAndAfter(
"""
try:
a += 1
except (Exception, ValueError) as e:
raise ValueError('a') from e
""",
"try:pass\nexcept(Exception,ValueError)as e:raise ValueError('a')from e",
"try:a+=1\nexcept(Exception,ValueError)as e:raise ValueError('a')from e",
)

run_minifier_and_assert_correct(before_and_after)
2 changes: 1 addition & 1 deletion version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
5.3.1
5.3.2