Skip to content

Commit

Permalink
Consider with blocks as single-item branches (#12311)
Browse files Browse the repository at this point in the history
## Summary

Ensures that, e.g., the following is not considered a
redefinition-without-use:

```python
import contextlib

foo = None
with contextlib.suppress(ImportError):
    from some_module import foo
```

Closes #12309.
  • Loading branch information
charliermarsh committed Jul 13, 2024
1 parent 940df67 commit 456d6a2
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 0 deletions.
21 changes: 21 additions & 0 deletions crates/ruff_linter/resources/test/fixtures/pyflakes/F811_31.py
Original file line number Diff line number Diff line change
@@ -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
13 changes: 13 additions & 0 deletions crates/ruff_linter/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_linter/src/rules/pyflakes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))]
Expand Down
Original file line number Diff line number Diff line change
@@ -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`

0 comments on commit 456d6a2

Please sign in to comment.