Skip to content

Commit 456d6a2

Browse files
authoredJul 13, 2024
Consider with blocks as single-item branches (#12311)
## 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.
1 parent 940df67 commit 456d6a2

File tree

4 files changed

+48
-0
lines changed

4 files changed

+48
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
"""Regression test for: https://github.com/astral-sh/ruff/issues/12309"""
2+
3+
import contextlib
4+
5+
foo = None
6+
with contextlib.suppress(ImportError):
7+
from some_module import foo
8+
9+
bar = None
10+
try:
11+
from some_module import bar
12+
except ImportError:
13+
pass
14+
15+
16+
try:
17+
baz = None
18+
19+
from some_module import baz
20+
except ImportError:
21+
pass

‎crates/ruff_linter/src/checkers/ast/mod.rs

+13
Original file line numberDiff line numberDiff line change
@@ -928,6 +928,19 @@ impl<'a> Visitor<'a> for Checker<'a> {
928928
self.visit_expr(expr);
929929
}
930930
}
931+
Stmt::With(ast::StmtWith {
932+
items,
933+
body,
934+
is_async: _,
935+
range: _,
936+
}) => {
937+
for item in items {
938+
self.visit_with_item(item);
939+
}
940+
self.semantic.push_branch();
941+
self.visit_body(body);
942+
self.semantic.pop_branch();
943+
}
931944
Stmt::While(ast::StmtWhile {
932945
test,
933946
body,

‎crates/ruff_linter/src/rules/pyflakes/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ mod tests {
126126
#[test_case(Rule::RedefinedWhileUnused, Path::new("F811_28.py"))]
127127
#[test_case(Rule::RedefinedWhileUnused, Path::new("F811_29.pyi"))]
128128
#[test_case(Rule::RedefinedWhileUnused, Path::new("F811_30.py"))]
129+
#[test_case(Rule::RedefinedWhileUnused, Path::new("F811_31.py"))]
129130
#[test_case(Rule::UndefinedName, Path::new("F821_0.py"))]
130131
#[test_case(Rule::UndefinedName, Path::new("F821_1.py"))]
131132
#[test_case(Rule::UndefinedName, Path::new("F821_2.py"))]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
source: crates/ruff_linter/src/rules/pyflakes/mod.rs
3+
---
4+
F811_31.py:19:29: F811 Redefinition of unused `baz` from line 17
5+
|
6+
17 | baz = None
7+
18 |
8+
19 | from some_module import baz
9+
| ^^^ F811
10+
20 | except ImportError:
11+
21 | pass
12+
|
13+
= help: Remove definition: `baz`

0 commit comments

Comments
 (0)