diff --git a/crates/ruff_linter/resources/test/fixtures/pyflakes/F811_31.py b/crates/ruff_linter/resources/test/fixtures/pyflakes/F811_31.py new file mode 100644 index 0000000000000..de1af2722a08b --- /dev/null +++ b/crates/ruff_linter/resources/test/fixtures/pyflakes/F811_31.py @@ -0,0 +1,21 @@ +"""Regression test for: https://github.com/astral-sh/ruff/issues/12309""" + +import contextlib + +foo = None +with contextlib.suppress(ImportError): + from some_module import foo + +bar = None +try: + from some_module import bar +except ImportError: + pass + + +try: + baz = None + + from some_module import baz +except ImportError: + pass diff --git a/crates/ruff_linter/src/checkers/ast/mod.rs b/crates/ruff_linter/src/checkers/ast/mod.rs index 42713917bc493..cb1580b5f7dd1 100644 --- a/crates/ruff_linter/src/checkers/ast/mod.rs +++ b/crates/ruff_linter/src/checkers/ast/mod.rs @@ -928,6 +928,19 @@ impl<'a> Visitor<'a> for Checker<'a> { self.visit_expr(expr); } } + Stmt::With(ast::StmtWith { + items, + body, + is_async: _, + range: _, + }) => { + for item in items { + self.visit_with_item(item); + } + self.semantic.push_branch(); + self.visit_body(body); + self.semantic.pop_branch(); + } Stmt::While(ast::StmtWhile { test, body, diff --git a/crates/ruff_linter/src/rules/pyflakes/mod.rs b/crates/ruff_linter/src/rules/pyflakes/mod.rs index 072e2d04e507f..c4c0f25d1e47f 100644 --- a/crates/ruff_linter/src/rules/pyflakes/mod.rs +++ b/crates/ruff_linter/src/rules/pyflakes/mod.rs @@ -126,6 +126,7 @@ mod tests { #[test_case(Rule::RedefinedWhileUnused, Path::new("F811_28.py"))] #[test_case(Rule::RedefinedWhileUnused, Path::new("F811_29.pyi"))] #[test_case(Rule::RedefinedWhileUnused, Path::new("F811_30.py"))] + #[test_case(Rule::RedefinedWhileUnused, Path::new("F811_31.py"))] #[test_case(Rule::UndefinedName, Path::new("F821_0.py"))] #[test_case(Rule::UndefinedName, Path::new("F821_1.py"))] #[test_case(Rule::UndefinedName, Path::new("F821_2.py"))] diff --git a/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_31.py.snap b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_31.py.snap new file mode 100644 index 0000000000000..75de2fbbce7df --- /dev/null +++ b/crates/ruff_linter/src/rules/pyflakes/snapshots/ruff_linter__rules__pyflakes__tests__F811_F811_31.py.snap @@ -0,0 +1,13 @@ +--- +source: crates/ruff_linter/src/rules/pyflakes/mod.rs +--- +F811_31.py:19:29: F811 Redefinition of unused `baz` from line 17 + | +17 | baz = None +18 | +19 | from some_module import baz + | ^^^ F811 +20 | except ImportError: +21 | pass + | + = help: Remove definition: `baz`