diff --git a/refurb/checks/contextlib/with_suppress.py b/refurb/checks/contextlib/with_suppress.py index 3295766..c0604d3 100644 --- a/refurb/checks/contextlib/with_suppress.py +++ b/refurb/checks/contextlib/with_suppress.py @@ -58,7 +58,8 @@ def check(node: TryStmt, errors: list[Error]) -> None: except_inner = f" ({inner})" case None: - inner = except_inner = "" + inner = "BaseException" + except_inner = "" case _: return diff --git a/refurb/checks/flow/no_with_assign.py b/refurb/checks/flow/no_with_assign.py index d85e3b2..47568f9 100644 --- a/refurb/checks/flow/no_with_assign.py +++ b/refurb/checks/flow/no_with_assign.py @@ -3,6 +3,7 @@ from mypy.nodes import ( AssignmentStmt, Block, + CallExpr, MypyFile, NameExpr, Statement, @@ -55,13 +56,25 @@ def check_stmts(body: list[Statement], errors: list[Error]) -> None: case WithStmt( body=Block( body=[AssignmentStmt(lvalues=[NameExpr() as name])] - ) + ), + expr=resources, ) if ( name.fullname and name.fullname == assign.lvalues[0].fullname # type: ignore ): - errors.append(ErrorInfo(assign.line, assign.column)) + # Skip if suppress() is one of the resources + + # see https://github.com/dosisod/refurb/issues/47 + for resource in resources: + match resource: + case CallExpr( + callee=NameExpr(fullname="contextlib.suppress") + ): + break + + else: + errors.append(ErrorInfo(assign.line, assign.column)) assign = None diff --git a/test/data/err_107.txt b/test/data/err_107.txt index 150935d..c9bd9ed 100644 --- a/test/data/err_107.txt +++ b/test/data/err_107.txt @@ -1,4 +1,4 @@ -test/data/err_107.py:3:1 [FURB107]: Replace `try: ... except: pass` with `with suppress(): ...` +test/data/err_107.py:3:1 [FURB107]: Replace `try: ... except: pass` with `with suppress(BaseException): ...` test/data/err_107.py:8:1 [FURB107]: Replace `try: ... except Exception: pass` with `with suppress(Exception): ...` test/data/err_107.py:14:1 [FURB107]: Replace `try: ... except Exception: pass` with `with suppress(Exception): ...` test/data/err_107.py:19:1 [FURB107]: Replace `try: ... except (ValueError, FileNotFoundError): pass` with `with suppress(ValueError, FileNotFoundError): ...` diff --git a/test/data/err_127.py b/test/data/err_127.py index 3684259..a1d113f 100644 --- a/test/data/err_127.py +++ b/test/data/err_127.py @@ -1,4 +1,4 @@ -from contextlib import nullcontext +from contextlib import nullcontext, suppress # these will match @@ -25,3 +25,9 @@ def func(): with nullcontext(): y = 2 + + +# see https://github.com/dosisod/refurb/issues/47 +x = 1 +with suppress(Exception): + x = 2