Skip to content

Commit

Permalink
Respect dummy-variable-rgx for unused bound exceptions (#6492)
Browse files Browse the repository at this point in the history
## Summary

This PR respects our unused variable regex when flagging bound
exceptions, so that you no longer get a violation for, e.g.:

```python
def f():
    try:
        pass
    except Exception as _:
        pass
```

This is an odd pattern, but I think it's surprising that the regex
_isn't_ respected here.

Closes #6391

## Test Plan

`cargo test`
  • Loading branch information
charliermarsh committed Aug 11, 2023
1 parent 5633745 commit cc151c3
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 5 deletions.
6 changes: 6 additions & 0 deletions crates/ruff/resources/test/fixtures/pyflakes/F841_0.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,9 @@ def do_thing(self):
obj = Foo()
obj.do_thing()


def f():
try:
pass
except Exception as _:
pass
8 changes: 7 additions & 1 deletion crates/ruff/src/checkers/ast/analyze/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ pub(crate) fn bindings(checker: &mut Checker) {

for binding in checker.semantic.bindings.iter() {
if checker.enabled(Rule::UnusedVariable) {
if binding.kind.is_bound_exception() && !binding.is_used() {
if binding.kind.is_bound_exception()
&& !binding.is_used()
&& !checker
.settings
.dummy_variable_rgx
.is_match(binding.name(checker.locator))
{
let mut diagnostic = Diagnostic::new(
pyflakes::rules::UnusedVariable {
name: binding.name(checker.locator).to_string(),
Expand Down
11 changes: 7 additions & 4 deletions crates/ruff/src/rules/pyflakes/rules/unused_variable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,10 +312,13 @@ pub(crate) fn unused_variable(checker: &Checker, scope: &Scope, diagnostics: &mu
&& !binding.is_global()
&& !binding.is_used()
&& !checker.settings.dummy_variable_rgx.is_match(name)
&& name != "__tracebackhide__"
&& name != "__traceback_info__"
&& name != "__traceback_supplement__"
&& name != "__debuggerskip__"
&& !matches!(
name,
"__tracebackhide__"
| "__traceback_info__"
| "__traceback_supplement__"
| "__debuggerskip__"
)
{
return Some((name.to_string(), binding.range, binding.source));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,4 +256,22 @@ F841_0.py:127:21: F841 Local variable `value` is assigned to but never used
|
= help: Remove assignment to unused variable `value`

F841_0.py:152:25: F841 [*] Local variable `_` is assigned to but never used
|
150 | try:
151 | pass
152 | except Exception as _:
| ^ F841
153 | pass
|
= help: Remove assignment to unused variable `_`

Fix
149 149 | def f():
150 150 | try:
151 151 | pass
152 |- except Exception as _:
152 |+ except Exception:
153 153 | pass


0 comments on commit cc151c3

Please sign in to comment.